code
stringlengths
4
1.01M
language
stringclasses
2 values
/** * @(#)MediaExportParameters.java * * This file is part of the Non-Linear Book project. * Copyright (c) 2012-2016 Anton P. Kolosov * Authors: Anton P. Kolosov, et al. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 * as published by the Free Software Foundation with the addition of the * following permission added to Section 15 as permitted in Section 7(a): * FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY * ANTON P. KOLOSOV. ANTON P. KOLOSOV DISCLAIMS THE WARRANTY OF NON INFRINGEMENT * OF THIRD PARTY RIGHTS * * 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 or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA, 02110-1301 USA. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License. * * You can be released from the requirements of the license by purchasing * a commercial license. Buying such a license is mandatory as soon as you * develop commercial activities involving the Non-Linear Book software without * disclosing the source code of your own applications. * * For more information, please contact Anton P. Kolosov at this * address: antokolos@gmail.com * * Copyright (c) 2012 Anton P. Kolosov All rights reserved. */ package com.nlbhub.nlb.domain; import com.nlbhub.nlb.api.PropertyManager; /** * The MediaExportParameters class represents parameters used when saving media files during export of the scheme * to some end format (such as INSTEAD game). * * @author Anton P. Kolosov * @version 1.0 8/9/12 */ public class MediaExportParameters { public enum Preset {CUSTOM, DEFAULT, NOCHANGE, COMPRESSED}; private static final MediaExportParameters NOCHANGE = new MediaExportParameters(Preset.NOCHANGE, false, 0); private static final MediaExportParameters COMPRESSED = new MediaExportParameters(Preset.COMPRESSED, true, 80); private static final MediaExportParameters DEFAULT = ( new MediaExportParameters( Preset.DEFAULT, PropertyManager.getSettings().getDefaultConfig().getExport().isConvertpng2jpg(), PropertyManager.getSettings().getDefaultConfig().getExport().getQuality() ) ); private Preset m_preset = Preset.CUSTOM; private boolean m_convertPNG2JPG; private int m_quality; public static MediaExportParameters fromPreset(Preset preset) { switch (preset) { case NOCHANGE: return MediaExportParameters.NOCHANGE; case COMPRESSED: return MediaExportParameters.COMPRESSED; default: return MediaExportParameters.DEFAULT; } } public static MediaExportParameters getDefault() { return DEFAULT; } /* public MediaExportParameters(boolean convertPNG2JPG, int quality) { m_preset = Preset.CUSTOM; m_convertPNG2JPG = convertPNG2JPG; m_quality = quality; } */ private MediaExportParameters(Preset preset, boolean convertPNG2JPG, int quality) { m_preset = preset; m_convertPNG2JPG = convertPNG2JPG; m_quality = quality; } public Preset getPreset() { return m_preset; } public boolean isConvertPNG2JPG() { return m_convertPNG2JPG; } public int getQuality() { return m_quality; } }
Java
# Friend Chat Friend Chat is a chat integration platform for Friend. It is built to make it fairly straightforward to add access to 3rd party chat APIs. It is a client - server architecture where the server handles the connection to the remote API and presents the content to the client. Multiple clients can be connected per account, all staying in sync. Accounts are created and logged in through Friend, no extra setup required. ## Video / Audio Conferencing, aka Live Friend Chat allows peer to peer video and audio calls over webRTC, supported by the presence service. The limits to number of participants is practical; the bandwidth and power of your device. #### Invites Live invites can be sent through any module. It is sent as a data string, and as long as the invitee is also using Friend Chat, it will be intercepted and presented to the user. The live session is then established over the presence service. #### Guests Any live session can be shared through a clickable link. This is a public invite and can be used by any number of people until it is explicitly canceled. People using this link will join as a guest with either a randomly generated name or one they choose themselves. #### Share your screen or app Screen sharing is available for chrome through an extension. The option is found in the live view menu, and will either prompt you install the extension or offer to initiate screen sharing. ## Modules Modules are integrations towards 3rd party chat services. They have a server part that communicates with the remote service/server API and a client part with a custom UI that presents the data. Current modules are IRC, Presence and Treeroot. Presence is always there and IRC is added by default. #### IRC Internet Relay Chat, because it would be weird not to have it. Covers most basic needs and commands. An abbreviated list of commands if you are new to IRC: * /nick new_nick - change your nick * /action does something silly - *me does something silly* * /join #channel_name - join a channel * /part - in channel, leave the channel This can also be changed in settings. More commands and how irc works in general can be found on the internet. #### Presence Presence provides temporary or persistent many-to-many rooms for chatting and video / audio conferencing. Invites to presence rooms can be sent through the other modules. More info in the FriendSoftwareLabs/presence repository! #### Treeroot The Treeroot module integrates the chat part of the Treeroot system. It provides one to one chat, optionally end to end encrypted. You'll need to add the module ( 'add chat account' in the menu ) then log in with ( or create a new ) Treeroot account.
Java
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../../img/clover.ico" /> <link rel="stylesheet" href="../../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../../style.css'); @import url('../../../../tree.css'); </style> <script src="../../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../../clover-tree.js" type="text/javascript"></script> <script src="../../../../clover.js" type="text/javascript"></script> <script src="../../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../../cloud.js" type="text/javascript"></script> <title>rapidminer-studio-core 转换结果 </title> </head> <body > <div id="page"> <header id="header" role="banner"> <nav class="aui-header aui-dropdown2-trigger-group" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo aui-header-logo-clover"> <a href="http://www.atlassian.com/clover" title="Open Atlassian Clover home page"><span class="aui-header-logo-device">Clover</span></a> </h1> </div> <div class="aui-header-secondary"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online Clover documentation" target="_blank" href="https://confluence.atlassian.com/display/CLOVER/Clover+Documentation+Home"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="aui-page-panel-inner"> <div class="aui-page-panel-nav aui-page-panel-nav-clover"> <div class="aui-page-header-inner" style="margin-bottom: 20px;"> <div class="aui-page-header-image"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </div> <div class="aui-page-header-main" > <h1> rapidminer-studio-core 转换结果 </h1> </div> </div> <nav class="aui-navgroup aui-navgroup-vertical"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading packages-nav-heading"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui package-filter-container"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="package-filter-no-results-message hidden"> <small>No results found.</small> </p> <div class="packages-tree-wrapper" data-root-relative="../../../../" data-package-name="com.rapidminer.gui.dnd"> <div class="packages-tree-container"></div> <div class="clover-packages-lozenges"></div> </div> </div> </div> </nav> </div> <section class="aui-page-panel-content"> <div class="aui-page-panel-content-clover"> <ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../../dashboard.html">Project Clover database 星期二 九月 5 2017 16:40:29 CST</a></li> </ol> <h1 class="aui-h2-clover"> Package com.rapidminer.gui.dnd </h1> <div class="aui-tabs horizontal-tabs"> <ul class="tabs-menu"> <li class="menu-item "> <a href="pkg-summary.html"><strong>Application code</strong></a> </li> <li class="menu-item active-tab"> <a href="top-risks.html"><strong>Top risks</strong></a> </li> <li class="menu-item "> <a href="quick-wins.html"><strong>Quick wins</strong></a> </li> </ul> <div class="tabs-pane active-pane" id="tabs-first"> <div>&#160;</div> <div class="aui-message aui-message-warning"> <p class="title"> <strong>Evaluation License</strong> </p> <p> This report was generated with an evaluation server license. <a href="http://www.atlassian.com/software/clover">Purchase Clover</a> or <a href="http://confluence.atlassian.com/x/JAgQCQ">configure your license.</a> </p> </div> <div style="text-align: right; margin-bottom: 10px"> <button class="aui-button aui-button-subtle" id="popupHelp"> <span class="aui-icon aui-icon-small aui-iconfont-help"></span>&#160;How to read this chart </button> <script> AJS.InlineDialog(AJS.$("#popupHelp"), "helpDialog", function (content, trigger, showPopup) { var description = topRisksDescription(); var title = 'Top Risks'; content.css({"padding": "20px"}).html( '<h2>' + title + '</h2>' + description); showPopup(); return false; }, { width: 600 } ); </script> </div> <div style="padding: 20px; border: 1px solid #cccccc; background-color: #f5f5f5; border-radius: 3px"> <div id="shallowPackageCloud" > </div> </div> </div> <!-- tabs-pane active-pane --> </div> <!-- aui-tabs horizontal-tabs --> </div> <!-- class="aui-page-panel-content-clover" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://www.atlassian.com/software/clover">Atlassian Clover</a> v 4.1.2 on 星期二 九月 5 2017 17:24:16 CST using coverage data from 星期四 一月 1 1970 08:00:00 CST. </li> </ul> <ul> <li>Clover Evaluation License registered to Clover Plugin. You have 29 day(s) before your license expires.</li> </ul> <div id="footer-logo"> <a target="_blank" href="http://www.atlassian.com/"> Atlassian </a> </div> </section> </footer> </section> <!-- class="aui-page-panel-content" --> </div> <!-- class="aui-page-panel-inner" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
Java
<div align="center" class="heading_gray"> <h3>User Registration</h3> </div> <br/> <?php echo form_open('user/user_registration/userinsert', array('id' => 'formUser')); echo blue_box_top(); ?> <table width="100%" border="0" cellspacing="0" cellpadding="4" align="center" class="heading_tab" style="margin-top:15px;"> <tr> <th colspan="4" align="left">User Creation</th> </tr> <tr> <td width="10%" class="">&nbsp;</td> <td align="left" width="27%" class="table_row_first">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;User Name : </td> <td align="left" width="55%" class="table_row_first"><?php echo form_input("txtNewUserName",@$selected_user[0]['user_name'], 'class="input_box" id="txtNewUserName"' );?></td> <td width="18%">&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td align="left" width="27%" class="table_row_first">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Password : </td> <td align="left" width="55%" class="table_row_first"><?php echo form_password("txtNewPassword",'', 'class="input_box" id="txtNewPassword"' );?></td> <td width="18%">&nbsp;</td> </tr> <!--<tr> <td>&nbsp;</td> <td align="left" width="27%" class="table_row_first">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;User Type : </td> <td align="left" width="55%" class="table_row_first"><?php echo (@$school_show == 'show') ? @$school_details[0]['class_end'] : form_dropdown("userType", array(0=>'...........', 1=>'Admin', 2 => 'User'), 'id="userType"','id="userType"');?></td> <td width="18%">&nbsp;</td> </tr>--> <?php if(count(@$user_rights) > 0 ){?> <tr> <td>&nbsp;</td> <td align="left" width="27%" class="table_row_first" valign="top">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;User Rights : </td> <td align="left" width="55%" class="table_row_first"> <?php $functionality_label = ''; for($i=0; $i<count($user_rights); $i++){ if($functionality_label != $user_rights[$i]['label_name']){ $functionality_label = $user_rights[$i]['label_name']; ?> <div class="clear_both"></div> <div class="functionality_label"><?php echo $user_rights[$i]['label_name']?></div> <?php } if(count(@$selected_user_rights) > 0 && @$selected_user_rights[0] != 0){ $checked = (in_array($user_rights[$i]['rf_id'], @$selected_user_rights)) ? 'TRUE' : ''; } else { $checked = ''; } $data = array( 'name' => 'chkRight_'.$user_rights[$i]['rf_id'], 'id' => 'chkRight_'.$user_rights[$i]['rf_id'], 'value' => $user_rights[$i]['rf_id'], 'checked' => $checked, 'style' => 'margin:5px', ); ?> <div class="clear_both"></div> <div class="functionalities"> <?php echo form_checkbox($data); echo form_label($user_rights[$i]['rf_functionality'], 'chkRight_'.$user_rights[$i]['rf_id']).'<br>'; ?> </div> <?php } ?> </td> <td width="18%">&nbsp;</td> </tr> <?php }?> <tr> <td align="center" colspan="4"> <?php echo (@$selected_user[0]['user_id'] != '') ? form_button('Update User', 'Update User', 'onClick="javascript: return fnsUserUpdate(\''.@$selected_user[0]['user_id'].'\')"').'&nbsp;'.form_button('Cancel', 'Cancel', 'onClick="javascript: return cancel()"'):form_submit('Add User', 'Add User', 'onClick="javascript: return fnsUserAdd()"');?> </td> </tr> </table> <input type="hidden" name="hidUserId" id="hidUserId" /> <?php echo blue_box_bottom(); echo form_close(); ?>
Java
jaleela_protestor_leader = Creature:new { objectName = "", socialGroup = "thug", faction = "thug", level = 17, chanceHit = 0.320000, damageMin = 180, damageMax = 190, baseXp = 1102, baseHAM = 2400, baseHAMmax = 3000, armor = 0, resists = {0,0,0,0,0,0,0,-1,-1}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0.000000, ferocity = 0, pvpBitmask = ATTACKABLE + ENEMY + AGGRESSIVE, creatureBitmask = PACK, optionsBitmask = 128, diet = HERBIVORE, templates = { "object/mobile/dressed_criminal_thug_human_male_01.iff" }, lootGroups = { { groups = { {group = "junk", chance = 4000000}, {group = "wearables_common", chance = 3000000}, {group = "loot_kit_parts", chance = 2000000}, {group = "tailor_components", chance = 1000000}, } } }, weapons = {"pirate_weapons_heavy"}, attacks = merge(brawlermaster,marksmanmaster) } CreatureTemplates:addCreatureTemplate(jaleela_protestor_leader, "jaleela_protestor_leader")
Java
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateOauthAuthCodesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('oauth_auth_codes', function (Blueprint $table) { $table->string('id', 100)->primary(); $table->unsignedBigInteger('user_id')->index(); $table->unsignedBigInteger('client_id'); $table->text('scopes')->nullable(); $table->boolean('revoked'); $table->dateTime('expires_at')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('oauth_auth_codes'); } }
Java
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AppModule } from '../../../../app.module'; import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material'; import { ConfirmDialogComponent } from './confirm-dialog.component'; describe('ConfirmDialogComponent', () => { let component: ConfirmDialogComponent; let dialog: MatDialog; let fixture: ComponentFixture<ConfirmDialogComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ AppModule, ], providers: [ { provide: MAT_DIALOG_DATA, useValue: {} }, { provide: MatDialogRef } ] }) .compileComponents(); })); beforeEach(() => { dialog = TestBed.get(MatDialog); fixture = TestBed.createComponent(ConfirmDialogComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
Java
{% extends 'task/default.html' %} {% block task-content %} <dl class="task__data"> {% if task.category %} <dt>Category</dt> <dd>{{ task.get_category_display }}</dd> {% endif %} {% if task.text %} <dt>Message</dt> <dd>{{task.text}}</dd> {% endif %} {% if task.user %} <dt>User</dt> <dd><a href="{% url 'admin:auth_user_change' task.user.pk %}">{{task.user.profile.full_name}}</a></dd> {% endif %} {% if task.foia %} <dt>Request</dt> <dd><a href="{{task.foia.get_absolute_url}}">{{task.foia}}</a> (<a href="{% url 'admin:foia_foiarequest_change' task.foia.pk %}">admin</a>) - MR #{{task.foia.pk}}</dd> {% elif task.agency %} <dt>Agency</dt> <dd><a href="{% url 'admin:agency_agency_change' task.agency.pk %}">{{task.agency}}</a></dd> {% elif task.jurisdiction %} <dt>Jurisdiction</dt> <dd><a href="{% url 'admin:jurisdiction_jurisdiction_change' task.jurisdiction.pk %}">{{task.jurisdiction}}</a></dd> {% endif %} </dl> <form method="POST" action="{{ endpoint }}" class="collapsable flag-reply"> <header> <p>&crarr; Reply to {{task.user.profile.full_name}} &lt;<a href="mailto:{{task.user.email}}">{{task.user.email}}</a>&gt;</p> </header> {% csrf_token %} <input type="hidden" name="task" value="{{task.pk}}"> {{ flag_form.text }} <footer class="submission-control"> <button type="submit" name="reply" value="true" class="primary button">Reply</button> <div class="checkbox-field"> <input type="checkbox" name="resolve" id="resolve-with-reply" checked> <label for="resolve-with-reply">Resolve after sending</label> </div> </footer> </form> {% endblock %}
Java
require 'spec_helper' require 'rollbar/middleware/sinatra' require 'sinatra/base' require 'rack/test' class SinatraDummy < Sinatra::Base class DummyError < StandardError; end use Rollbar::Middleware::Sinatra get '/foo' do raise DummyError.new end get '/bar' do 'this will not crash' end post '/crash_post' do raise DummyError.new end end describe Rollbar::Middleware::Sinatra, :reconfigure_notifier => true do include Rack::Test::Methods def app SinatraDummy end let(:logger_mock) { double('logger').as_null_object } before do Rollbar.configure do |config| config.logger = logger_mock config.framework = 'Sinatra' end end let(:uncaught_level) do Rollbar.configuration.uncaught_exception_level end let(:expected_report_args) do [uncaught_level, exception, { :use_exception_level_filters => true }] end describe '#call' do context 'for a crashing endpoint' do # this is the default for test mode in Sinatra context 'with raise_errors? == true' do let(:exception) { kind_of(SinatraDummy::DummyError) } before do allow(app.settings).to receive(:raise_errors?).and_return(true) end it 'reports the error to Rollbar API and raises error' do expect(Rollbar).to receive(:log).with(*expected_report_args) expect do get '/foo' end.to raise_error(SinatraDummy::DummyError) end end context 'with raise_errors? == false' do let(:exception) { kind_of(SinatraDummy::DummyError) } before do allow(app.settings).to receive(:raise_errors?).and_return(false) end it 'reports the error to Rollbar, but nothing is raised' do expect(Rollbar).to receive(:log).with(*expected_report_args) get '/foo' end end end context 'for a NOT crashing endpoint' do it 'doesnt report any error to Rollbar API' do expect(Rollbar).not_to receive(:log) get '/bar' end end context 'if the middleware itself fails' do let(:exception) { Exception.new } before do allow_any_instance_of(described_class).to receive(:framework_error).and_raise(exception) allow(app.settings).to receive(:raise_errors?).and_return(false) end it 'reports the report error' do expect(Rollbar).to receive(:log).with(*expected_report_args) expect do get '/foo' end.to raise_error(exception) end end context 'with GET parameters' do let(:exception) { kind_of(SinatraDummy::DummyError) } let(:params) do { 'key' => 'value' } end it 'appear in the sent payload' do expect do get '/foo', params end.to raise_error(exception) expect(Rollbar.last_report[:request][:GET]).to be_eql(params) end end context 'with POST parameters' do let(:exception) { kind_of(SinatraDummy::DummyError) } let(:params) do { 'key' => 'value' } end it 'appear in the sent payload' do expect do post '/crash_post', params end.to raise_error(exception) expect(Rollbar.last_report[:request][:POST]).to be_eql(params) end end context 'with JSON POST parameters' do let(:exception) { kind_of(SinatraDummy::DummyError) } let(:params) do { 'key' => 'value' } end it 'appears in the sent payload when application/json is the content type' do expect do post '/crash_post', params.to_json, { 'CONTENT_TYPE' => 'application/json' } end.to raise_error(exception) expect(Rollbar.last_report[:request][:body]).to be_eql(params.to_json) end it 'appears in the sent payload when the accepts header contains json' do expect do post '/crash_post', params, { 'ACCEPT' => 'application/vnd.github.v3+json' } end.to raise_error(exception) expect(Rollbar.last_report[:request][:POST]).to be_eql(params) end end it 'resets the notifier scope in every request' do get '/bar' id1 = Rollbar.scope_object.object_id get '/bar' id2 = Rollbar.scope_object.object_id expect(id1).not_to be_eql(id2) end context 'with person data' do let(:exception) { kind_of(SinatraDummy::DummyError) } let(:person_data) do { 'email' => 'person@example.com' } end it 'includes person data from env' do expect do get '/foo', {}, 'rollbar.person_data' => person_data end.to raise_error(exception) expect(Rollbar.last_report[:person]).to be_eql(person_data) end it 'includes empty person data when not in env' do expect do get '/foo' end.to raise_error(exception) expect(Rollbar.last_report[:person]).to be_eql({}) end end end end
Java
/* * Asqatasun - Automated webpage assessment * Copyright (C) 2008-2020 Asqatasun.org * * 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/>. * * Contact us by mail: asqatasun AT asqatasun DOT org */ package org.asqatasun.rules.rgaa30; import org.asqatasun.ruleimplementation.AbstractNotTestedRuleImplementation; /** * Implementation of the rule 1.10.1 of the referential Rgaa 3.0. * * For more details about the implementation, refer to <a href="http://doc.asqatasun.org/en/90_Rules/rgaa3.0/01.Images/Rule-1-10-1.html">the rule 1.10.1 design page.</a> * @see <a href="http://references.modernisation.gouv.fr/referentiel-technique-0#test-1-10-1"> 1.10.1 rule specification</a> */ public class Rgaa30Rule011001 extends AbstractNotTestedRuleImplementation { /** * Default constructor */ public Rgaa30Rule011001 () { super(); } }
Java
'use strict'; var phonetic = require('phonetic'); var socketio = require('socket.io'); var _ = require('underscore'); var load = function(http) { var io = socketio(http); var ioNamespace = '/'; var getEmptyRoomId = function() { var roomId = null; do { roomId = phonetic.generate().toLowerCase() } while (io.nsps[ioNamespace].adapter.rooms[roomId]); return roomId; }; var sendRoomInfo = function(socket, info) { if (!info.roomId) { return; } var clients = io.nsps[ioNamespace].adapter.rooms[info.roomId]; io.sockets.in(info.roomId).emit('room.info', { id: info.roomId, count: clients ? Object.keys(clients).length : 0 }); }; var onJoin = function(socket, info, data) { if (info.roomId) { return; } info.roomId = data && data.roomId ? data.roomId : null; if (!info.roomId || !io.nsps[ioNamespace].adapter.rooms[data.roomId]) { info.roomId = getEmptyRoomId(socket); console.log('[Socket] Assigning room id ' + info.roomId + ' to ip ' + socket.handshake.address); } else { console.log('[Socket] Assigning room id ' + info.roomId + ' to ip ' + socket.handshake.address + ' (from client)'); } socket.join(info.roomId); socket.emit('join', { roomId: info.roomId }); sendRoomInfo(socket, info); }; var onEvent = function(socket, info, event, data) { if (!info.roomId) { return; } socket.broadcast.to(info.roomId).emit(event, data); }; var onChunk = function(socket, info, data) { socket.emit('file.ack', { guid: data.guid }); onEvent(socket, info, 'file.chunk', data); }; var onConnection = function(socket) { console.log('[Socket] New connection from ip ' + socket.handshake.address); var info = { roomId: null }; socket.on('disconnect', function() { console.log('[Socket] Connection from ip ' + socket.handshake.address + ' disconnected'); sendRoomInfo(socket, info); }); socket.on('join', _.partial(onJoin, socket, info)); socket.on('file.start', _.partial(onEvent, socket, info, 'file.start')); socket.on('file.chunk', _.partial(onChunk, socket, info)); } io.on('connection', onConnection); }; module.exports = { load: load };
Java
#pragma once class cosmos; #include "game/transcendental/step_declaration.h" class position_copying_system { public: void update_transforms(const logic_step step); };
Java
# Does it have wifi? ## Development Requires **Node 0.12+**. Install: ```bash $ npm install -g gulp $ npm install ``` Run server with auto-reload (without minification): ```bash $ gulp ``` To force minification of assets (build takes a bit longer) include the `--minified` flag: ```bash $ gulp --minified ``` ## Production deployment SSH as root into the production server: ``` $ ssh root@45.55.241.79 $ cd /opt/doesithavewifi $ git pull $ npm run build ``` ## Credits * [Ramesh Nair](https://github.com/hiddentao) * [Jeff Lau](https://github.com/jefflau) * [Leon Talbert](https://github.com/LeonmanRolls) ## License AGPLv3 - see LICENSE.txt
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <html> <head> </head> <body bgcolor="white"> Provides test classes. </body> </html>
Java
ALTER TABLE `album` CHANGE fichier fichier varchar(250);
Java
/* * Fluffy Meow - Torrent RSS generator for TV series * Copyright (C) 2015 Victor Denisov * * 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/>. */ package org.plukh.fluffymeow.aws; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.DescribeTagsRequest; import com.amazonaws.services.ec2.model.DescribeTagsResult; import com.amazonaws.services.ec2.model.Filter; import com.amazonaws.services.ec2.model.TagDescription; import org.apache.http.client.fluent.Request; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.IOException; public class AWSInstanceInfoProviderImpl implements InstanceInfoProvider { private static final Logger log = LogManager.getLogger(AWSInstanceInfoProviderImpl.class); private static final String NAME_TAG = "Name"; private static final String DEPLOYMENT_ID_TAG = "deploymentId"; private InstanceInfo instanceInfo; public AWSInstanceInfoProviderImpl() { } @Override public InstanceInfo getInstanceInfo() { if (instanceInfo == null) { try { AmazonEC2 ec2 = new AmazonEC2Client(); String instanceId = Request.Get("http://169.254.169.254/latest/meta-data/instance-id").execute().returnContent().asString(); if (log.isDebugEnabled()) log.debug("Instance Id: " + instanceId); DescribeTagsRequest tagsRequest = new DescribeTagsRequest().withFilters( new Filter().withName("resource-id").withValues(instanceId), new Filter().withName("key").withValues(NAME_TAG, DEPLOYMENT_ID_TAG)); DescribeTagsResult tagsResult = ec2.describeTags(tagsRequest); String name = getTag(tagsResult, NAME_TAG); if (log.isDebugEnabled()) log.debug("Instance name: " + name); String deploymentId = getTag(tagsResult, DEPLOYMENT_ID_TAG); if (log.isDebugEnabled()) log.debug("Deployment: " + deploymentId); instanceInfo = new InstanceInfo() .withInstanceId(instanceId) .withName(name) .withDeploymentId(deploymentId); } catch (IOException e) { throw new AWSInstanceInfoException("Error retrieving AWS instance info", e); } } return instanceInfo; } private String getTag(DescribeTagsResult tagsResult, String tagName) { for (TagDescription tag : tagsResult.getTags()) { if (tag.getKey().equals(tagName)) return tag.getValue(); } return null; } }
Java
require_relative 'api_fixtures_helper' class FakeApiResponse include ApiFixturesHelper def app_init parse(app_init_plist) end def all_cinemas parse(all_cinemas_plist) end def film_times(cinema_id, film_id) parse(film_times_plist(cinema_id, film_id)) end end
Java
# ETConf -- web-based user-friendly computer hardware configurator # Copyright (C) 2010-2011 ETegro Technologies, PLC <http://etegro.com/> # Sergey Matveev <sergey.matveev@etegro.com> # # 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/>. from django.conf.urls.defaults import * urlpatterns = patterns( "configurator.giver.views", ( r"^perform/(?P<computermodel_alias>.+)/$", "perform" ), ( r"^configurator/(?P<computermodel_alias>.+)/$", "configurator" ), ( r"^computermodel/request/(?P<computermodel_alias>.+)$", "computermodel_request" ), )
Java
/* * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS) * Copyright (c) 2016-2017 metaverse core developers (see MVS-AUTHORS) * * This file is part of metaverse. * * metaverse is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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/>. */ #include <metaverse/bitcoin/message/alert.hpp> #include <boost/iostreams/stream.hpp> #include <metaverse/bitcoin/message/version.hpp> #include <metaverse/bitcoin/utility/assert.hpp> #include <metaverse/bitcoin/utility/container_sink.hpp> #include <metaverse/bitcoin/utility/container_source.hpp> #include <metaverse/bitcoin/utility/istream_reader.hpp> #include <metaverse/bitcoin/utility/ostream_writer.hpp> namespace libbitcoin { namespace message { const std::string alert::command = "alert"; const uint32_t alert::version_minimum = version::level::minimum; const uint32_t alert::version_maximum = version::level::maximum; alert alert::factory_from_data(uint32_t version, const data_chunk& data) { alert instance; instance.from_data(version, data); return instance; } alert alert::factory_from_data(uint32_t version, std::istream& stream) { alert instance; instance.from_data(version, stream); return instance; } alert alert::factory_from_data(uint32_t version, reader& source) { alert instance; instance.from_data(version, source); return instance; } bool alert::is_valid() const { return !payload.empty() || !signature.empty(); } void alert::reset() { payload.clear(); payload.shrink_to_fit(); signature.clear(); signature.shrink_to_fit(); } bool alert::from_data(uint32_t version, const data_chunk& data) { boost::iostreams::stream<byte_source<data_chunk>> istream(data); return from_data(version, istream); } bool alert::from_data(uint32_t version, std::istream& stream) { istream_reader source(stream); return from_data(version, source); } bool alert::from_data(uint32_t version, reader& source) { reset(); auto size = source.read_variable_uint_little_endian(); BITCOIN_ASSERT(size <= bc::max_size_t); const auto payload_size = static_cast<size_t>(size); size_t signature_size = 0; auto result = static_cast<bool>(source); if (result) { payload = source.read_data(payload_size); result = source && (payload.size() == payload_size); } if (result) { size = source.read_variable_uint_little_endian(); BITCOIN_ASSERT(size <= bc::max_size_t); signature_size = static_cast<size_t>(size); result = source; } if (result) { signature = source.read_data(signature_size); result = source && (signature.size() == signature_size); } if (!result) reset(); return result; } data_chunk alert::to_data(uint32_t version) const { data_chunk data; boost::iostreams::stream<byte_sink<data_chunk>> ostream(data); to_data(version, ostream); ostream.flush(); BITCOIN_ASSERT(data.size() == serialized_size(version)); return data; } void alert::to_data(uint32_t version, std::ostream& stream) const { ostream_writer sink(stream); to_data(version, sink); } void alert::to_data(uint32_t version, writer& sink) const { sink.write_variable_uint_little_endian(payload.size()); sink.write_data(payload); sink.write_variable_uint_little_endian(signature.size()); sink.write_data(signature); } uint64_t alert::serialized_size(uint32_t version) const { return variable_uint_size(payload.size()) + payload.size() + variable_uint_size(signature.size()) + signature.size(); } bool operator==(const alert& left, const alert& right) { bool result = (left.payload.size() == right.payload.size()) && (left.signature.size() == right.signature.size()); for (size_t i = 0; i < left.payload.size() && result; i++) result = (left.payload[i] == right.payload[i]); for (size_t i = 0; i < left.signature.size() && result; i++) result = (left.signature[i] == right.signature[i]); return result; } bool operator!=(const alert& left, const alert& right) { return !(left == right); } } // end message } // end libbitcoin
Java
module BABYLON { export class Animation { private _keys: Array<any>; private _offsetsCache = {}; private _highLimitsCache = {}; private _stopped = false; public _target; private _easingFunction: IEasingFunction; public targetPropertyPath: string[]; public currentFrame: number; public static CreateAndStartAnimation(name: string, mesh: AbstractMesh, tartgetProperty: string, framePerSecond: number, totalFrame: number, from: any, to: any, loopMode?: number) { var dataType = undefined; if (!isNaN(parseFloat(from)) && isFinite(from)) { dataType = Animation.ANIMATIONTYPE_FLOAT; } else if (from instanceof Quaternion) { dataType = Animation.ANIMATIONTYPE_QUATERNION; } else if (from instanceof Vector3) { dataType = Animation.ANIMATIONTYPE_VECTOR3; } else if (from instanceof Vector2) { dataType = Animation.ANIMATIONTYPE_VECTOR2; } else if (from instanceof Color3) { dataType = Animation.ANIMATIONTYPE_COLOR3; } if (dataType == undefined) { return null; } var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode); var keys = []; keys.push({ frame: 0, value: from }); keys.push({ frame: totalFrame, value: to }); animation.setKeys(keys); mesh.animations.push(animation); return mesh.getScene().beginAnimation(mesh, 0, totalFrame,(animation.loopMode === 1)); } constructor(public name: string, public targetProperty: string, public framePerSecond: number, public dataType: number, public loopMode?: number) { this.targetPropertyPath = targetProperty.split("."); this.dataType = dataType; this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode; } // Methods public isStopped(): boolean { return this._stopped; } public getKeys(): any[] { return this._keys; } public getEasingFunction() { return this._easingFunction; } public setEasingFunction(easingFunction: EasingFunction) { this._easingFunction = easingFunction; } public floatInterpolateFunction(startValue: number, endValue: number, gradient: number): number { return startValue + (endValue - startValue) * gradient; } public quaternionInterpolateFunction(startValue: Quaternion, endValue: Quaternion, gradient: number): Quaternion { return Quaternion.Slerp(startValue, endValue, gradient); } public vector3InterpolateFunction(startValue: Vector3, endValue: Vector3, gradient: number): Vector3 { return Vector3.Lerp(startValue, endValue, gradient); } public vector2InterpolateFunction(startValue: Vector2, endValue: Vector2, gradient: number): Vector2 { return Vector2.Lerp(startValue, endValue, gradient); } public color3InterpolateFunction(startValue: Color3, endValue: Color3, gradient: number): Color3 { return Color3.Lerp(startValue, endValue, gradient); } public matrixInterpolateFunction(startValue: Matrix, endValue: Matrix, gradient: number): Matrix { var startScale = new Vector3(0, 0, 0); var startRotation = new Quaternion(); var startTranslation = new Vector3(0, 0, 0); startValue.decompose(startScale, startRotation, startTranslation); var endScale = new Vector3(0, 0, 0); var endRotation = new Quaternion(); var endTranslation = new Vector3(0, 0, 0); endValue.decompose(endScale, endRotation, endTranslation); var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient); var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient); var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient); var result = Matrix.Compose(resultScale, resultRotation, resultTranslation); return result; } public clone(): Animation { var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode); clone.setKeys(this._keys); return clone; } public setKeys(values: Array<any>): void { this._keys = values.slice(0); this._offsetsCache = {}; this._highLimitsCache = {}; } private _getKeyValue(value: any): any { if (typeof value === "function") { return value(); } return value; } private _interpolate(currentFrame: number, repeatCount: number, loopMode: number, offsetValue?, highLimitValue?) { if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) { return highLimitValue.clone ? highLimitValue.clone() : highLimitValue; } this.currentFrame = currentFrame; // Try to get a hash to find the right key var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1)); if (this._keys[startKey].frame >= currentFrame) { while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) { startKey--; } } for (var key = startKey; key < this._keys.length ; key++) { if (this._keys[key + 1].frame >= currentFrame) { var startValue = this._getKeyValue(this._keys[key].value); var endValue = this._getKeyValue(this._keys[key + 1].value); // gradient : percent of currentFrame between the frame inf and the frame sup var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame); // check for easingFunction and correction of gradient if (this._easingFunction != null) { gradient = this._easingFunction.ease(gradient); } switch (this.dataType) { // Float case Animation.ANIMATIONTYPE_FLOAT: switch (loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: return this.floatInterpolateFunction(startValue, endValue, gradient); case Animation.ANIMATIONLOOPMODE_RELATIVE: return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient); } break; // Quaternion case Animation.ANIMATIONTYPE_QUATERNION: var quaternion = null; switch (loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient); break; case Animation.ANIMATIONLOOPMODE_RELATIVE: quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount)); break; } return quaternion; // Vector3 case Animation.ANIMATIONTYPE_VECTOR3: switch (loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: return this.vector3InterpolateFunction(startValue, endValue, gradient); case Animation.ANIMATIONLOOPMODE_RELATIVE: return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount)); } // Vector2 case Animation.ANIMATIONTYPE_VECTOR2: switch (loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: return this.vector2InterpolateFunction(startValue, endValue, gradient); case Animation.ANIMATIONLOOPMODE_RELATIVE: return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount)); } // Color3 case Animation.ANIMATIONTYPE_COLOR3: switch (loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: return this.color3InterpolateFunction(startValue, endValue, gradient); case Animation.ANIMATIONLOOPMODE_RELATIVE: return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount)); } // Matrix case Animation.ANIMATIONTYPE_MATRIX: switch (loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: // return this.matrixInterpolateFunction(startValue, endValue, gradient); case Animation.ANIMATIONLOOPMODE_RELATIVE: return startValue; } default: break; } break; } } return this._getKeyValue(this._keys[this._keys.length - 1].value); } public animate(delay: number, from: number, to: number, loop: boolean, speedRatio: number): boolean { if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) { this._stopped = true; return false; } var returnValue = true; // Adding a start key at frame 0 if missing if (this._keys[0].frame !== 0) { var newKey = { frame: 0, value: this._keys[0].value }; this._keys.splice(0, 0, newKey); } // Check limits if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) { from = this._keys[0].frame; } if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) { to = this._keys[this._keys.length - 1].frame; } // Compute ratio var range = to - from; var offsetValue; // ratio represents the frame delta between from and to var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0; var highLimitValue = 0; if (ratio > range && !loop) { // If we are out of range and not looping get back to caller returnValue = false; highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value); } else { // Get max value if required if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) { var keyOffset = to.toString() + from.toString(); if (!this._offsetsCache[keyOffset]) { var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE); var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE); switch (this.dataType) { // Float case Animation.ANIMATIONTYPE_FLOAT: this._offsetsCache[keyOffset] = toValue - fromValue; break; // Quaternion case Animation.ANIMATIONTYPE_QUATERNION: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); break; // Vector3 case Animation.ANIMATIONTYPE_VECTOR3: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); // Vector2 case Animation.ANIMATIONTYPE_VECTOR2: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); // Color3 case Animation.ANIMATIONTYPE_COLOR3: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); default: break; } this._highLimitsCache[keyOffset] = toValue; } highLimitValue = this._highLimitsCache[keyOffset]; offsetValue = this._offsetsCache[keyOffset]; } } if (offsetValue === undefined) { switch (this.dataType) { // Float case Animation.ANIMATIONTYPE_FLOAT: offsetValue = 0; break; // Quaternion case Animation.ANIMATIONTYPE_QUATERNION: offsetValue = new Quaternion(0, 0, 0, 0); break; // Vector3 case Animation.ANIMATIONTYPE_VECTOR3: offsetValue = Vector3.Zero(); break; // Vector2 case Animation.ANIMATIONTYPE_VECTOR2: offsetValue = Vector2.Zero(); break; // Color3 case Animation.ANIMATIONTYPE_COLOR3: offsetValue = Color3.Black(); } } // Compute value var repeatCount = (ratio / range) >> 0; var currentFrame = returnValue ? from + ratio % range : to; var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue); // Set value if (this.targetPropertyPath.length > 1) { var property = this._target[this.targetPropertyPath[0]]; for (var index = 1; index < this.targetPropertyPath.length - 1; index++) { property = property[this.targetPropertyPath[index]]; } property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue; } else { this._target[this.targetPropertyPath[0]] = currentValue; } if (this._target.markAsDirty) { this._target.markAsDirty(this.targetProperty); } if (!returnValue) { this._stopped = true; } return returnValue; } // Statics private static _ANIMATIONTYPE_FLOAT = 0; private static _ANIMATIONTYPE_VECTOR3 = 1; private static _ANIMATIONTYPE_QUATERNION = 2; private static _ANIMATIONTYPE_MATRIX = 3; private static _ANIMATIONTYPE_COLOR3 = 4; private static _ANIMATIONTYPE_VECTOR2 = 5; private static _ANIMATIONLOOPMODE_RELATIVE = 0; private static _ANIMATIONLOOPMODE_CYCLE = 1; private static _ANIMATIONLOOPMODE_CONSTANT = 2; public static get ANIMATIONTYPE_FLOAT(): number { return Animation._ANIMATIONTYPE_FLOAT; } public static get ANIMATIONTYPE_VECTOR3(): number { return Animation._ANIMATIONTYPE_VECTOR3; } public static get ANIMATIONTYPE_VECTOR2(): number { return Animation._ANIMATIONTYPE_VECTOR2; } public static get ANIMATIONTYPE_QUATERNION(): number { return Animation._ANIMATIONTYPE_QUATERNION; } public static get ANIMATIONTYPE_MATRIX(): number { return Animation._ANIMATIONTYPE_MATRIX; } public static get ANIMATIONTYPE_COLOR3(): number { return Animation._ANIMATIONTYPE_COLOR3; } public static get ANIMATIONLOOPMODE_RELATIVE(): number { return Animation._ANIMATIONLOOPMODE_RELATIVE; } public static get ANIMATIONLOOPMODE_CYCLE(): number { return Animation._ANIMATIONLOOPMODE_CYCLE; } public static get ANIMATIONLOOPMODE_CONSTANT(): number { return Animation._ANIMATIONLOOPMODE_CONSTANT; } } }
Java
// //{block name="backend/create_backend_order/view/toolbar"} // Ext.define('Shopware.apps.SwagBackendOrder.view.main.Toolbar', { extend: 'Ext.toolbar.Toolbar', alternateClassName: 'SwagBackendOrder.view.main.Toolbar', alias: 'widget.createbackendorder-toolbar', dock: 'top', ui: 'shopware-ui', padding: '0 10 0 10', snippets: { buttons: { openCustomer: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/button/open_customer"}Open Customer{/s}', createCustomer: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/button/create_customer"}Create Customer{/s}', createGuest: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/button/create_guest"}Create Guest{/s}' }, shop: { noCustomer: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/shop/label/no_costumer"}Shop: No customer selected.{/s}', default: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/shop/label/default"}Shop: {/s}' }, currencyLabel: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/currency/label"}Choose currency{/s}', languageLabel: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/language/label"}Language{/s}' }, /** * */ initComponent: function () { var me = this; me.items = me.createToolbarItems(); me.languageStore = Ext.create('Ext.data.Store', { name: 'languageStore', fields: ['id', 'mainId', 'categoryId', 'name', 'title', 'default'] }); /** * automatically selects the standard currency */ me.currencyStore = me.subApplication.getStore('Currency'); me.currencyStore.on('load', function () { me.changeCurrencyComboBox.bindStore(me.currencyStore); var standardCurrency = me.currencyStore.findExact('default', 1); if (standardCurrency > -1) { me.currencyModel = me.currencyStore.getAt(standardCurrency); me.changeCurrencyComboBox.select(me.currencyModel); me.currencyModel.set('selected', 1); } else { me.changeCurrencyComboBox.select(me.currencyStore.first()); me.currencyStore.first().set('selected', 1); } }); me.customerSearchField.on('valueselect', function () { me.openCustomerButton.setDisabled(false); }); //selects and loads the language sub shops var customerStore = me.subApplication.getStore('Customer'); customerStore.on('load', function () { if (typeof customerStore.getAt(0) !== 'undefined') { var shopName = '', customerModel = customerStore.getAt(0); var languageId = customerModel.get('languageId'); var index = customerModel.languageSubShop().findExact('id', languageId); if (index >= 0) { shopName = customerModel.languageSubShop().getAt(index).get('name'); } else { index = customerModel.shop().findExact('id', languageId); shopName = customerModel.shop().getAt(index).get('name'); } me.shopLabel.setText(me.snippets.shop.default + shopName); me.fireEvent('changeCustomer'); me.getLanguageShops(customerModel.shop().getAt(0).get('id'), customerStore.getAt(0).get('languageId')); } }); me.callParent(arguments); }, /** * register the events */ registerEvents: function () { this.addEvents( 'changeSearchField' ) }, /** * creates the top toolbar items * * @returns [] */ createToolbarItems: function () { var me = this; me.customerSearchField = me.createCustomerSearch('customerName', 'id', 'email'); me.createCustomerButton = Ext.create('Ext.button.Button', { text: me.snippets.buttons.createCustomer, handler: function () { me.fireEvent('createCustomer', false); } }); me.createGuestButton = Ext.create('Ext.button.Button', { text: me.snippets.buttons.createGuest, handler: function () { me.fireEvent('createCustomer', true); } }); me.openCustomerButton = Ext.create('Ext.button.Button', { text: me.snippets.buttons.openCustomer, disabled: true, margin: '0 30 0 0', handler: function () { me.fireEvent('openCustomer'); } }); me.shopLabel = Ext.create('Ext.form.Label', { text: me.snippets.shop.noCustomer, style: { fontWeight: 'bold' } }); me.languageComboBox = Ext.create('Ext.form.field.ComboBox', { fieldLabel: me.snippets.languageLabel, labelWidth: 65, store: me.languageStore, queryMode: 'local', displayField: 'name', width: '20%', valueField: 'id', listeners: { change: { fn: function (comboBox, newValue, oldValue, eOpts) { me.fireEvent('changeLanguage', newValue); } } } }); me.changeCurrencyComboBox = Ext.create('Ext.form.field.ComboBox', { fieldLabel: me.snippets.currencyLabel, stores: me.currencyStore, queryMode: 'local', displayField: 'currency', width: '20%', valueField: 'id', listeners: { change: { fn: function (comboBox, newValue, oldValue, eOpts) { me.fireEvent('changeCurrency', comboBox, newValue, oldValue, eOpts); } } } }); return [ me.changeCurrencyComboBox, me.languageComboBox, me.shopLabel, '->', me.createCustomerButton, me.createGuestButton, me.openCustomerButton, me.customerSearchField ]; }, /** * * @param returnValue * @param hiddenReturnValue * @param name * @return Shopware.form.field.ArticleSearch */ createCustomerSearch: function (returnValue, hiddenReturnValue, name) { var me = this; me.customerStore = me.subApplication.getStore('Customer'); return Ext.create('Shopware.apps.SwagBackendOrder.view.main.CustomerSearch', { name: name, subApplication: me.subApplication, returnValue: returnValue, hiddenReturnValue: hiddenReturnValue, articleStore: me.customerStore, allowBlank: false, getValue: function () { me.store.getAt(me.record.rowIdx).set(name, this.getSearchField().getValue()); return this.getSearchField().getValue(); }, setValue: function (value) { this.getSearchField().setValue(value); } }); }, /** * @param mainShopId * @param languageId */ getLanguageShops: function (mainShopId, languageId) { var me = this; Ext.Ajax.request({ url: '{url action="getLanguageSubShops"}', params: { mainShopId: mainShopId }, success: function (response) { me.languageStore.removeAll(); var languageSubShops = Ext.JSON.decode(response.responseText); languageSubShops.data.forEach(function (record) { me.languageStore.add(record); }); me.languageComboBox.bindStore(me.languageStore); //selects the default language shop var languageIndex = me.languageStore.findExact('mainId', null); me.languageComboBox.setValue(languageId); } }); } }); // //{/block} //
Java
/** * This file is part of mycollab-services. * * mycollab-services 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. * * mycollab-services 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 mycollab-services. If not, see <http://www.gnu.org/licenses/>. */ package com.esofthead.mycollab.module.crm.service.ibatis; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.esofthead.mycollab.common.interceptor.aspect.Auditable; import com.esofthead.mycollab.common.interceptor.aspect.Traceable; import com.esofthead.mycollab.core.persistence.ICrudGenericDAO; import com.esofthead.mycollab.core.persistence.ISearchableDAO; import com.esofthead.mycollab.core.persistence.service.DefaultService; import com.esofthead.mycollab.module.crm.dao.ProductMapper; import com.esofthead.mycollab.module.crm.dao.ProductMapperExt; import com.esofthead.mycollab.module.crm.domain.Product; import com.esofthead.mycollab.module.crm.domain.criteria.ProductSearchCriteria; import com.esofthead.mycollab.module.crm.service.ProductService; @Service @Transactional public class ProductServiceImpl extends DefaultService<Integer, Product, ProductSearchCriteria> implements ProductService { @Autowired private ProductMapper productMapper; @Autowired private ProductMapperExt productMapperExt; @Override public ICrudGenericDAO<Integer, Product> getCrudMapper() { return productMapper; } @Override public ISearchableDAO<ProductSearchCriteria> getSearchMapper() { return productMapperExt; } }
Java
/* * jHears, acoustic fingerprinting framework. * Copyright (C) 2009-2010 Juha Heljoranta. * * This file is part of jHears. * * jHears 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. * * jHears 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 jHears. If not, see <http://www.gnu.org/licenses/>. */ /** * */ package org.jhears.server; import java.util.Map; public interface IUser { String getName(); Long getId(); Map<String, String> getProperties(); }
Java
<?php /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); //Vardef Handler Object class VarDefHandler { var $meta_array_name; var $target_meta_array = false; var $start_none = false; var $extra_array = array(); //used to add custom items var $options_array = array(); var $module_object; var $start_none_lbl = null; function VarDefHandler(& $module, $meta_array_name=null){ $this->module_object = $module; if($meta_array_name!=null){ global $vardef_meta_array; include("include/VarDefHandler/vardef_meta_arrays.php"); $this->target_meta_array = $vardef_meta_array[$meta_array_name]; } //end function setup } function get_vardef_array($use_singular=false, $remove_dups = false, $use_field_name = false, $use_field_label = false){ global $dictionary; global $current_language; global $app_strings; global $app_list_strings; $temp_module_strings = return_module_language($current_language, $this->module_object->module_dir); $base_array = $this->module_object->field_defs; //$base_array = $dictionary[$this->module_object->object_name]['fields']; ///Inclue empty none set or not if($this->start_none==true){ if(!empty($this->start_none_lbl)){ $this->options_array[''] = $this->start_none_lbl; } else { $this->options_array[''] = $app_strings['LBL_NONE']; } } ///used for special one off items added to filter array ex. would be href link for alert templates if(!empty($this->extra_array)){ foreach($this->extra_array as $key => $value){ $this->options_array[$key] = $value; } } /////////end special one off////////////////////////////////// foreach($base_array as $key => $value_array){ $compare_results = $this->compare_type($value_array); if($compare_results == true){ $label_name = ''; if($value_array['type'] == 'link' && !$use_field_label){ $this->module_object->load_relationship($value_array['name']); if(!empty($app_list_strings['moduleList'][$this->module_object->$value_array['name']->getRelatedModuleName()])){ $label_name = $app_list_strings['moduleList'][$this->module_object->$value_array['name']->getRelatedModuleName()]; }else{ $label_name = $this->module_object->$value_array['name']->getRelatedModuleName(); } } else if(!empty($value_array['vname'])){ $label_name = $value_array['vname']; } else { $label_name = $value_array['name']; } $label_name = get_label($label_name, $temp_module_strings); if(!empty($value_array['table'])){ //Custom Field $column_table = $value_array['table']; } else { //Non-Custom Field $column_table = $this->module_object->table_name; } if($value_array['type'] == 'link'){ if($use_field_name){ $index = $value_array['name']; }else{ $index = $this->module_object->$key->getRelatedModuleName(); } }else{ $index = $key; } $value = trim($label_name, ':'); if($remove_dups){ if(!in_array($value, $this->options_array)) $this->options_array[$index] = $value; } else $this->options_array[$index] = $value; //end if field is included } //end foreach } if($use_singular == true){ return convert_module_to_singular($this->options_array); } else { return $this->options_array; } //end get_vardef_array } function compare_type($value_array){ //Filter nothing? if(!is_array($this->target_meta_array)){ return true; } ////////Use the $target_meta_array; if(isset($this->target_meta_array['inc_override'])){ foreach($this->target_meta_array['inc_override'] as $attribute => $value){ foreach($value as $actual_value){ if(isset($value_array[$attribute]) && $value_array[$attribute] == $actual_value) return true; } if(isset($value_array[$attribute]) && $value_array[$attribute] == $value) return true; } } if(isset($this->target_meta_array['ex_override'])){ foreach($this->target_meta_array['ex_override'] as $attribute => $value){ foreach($value as $actual_value){ if(isset($value_array[$attribute]) && $value_array[$attribute] == $actual_value) return false; if(isset($value_array[$attribute]) && $value_array[$attribute] == $value) return false; } //end foreach inclusion array } } if(isset($this->target_meta_array['inclusion'])){ foreach($this->target_meta_array['inclusion'] as $attribute => $value){ if($attribute=="type"){ foreach($value as $actual_value){ if(isset($value_array[$attribute]) && $value_array[$attribute] != $actual_value) return false; } } else { if(isset($value_array[$attribute]) && $value_array[$attribute] != $value) return false; } //end foreach inclusion array } } if(isset($this->target_meta_array['exclusion'])){ foreach($this->target_meta_array['exclusion'] as $attribute => $value){ foreach($value as $actual_value){ if ( $attribute == 'reportable' ) { if ( $actual_value == 'true' ) $actual_value = 1; if ( $actual_value == 'false' ) $actual_value = 0; } if(isset($value_array[$attribute]) && $value_array[$attribute] == $actual_value) return false; } //end foreach inclusion array } } return true; //end function compare_type } //end class VarDefHandler } ?>
Java
/* * Copyright (C) 2000 - 2021 Silverpeas * * 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. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "https://www.silverpeas.org/legal/floss_exception.html" * * 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/>. */ package org.silverpeas.core.pdc.pdc.model; import org.silverpeas.core.pdc.pdc.service.PdcManager; import org.silverpeas.core.pdc.tree.model.TreeNode; import org.silverpeas.core.persistence.datasource.model.CompositeEntityIdentifier; import org.silverpeas.core.persistence.datasource.model.jpa.BasicJpaEntity; import javax.persistence.Entity; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Transient; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Spliterator; import java.util.function.Consumer; /** * A value of one of the PdC's axis. A value belongs to an axis. An axis represents a given concept * for which it defines an hierarchic tree of semantic terms belonging to the concept. A value of * an axis is then the path from the axis origin down to a given node of the tree, where each node * is a term refining or specifying the parent term a little more. For example, for an axis * representing the concept of geography, one possible value can be * "France / Rhônes-Alpes / Isère / Grenoble" where France, Rhônes-Alpes, Isère and Grenoble are * each a term (thus a node) in the axis. * "France" is another value, parent of the above one, and that is also a base value of the axis as * it has no parent (one of the root values of the axis). */ @Entity @Table(name = "pdcaxisvalue") @NamedQuery(name = "findByAxisId", query = "from PdcAxisValue where axisId = :axisId") public class PdcAxisValue extends BasicJpaEntity<PdcAxisValue, PdcAxisValuePk> { private static final long serialVersionUID = 2345886411781136417L; @Transient private transient TreeNode treeNode; @Transient private transient TreeNodeList treeNodeParents = new TreeNodeList(); protected PdcAxisValue() { } /** * Creates a value of a PdC's axis from the specified tree node. Currently, an axis of the PdC is * persisted as an hierarchical tree in which each node is a value of the axis. * @param treeNode the current persistence representation of the axis value. * @return a PdC axis value. */ public static PdcAxisValue aPdcAxisValueFromTreeNode(final TreeNode treeNode) { try { List<? extends TreeNode> parents = null; if (treeNode.hasFather()) { PdcManager pdcManager = getPdcManager(); parents = pdcManager.getFullPath(treeNode.getFatherId(), treeNode.getTreeId()); } return new PdcAxisValue().fromTreeNode(treeNode).withAsTreeNodeParents(parents). inAxisId(treeNode.getTreeId()); } catch (PdcException ex) { throw new PdcRuntimeException(ex); } } /** * Creates a value of a PdC's axis from the specified value information. Currently, an axis of the * PdC is persisted as an hierarchical tree in which each node is a value of the axis. The * parameters refers the unique identifier of the node and in the tree related to the axis * identifier. * @param valueId the unique identifier of the existing value. * @param axisId the unique identifier of the axis the value belongs to. * @return a PdC axis value. */ public static PdcAxisValue aPdcAxisValue(String valueId, String axisId) { return new PdcAxisValue().setId( valueId + CompositeEntityIdentifier.COMPOSITE_SEPARATOR + axisId); } /** * Gets the unique identifier of the axis to which this value belongs to. * @return the unique identifier of the axis value. */ public String getAxisId() { return getNativeId().getAxisId().toString(); } /** * Gets the unique value identifier. * @return the unique value identifier. */ public String getValueId() { return getNativeId().getValueId().toString(); } /** * Gets all the values into which this one can be refined or specifying in a little more. Theses * values are the children of this one in the semantic tree represented by the axis to which this * value belongs. * @return an unmodifiable set of values that are children of this one. If this value is a leaf, * then an empty set is returned. */ public Set<PdcAxisValue> getChildValues() { try { Set<PdcAxisValue> children = new HashSet<>(); List<String> childNodeIds = getPdcManager().getDaughterValues(getAxisId(), getValueId()); for (String aNodeId : childNodeIds) { children.add(aPdcAxisValue(aNodeId, getAxisId())); } return Collections.unmodifiableSet(children); } catch (PdcException ex) { throw new PdcRuntimeException(ex); } } /** * Gets the value this one refines or specifies a little more. The returned value is the parent * of this one in the semantic tree represented by the axis to which this value belongs. * @return the axis value parent of this one or null if this value has no parent (in that case, * this value is a base one). */ public PdcAxisValue getParentValue() { final PdcAxisValue parent; TreeNode node = getTreeNode(); if (node.hasFather()) { int lastNodeIndex = treeNodeParents.size() - 1; TreeNode aTreeNode = treeNodeParents.get(lastNodeIndex); String valueId = aTreeNode.getPK().getId(); String axisId = getAxisId(); PdcAxisValue pdcAxisValue = new PdcAxisValue().setId( valueId + CompositeEntityIdentifier.COMPOSITE_SEPARATOR + axisId); parent = pdcAxisValue.fromTreeNode(aTreeNode).inAxisId(getAxisId()) .withAsTreeNodeParents(treeNodeParents.subList(0, lastNodeIndex)); } else { parent = null; } return parent; } /** * Gets the term carried by this value. * @return the term of the value. */ public String getTerm() { return getTreeNode().getName(); } /** * Gets the term carried by this value and translated in the specified language. * @param language the language in which the term should be translated. * @return the term translated in the specified language. If no such translation exists, then * return the default term as get by calling getTerm() method. */ public String getTermTranslatedIn(String language) { return getTreeNode().getName(language); } /** * Is this value is a base one? * @return true if this value is an axis base value. */ public boolean isBaseValue() { // as the root in the tree represents the axis itself, a base value is a direct children of the // root. return getTreeNodeParents().size() <= 1; } /** * Gets the meaning carried by this value. The meaning is in fact the complete path of terms that * made this value. For example, in an axis representing the geography, the meaning of the value * "France / Rhônes-Alpes / Isère" is "Geography / France / Rhônes-Alpes / Isère". * @return the meaning carried by this value, in other words the complete path of this value. */ public String getMeaning() { return getMeaningTranslatedIn(""); } /** * Gets the meaning carried by this value translated in the specified language. The meaning is in * fact the complete path of translated terms that made this value. For example, in an axis * representing the geography, the meaning of the value "France / Rhônes-Alpes / Isère" is in * french "Geographie / France / Rhônes-Alpes / Isère". * @return the meaning carried by this value, in other words the complete path of this value * translated in the specified language. If no such translations exist, then the result is * equivalent to the call of the getMeaning() method. */ public String getMeaningTranslatedIn(String language) { final String meaning; final String theLanguage = (language == null ? "" : language); PdcAxisValue theParent = getParentValue(); if (theParent != null) { meaning = theParent.getMeaningTranslatedIn(theLanguage) + " / "; } else { meaning = ""; } return meaning + getTerm(); } /** * Gets the path of this value from the root value (that is a base value of the axis). The path * is * made up of the identifiers of each parent value; for example : /0/2/3 * @return the path of its value. */ public String getValuePath() { return getTreeNode().getPath() + getValueId(); } /** * Copies this value into another one. In fact, the attributes of the copy refers to the same * object referred by the attributes of this instance. * @return a copy of this PdC axis value. */ protected PdcAxisValue copy() { PdcAxisValue copy = PdcAxisValue.aPdcAxisValue(getValueId(), getAxisId()); copy.treeNode = treeNode; copy.treeNodeParents = treeNodeParents; return copy; } /** * Gets the axis to which this value belongs to and that is used to classify contents on the PdC. * @return a PdC axis configured to be used in the classification of contents. */ protected UsedAxis getUsedAxis() { try { PdcManager pdc = getPdcManager(); UsedAxis usedAxis = pdc.getUsedAxis(getAxisId()); AxisHeader axisHeader = pdc.getAxisHeader(getAxisId()); usedAxis._setAxisHeader(axisHeader); usedAxis._setAxisName(axisHeader.getName()); return usedAxis; } catch (PdcException ex) { throw new PdcRuntimeException(ex); } } /** * Gets the persisted representation of this axis value. By the same way, the parents of this * tree node are also set. * @return a tree node representing this axis value in the persistence layer. */ protected TreeNode getTreeNode() { if (this.treeNode == null || (this.treeNodeParents == null && this.treeNode.hasFather())) { loadTreeNodes(); } return this.treeNode; } protected void setId(long id) { getNativeId().setValueId(id); } protected PdcAxisValue withId(String id) { getNativeId().setValueId(Long.valueOf(id)); return this; } protected PdcAxisValue inAxisId(String axisId) { getNativeId().setAxisId(Long.valueOf(axisId)); return this; } protected PdcAxisValue fromTreeNode(final TreeNode treeNode) { getNativeId().setValueId(Long.valueOf(treeNode.getPK().getId())); this.treeNode = treeNode; return this; } protected PdcAxisValue withAsTreeNodeParents(final List<? extends TreeNode> parents) { this.treeNodeParents.setAll(parents); return this; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final PdcAxisValue other = (PdcAxisValue) obj; if (this.getNativeId().getValueId() != other.getNativeId().getValueId() && (this.getNativeId().getValueId() == null || !this.getNativeId().getValueId().equals(other.getNativeId().getValueId()))) { return false; } return this.getNativeId().getAxisId() == other.getNativeId().getAxisId() || (this.getNativeId().getAxisId() != null && !this.getNativeId().getAxisId().equals(other.getNativeId().getAxisId())); } @Override public int hashCode() { int hash = 5; hash = 89 * hash + (this.getNativeId().getValueId() != null ? this.getNativeId().getValueId().hashCode() : 0); hash = 89 * hash + (this.getNativeId().getAxisId() != null ? this.getNativeId().getAxisId().hashCode() : 0); return hash; } @Override public String toString() { return ""; } /** * Converts this PdC axis value to a ClassifyValue instance. This method is for compatibility * with the old way to manage the classification. * @return a ClassifyValue instance. * @throws PdcException if an error occurs while transforming this value into a ClassifyValue * instance. */ public ClassifyValue toClassifyValue() { ClassifyValue value = new ClassifyValue(Integer.valueOf(getAxisId()), getValuePath() + "/"); List<Value> fullPath = new ArrayList<>(); for (TreeNode aTreeNode : getTreeNodeParents()) { fullPath.add(new Value(aTreeNode.getPK().getId(), aTreeNode.getTreeId(), aTreeNode.getName(), aTreeNode.getDescription(), aTreeNode.getCreationDate(), aTreeNode.getCreatorId(), aTreeNode.getPath(), aTreeNode.getLevelNumber(), aTreeNode. getOrderNumber(), aTreeNode.getFatherId())); } TreeNode lastValue = getTreeNode(); fullPath.add(new Value(lastValue.getPK().getId(), lastValue.getTreeId(), lastValue.getName(), lastValue.getDescription(), lastValue.getCreationDate(), lastValue.getCreatorId(), lastValue.getPath(), lastValue.getLevelNumber(), lastValue.getOrderNumber(), lastValue.getFatherId())); value.setFullPath(fullPath); return value; } protected TreeNodeList getTreeNodeParents() { if (this.treeNodeParents == null) { loadTreeNodes(); } return this.treeNodeParents; } private void loadTreeNodes() { try { PdcManager pdc = getPdcManager(); String treeId = pdc.getTreeId(getAxisId()); List<? extends TreeNode> paths = pdc.getFullPath(getValueId(), treeId); int lastNodeIndex = paths.size() - 1; this.treeNode = paths.get(lastNodeIndex); this.treeNodeParents.setAll(paths.subList(0, lastNodeIndex)); } catch (PdcException ex) { throw new PdcRuntimeException(ex); } } private static PdcManager getPdcManager() { return PdcManager.get(); } private class TreeNodeList implements Iterable<TreeNode> { private final List<TreeNode> treeNodes = new ArrayList<>(); public int size() { return treeNodes.size(); } public TreeNode get(final int index) { return treeNodes.get(index); } public List<TreeNode> subList(final int fromIndex, final int toIndex) { return treeNodes.subList(fromIndex, toIndex); } public void setAll(final Collection<? extends TreeNode> nodes) { this.treeNodes.clear(); this.treeNodes.addAll(nodes); } @Override public Iterator<TreeNode> iterator() { return this.treeNodes.iterator(); } @Override public void forEach(final Consumer<? super TreeNode> action) { this.treeNodes.forEach(action); } @Override public Spliterator<TreeNode> spliterator() { return this.treeNodes.spliterator(); } } }
Java
## Device Admin user stories #### Install app on device #### Register app with right instance #### Sign in to app #### Create, update, delete enumerator users on the app #### Clean data from the app #### Check daily work of enumerators #### Manual backup of data #### Manual upload of data
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/transitional.dtd"> <html><head> <meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8"> <link rel="stylesheet" type="text/css" href="estilos.css" /> <title> Indice de Ley Orgánica de Educación Enmarcada en los Derechos Humanos, como contribuci&oacute; en EDUCERE</title> </head><body> <div id="container"> <div id="pageHeader"> </div> <div id="pageContehome"> <center><big><a href="../index.html">Indices EDUCERE</a><br></big></center> <entry> <number> 811<br> </number> <results> <titulo> Ley Orgánica de Educación Enmarcada en los Derechos Humanos<br> </titulo> <subtitulo> -- <br> </subtitulo> <autores> [[Trejo Urquiola, Walter]]<br> </autores> <titulo> <a href="http://www.saber.ula.ve/handle/123456789/19615">http://www.saber.ula.ve/handle/123456789/19615</a><br> <creado> 2001-07-01<br> </creado> </titulo> <results> <div></div> <h2 align="center">La frase: Ley Orgánica de Educación Enmarcada en los Derechos Humanos</h2> <h3 align="center">Produjo 7 resultados</h3> <table align="center" border="1" width="100%"> <tr><th>Relevancia</th><th>Archivo (URL implicito)</th><th>Tama�o (en Bytes)</th></tr> <tr><td>1000</td><td><a href=".%2fpdfs%2fv12n41%2farticulo14.pdf">articulo14.pdf</a></td><td><em>2380231</em></td></tr> <tr><td>930</td><td><a href=".%2fpdfs%2fv5n14%2farticulo11.pdf">articulo11.pdf</a></td><td><em>77241</em></td></tr> <tr><td>848</td><td><a href=".%2fpdfs%2fv11n36%2farticulo17.pdf">articulo17.pdf</a></td><td><em>875718</em></td></tr> <tr><td>822</td><td><a href=".%2fpdfs%2fv3n8%2farticulo3-8-11.pdf">articulo3-8-11.pdf</a></td><td><em>755003</em></td></tr> <tr><td>819</td><td><a href=".%2fpdfs%2fv6n17%2farticulo18.pdf">articulo18.pdf</a></td><td><em>363494</em></td></tr> <tr><td>794</td><td><a href=".%2fpdfs%2fv13n45%2farticulo11.pdf">articulo11.pdf</a></td><td><em>301176</em></td></tr> <tr><td>768</td><td><a href=".%2fpdfs%2fv5n16%2farticulo7.pdf">articulo7.pdf</a></td><td><em>408479</em></td></tr> </table> </results> </entry> </div> <div id="footer"><p>EDUCERE. La Revista Venezolana de Educación Escuela de Educación. <br/> Facultad de Humanidades y Educación Universidad de Los Andes,<br/> Mérida - Venezuela<br/> <br/> <br/> </p> </div> </div> </body> </html>
Java
package io.github.jhg543.mellex.operation; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import io.github.jhg543.mellex.ASTHelper.*; import io.github.jhg543.mellex.antlrparser.DefaultSQLBaseListener; import io.github.jhg543.mellex.antlrparser.DefaultSQLLexer; import io.github.jhg543.mellex.antlrparser.DefaultSQLParser; import io.github.jhg543.mellex.antlrparser.DefaultSQLParser.Sql_stmtContext; import io.github.jhg543.mellex.inputsource.BasicTableDefinitionProvider; import io.github.jhg543.mellex.inputsource.TableDefinitionProvider; import io.github.jhg543.mellex.listeners.ColumnDataFlowListener; import io.github.jhg543.mellex.util.Misc; import io.github.jhg543.nyallas.graphmodel.*; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; public class StringEdgePrinter { private static final Logger log = LoggerFactory.getLogger(StringEdgePrinter.class); private static int ERR_NOSQL = 1; private static int ERR_PARSE = 2; private static int ERR_SEMANTIC = 3; private static int ERR_OK = 0; private static int printSingleFile(Path srcdir, Path dstdir, int scriptNumber, TableDefinitionProvider tp) { // generate a hash to mark vt table names String srcHash = Integer.toHexString(srcdir.hashCode()); // create destination dir try { Files.createDirectories(dstdir); } catch (IOException e) { throw new RuntimeException(e); } try (PrintWriter err = new PrintWriter(dstdir.resolve("log").toAbsolutePath().toString(), "utf-8")) { // trim perl code String sql = Misc.trimPerlScript(srcdir, StandardCharsets.UTF_8); if (sql == null) { err.println("Can't extract sql from file " + srcdir.toString()); return ERR_NOSQL; } // log actual sql statement ( for corrent line number ..) try (PrintWriter writer = new PrintWriter(dstdir.resolve("sql").toAbsolutePath().toString(), "utf-8")) { writer.append(sql); } // antlr parse AtomicInteger errorCount = new AtomicInteger(); ANTLRInputStream in = new ANTLRInputStream(sql); DefaultSQLLexer lexer = new DefaultSQLLexer(in); CommonTokenStream tokens = new CommonTokenStream(lexer); DefaultSQLParser parser = new DefaultSQLParser(tokens); parser.removeErrorListeners(); parser.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { err.println("line" + line + ":" + charPositionInLine + "at" + offendingSymbol + ":" + msg); errorCount.incrementAndGet(); } }); err.println("-------Parse start---------"); ParseTree tree = null; try { tree = parser.parse(); if (errorCount.get() > 0) { return ERR_PARSE; } } catch (Exception e) { e.printStackTrace(err); return ERR_PARSE; } err.println("-------Parse OK, Semantic Analysis start --------"); ParseTreeWalker w = new ParseTreeWalker(); try { ColumnDataFlowListener s = new ColumnDataFlowListener(tp, tokens); w.walk(s, tree); } catch (Exception e) { e.printStackTrace(err); return ERR_SEMANTIC; } err.println("-------Semantic OK, Writing result --------"); // Remove volatile tables VolatileTableRemover graph = new VolatileTableRemover(); // DAG dag = new DAG(); // ZeroBasedStringIdGenerator ids = new // ZeroBasedStringIdGenerator(); Map<String, Vertex<String, Integer>> vmap = new HashMap<>(); // Output result and initialize volatile tables removal process try (PrintWriter out = new PrintWriter(dstdir.resolve("out").toAbsolutePath().toString(), "utf-8")) { out.println("ScriptID StmtID StmtType DestCol SrcCol ConnectionType"); String template = "%d %d %s %s.%s %s.%s %d\n"; DefaultSQLBaseListener pr = new DefaultSQLBaseListener() { int stmtNumber = 0; @Override public void exitSql_stmt(Sql_stmtContext ctx) { super.exitSql_stmt(ctx); String stmtType = null; SubQuery q = null; if (ctx.insert_stmt() != null) { stmtType = "I"; q = ctx.insert_stmt().stmt; } if (ctx.create_table_stmt() != null) { if (ctx.create_table_stmt().insert != null) { stmtType = "C"; q = ctx.create_table_stmt().insert; } } if (ctx.create_view_stmt() != null) { stmtType = "V"; q = ctx.create_view_stmt().insert; } if (ctx.update_stmt() != null) { stmtType = "U"; q = ctx.update_stmt().q; } if (q != null) { // what's vt's scope? Set<String> vts = tp.getVolatileTables().keySet(); String dstTable = q.dbobj.toDotString(); boolean isDstVT = vts.contains(dstTable); if (isDstVT) { dstTable = "VT_" + srcHash + "_" + dstTable; } for (ResultColumn c : q.columns) { for (InfSource source : c.inf.getSources()) { ObjectName srcname = source.getSourceObject(); String srcTable = srcname.toDotStringExceptLast(); boolean isSrcVT = vts.contains(srcTable); if (isSrcVT) { srcTable = "VT_" + srcHash + "_" + srcTable; } out.append(String.format(template, scriptNumber, stmtNumber, stmtType, dstTable, c.name, srcTable, srcname.toDotStringLast(), source.getConnectionType().getMarker())); // collapse volatile table String dst = dstTable + "." + c.name; String src = srcTable + "." + srcname.toDotStringLast(); // Integer dstnum = ids.queryNumber(dst); // Integer srcnum = ids.queryNumber(src); Vertex<String, Integer> srcv; srcv = vmap.get(src); if (srcv == null) { srcv = graph.addVertex(BasicVertex::new); vmap.put(src, srcv); srcv.setVertexData(src); if (isSrcVT) { srcv.setMarker(0); } } Vertex<String, Integer> dstv; dstv = vmap.get(dst); if (dstv == null) { dstv = graph.addVertex(BasicVertex::new); vmap.put(dst, dstv); dstv.setVertexData(dst); if (isDstVT) { dstv.setMarker(0); } } Edge<String, Integer> edge = new BasicEdge<String, Integer>(srcv, dstv); edge.setEdgeData(source.getConnectionType().getMarker()); graph.addEdge(edge); } } } else { // log.warn("query null for sm " + stmtNumber); } stmtNumber++; } }; w.walk(pr, tree); } // Int2ObjectMap<Node> collapsed = dag.collapse(scriptNumber); graph.remove(); // write result (with volatile tables removed) try (PrintWriter out = new PrintWriter(dstdir.resolve("novt").toAbsolutePath().toString(), "utf-8")) { out.println("scriptid,dstsch,dsttbl,dstcol,srcsch,srctbl,srccol,contype"); String template = "%d,%s,%s,%s,%s,%s,%s,%d\n"; for (Vertex<String, Integer> v : graph.getVertexes()) { for (Edge<String, Integer> e : v.getOutgoingEdges()) { String dst = e.getTarget().getVertexData(); String src = e.getSource().getVertexData(); List<String> t1 = Splitter.on('.').splitToList(dst); if (t1.size() == 2) { t1 = new ArrayList<String>(t1); t1.add(0, "3X_NOSCHEMA_" + scriptNumber); } List<String> t2 = Splitter.on('.').splitToList(src); if (t2.size() == 2) { t2 = new ArrayList<String>(t1); t2.add(0, "3X_NOSCHEMA_" + scriptNumber); } out.append(String.format(template, scriptNumber, t1.get(0), t1.get(1), t1.get(2), t2.get(0), t2.get(1), t2.get(2), e.getEdgeData())); } } } tp.clearVolatileTables(); err.println("-------Success --------"); return 0; } catch (FileNotFoundException | UnsupportedEncodingException e) { throw new RuntimeException(e); } } public static int[] printStringEdge(Path srcdir, Path dstdir, Predicate<Path> filefilter, int scriptNumberStart, boolean caseSensitive) { // ensure directories exist Preconditions.checkState(Files.isDirectory(srcdir)); try { Files.createDirectories(dstdir); } catch (IOException e1) { throw new RuntimeException(e1); } // set up variables GlobalSettings.setCaseSensitive(caseSensitive); AtomicInteger scriptNumber = new AtomicInteger(scriptNumberStart); TableDefinitionProvider tp = new BasicTableDefinitionProvider(Misc::nameSym); int[] stats = new int[10]; // open global output files try (PrintWriter out = new PrintWriter(dstdir.resolve("stats").toAbsolutePath().toString(), "utf-8"); PrintWriter cols = new PrintWriter(dstdir.resolve("cols").toAbsolutePath().toString(), "utf-8"); PrintWriter numbers = new PrintWriter(dstdir.resolve("number").toAbsolutePath().toString(), "utf-8")) { // for each file Files.walk(srcdir).filter(filefilter).sorted().forEach(path -> { int sn = scriptNumber.getAndIncrement(); numbers.println("" + sn + " " + path.toString()); String srcHash = Integer.toHexString(path.hashCode()); Path workdir = dstdir.resolve(path.getFileName()).resolve(srcHash); // deal with single files. int retcode = printSingleFile(path, workdir, sn, tp); if (retcode > 0) { out.println(String.format("%s %d %d", path.toString(), retcode, sn)); } stats[retcode]++; }); out.println("OK=" + stats[ERR_OK]); out.println("NOSQL=" + stats[ERR_NOSQL]); out.println("PARSE=" + stats[ERR_PARSE]); out.println("SEMANTIC=" + stats[ERR_SEMANTIC]); tp.getPermanentTables().forEach((name, stmt) -> { stmt.columns.forEach(colname -> cols.println(name + "." + colname.name)); }); return stats; } catch (IOException e) { throw new RuntimeException(e); } } public static void main(String[] args) throws Exception { Predicate<Path> filefilter = x -> Files.isRegularFile(x) && (x.getFileName().toString().toLowerCase().endsWith(".sql") || x.getFileName().toString().toLowerCase() .endsWith(".pl")) && x.toString().toUpperCase().endsWith("BIN\\" + x.getFileName().toString().toUpperCase()); // printStringEdge(Paths.get("d:/dataflow/work1/script/mafixed"), // Paths.get("d:/dataflow/work2/mares"), filefilter, 0, false); printStringEdge(Paths.get("d:/dataflow/work1/debug"), Paths.get("d:/dataflow/work2/debugres"), filefilter, 0, false); // printStringEdge(Paths.get("d:/dataflow/work1/f1/sor"), // Paths.get("d:/dataflow/work2/result2/sor"), filefilter, 0, false); } }
Java
require 'open_food_network/referer_parser' module Admin class EnterprisesController < ResourceController before_filter :load_enterprise_set, :only => :index before_filter :load_countries, :except => [:index, :register, :check_permalink] before_filter :load_methods_and_fees, :only => [:new, :edit, :update, :create] before_filter :load_groups, :only => [:new, :edit, :update, :create] before_filter :load_taxons, :only => [:new, :edit, :update, :create] before_filter :check_can_change_sells, only: :update before_filter :check_can_change_bulk_sells, only: :bulk_update before_filter :override_owner, only: :create before_filter :override_sells, only: :create before_filter :check_can_change_owner, only: :update before_filter :check_can_change_bulk_owner, only: :bulk_update before_filter :check_can_change_managers, only: :update before_filter :strip_new_properties, only: [:create, :update] before_filter :load_properties, only: [:edit, :update] before_filter :setup_property, only: [:edit] helper 'spree/products' include ActionView::Helpers::TextHelper include OrderCyclesHelper def index respond_to do |format| format.html format.json do render json: @collection, each_serializer: Api::Admin::IndexEnterpriseSerializer, spree_current_user: spree_current_user end end end def welcome render layout: "spree/layouts/bare_admin" end def update invoke_callbacks(:update, :before) if @object.update_attributes(params[object_name]) invoke_callbacks(:update, :after) flash[:success] = flash_message_for(@object, :successfully_updated) respond_with(@object) do |format| format.html { redirect_to location_after_save } format.js { render :layout => false } format.json { render json: @object, serializer: Api::Admin::IndexEnterpriseSerializer, spree_current_user: spree_current_user } end else invoke_callbacks(:update, :fails) respond_with(@object) do |format| format.json { render json: { errors: @object.errors.messages }, status: :unprocessable_entity } end end end def register if params[:sells] == 'unspecified' flash[:error] = "Please select a package" return render :welcome, layout: "spree/layouts/bare_admin" end attributes = { sells: params[:sells], visible: true } if ['own', 'any'].include? params[:sells] attributes[:shop_trial_start_date] = @enterprise.shop_trial_start_date || Time.now end if @enterprise.update_attributes(attributes) flash[:success] = "Congratulations! Registration for #{@enterprise.name} is complete!" redirect_to admin_path else flash[:error] = "Could not complete registration for #{@enterprise.name}" render :welcome, layout: "spree/layouts/bare_admin" end end def bulk_update @enterprise_set = EnterpriseSet.new(collection, params[:enterprise_set]) touched_enterprises = @enterprise_set.collection.select(&:changed?) if @enterprise_set.save flash[:success] = "Enterprises updated successfully" # 18-3-2015: It seems that the form for this action sometimes loads bogus values for # the 'sells' field, and submitting that form results in a bunch of enterprises with # values that have mysteriously changed. This statement is here to help debug that # issue, and should be removed (along with its display in index.html.haml) when the # issue has been resolved. flash[:action] = "Updated #{pluralize(touched_enterprises.count, 'enterprise')}: #{touched_enterprises.map(&:name).join(', ')}" redirect_to main_app.admin_enterprises_path else @enterprise_set.collection.select! { |e| touched_enterprises.include? e } flash[:error] = 'Update failed' render :index end end def for_order_cycle respond_to do |format| format.json do render json: ActiveModel::ArraySerializer.new( @collection, each_serializer: Api::Admin::ForOrderCycle::EnterpriseSerializer, spree_current_user: spree_current_user ).to_json end end end protected def build_resource_with_address enterprise = build_resource_without_address enterprise.address = Spree::Address.new enterprise.address.country = Spree::Country.find_by_id(Spree::Config[:default_country_id]) enterprise end alias_method_chain :build_resource, :address # Overriding method on Spree's resource controller, # so that resources are found using permalink def find_resource Enterprise.find_by_permalink(params[:id]) end private def load_enterprise_set @enterprise_set = EnterpriseSet.new(collection) if spree_current_user.admin? end def load_countries @countries = Spree::Country.order(:name) end def collection case action when :for_order_cycle order_cycle = OrderCycle.find_by_id(params[:order_cycle_id]) if params[:order_cycle_id] coordinator = Enterprise.find_by_id(params[:coordinator_id]) if params[:coordinator_id] order_cycle = OrderCycle.new(coordinator: coordinator) if order_cycle.nil? && coordinator.present? return OpenFoodNetwork::OrderCyclePermissions.new(spree_current_user, order_cycle).visible_enterprises when :index if spree_current_user.admin? OpenFoodNetwork::Permissions.new(spree_current_user). editable_enterprises. order('is_primary_producer ASC, name') elsif json_request? OpenFoodNetwork::Permissions.new(spree_current_user).editable_enterprises else Enterprise.where("1=0") unless json_request? end else # TODO was ordered with is_distributor DESC as well, not sure why or how we want to sort this now OpenFoodNetwork::Permissions.new(spree_current_user). editable_enterprises. order('is_primary_producer ASC, name') end end def collection_actions [:index, :for_order_cycle, :bulk_update] end def load_methods_and_fees @payment_methods = Spree::PaymentMethod.managed_by(spree_current_user).sort_by!{ |pm| [(@enterprise.payment_methods.include? pm) ? 0 : 1, pm.name] } @shipping_methods = Spree::ShippingMethod.managed_by(spree_current_user).sort_by!{ |sm| [(@enterprise.shipping_methods.include? sm) ? 0 : 1, sm.name] } @enterprise_fees = EnterpriseFee.managed_by(spree_current_user).for_enterprise(@enterprise).order(:fee_type, :name).all end def load_groups @groups = EnterpriseGroup.managed_by(spree_current_user) | @enterprise.groups end def load_taxons @taxons = Spree::Taxon.order(:name) end def check_can_change_bulk_sells unless spree_current_user.admin? params[:enterprise_set][:collection_attributes].each do |i, enterprise_params| enterprise_params.delete :sells unless spree_current_user == Enterprise.find_by_id(enterprise_params[:id]).owner end end end def check_can_change_sells unless spree_current_user.admin? || spree_current_user == @enterprise.owner params[:enterprise].delete :sells end end def override_owner params[:enterprise][:owner_id] = spree_current_user.id unless spree_current_user.admin? end def override_sells unless spree_current_user.admin? has_hub = spree_current_user.owned_enterprises.is_hub.any? new_enterprise_is_producer = Enterprise.new(params[:enterprise]).is_primary_producer params[:enterprise][:sells] = (has_hub && !new_enterprise_is_producer) ? 'any' : 'none' end end def check_can_change_owner unless ( spree_current_user == @enterprise.owner ) || spree_current_user.admin? params[:enterprise].delete :owner_id end end def check_can_change_bulk_owner unless spree_current_user.admin? params[:enterprise_set][:collection_attributes].each do |i, enterprise_params| enterprise_params.delete :owner_id end end end def check_can_change_managers unless ( spree_current_user == @enterprise.owner ) || spree_current_user.admin? params[:enterprise].delete :user_ids end end def strip_new_properties unless spree_current_user.admin? || params[:enterprise][:producer_properties_attributes].nil? names = Spree::Property.pluck(:name) params[:enterprise][:producer_properties_attributes].each do |key, property| params[:enterprise][:producer_properties_attributes].delete key unless names.include? property[:property_name] end end end def load_properties @properties = Spree::Property.pluck(:name) end def setup_property @enterprise.producer_properties.build end # Overriding method on Spree's resource controller def location_after_save referer_path = OpenFoodNetwork::RefererParser::path(request.referer) refered_from_edit = referer_path == main_app.edit_admin_enterprise_path(@enterprise) if params[:enterprise].key?(:producer_properties_attributes) && !refered_from_edit main_app.admin_enterprises_path else main_app.edit_admin_enterprise_path(@enterprise) end end end end
Java
# Slight modification from: https://nodejs.org/en/docs/guides/nodejs-docker-webapp/ # Assumes there is Orchestrator like Nomad to handle process dying :P FROM node:boron RUN mkdir -p /usr/src/app WORKDIR /usr/src/app # Copy source code over (including package.json) COPY ./Code /usr/src/app # and Yarn it # and Set the right permission RUN yarn && chown -R node:node . # Copy the Top Secret ENV COPY env-example /usr/src/app/.env USER node CMD [ "npm", "start" ] EXPOSE 3000
Java
--- "layout": contract "datum podpisu": 2020-07-01 "datum účinnosti": 2020-07-01 "datum ukončení": 0000-00-00 "title": "NDA - Blanka Lednická" "použité smluvní typy": - NDA "předmět": "Dohoda o ochraně důvěrných informací" "stav": V plnění "náklady": 0 "místo uložení": Centrální spisovna "smluvní strany": - "jméno": "Blanka Lednická" "bydliště": Olešná "narozen": 1980 "orgán": Česká pirátská strana "zástupce": Aleš Krupa "funkce": Vedoucí kanceláře - Česká pirátská strana "soubory": - "podepsaná verze": nda_lednicka.pdf ---
Java
package com.neverwinterdp.scribengin.dataflow.example.wire; import java.util.Properties; import com.neverwinterdp.message.Message; import com.neverwinterdp.scribengin.dataflow.DataSet; import com.neverwinterdp.scribengin.dataflow.Dataflow; import com.neverwinterdp.scribengin.dataflow.DataflowDescriptor; import com.neverwinterdp.scribengin.dataflow.DataflowSubmitter; import com.neverwinterdp.scribengin.dataflow.KafkaDataSet; import com.neverwinterdp.scribengin.dataflow.KafkaWireDataSetFactory; import com.neverwinterdp.scribengin.dataflow.Operator; import com.neverwinterdp.scribengin.shell.ScribenginShell; import com.neverwinterdp.storage.kafka.KafkaStorageConfig; import com.neverwinterdp.util.JSONSerializer; import com.neverwinterdp.vm.client.VMClient; public class ExampleWireDataflowSubmitter { private String dataflowID; private int defaultReplication; private int defaultParallelism; private int numOfWorker; private int numOfExecutorPerWorker; private String inputTopic; private String outputTopic; private ScribenginShell shell; private DataflowSubmitter submitter; private String localAppHome; private String dfsAppHome; public ExampleWireDataflowSubmitter(ScribenginShell shell){ this(shell, new Properties()); } /** * Constructor - sets shell to access Scribengin and configuration properties * @param shell ScribenginShell to connect to Scribengin with * @param props Properties to configure the dataflow */ public ExampleWireDataflowSubmitter(ScribenginShell shell, Properties props){ //This it the shell to communicate with Scribengin with this.shell = shell; //The dataflow's ID. All dataflows require a unique ID when running dataflowID = props.getProperty("dataflow.id", "WireDataflow"); //The default replication factor for Kafka defaultReplication = Integer.parseInt(props.getProperty("dataflow.replication", "1")); //The number of DataStreams to deploy defaultParallelism = Integer.parseInt(props.getProperty("dataflow.parallelism", "2")); //The number of workers to deploy (i.e. YARN containers) numOfWorker = Integer.parseInt(props.getProperty("dataflow.numWorker", "5")); //The number of executors per worker (i.e. threads per YARN container) numOfExecutorPerWorker = Integer.parseInt(props.getProperty("dataflow.numExecutorPerWorker", "5")); //The kafka input topic inputTopic = props.getProperty("dataflow.inputTopic", "input.topic"); //The kafka output topic outputTopic = props.getProperty("dataflow.outputTopic", "output.topic"); //The example hdfs dataflow local location localAppHome = props.getProperty("dataflow.localapphome", "N/A"); //DFS location to upload the example dataflow dfsAppHome = props.getProperty("dataflow.dfsAppHome", "/applications/dataflow/splitterexample"); } /** * The logic to submit the dataflow * @param kafkaZkConnect [host]:[port] of Kafka's Zookeeper conenction * @throws Exception */ public void submitDataflow(String kafkaZkConnect) throws Exception{ //Upload the dataflow to HDFS VMClient vmClient = shell.getScribenginClient().getVMClient(); vmClient.uploadApp(localAppHome, dfsAppHome); Dataflow dfl = buildDataflow(kafkaZkConnect); //Get the dataflow's descriptor DataflowDescriptor dflDescriptor = dfl.buildDataflowDescriptor(); //Output the descriptor in human-readable JSON System.out.println(JSONSerializer.INSTANCE.toString(dflDescriptor)); //Ensure all your sources and sinks are up and running first, then... //Submit the dataflow and wait until it starts running submitter = new DataflowSubmitter(shell.getScribenginClient(), dfl).submit().waitForDataflowRunning(60000); } /** * Wait for the dataflow to complete within the given timeout * @param timeout Timeout in ms * @throws Exception */ public void waitForDataflowCompletion(int timeout) throws Exception{ submitter.waitForDataflowStop(timeout); } /** * The logic to build the dataflow configuration * The main takeaway between this dataflow and the ExampleSimpleDataflowSubmitter * is the use of dfl.useWireDataSetFactory() * This factory allows us to tie together operators * with Kafka topics between them * @param kafkaZkConnect [host]:[port] of Kafka's Zookeeper conenction * @return */ public Dataflow buildDataflow(String kafkaZkConnect){ //Create the new Dataflow object // <Message,Message> pertains to the <input,output> object for the data Dataflow dfl = new Dataflow(dataflowID); //Example of how to set the KafkaWireDataSetFactory dfl. setDefaultParallelism(defaultParallelism). setDefaultReplication(defaultReplication). useWireDataSetFactory(new KafkaWireDataSetFactory(kafkaZkConnect)); dfl.getWorkerDescriptor().setNumOfInstances(numOfWorker); dfl.getWorkerDescriptor().setNumOfExecutor(numOfExecutorPerWorker); //Define our input source - set name, ZK host:port, and input topic name KafkaDataSet<Message> inputDs = dfl.createInput(new KafkaStorageConfig("input", kafkaZkConnect, inputTopic)); //Define our output sink - set name, ZK host:port, and output topic name DataSet<Message> outputDs = dfl.createOutput(new KafkaStorageConfig("output", kafkaZkConnect, outputTopic)); //Define which operators to use. //This will be the logic that ties the datasets and operators together Operator splitter = dfl.createOperator("splitteroperator", SplitterDataStreamOperator.class); Operator odd = dfl.createOperator("oddoperator", PersisterDataStreamOperator.class); Operator even = dfl.createOperator("evenoperator", PersisterDataStreamOperator.class); //Send all input to the splitter operator inputDs.useRawReader().connect(splitter); //The splitter operator then connects to the odd and even operators splitter.connect(odd) .connect(even); //Both the odd and even operator connect to the output dataset // This is arbitrary, we could connect them to any dataset or operator we wanted odd.connect(outputDs); even.connect(outputDs); return dfl; } public String getDataflowID() { return dataflowID; } public String getInputTopic() { return inputTopic; } public String getOutputTopic() { return outputTopic; } }
Java
package com.gmail.nossr50.commands.party; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.commands.CommandHelper; import com.gmail.nossr50.datatypes.PlayerProfile; import com.gmail.nossr50.events.chat.McMMOPartyChatEvent; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.party.Party; import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.util.Users; public class PCommand implements CommandExecutor { private final mcMMO plugin; public PCommand (mcMMO plugin) { this.plugin = plugin; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { PlayerProfile profile; String usage = ChatColor.RED + "Proper usage is /p <party-name> <message>"; //TODO: Needs more locale. if (CommandHelper.noCommandPermissions(sender, "mcmmo.commands.party")) { return true; } switch (args.length) { case 0: if (sender instanceof Player) { profile = Users.getProfile((Player) sender); if (profile.getAdminChatMode()) { profile.toggleAdminChat(); } profile.togglePartyChat(); if (profile.getPartyChatMode()) { sender.sendMessage(LocaleLoader.getString("Commands.Party.Chat.On")); } else { sender.sendMessage(LocaleLoader.getString("Commands.Party.Chat.Off")); } } else { sender.sendMessage(usage); } return true; default: if (sender instanceof Player) { Player player = (Player) sender; Party party = Users.getProfile(player).getParty(); if (party == null) { player.sendMessage(LocaleLoader.getString("Commands.Party.None")); return true; } StringBuffer buffer = new StringBuffer(); buffer.append(args[0]); for (int i = 1; i < args.length; i++) { buffer.append(" "); buffer.append(args[i]); } String message = buffer.toString(); McMMOPartyChatEvent chatEvent = new McMMOPartyChatEvent(player.getName(), party.getName(), message); plugin.getServer().getPluginManager().callEvent(chatEvent); if (chatEvent.isCancelled()) { return true; } message = chatEvent.getMessage(); String prefix = ChatColor.GREEN + "(" + ChatColor.WHITE + player.getName() + ChatColor.GREEN + ") "; plugin.getLogger().info("[P](" + party.getName() + ")" + "<" + player.getName() + "> " + message); for (Player member : party.getOnlineMembers()) { member.sendMessage(prefix + message); } } else { if (args.length < 2) { sender.sendMessage(usage); return true; } if (!PartyManager.getInstance().isParty(args[0])) { sender.sendMessage(LocaleLoader.getString("Party.InvalidName")); return true; } StringBuffer buffer = new StringBuffer(); buffer.append(args[1]); for (int i = 2; i < args.length; i++) { buffer.append(" "); buffer.append(args[i]); } String message = buffer.toString(); McMMOPartyChatEvent chatEvent = new McMMOPartyChatEvent("Console", args[0], message); plugin.getServer().getPluginManager().callEvent(chatEvent); if (chatEvent.isCancelled()) { return true; } message = chatEvent.getMessage(); String prefix = ChatColor.GREEN + "(" + ChatColor.WHITE + "*Console*" + ChatColor.GREEN + ") "; plugin.getLogger().info("[P](" + args[0] + ")" + "<*Console*> " + message); for (Player member : PartyManager.getInstance().getOnlineMembers(args[0])) { member.sendMessage(prefix + message); } } return true; } } }
Java
DELETE FROM `weenie` WHERE `class_Id` = 46553; INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`) VALUES (46553, 'ace46553-oyoroisandals', 2, '2019-02-10 00:00:00') /* Clothing */; INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`) VALUES (46553, 1, 2) /* ItemType - Armor */ , (46553, 4, 65536) /* ClothingPriority - Feet */ , (46553, 5, 420) /* EncumbranceVal */ , (46553, 9, 384) /* ValidLocations - LowerLegWear, FootWear */ , (46553, 10, 384) /* CurrentWieldedLocation - LowerLegWear, FootWear */ , (46553, 16, 1) /* ItemUseable - No */ , (46553, 19, 70) /* Value */ , (46553, 28, 660) /* ArmorLevel */ , (46553, 33, 1) /* Bonded - Bonded */ , (46553, 93, 1044) /* PhysicsState - Ethereal, IgnoreCollisions, Gravity */ , (46553, 106, 100) /* ItemSpellcraft */ , (46553, 107, 0) /* ItemCurMana */ , (46553, 108, 1000) /* ItemMaxMana */ , (46553, 109, 0) /* ItemDifficulty */ , (46553, 158, 7) /* WieldRequirements - Level */ , (46553, 159, 1) /* WieldSkillType - Axe */ , (46553, 160, 180) /* WieldDifficulty */ , (46553, 265, 14) /* EquipmentSetId - Adepts */ , (46553, 8041, 101) /* PCAPRecordedPlacement - Resting */; INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`) VALUES (46553, 22, True ) /* Inscribable */ , (46553, 100, True ) /* Dyable */; INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`) VALUES (46553, 5, -0.033) /* ManaRate */ , (46553, 13, 2.9) /* ArmorModVsSlash */ , (46553, 14, 3.2) /* ArmorModVsPierce */ , (46553, 15, 2.9) /* ArmorModVsBludgeon */ , (46553, 16, 2.3) /* ArmorModVsCold */ , (46553, 17, 2.3) /* ArmorModVsFire */ , (46553, 18, 2.5) /* ArmorModVsAcid */ , (46553, 19, 2.3) /* ArmorModVsElectric */ , (46553, 165, 1) /* ArmorModVsNether */; INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`) VALUES (46553, 1, 'O-Yoroi Sandals') /* Name */; INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`) VALUES (46553, 1, 33554654) /* Setup */ , (46553, 3, 536870932) /* SoundTable */ , (46553, 6, 67108990) /* PaletteBase */ , (46553, 8, 100676025) /* Icon */ , (46553, 22, 872415275) /* PhysicsEffectTable */ , (46553, 8001, 2588696) /* PCAPRecordedWeenieHeader - Value, Usable, Wielder, ValidLocations, CurrentlyWieldedLocation, Priority, Burden */ , (46553, 8003, 18) /* PCAPRecordedObjectDesc - Inscribable, Attackable */ , (46553, 8005, 137217) /* PCAPRecordedPhysicsDesc - CSetup, STable, PeTable, AnimationFrame */; INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`) VALUES (46553, 8000, 2345789235) /* PCAPRecordedObjectIID */; INSERT INTO `weenie_properties_spell_book` (`object_Id`, `spell`, `probability`) VALUES (46553, 4391, 2) /* AcidBane8 */ , (46553, 4393, 2) /* BladeBane8 */ , (46553, 4397, 2) /* BludgeonBane8 */ , (46553, 4401, 2) /* FlameBane8 */ , (46553, 4403, 2) /* FrostBane8 */ , (46553, 4407, 2) /* Impenetrability8 */ , (46553, 4409, 2) /* LightningBane8 */ , (46553, 4412, 2) /* PiercingBane8 */ , (46553, 4700, 2) /* CANTRIPLIFEMAGICAPTITUDE3 */; INSERT INTO `weenie_properties_palette` (`object_Id`, `sub_Palette_Id`, `offset`, `length`) VALUES (46553, 67110021, 160, 8); INSERT INTO `weenie_properties_texture_map` (`object_Id`, `index`, `old_Id`, `new_Id`) VALUES (46553, 0, 83889344, 83895201) , (46553, 0, 83887066, 83895202); INSERT INTO `weenie_properties_anim_part` (`object_Id`, `index`, `animation_Id`) VALUES (46553, 0, 16778416);
Java
import { TYPES } from 'core/app/types' import { StateManager } from 'core/dialog' import { ContainerModule, interfaces } from 'inversify' import { DecisionEngine } from './decision-engine' import { DialogEngine } from './dialog-engine' import { FlowService } from './flow/flow-service' import { FlowNavigator } from './flow/navigator' import { InstructionFactory } from './instruction/factory' import { InstructionProcessor } from './instruction/processor' import { ActionStrategy, TransitionStrategy } from './instruction/strategy' import { DialogJanitor } from './janitor' export const DialogContainerModule = new ContainerModule((bind: interfaces.Bind) => { bind<DialogEngine>(TYPES.DialogEngine) .to(DialogEngine) .inSingletonScope() bind<DecisionEngine>(TYPES.DecisionEngine) .to(DecisionEngine) .inSingletonScope() bind<FlowNavigator>(TYPES.FlowNavigator) .to(FlowNavigator) .inSingletonScope() bind<FlowService>(TYPES.FlowService) .to(FlowService) .inSingletonScope() bind<InstructionFactory>(TYPES.InstructionFactory) .to(InstructionFactory) .inSingletonScope() bind<InstructionProcessor>(TYPES.InstructionProcessor) .to(InstructionProcessor) .inSingletonScope() bind<ActionStrategy>(TYPES.ActionStrategy) .to(ActionStrategy) .inRequestScope() bind<TransitionStrategy>(TYPES.TransitionStrategy) .to(TransitionStrategy) .inRequestScope() bind<DialogJanitor>(TYPES.DialogJanitorRunner) .to(DialogJanitor) .inSingletonScope() bind<StateManager>(TYPES.StateManager) .to(StateManager) .inSingletonScope() })
Java
/* uSquare 1.0 - Universal Responsive Grid Copyright (c) 2012 Br0 (shindiristudio.com) Project site: http://codecanyon.net/ Project demo: http://shindiristudio.com/usquare/ */ (function($) { function uSquareItem(element, options) { this.$item = $(element); this.$parent = options.$parent; this.options = options; this.$trigger = this.$(options.trigger); this.$close = this.$('.close'); this.$info = this.$(options.moreInfo); this.$trigger_text = this.$trigger.find('.usquare_square_text_wrapper'); this.$usquare_about = this.$info.find('.usquare_about'); this.$trigger.on('click', $.proxy(this.show, this)); this.$close.on('click', $.proxy(this.close, this)); options.$overlay.on('click', $.proxy(this.close, this)); }; uSquareItem.prototype = { show: function(e) { e.preventDefault(); if (!this.$parent.data('in_trans')) { if (!this.$item.data('showed')) { this.$parent.data('in_trans', 1); this.$item.data('showed', 1); if (this.options.before_item_opening_callback) this.options.before_item_opening_callback(this.$item); var item_position = this.$item.position(); var trigger_text_position; var this_backup=this; var moving=0; if (item_position.top>0) // && this.$parent.width()>=640) { var parent_position=this.$parent.offset(); var parent_top = parent_position.top; var non_visible_area=$(window).scrollTop()-parent_top; var going_to=item_position.top; if (non_visible_area>0) { var non_visible_row=Math.floor(non_visible_area/this.$item.height())+1; going_to=this.$item.height()*non_visible_row; going_to=item_position.top-going_to; } if (going_to>0) moving=1; if (moving) { this.$item.data('moved', going_to); var top_string='-'+going_to+'px'; var speed=this.options.opening_speed+(going_to/160)*100; this.$item.animate({top: top_string}, speed, this.options.easing, function(){ trigger_text_position = this_backup.$item.height() - this_backup.$trigger_text.height(); this_backup.$trigger_text.data('top', trigger_text_position); this_backup.$trigger_text.css('top', trigger_text_position); this_backup.$trigger_text.css('bottom', 'auto'); this_backup.$trigger_text.animate({'top': 0}, 'slow'); }); } } if (!moving) { trigger_text_position = this_backup.$item.height() - this_backup.$trigger_text.height(); this_backup.$trigger_text.data('top', trigger_text_position); this_backup.$trigger_text.css('top', trigger_text_position); this_backup.$trigger_text.css('bottom', 'auto'); this_backup.$trigger_text.animate({'top': 0}, 'slow'); } this.$item.addClass('usquare_block_selected'); var height_backup=this.$info.css('height'); this.$info.css('height', 0); this.$info.show(); this.$usquare_about.mCustomScrollbar("update"); if (this.options.before_info_rolling_callback) this.options.before_info_rolling_callback(this.$item); this.$info.animate({height:height_backup}, 'slow', this.options.easing, function() { this_backup.$parent.data('in_trans', 0); if (this_backup.options.after_info_rolling_callback) this_backup.options.after_info_rolling_callback(this_backup.$item); }); } } }, close: function(e) { e.preventDefault(); if (!this.$parent.data('in_trans')) { if (this.$item.data('showed')) { var this_backup=this; this.$info.hide(); var trigger_text_position_top = this_backup.$item.height() - this_backup.$trigger_text.height(); this_backup.$item.removeClass('usquare_block_selected'); if (this.$item.data('moved')) { var top_backup=this.$item.data('moved'); var speed=this.options.closing_speed+(top_backup/160)*100; this.$item.data('moved', 0); this.$item.animate({'top': 0}, speed, this.options.easing, function() { this_backup.$trigger_text.animate({'top': trigger_text_position_top}, 'slow'); }); } else { this_backup.$trigger_text.animate({'top': trigger_text_position_top}, 'slow'); } this.$item.data('showed', 0); } } }, $: function (selector) { return this.$item.find(selector); } }; function uSquare(element, options) { var self = this; this.options = $.extend({}, $.fn.uSquare.defaults, options); this.$element = $(element); this.$overlay = this.$('.usquare_module_shade'); this.$items = this.$(this.options.block); this.$triggers = this.$(this.options.trigger); this.$closes = this.$('.close'); this.$triggers.on('click', $.proxy(this.overlayShow, this)); this.$closes.on('click', $.proxy(this.overlayHide, this)); this.$overlay.on('click', $.proxy(this.overlayHide, this)); $.each( this.$items, function(i, element) { new uSquareItem(element, $.extend(self.options, {$overlay: self.$overlay, $parent: self.$element }) ); }); }; uSquare.prototype = { $: function (selector) { return this.$element.find(selector); }, overlayShow: function() { this.$overlay.fadeIn('slow', function(){ $(this).css({opacity : 0.5}); }) }, overlayHide: function() { if (!this.$element.data('in_trans')) { this.$overlay.fadeOut('slow'); } } }; $.fn.uSquare = function ( option ) { return this.each(function () { var $this = $(this), data = $this.data('tooltip'), options = typeof option == 'object' && option; data || $this.data('tooltip', (data = new uSquare(this, options))); (typeof option == 'string') && data[option](); }); }; $.fn.uSquare.Constructor = uSquare; $.fn.uSquare.defaults = { block: '.usquare_block', trigger: '.usquare_square', moreInfo: '.usquare_block_extended', opening_speed: 300, closing_speed: 500, easing: 'swing', before_item_opening_callback: null, before_info_rolling_callback: null, after_info_rolling_callback: null }; })(jQuery); $(window).load(function() { $(".usquare_about").mCustomScrollbar(); });
Java
var searchData= [ ['backtrace',['backtrace',['../class_logger.html#a5deb9b10c43285287a9113f280ee8fab',1,'Logger']]], ['baseexception',['BaseException',['../class_base_exception.html',1,'']]], ['baseexception_2ephp',['BaseException.php',['../_base_exception_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_menu_2_basic_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_paginator_2_basic_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_auth_2_basic_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_t_mail_2_basic_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_form_2_basic_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_grid_2_basic_8php.html',1,'']]], ['basicauth',['BasicAuth',['../class_basic_auth.html',1,'']]], ['basicauth_2ephp',['BasicAuth.php',['../_basic_auth_8php.html',1,'']]], ['beforedelete',['beforeDelete',['../class_s_q_l___relation.html#a44c9d7a3b22619b53d4f49f1070d5235',1,'SQL_Relation']]], ['beforefield',['beforeField',['../class_form___field.html#aa4bbfb40048e1c3fe939621179652be1',1,'Form_Field']]], ['beforeinsert',['beforeInsert',['../class_s_q_l___relation.html#ada6a7f2abf3ba1c19e4ba3711da1a61e',1,'SQL_Relation']]], ['beforeload',['beforeLoad',['../class_s_q_l___relation.html#a665492752f54f9cbc3fd2cae51ca4373',1,'SQL_Relation']]], ['beforemodify',['beforeModify',['../class_s_q_l___relation.html#a3ad587772d12f99af11a3db64d879210',1,'SQL_Relation']]], ['beforesave',['beforeSave',['../class_s_q_l___relation.html#ab9e4fb36c177d9633b81fc184f7bd933',1,'SQL_Relation']]], ['begintransaction',['beginTransaction',['../class_d_b.html#af3380f3b13931d581fa973a382946b32',1,'DB\beginTransaction()'],['../class_d_blite__mysql.html#a06fdc3063ff49b8de811683aae3483e6',1,'DBlite_mysql\beginTransaction()']]], ['belowfield',['belowField',['../class_form___field.html#a27cd7c6e75ed8c09aae8af32905a888d',1,'Form_Field']]], ['box_2ephp',['Box.php',['../_box_8php.html',1,'']]], ['breakhook',['breakHook',['../class_abstract_object.html#a446b3f8327b3272c838ae46f40a9da06',1,'AbstractObject']]], ['bt',['bt',['../class_d_b__dsql.html#aa374d1bfaabf3f546fe8862d09f4a096',1,'DB_dsql']]], ['button',['Button',['../class_button.html',1,'']]], ['button_2ephp',['Button.php',['../_button_8php.html',1,'']]], ['button_2ephp',['Button.php',['../_form_2_button_8php.html',1,'']]], ['button_2ephp',['Button.php',['../_view_2_button_8php.html',1,'']]], ['buttonset',['ButtonSet',['../class_button_set.html',1,'']]], ['buttonset_2ephp',['ButtonSet.php',['../_button_set_8php.html',1,'']]], ['buttonset_2ephp',['ButtonSet.php',['../_view_2_button_set_8php.html',1,'']]] ];
Java
<div class="role-filter"> <div class="fw-700 m-b-5">{{"ROLE"|translate}}</div> <div> <div class="checkbox-inline" ng-class="{'selected':roles.tank.selected}" uib-tooltip="{{'TANK'|translate}}"> <label class="tank"> <input ng-model="roles.tank.selected" type="checkbox"> </label> </div> <div class="checkbox-inline" ng-class="{'selected':roles.heal.selected}" uib-tooltip="{{'HEAL'|translate}}"> <label class="heal"> <input ng-model="roles.heal.selected" type="checkbox"> </label> </div> <div class="checkbox-inline" ng-class="{'selected':roles.melee_dps.selected}" uib-tooltip="{{'MELEE_DPS'|translate}}"> <label class="melee_dps"> <input ng-model="roles.melee_dps.selected" type="checkbox"> </label> </div> <div class="checkbox-inline" ng-class="{'selected':roles.ranged_dps.selected}" uib-tooltip="{{'RANGED_DPS'|translate}}"> <label class="ranged_dps"> <input ng-model="roles.ranged_dps.selected" type="checkbox"> </label> </div> </div> </div>
Java
body { font-family: 'DejaVu Sans Condensed'; font-size: 11pt; } p { text-align: justify; margin-bottom: 4pt; margin-top:0pt; } table {font-family: 'DejaVu Sans Condensed'; font-size: 10pt; line-height: 1.2; margin-top: 2pt; margin-bottom: 5pt; border-collapse: collapse; } thead { font-weight: bold; vertical-align: bottom; } tfoot { font-weight: bold; vertical-align: top; } thead td { font-weight: bold; } tfoot td { font-weight: bold; } .Thead { font-weight: bold; vertical-align: bottom; } .Thead td { font-weight: bold; } .headerrow td, .headerrow th { background-gradient: linear #b7cebd #f5f8f5 0 1 0 0.2; } .footerrow td, .footerrow th { background-gradient: linear #b7cebd #f5f8f5 0 1 0 0.2; } th { font-weight: bold; vertical-align: top; padding-left: 2mm; padding-right: 2mm; padding-top: 0.5mm; padding-bottom: 0.5mm; } td { padding-left: 2mm; vertical-align: top; padding-right: 2mm; padding-top: 0.5mm; padding-bottom: 0.5mm; } th p { margin:0pt; } td p { margin:0pt; } table.widecells td { padding-left: 5mm; padding-right: 5mm; } table.tallcells td { padding-top: 3mm; padding-bottom: 3mm; } hr { width: 70%; height: 1px; text-align: center; color: #999999; margin-top: 8pt; margin-bottom: 8pt; } a { color: #000066; font-style: normal; text-decoration: underline; font-weight: normal; } pre { font-family: 'DejaVu Sans Mono'; font-size: 9pt; margin-top: 5pt; margin-bottom: 5pt; } h1 { font-weight: normal; font-size: 26pt; color: #000066; font-family: 'DejaVu Sans Condensed'; margin-top: 18pt; margin-bottom: 6pt; border-top: 0.075cm solid #000000; border-bottom: 0.075cm solid #000000; page-break-after:avoid; } h2 { font-weight: bold; font-size: 12pt; color: #000066; font-family: 'DejaVu Sans Condensed'; margin-top: 6pt; margin-bottom: 6pt; border-top: 0.07cm solid #000000; border-bottom: 0.07cm solid #000000; text-transform:uppercase; page-break-after:avoid; } h3 { font-weight: normal; font-size: 26pt; color: #000000; font-family: 'DejaVu Sans Condensed'; margin-top: 0pt; margin-bottom: 6pt; border-top: 0; border-bottom: 0; page-break-after:avoid; } h4 { font-size: 13pt; color: #9f2b1e; border-bottom: 0.07cm solid #000000; font-family: 'DejaVu Sans Condensed'; margin-top: 10pt; margin-bottom: 7pt; font-variant: small-caps; /* margin-collapse:collapse; */page-break-after:avoid; } h5 { font-weight: bold; font-style:italic; ; font-size: 11pt; color: #000044; font-family: 'DejaVu Sans Condensed'; margin-top: 8pt; margin-bottom: 4pt; page-break-after:avoid; } h6 { font-weight: bold; font-size: 9.5pt; color: #333333; font-family: 'DejaVu Sans Condensed'; margin-top: 6pt; margin-bottom: ; page-break-after:avoid; } .breadcrumb { text-align: right; font-size: 8pt; font-family: 'DejaVu Serif Condensed'; color: #666666; font-weight: bold; font-style: normal; margin-bottom: 6pt; } .bpmTopic tbody tr:nth-child(even) { background-color: #f5f8f5; } .bpmTopicC tbody tr:nth-child(even) { background-color: #f5f8f5; } .bpmNoLines tbody tr:nth-child(even) { background-color: #f5f8f5; } .bpmNoLinesC tbody tr:nth-child(even) { background-color: #f5f8f5; } .bpmTopnTail tbody tr:nth-child(even) { background-color: #f5f8f5; } .bpmTopnTailC tbody tr:nth-child(even) { background-color: #f5f8f5; } .evenrow td, .evenrow th { background-color: #f5f8f5; } .oddrow td, .oddrow th { background-color: #e3ece4; } .bpmTopic { background-color: #e3ece4; } .bpmTopicC { background-color: #e3ece4; } .bpmNoLines { background-color: #e3ece4; } .bpmNoLinesC { background-color: #e3ece4; } .bpmClear { } .bpmClearC { text-align: center; } .bpmTopnTail { background-color: #e3ece4; topntail: 0.02cm solid #495b4a;} .bpmTopnTailC { background-color: #e3ece4; topntail: 0.02cm solid #495b4a;} .bpmTopnTailClear { topntail: 0.02cm solid #495b4a; } .bpmTopnTailClearC { topntail: 0.02cm solid #495b4a; } .bpmTopicC td, .bpmTopicC td p { text-align: center; } .bpmNoLinesC td, .bpmNoLinesC td p { text-align: center; } .bpmClearC td, .bpmClearC td p { text-align: center; } .bpmTopnTailC td, .bpmTopnTailC td p { text-align: center; } .bpmTopnTailClearC td, .bpmTopnTailClearC td p { text-align: center; } .pmhMiddleCenter { text-align:center; vertical-align:middle; } .pmhMiddleRight { text-align:right; vertical-align:middle; } .pmhBottomCenter { text-align:center; vertical-align:bottom; } .pmhBottomRight { text-align:right; vertical-align:bottom; } .pmhTopCenter { text-align:center; vertical-align:top; } .pmhTopRight { text-align:right; vertical-align:top; } .pmhTopLeft { text-align:left; vertical-align:top; } .pmhBottomLeft { text-align:left; vertical-align:bottom; } .pmhMiddleLeft { text-align:left; vertical-align:middle; } .infobox { margin-top:10pt; background-color:#DDDDBB; text-align:center; border:1px solid #880000; } .bpmTopic td, .bpmTopic th { border-top: 1px solid #FFFFFF; } .bpmTopicC td, .bpmTopicC th { border-top: 1px solid #FFFFFF; } .bpmTopnTail td, .bpmTopnTail th { border-top: 1px solid #FFFFFF; } .bpmTopnTailC td, .bpmTopnTailC th { border-top: 1px solid #FFFFFF; } .dettaglio { margin:0px;padding:0px; width:100%; box-shadow: 10px 10px 5px #888888; border:1px solid #000000; -moz-border-radius-bottomleft:0px; -webkit-border-bottom-left-radius:0px; border-bottom-left-radius:0px; -moz-border-radius-bottomright:0px; -webkit-border-bottom-right-radius:0px; border-bottom-right-radius:0px; -moz-border-radius-topright:0px; -webkit-border-top-right-radius:0px; border-top-right-radius:0px; -moz-border-radius-topleft:0px; -webkit-border-top-left-radius:0px; border-top-left-radius:0px; } .dettaglio table{ border-collapse: collapse; border-spacing: 0; width:100%; height:100%; margin:0px;padding:0px; } .dettaglio tr:last-child td:last-child { -moz-border-radius-bottomright:0px; -webkit-border-bottom-right-radius:0px; border-bottom-right-radius:0px; } .dettaglio table tr:first-child td:first-child { -moz-border-radius-topleft:0px; -webkit-border-top-left-radius:0px; border-top-left-radius:0px; } .dettaglio table tr:first-child td:last-child { -moz-border-radius-topright:0px; -webkit-border-top-right-radius:0px; border-top-right-radius:0px; } .dettaglio tr:last-child td:first-child{ -moz-border-radius-bottomleft:0px; -webkit-border-bottom-left-radius:0px; border-bottom-left-radius:0px; } .dettaglio tr:hover td{ } .dettaglio tr:nth-child(odd){ background-color:#e5e5e5; } .dettaglio tr:nth-child(even) { background-color:#ffffff; } .dettaglio td{ vertical-align:middle; border:1px solid #000000; border-width:0px 1px 1px 0px; text-align:left; padding:7px; font-size:10px; font-family:Arial; font-weight:normal; color:#000000; } .dettaglio tr:last-child td{ border-width:0px 1px 0px 0px; } .dettaglio tr td:last-child{ border-width:0px 0px 1px 0px; } .dettaglio tr:last-child td:last-child{ border-width:0px 0px 0px 0px; } .dettaglio tr:first-child td{ background:-o-linear-gradient(bottom, #cccccc 5%, #b2b2b2 100%); background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #b2b2b2) ); background:-moz-linear-gradient( center top, #cccccc 5%, #b2b2b2 100% ); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#cccccc", endColorstr="#b2b2b2"); background: -o-linear-gradient(top,#cccccc,b2b2b2); background-color:#cccccc; border:0px solid #000000; text-align:center; border-width:0px 0px 1px 1px; font-size:14px; font-family:Arial; font-weight:bold; color:#000000; } .dettaglio tr:first-child:hover td{ background:-o-linear-gradient(bottom, #cccccc 5%, #b2b2b2 100%); background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #b2b2b2) ); background:-moz-linear-gradient( center top, #cccccc 5%, #b2b2b2 100% ); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#cccccc", endColorstr="#b2b2b2"); background: -o-linear-gradient(top,#cccccc,b2b2b2); background-color:#cccccc; } .dettaglio tr:first-child td:first-child{ border-width:0px 0px 1px 0px; } .dettaglio tr:first-child td:last-child{ border-width:0px 0px 1px 1px; }
Java
/* Copyright (c) 2014-2022 AscEmu Team <http://www.ascemu.org> This file is released under the MIT license. See README-MIT for more information. */ #pragma once #include <cstdint> #include "ManagedPacket.h" #include "WorldPacket.h" namespace AscEmu::Packets { class CmsgQuestgiverRequestReward : public ManagedPacket { public: WoWGuid questgiverGuid; uint32_t questId; CmsgQuestgiverRequestReward() : CmsgQuestgiverRequestReward(0, 0) { } CmsgQuestgiverRequestReward(uint64_t questgiverGuid, uint32_t questId) : ManagedPacket(CMSG_QUESTGIVER_REQUEST_REWARD, 12), questgiverGuid(questgiverGuid), questId(questId) { } bool internalSerialise(WorldPacket& /*packet*/) override { return false; } bool internalDeserialise(WorldPacket& packet) override { uint64_t unpackedGuid; packet >> unpackedGuid >> questId; questgiverGuid.Init(unpackedGuid); return true; } }; }
Java
package org.demo.jdk.utilapis; public class Bird implements Flyable { private int speed = 15; @Override public void fly() { System.out.println("I'm Bird, my speed is " + speed + "."); } }
Java
<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Libraries; use App\Exceptions\UserVerificationException; use App\Mail\UserVerification as UserVerificationMail; use App\Models\Country; use App\Models\LoginAttempt; use Datadog; use Mail; class UserVerification { private $request; private $state; private $user; public static function fromCurrentRequest() { $verification = request()->attributes->get('user_verification'); if ($verification === null) { $verification = new static( auth()->user(), request(), UserVerificationState::fromCurrentRequest() ); request()->attributes->set('user_verification', $verification); } return $verification; } public static function logAttempt(string $source, string $type, string $reason = null): void { Datadog::increment( config('datadog-helper.prefix_web').'.verification.attempts', 1, compact('reason', 'source', 'type') ); } private function __construct($user, $request, $state) { $this->user = $user; $this->request = $request; $this->state = $state; } public function initiate() { $statusCode = 401; app('route-section')->setError("{$statusCode}-verification"); // Workaround race condition causing $this->issue() to be called in parallel. // Mainly observed when logging in as privileged user. if ($this->request->ajax()) { $routeData = app('route-section')->getOriginal(); if ($routeData['controller'] === 'notifications_controller' && $routeData['action'] === 'index') { return response(['error' => 'verification'], $statusCode); } } $email = $this->user->user_email; if (!$this->state->issued()) { static::logAttempt('input', 'new'); $this->issue(); } if ($this->request->ajax()) { return response([ 'authentication' => 'verify', 'box' => view( 'users._verify_box', compact('email') )->render(), ], $statusCode); } else { return ext_view('users.verify', compact('email'), null, $statusCode); } } public function isDone() { return $this->state->isDone(); } public function issue() { $user = $this->user; if (!present($user->user_email)) { return; } $keys = $this->state->issue(); LoginAttempt::logAttempt($this->request->getClientIp(), $this->user, 'verify'); $requestCountry = Country ::where('acronym', request_country($this->request)) ->pluck('name') ->first(); Mail::to($user) ->queue(new UserVerificationMail( compact('keys', 'user', 'requestCountry') )); } public function markVerifiedAndRespond() { $this->state->markVerified(); return response([], 200); } public function reissue() { if ($this->state->isDone()) { return $this->markVerifiedAndRespond(); } $this->issue(); return response(['message' => trans('user_verification.errors.reissued')], 200); } public function verify() { $key = str_replace(' ', '', $this->request->input('verification_key')); try { $this->state->verify($key); } catch (UserVerificationException $e) { static::logAttempt('input', 'fail', $e->reasonKey()); if ($e->reasonKey() === 'incorrect_key') { LoginAttempt::logAttempt($this->request->getClientIp(), $this->user, 'verify-mismatch', $key); } if ($e->shouldReissue()) { $this->issue(); } return error_popup($e->getMessage()); } static::logAttempt('input', 'success'); return $this->markVerifiedAndRespond(); } }
Java
<html> <head> <title>Frankenstein, 1831, Vol. 2, Chap. 3, Frame 6</title> </head> <body> <p> "Having thus arranged my dwelling, and carpeted it with clean straw, I retired; for I saw the figure of a man at a distance, and I remembered too well my treatment the night before, to trust myself in his power. I had first, however, provided for my sustenance for that day, by a loaf of coarse bread, which I purloined, and a cup with which I could drink, more conveniently than from my hand, of the pure water which flowed by my retreat. The floor was a little raised, so that it was kept perfectly dry, and by its vicinity to the chimney of the cottage it was tolerably warm.</p><p> "Being thus provided, I resolved to reside in this hovel, until something should occur which might alter my determination. It was indeed <a href="../V2notes/paradise.html">a paradise</a>, compared to the bleak forest, my former residence, the rain-dropping branches, and dank earth. I ate my breakfast with pleasure, and was about to remove a plank to procure myself a little water, when I heard a step, and looking through a small chink, I beheld a young creature, with a pail on her head, passing before my hovel. The girl was young, and of gentle demeanour, <a href="../V2notes/unlike.html">unlike what I have since found cottagers and farm-house servants to be</a>. Yet she was <a href="../V2notes/meanly.html">meanly dressed</a>, a coarse blue petticoat and a linen jacket being her only garb; her fair hair was plaited, but not adorned; she looked patient, yet sad. I lost sight of her; and in about a quarter of an hour she returned, bearing the pail, which was now partly filled with milk. As she walked along, seemingly incommoded by the burden, a young man met her, whose countenance expressed a deeper despondence. Uttering a few sounds with an air of melancholy, he took the pail from her head, and bore it to the cottage himself. She followed, and they disappeared. Presently I saw the young man again, with some tools in his hand, cross the field behind the cottage; and the girl was also busied, sometimes in the house, and sometimes in the yard.</p> </body> </html>
Java
/* Copyright (C) 2018 by Claude SIMON (http://zeusw.org/epeios/contact.html). This file is part of XDHWebQ. XDHWebQ 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. XDHWebQ 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 XDHWebQ. If not, see <http://www.gnu.org/licenses/>. */ #ifndef REGISTRY_INC_ # define REGISTRY_INC_ # include "xdwrgstry.h" namespace registry { using namespace xdwrgstry; namespace parameter { using namespace xdwrgstry::parameter; } namespace definition { using namespace xdwrgstry::definition; } } #endif
Java
/* Copyright (C) 2015 Jack Fagner This file is part of OpenTidl. OpenTidl 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. OpenTidl 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 OpenTidl. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenTidl.Models; using OpenTidl.Models.Base; using OpenTidl.Transport; using OpenTidl.Enums; using System.IO; namespace OpenTidl { public partial class OpenTidlClient { #region image methods /// <summary> /// Helper method to retrieve a stream with an album cover image /// </summary> public Stream GetAlbumCover(AlbumModel model, AlbumCoverSize size) { return GetAlbumCover(model.Cover, model.Id, size); } /// <summary> /// Helper method to retrieve a stream with an album cover image /// </summary> public Stream GetAlbumCover(String cover, Int32 albumId, AlbumCoverSize size) { var w = 750; var h = 750; if (!RestUtility.ParseImageSize(size.ToString(), out w, out h)) throw new ArgumentException("Invalid image size", "size"); String url = null; if (!String.IsNullOrEmpty(cover)) url = String.Format("http://resources.wimpmusic.com/images/{0}/{1}x{2}.jpg", cover.Replace('-', '/'), w, h); else url = String.Format("http://images.tidalhifi.com/im/im?w={1}&h={2}&albumid={0}&noph", albumId, w, h); return RestClient.GetStream(url); } /// <summary> /// Helper method to retrieve a stream with an artists picture /// </summary> public Stream GetArtistPicture(ArtistModel model, ArtistPictureSize size) { return GetArtistPicture(model.Picture, model.Id, size); } /// <summary> /// Helper method to retrieve a stream with an artists picture /// </summary> public Stream GetArtistPicture(String picture, Int32 artistId, ArtistPictureSize size) { var w = 750; var h = 500; if (!RestUtility.ParseImageSize(size.ToString(), out w, out h)) throw new ArgumentException("Invalid image size", "size"); String url = null; if (!String.IsNullOrEmpty(picture)) url = String.Format("http://resources.wimpmusic.com/images/{0}/{1}x{2}.jpg", picture.Replace('-', '/'), w, h); else url = String.Format("http://images.tidalhifi.com/im/im?w={1}&h={2}&artistid={0}&noph", artistId, w, h); return RestClient.GetStream(url); } /// <summary> /// Helper method to retrieve a stream with a playlist image /// </summary> public Stream GetPlaylistImage(PlaylistModel model, PlaylistImageSize size) { return GetPlaylistImage(model.Image, model.Uuid, size); } /// <summary> /// Helper method to retrieve a stream with a playlist image /// </summary> public Stream GetPlaylistImage(String image, String playlistUuid, PlaylistImageSize size) { var w = 750; var h = 500; if (!RestUtility.ParseImageSize(size.ToString(), out w, out h)) throw new ArgumentException("Invalid image size", "size"); String url = null; if (!String.IsNullOrEmpty(image)) url = String.Format("http://resources.wimpmusic.com/images/{0}/{1}x{2}.jpg", image.Replace('-', '/'), w, h); else url = String.Format("http://images.tidalhifi.com/im/im?w={1}&h={2}&uuid={0}&rows=2&cols=3&noph", playlistUuid, w, h); return RestClient.GetStream(url); } /// <summary> /// Helper method to retrieve a stream with a video conver image /// </summary> public Stream GetVideoImage(VideoModel model, VideoImageSize size) { return GetVideoImage(model.ImageId, model.ImagePath, size); } /// <summary> /// Helper method to retrieve a stream with a video conver image /// </summary> public Stream GetVideoImage(String imageId, String imagePath, VideoImageSize size) { var w = 750; var h = 500; if (!RestUtility.ParseImageSize(size.ToString(), out w, out h)) throw new ArgumentException("Invalid image size", "size"); String url = null; if (!String.IsNullOrEmpty(imageId)) url = String.Format("http://resources.wimpmusic.com/images/{0}/{1}x{2}.jpg", imageId.Replace('-', '/'), w, h); else url = String.Format("http://images.tidalhifi.com/im/im?w={1}&h={2}&img={0}&noph", imagePath, w, h); return RestClient.GetStream(url); } #endregion #region track/video methods /// <summary> /// Helper method to retrieve the audio/video stream with correct user-agent, etc. /// </summary> public Stream GetStream(String streamUrl) { return RestClient.GetStream(streamUrl); } #endregion } }
Java
# -*- coding: utf-8 -*- ############################################################################## # # Infrastructure # Copyright (C) 2014 Ingenieria ADHOC # No email # # 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/>. # ############################################################################## import re from openerp import netsvc from openerp.osv import osv, fields class database_type(osv.osv): """""" _name = 'infrastructure.database_type' _description = 'database_type' _columns = { 'name': fields.char(string='Name', required=True), 'prefix': fields.char(string='Prefix', required=True, size=4), 'url_prefix': fields.char(string='URL Prefix'), 'automatic_drop': fields.boolean(string='Automatic Drop'), 'automatic_drop_days': fields.integer(string='Automatic Drop Days'), 'protect_db': fields.boolean(string='Protect DBs?'), 'color': fields.integer(string='Color'), 'automatic_deactivation': fields.boolean(string='Atumatic Deactivation?'), 'auto_deactivation_days': fields.integer(string='Automatic Drop Days'), 'url_example': fields.char(string='URL Example'), 'bd_name_example': fields.char(string='BD Name Example'), 'db_back_up_policy_ids': fields.many2many('infrastructure.db_back_up_policy', 'infrastructure_database_type_ids_db_back_up_policy_ids_rel', 'database_type_id', 'db_back_up_policy_id', string='Suggested Backup Policies'), } _defaults = { } _constraints = [ ] database_type() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Java
<span ng-if="editable" class="omny-edit-section" ng-click="changeUrl()">Edit</span> <iframe ng-if="videoSource" width="854" height="510" ng-src="{{videoSource}}" frameborder="0" allowfullscreen></iframe>
Java
# frozen_string_literal: true require 'rails_helper' describe StudentsController do let(:user) { create(:student) } before { allow(controller).to receive(:current_user) { user } } it { should use_before_action :authorize! } describe '#index' do let!(:classroom) { create(:classroom) } let!(:students_classrooms) { create(:students_classrooms, student_id: user.id, classroom_id: classroom.id) } it 'should set the current user and js file' do get :index expect(assigns(:current_user)).to eq user expect(assigns(:js_file)).to eq "student" end it 'should find the classroom and set flash' do get :index, params: { joined: "success", classroom: classroom.id } expect(flash["join-class-notification"]).to eq "You have joined #{classroom.name} 🎉🎊" end end describe '#join_classroom' do let(:student) { create(:student) } before { allow(controller).to receive(:current_user) { student } } it 'should redirect for an invalid class_code' do get :join_classroom, params: { classcode: 'nonsense_doesnt_exist' } expect(response).to redirect_to '/classes' expect(flash[:error]).to match("Oops! There is no class with the code nonsense_doesnt_exist. Ask your teacher for help.") end it 'should redirect for a valid class_code' do classroom = create(:classroom, code: 'existing_code') get :join_classroom, params: { classcode: classroom.code } expect(response).to redirect_to "/classrooms/#{classroom.id}?joined=success" end end describe '#account_settings' do it 'should set the current user and js file' do get :account_settings expect(assigns(:current_user)).to eq user expect(assigns(:js_file)).to eq "student" end end describe '#student_demo' do context 'when Angie Thomas exists' do let!(:angie) { create(:user, email: 'angie_thomas_demo@quill.org') } it 'should sign in angie and redirect to profile' do get :student_demo expect(session[:user_id]).to eq angie.id expect(response).to redirect_to '/classes' end end context 'when angie thomas does not exist' do it 'should destroy recreate the demo and redirect to student demo' do expect(Demo::ReportDemoDestroyer).to receive(:destroy_demo).with(nil) expect(Demo::ReportDemoCreator).to receive(:create_demo).with(nil) get :student_demo expect(response).to redirect_to "/student_demo" end end end describe '#student_demo_ap' do context 'when bell hooks exists' do let!(:bell) { create(:user, email: 'bell_hooks_demo@quill.org') } it 'should sign in bell and redirect to profile' do get :demo_ap expect(session[:user_id]).to eq bell.id expect(response).to redirect_to '/classes' end end context 'when bell hooks does not exist' do it 'should recreate the demo and redirect to student demo' do expect(Demo::ReportDemoAPCreator).to receive(:create_demo).with(nil) get :demo_ap expect(response).to redirect_to "/student_demo_ap" end end end describe '#update_account' do let!(:user) { create(:user, name: "Maya Angelou", email: 'maya_angelou_demo@quill.org', username: "maya-angelou", role: "student") } let!(:second_user) { create(:user, name: "Harvey Milk", email: 'harvey@quill.org', username: "harvey-milk", role: "student") } it 'should update the name, email and username' do put :update_account, params: { email: "pablo@quill.org", username: "pabllo-vittar", name: "Pabllo Vittar" } expect(user.reload.email).to eq "pablo@quill.org" expect(user.reload.username).to eq "pabllo-vittar" expect(user.reload.name).to eq "Pabllo Vittar" end it 'should update only the fields that are changed' do put :update_account, params: { email: "pablo@quill.org", username: "rainha-do-carnaval", name: "Pabllo Vittar" } expect(user.reload.email).to eq "pablo@quill.org" expect(user.reload.username).to eq "rainha-do-carnaval" expect(user.reload.name).to eq "Pabllo Vittar" end it 'should not update the email or username if already taken' do put :update_account, params: { email: "harvey@quill.org", username: "pabllo-vittar", name: "Pabllo Vittar" } expect(user.reload.errors.messages[:email].first).to eq "That email is taken. Try another." put :update_account, params: { email: "pablo@quill.org", username: "harvey-milk", name: "Pabllo Vittar" } expect(user.reload.errors.messages[:username].first).to eq "That username is taken. Try another." end end end
Java
# SPDX-License-Identifier: AGPL-3.0-or-later """ SepiaSearch (Videos) """ from json import loads from dateutil import parser, relativedelta from urllib.parse import urlencode from datetime import datetime # about about = { "website": 'https://sepiasearch.org', "wikidata_id": None, "official_api_documentation": "https://framagit.org/framasoft/peertube/search-index/-/tree/master/server/controllers/api", # NOQA "use_official_api": True, "require_api_key": False, "results": 'JSON', } categories = ['videos'] paging = True time_range_support = True safesearch = True supported_languages = [ 'en', 'fr', 'ja', 'eu', 'ca', 'cs', 'eo', 'el', 'de', 'it', 'nl', 'es', 'oc', 'gd', 'zh', 'pt', 'sv', 'pl', 'fi', 'ru' ] base_url = 'https://sepiasearch.org/api/v1/search/videos' safesearch_table = { 0: 'both', 1: 'false', 2: 'false' } time_range_table = { 'day': relativedelta.relativedelta(), 'week': relativedelta.relativedelta(weeks=-1), 'month': relativedelta.relativedelta(months=-1), 'year': relativedelta.relativedelta(years=-1) } embedded_url = '<iframe width="540" height="304" src="{url}" frameborder="0" allowfullscreen></iframe>' def minute_to_hm(minute): if isinstance(minute, int): return "%d:%02d" % (divmod(minute, 60)) return None def request(query, params): params['url'] = base_url + '?' + urlencode({ 'search': query, 'start': (params['pageno'] - 1) * 10, 'count': 10, 'sort': '-match', 'nsfw': safesearch_table[params['safesearch']] }) language = params['language'].split('-')[0] if language in supported_languages: params['url'] += '&languageOneOf[]=' + language if params['time_range'] in time_range_table: time = datetime.now().date() + time_range_table[params['time_range']] params['url'] += '&startDate=' + time.isoformat() return params def response(resp): results = [] search_results = loads(resp.text) if 'data' not in search_results: return [] for result in search_results['data']: title = result['name'] content = result['description'] thumbnail = result['thumbnailUrl'] publishedDate = parser.parse(result['publishedAt']) embedded = embedded_url.format(url=result.get('embedUrl')) author = result.get('account', {}).get('displayName') length = minute_to_hm(result.get('duration')) url = result['url'] results.append({'url': url, 'title': title, 'content': content, 'author': author, 'length': length, 'template': 'videos.html', 'publishedDate': publishedDate, 'embedded': embedded, 'thumbnail': thumbnail}) return results
Java
<?php /* Kevin Froman - Easy IPFS: easily interact with IPFS in php via this simple API Copyright (C) 2017 Kevin Froman 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/> */ class IPFS { function foo(){ return 'bar'; } function cat($hash){ $gotData = ''; $server = curl_init(); curl_setopt($server, CURLOPT_URL, 'http://127.0.0.1:5001/api/v0/cat?arg=' . $hash); curl_setopt($server, CURLOPT_RETURNTRANSFER, true); curl_setopt($server, CURLOPT_BINARYTRANSFER, false); $gotData = curl_exec($server); curl_close($server); return $gotData; } function resolve($name){ $gotData = ''; $json = ''; $server = curl_init(); curl_setopt($server, CURLOPT_URL, 'http://127.0.0.1:5001/api/v0/name/resolve?arg=' . $name); curl_setopt($server, CURLOPT_RETURNTRANSFER, true); $gotData = curl_exec($server); $gotData = json_decode($gotData, true); if (isset($gotData['Path'])){ $gotData = str_replace('/ipfs/', '', $gotData['Path']); } else{ $gotData = 'invalid'; } curl_close($server); return $gotData; } function dataAdd($file){ $gotData = ''; $server = curl_init(); curl_setopt($server, CURLOPT_POST, 1); curl_setopt($server, CURLOPT_RETURNTRANSFER, true); $data = array('file' => new CurlFile($file)); curl_setopt($server, CURLOPT_SAFE_UPLOAD, false); // required as of PHP 5.6.0 curl_setopt($server, CURLOPT_POSTFIELDS, $data); curl_setopt($server, CURLOPT_URL, 'http://127.0.0.1:5001/api/v0/add'); $data = curl_exec($server); curl_close($server); return $data; } function namePublish($data) { $server = curl_init(); $data = dataAdd($data); curl_setopt($server, CURLOPT_URL, 'http://127.0.0.1:5001/api/v0/name/publish?arg=' . $data . '&lifetime=1m&'); curl_exec($server); curl_close($server); return true; } } ?>
Java
import React from 'react'; import { render, waitForElement } from 'react-testing-library'; import FakeDataProvider from '@olimat/web/utils/test/FakeDataProvider'; import MockErrorProvider from '@olimat/web/utils/test/MockErrorProvider'; import MockNextContext from '@olimat/web/utils/test/MockNextContext'; import { renderApollo } from '@olimat/web/utils/test/test-utils'; import ExamDetails from './Details'; const MockExamDetails = () => ( <MockNextContext router={{ query: { id: 'theExamId1' } }}> <ExamDetails /> </MockNextContext> ); // Talvez uma solução melhor seria criar um mock para o contexto do Next.js // https://github.com/zeit/next.js/issues/5205 // Outra opção é exportar o componente sem embrulhá-lo com os HoC, e passar os mocks // https://stackoverflow.com/questions/44204828 describe('<ExamDetails />', () => { test.skip('renders loading state initially', () => { const { getByText } = renderApollo(<MockExamDetails />); getByText(/loading/i); }); test('renders the details of an exam', async () => { const customResolvers = { // We need to update the GraphQL API as well Exam: () => ({ title: '2017 - Fase 3 - Ano 5', }), }; const { getByText, getByTestId } = render( <FakeDataProvider customResolvers={customResolvers}> <MockExamDetails /> </FakeDataProvider>, ); await waitForElement(() => getByText(customResolvers.Exam().title)); const questionListNode = getByTestId('questionList'); expect(questionListNode).toBeInTheDocument(); // toBe(10) couples the test with the mocked server // https://youtu.be/K445DtQ5oHY?t=1476 expect(questionListNode.children.length).toBe(10); }); test('renders error message', async () => { const errorMsg = 'Que pena'; const { getByText } = render( <MockErrorProvider graphqlErrors={[{ message: errorMsg }]}> <MockExamDetails /> </MockErrorProvider>, ); await waitForElement(() => getByText(errorMsg, { exact: false })); }); });
Java
<?php // This file declares a new entity type. For more details, see "hook_civicrm_entityTypes" at: // https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_entityTypes return [ [ 'name' => 'CivirulesLog', 'class' => 'CRM_Civiruleslogger_DAO_CivirulesLog', 'table' => 'civicrm_civirules_log', ], ];
Java
{% extends "podcast-base.html" %} {% load i18n %} {% load humanize %} {% load episodes %} {% load podcasts %} {% load devices %} {% load charts %} {% load utils %} {% load menu %} {% block mainmenu %}{{ "/podcast/"|main_menu }}{% endblock %} {% block sectionmenu %} {% if podcast.title %} {{ "/podcast/"|section_menu:podcast.title }} {% else %} {{ "/podcast/"|section_menu:"Unnamed Podcast" }} {% endif %} {% endblock %} {% block title %}{{ podcast.title|default:"Unnamed Podcast"|striptags }}{% endblock %} {% block content %} {% if episode %} <div class="first-episode"> {% include "components/episode-box.html" with podcast=podcast episode=episode long=True only %} </div> {% endif %} <hr /> <div class="btn-toolbar"> {% if is_publisher %} <div class="btn-group"> <a class="btn btn-default" href="{% podcast_link_target podcast "podcast-publisher-detail" %}"> <i class="icon-wrench"></i> {% trans "Publisher Pages" %} </a> </div> {% endif %} {% if not user.is_authenticated %} <div class="btn-group"> <a class="btn btn-default" href="{% podcast_link_target podcast "subscribe" %}"> <i class="icon-plus"></i> {% trans "Login to Subscribe" %} </a> </div> {% endif %} {% if devices or can_subscribe %} <div class="btn-group"> {% if can_subscribe %} <button class="btn btn-primary" onclick="submitForm('subscribe+all');"> <i class="icon-plus-sign"></i> {% trans "Subscribe" %} </button> <button class="btn dropdown-toggle btn-primary" data-toggle="dropdown"> <span class="caret"></span> </button> {% else %} <button class="btn btn-default" onclick="submitForm('unsubscribe+all');"> <i class="icon-remove-sign"></i> {% trans "Unsubscribe" %} </button> <button class="btn dropdown-toggle btn-default" data-toggle="dropdown"> <span class="caret"></span> </button> {% endif %} <ul class="dropdown-menu"> {% if can_subscribe %} <li value="+all"> <a href="javascript:void(0);" onclick="submitForm('subscribe+all');"> <i class="icon-plus-sign"></i> {% trans "Subscribe on all devices" %} </a> <form class="internal" method="post" action="{% podcast_link_target podcast "subscribe-all" %}" id="subscribe+all"> {% csrf_token %} </form> </li> {% endif %} {% for device in subscribe_targets %} <li value="{{ device.uid }}"> <a href="javascript:void(0);" onclick="submitForm('subscribe-{{ device|devices_uids }}');"> <i class="icon-plus"></i> {{ device|devices_name }} </a> <form class="internal" action="{% podcast_link_target podcast "subscribe" %}" method="post" id="subscribe-{{ device|devices_uids }}"> {% csrf_token %} <input type="hidden" name="targets" value="{{ device|devices_uids }}" /> </form> </li> {% endfor %} {% if can_subscribe and devices %} <li class="divider"></li> {% endif %} {% if devices %} <li value="+none"> <a href="javascript:void(0);" onclick="submitForm('unsubscribe+all');"> <i class="icon-remove-sign"></i> {% trans "Unsubscribe from all devices " %} </a> <form class="internal" method="post" action="{% podcast_link_target podcast "unsubscribe-all" %}" id="unsubscribe+all"> {% csrf_token %} </form> </li> {% endif %} {% for device in devices %} <li value="{{ device.uid }}"> <a href="javascript:void(0);" onclick="submitForm('unsubscribe-{{ device.uid }}');"> <i class="icon-remove"></i> {{ device|devices_name }} </a> <form class="internal" method="post" action="{% podcast_link_target podcast "unsubscribe" device.uid %}?return_to={% podcast_link_target podcast %}" id="unsubscribe-{{ device.uid }}"> {% csrf_token %} </form> </li> {% endfor %} </ul> </div> {% endif %} {% if has_history %} <a class="btn btn-default" href="{% podcast_link_target podcast "podcast-history" %}"> <i class="icon-calendar"></i> {% trans "Subscription History" %} </a> {% endif %} <a href="javascript:void(0);" onclick="$('#tag-box').toggle();" class="btn btn-default"> <i class="icon-tag"></i> {% trans "Tags" %} </a> {% if user.is_staff %} <a class="btn btn-default" href="{% edit_link podcast %}"> <i class="icon-cogs"></i>Admin </a> {% endif %} </div> <div id="tag-box"> <hr /> <i class="icon-tag"></i> <strong>{% trans "Tags" %}: </strong> {% for tag in tags %} {% spaceless %} {% if tag.is_own %} <span class="own">{{ tag.tag }} <a class="remove" href="{% podcast_link_target podcast "remove-tag" %}?tag={{ tag.tag }}">X</a></span> {% else %} <span class="other">{{ tag.tag }}</span> {% endif %} {% if not forloop.last %} <span class="seperator">,</span> {% endif %} {% endspaceless %} {% endfor %} {% if user.is_authenticated %} <form class="form-inline" action="{% podcast_link_target podcast "add-tag" %}"> <div class="input-group"> <span class="input-group-addon input-sm"><i class="icon-tag"></i></span> <input class="input-sm form-control" type="text" name="tag" /> <span class="input-group-btn"> <button class="btn btn-success btn-sm" type="submit"> <i class="icon-plus"></i> </button> </span> </div> </form> {% endif %} </div> <hr /> {% if episodes %} <h3>{% trans "Older Episodes" %}</h3> <div class="episodes"> {% for episode in episodes %} {% include "components/episode-box.html" with episode=episode podcast=podcast only %} {% endfor %} </div> <ul class="pagination"> {% for page in page_list %} <li> {% if page == "..." %} <span>{{ page }}</span> {% else %} {% if page == current_page %} <a href="{% podcast_link_target podcast "podcast-all-episodes" %}?page={{ page }}"><strong>{{ page }}</strong></a> {% else %} <a href="{% podcast_link_target podcast "podcast-all-episodes" %}?page={{ page }}">{{ page }}</a> {% endif %} {% endif %} </li> {% endfor %} </ul> {% endif %} {% endblock %} {% block javascript %} {{ block.super }} <script language="javascript"> <!-- function submitForm(formid) { document.forms[formid].submit(); return true; } {% if not has_tagged %} // done in JS so that box is always visible if JS is disabled $('#tag-box').toggle(); {% endif %} --> </script> {% endblock %}
Java
/* Classe gerada automaticamente pelo MSTech Code Creator */ namespace MSTech.GestaoEscolar.BLL { using MSTech.Business.Common; using MSTech.GestaoEscolar.Entities; using MSTech.GestaoEscolar.DAL; using System.Data; using MSTech.Data.Common; using System.Collections.Generic; using System.Linq; using MSTech.Validation.Exceptions; /// <summary> /// Description: CLS_AlunoAvaliacaoTurmaQualidade Business Object. /// </summary> public class CLS_AlunoAvaliacaoTurmaQualidadeBO : BusinessBase<CLS_AlunoAvaliacaoTurmaQualidadeDAO, CLS_AlunoAvaliacaoTurmaQualidade> { #region Consultas /// <summary> /// Seleciona os tipo de qualidade por matrícula do aluno. /// </summary> /// <param name="tur_id">ID da turma.</param> /// <param name="alu_id">ID do aluno.</param> /// <param name="mtu_id">ID da matrícula turma do aluno.</param> /// <param name="fav_id">ID do formato de avaliação.</param> /// <param name="ava_id">ID da avaliação.</param> /// <returns></returns> public static DataTable SelecionaPorMatriculaTurma(long tur_id, long alu_id, int mtu_id, int fav_id, int ava_id) { return new CLS_AlunoAvaliacaoTurmaQualidadeDAO().SelecionaPorMatriculaTurma(tur_id, alu_id, mtu_id, fav_id, ava_id); } /// <summary> /// Seleciona uma lista de tipo de qualidade por matrícula do aluno. /// </summary> /// <param name="tur_id">ID da turma.</param> /// <param name="alu_id">ID do aluno.</param> /// <param name="mtu_id">ID da matrícula turma do aluno.</param> /// <param name="fav_id">ID do formato de avaliação.</param> /// <param name="ava_id">ID da avaliação.</param> /// <returns></returns> public static List<CLS_AlunoAvaliacaoTurmaQualidade> SelecionaListaPorMatriculaTurma(long tur_id, long alu_id, int mtu_id, int fav_id, int ava_id, TalkDBTransaction banco = null) { CLS_AlunoAvaliacaoTurmaQualidadeDAO dao = banco == null ? new CLS_AlunoAvaliacaoTurmaQualidadeDAO() : new CLS_AlunoAvaliacaoTurmaQualidadeDAO { _Banco = banco }; return (from DataRow dr in dao.SelecionaPorMatriculaTurma(tur_id, alu_id, mtu_id, fav_id, ava_id).Rows select dao.DataRowToEntity(dr, new CLS_AlunoAvaliacaoTurmaQualidade())).ToList(); } #endregion #region Saves /// <summary> /// O método salva as qualidade cadastradas para o aluno e deleta as que forem desmarcadas. /// </summary> /// <param name="tur_id">ID da turma.</param> /// <param name="alu_id">ID do aluno.</param> /// <param name="mtu_id">ID da matrícula turma do aluno.</param> /// <param name="fav_id">ID do formato de avaliação.</param> /// <param name="ava_id">ID da avaliação.</param> /// <param name="lista">Lista de qualidades adicionadas</param> /// <param name="banco"></param> /// <returns></returns> public static bool Salvar(long tur_id, long alu_id, int mtu_id, int fav_id, int ava_id, List<CLS_AlunoAvaliacaoTurmaQualidade> lista, TalkDBTransaction banco) { bool retorno = true; List<CLS_AlunoAvaliacaoTurmaQualidade> listaCadastrados = SelecionaListaPorMatriculaTurma(tur_id, alu_id, mtu_id, fav_id, ava_id, banco); if (lista.Any()) { List<CLS_AlunoAvaliacaoTurmaQualidade> listaExcluir = !listaCadastrados.Any() ? new List<CLS_AlunoAvaliacaoTurmaQualidade>() : listaCadastrados.Where(p => !lista.Contains(p)).ToList(); List<CLS_AlunoAvaliacaoTurmaQualidade> listaSalvar = listaCadastrados.Any() ? lista.Where(p => !listaCadastrados.Contains(p)).ToList() : lista; retorno &= !listaExcluir.Any() ? retorno : listaExcluir.Aggregate(true, (excluiu, qualidade) => excluiu & Delete(qualidade, banco)); retorno &= !listaSalvar.Any() ? retorno : listaSalvar.Aggregate(true, (salvou, qualidade) => salvou & Save(qualidade, banco)); } else { retorno &= !listaCadastrados.Any() ? retorno : listaCadastrados.Aggregate(true, (excluiu, qualidade) => excluiu & Delete(qualidade, banco)); } return retorno; } /// <summary> /// O método salva um registro na tabela CLS_AlunoAvaliacaoTurmaQualidade. /// </summary> /// <param name="entity">Entidade CLS_AlunoAvaliacaoTurmaQualidade</param> /// <param name="banco"></param> /// <returns></returns> public static new bool Save(CLS_AlunoAvaliacaoTurmaQualidade entity, TalkDBTransaction banco) { if (entity.Validate()) { return new CLS_AlunoAvaliacaoTurmaQualidadeDAO { _Banco = banco }.Salvar(entity); } throw new ValidationException(GestaoEscolarUtilBO.ErrosValidacao(entity)); } /// <summary> /// O método salva um registro na tabela CLS_AlunoAvaliacaoTurmaQualidade. /// </summary> /// <param name="entity">Entidade CLS_AlunoAvaliacaoTurmaQualidade</param> /// <returns></returns> public static new bool Save(CLS_AlunoAvaliacaoTurmaQualidade entity) { if (entity.Validate()) { return new CLS_AlunoAvaliacaoTurmaQualidadeDAO().Salvar(entity); } throw new ValidationException(GestaoEscolarUtilBO.ErrosValidacao(entity)); } #endregion } }
Java
module Laser # Class that's just a name. Substitute for symbols, which can overlap # with user-code values. class PlaceholderObject def initialize(name) @name = name end def inspect @name end alias_method :to_s, :inspect end end
Java
/* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "S1AP-IEs" * found in "../support/s1ap-r16.4.0/36413-g40.asn" * `asn1c -pdu=all -fcompound-names -findirect-choice -fno-include-deps -no-gen-BER -no-gen-XER -no-gen-OER -no-gen-UPER` */ #ifndef _S1AP_LastVisitedGERANCellInformation_H_ #define _S1AP_LastVisitedGERANCellInformation_H_ #include <asn_application.h> /* Including external dependencies */ #include <NULL.h> #include <constr_CHOICE.h> #ifdef __cplusplus extern "C" { #endif /* Dependencies */ typedef enum S1AP_LastVisitedGERANCellInformation_PR { S1AP_LastVisitedGERANCellInformation_PR_NOTHING, /* No components present */ S1AP_LastVisitedGERANCellInformation_PR_undefined /* Extensions may appear below */ } S1AP_LastVisitedGERANCellInformation_PR; /* S1AP_LastVisitedGERANCellInformation */ typedef struct S1AP_LastVisitedGERANCellInformation { S1AP_LastVisitedGERANCellInformation_PR present; union S1AP_LastVisitedGERANCellInformation_u { NULL_t undefined; /* * This type is extensible, * possible extensions are below. */ } choice; /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } S1AP_LastVisitedGERANCellInformation_t; /* Implementation */ extern asn_TYPE_descriptor_t asn_DEF_S1AP_LastVisitedGERANCellInformation; extern asn_CHOICE_specifics_t asn_SPC_S1AP_LastVisitedGERANCellInformation_specs_1; extern asn_TYPE_member_t asn_MBR_S1AP_LastVisitedGERANCellInformation_1[1]; extern asn_per_constraints_t asn_PER_type_S1AP_LastVisitedGERANCellInformation_constr_1; #ifdef __cplusplus } #endif #endif /* _S1AP_LastVisitedGERANCellInformation_H_ */ #include <asn_internal.h>
Java
/** * Copyright (c) 2002-2011 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.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 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/>. */ package org.neo4j.graphdb.index; import java.util.Iterator; import java.util.NoSuchElementException; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.Transaction; /** * An {@link Iterator} with additional {@link #size()} and {@link #close()} * methods on it, used for iterating over index query results. It is first and * foremost an {@link Iterator}, but also an {@link Iterable} JUST so that it * can be used in a for-each loop. The <code>iterator()</code> method * <i>always</i> returns <code>this</code>. * * The size is calculated before-hand so that calling it is always fast. * * When you're done with the result and haven't reached the end of the * iteration {@link #close()} must be called. Results which are looped through * entirely closes automatically. Typical use: * * <pre> * IndexHits<Node> hits = index.get( "key", "value" ); * try * { * for ( Node node : hits ) * { * // do something with the hit * } * } * finally * { * hits.close(); * } * </pre> * * @param <T> the type of items in the Iterator. */ public interface IndexHits<T> extends Iterator<T>, Iterable<T> { /** * Returns the size of this iterable, in most scenarios this value is accurate * while in some scenarios near-accurate. * * There's no cost in calling this method. It's considered near-accurate if this * {@link IndexHits} object has been returned when inside a {@link Transaction} * which has index modifications, of a certain nature. Also entities * ({@link Node}s/{@link Relationship}s) which have been deleted from the graph, * but are still in the index will also affect the accuracy of the returned size. * * @return the near-accurate size if this iterable. */ int size(); /** * Closes the underlying search result. This method should be called * whenever you've got what you wanted from the result and won't use it * anymore. It's necessary to call it so that underlying indexes can dispose * of allocated resources for this search result. * * You can however skip to call this method if you loop through the whole * result, then close() will be called automatically. Even if you loop * through the entire result and then call this method it will silently * ignore any consequtive call (for convenience). */ void close(); /** * Returns the first and only item from the result iterator, or {@code null} * if there was none. If there were more than one item in the result a * {@link NoSuchElementException} will be thrown. This method must be called * first in the iteration and will grab the first item from the iteration, * so the result is considered broken after this call. * * @return the first and only item, or {@code null} if none. */ T getSingle(); /** * Returns the score of the most recently fetched item from this iterator * (from {@link #next()}). The range of the returned values is up to the * {@link Index} implementation to dictate. * @return the score of the most recently fetched item from this iterator. */ float currentScore(); }
Java
import { createSlice, createEntityAdapter, Reducer, AnyAction, PayloadAction } from '@reduxjs/toolkit'; import { fetchAll, fetchDetails, install, uninstall, loadPluginDashboards, panelPluginLoaded } from './actions'; import { CatalogPlugin, PluginListDisplayMode, ReducerState, RequestStatus } from '../types'; import { STATE_PREFIX } from '../constants'; import { PanelPlugin } from '@grafana/data'; export const pluginsAdapter = createEntityAdapter<CatalogPlugin>(); const isPendingRequest = (action: AnyAction) => new RegExp(`${STATE_PREFIX}\/(.*)\/pending`).test(action.type); const isFulfilledRequest = (action: AnyAction) => new RegExp(`${STATE_PREFIX}\/(.*)\/fulfilled`).test(action.type); const isRejectedRequest = (action: AnyAction) => new RegExp(`${STATE_PREFIX}\/(.*)\/rejected`).test(action.type); // Extract the trailing '/pending', '/rejected', or '/fulfilled' const getOriginalActionType = (type: string) => { const separator = type.lastIndexOf('/'); return type.substring(0, separator); }; const slice = createSlice({ name: 'plugins', initialState: { items: pluginsAdapter.getInitialState(), requests: {}, settings: { displayMode: PluginListDisplayMode.Grid, }, // Backwards compatibility // (we need to have the following fields in the store as well to be backwards compatible with other parts of Grafana) // TODO<remove once the "plugin_admin_enabled" feature flag is removed> plugins: [], errors: [], searchQuery: '', hasFetched: false, dashboards: [], isLoadingPluginDashboards: false, panels: {}, } as ReducerState, reducers: { setDisplayMode(state, action: PayloadAction<PluginListDisplayMode>) { state.settings.displayMode = action.payload; }, }, extraReducers: (builder) => builder // Fetch All .addCase(fetchAll.fulfilled, (state, action) => { pluginsAdapter.upsertMany(state.items, action.payload); }) // Fetch Details .addCase(fetchDetails.fulfilled, (state, action) => { pluginsAdapter.updateOne(state.items, action.payload); }) // Install .addCase(install.fulfilled, (state, action) => { pluginsAdapter.updateOne(state.items, action.payload); }) // Uninstall .addCase(uninstall.fulfilled, (state, action) => { pluginsAdapter.updateOne(state.items, action.payload); }) // Load a panel plugin (backward-compatibility) // TODO<remove once the "plugin_admin_enabled" feature flag is removed> .addCase(panelPluginLoaded, (state, action: PayloadAction<PanelPlugin>) => { state.panels[action.payload.meta.id] = action.payload; }) // Start loading panel dashboards (backward-compatibility) // TODO<remove once the "plugin_admin_enabled" feature flag is removed> .addCase(loadPluginDashboards.pending, (state, action) => { state.isLoadingPluginDashboards = true; state.dashboards = []; }) // Load panel dashboards (backward-compatibility) // TODO<remove once the "plugin_admin_enabled" feature flag is removed> .addCase(loadPluginDashboards.fulfilled, (state, action) => { state.isLoadingPluginDashboards = false; state.dashboards = action.payload; }) .addMatcher(isPendingRequest, (state, action) => { state.requests[getOriginalActionType(action.type)] = { status: RequestStatus.Pending, }; }) .addMatcher(isFulfilledRequest, (state, action) => { state.requests[getOriginalActionType(action.type)] = { status: RequestStatus.Fulfilled, }; }) .addMatcher(isRejectedRequest, (state, action) => { state.requests[getOriginalActionType(action.type)] = { status: RequestStatus.Rejected, error: action.payload, }; }), }); export const { setDisplayMode } = slice.actions; export const reducer: Reducer<ReducerState, AnyAction> = slice.reducer;
Java
# -*- coding: utf-8 -*- # # SPDX-FileCopyrightText: 2013-2021 Agora Voting SL <contact@nvotes.com> # # SPDX-License-Identifier: AGPL-3.0-only # import pickle import base64 import json import re from datetime import datetime from flask import Blueprint, request, make_response, abort from frestq.utils import loads, dumps from frestq.tasks import SimpleTask, TaskError from frestq.app import app, db from models import Election, Authority, QueryQueue from create_election.performer_jobs import check_election_data from taskqueue import queue_task, apply_task, dequeue_task public_api = Blueprint('public_api', __name__) def error(status, message=""): if message: data = json.dumps(dict(message=message)) else: data="" return make_response(data, status) @public_api.route('/dequeue', methods=['GET']) def dequeue(): try: dequeue_task() except Exception as e: return make_response(dumps(dict(status=e.message)), 202) return make_response(dumps(dict(status="ok")), 202) @public_api.route('/election', methods=['POST']) def post_election(): ''' POST /election Creates an election, with the given input data. This involves communicating with the different election authorities to generate the joint public key. Example request: POST /election { "id": 1110, "title": "Votación de candidatos", "description": "Selecciona los documentos polí­tico, ético y organizativo con los que Podemos", "director": "wadobo-auth1", "authorities": "openkratio-authority", "layout": "pcandidates-election", "presentation": { "share_text": "lo que sea", "theme": "foo", "urls": [ { "title": "", "url": "" } ], "theme_css": "whatever" }, "end_date": "2013-12-09T18:17:14.457000", "start_date": "2013-12-06T18:17:14.457000", "questions": [ { "description": "", "layout": "pcandidates-election", "max": 1, "min": 0, "num_winners": 1, "title": "Secretarí­a General", "randomize_answer_order": true, "tally_type": "plurality-at-large", "answer_total_votes_percentage": "over-total-valid-votes", "answers": [ { "id": 0, "category": "Equipo de Enfermeras", "details": "", "sort_order": 1, "urls": [ { "title": "", "url": "" } ], "text": "Fulanita de tal", } ] } ], "authorities": [ { "name": "Asociación Sugus GNU/Linux", "orchestra_url": "https://sugus.eii.us.es/orchestra", "ssl_cert": "-----BEGIN CERTIFICATE-----\nMIIFATCCA+mgAwIBAgIQAOli4NZQEWpKZeYX25jjwDANBgkqhkiG9w0BAQUFADBz\n8YOltJ6QfO7jNHU9jh/AxeiRf6MibZn6fvBHvFCrVBvDD43M0gdhMkVEDVNkPaak\nC7AHA/waXZ2EwW57Chr2hlZWAkwkFvsWxNt9BgJAJJt4CIVhN/iau/SaXD0l0t1N\nT0ye54QPYl38Eumvc439Yd1CeVS/HYbP0ISIfpNkkFA5TiQdoA==\n-----END CERTIFICATE-----" }, { "name": "Agora Ciudadana", "orchestra_url": "https://agoravoting.com:6874/orchestra", "ssl_cert": "-----BEGIN CERTIFICATE-----\nMIIFATCCA+mgAwIBAgIQAOli4NZQEWpKZeYX25jjwDANBgkqhkiG9w0BAQUFADBz\n8YOltJ6QfO7jNHU9jh/AxeiRf6MibZn6fvBHvFCrVBvDD43M0gdhMkVEDVNkPaak\nC7AHA/waXZ2EwW57Chr2hlZWAkwkFvsWxNt9BgJAJJt4CIVhN/iau/SaXD0l0t1N\nT0ye54QPYl38Eumvc439Yd1CeVS/HYbP0ISIfpNkkFA5TiQdoA==\n-----END CERTIFICATE-----" }, { "name": "Wadobo Labs", "orchestra_url": "https://wadobo.com:6874/orchestra", "ssl_cert": "-----BEGIN CERTIFICATE-----\nMIIFATCCA+mgAwIBAgIQAOli4NZQEWpKZeYX25jjwDANBgkqhkiG9w0BAQUFADBz\n8YOltJ6QfO7jNHU9jh/AxeiRf6MibZn6fvBHvFCrVBvDD43M0gdhMkVEDVNkPaak\nC7AHA/waXZ2EwW57Chr2hlZWAkwkFvsWxNt9BgJAJJt4CIVhN/iau/SaXD0l0t1N\nT0ye54QPYl38Eumvc439Yd1CeVS/HYbP0ISIfpNkkFA5TiQdoA==\n-----END CERTIFICATE-----" } ] } On success, response is empty with status 202 Accepted and returns something like: { "task_id": "ba83ee09-aa83-1901-bb11-e645b52fc558", } When the election finally gets processed, the callback_url is called with a POST containing the protInfo.xml file generated jointly by each authority, following this example response: { "status": "finished", "reference": { "election_id": "d9e5ee09-03fa-4890-aa83-2fc558e645b5", "action": "POST /election" }, "session_data": [{ "session_id": "deadbeef-03fa-4890-aa83-2fc558e645b5", "publickey": ["<pubkey codified in hexadecimal>"] }] } Note that this protInfo.xml will contain the election public key, but also some other information. In particular, it's worth noting that the http and hint servers' urls for each authority could change later, if election-orchestra needs it. If there was an error, then the callback will be called following this example format: { "status": "error", "reference": { "session_id": "d9e5ee09-03fa-4890-aa83-2fc558e645b5", "action": "POST /election" }, "data": { "message": "error message" } } ''' data = request.get_json(force=True, silent=True) d = base64.b64encode(pickle.dumps(data)).decode('utf-8') queueid = queue_task(task='election', data=d) return make_response(dumps(dict(queue_id=queueid)), 202) @public_api.route('/tally', methods=['POST']) def post_tally(): ''' POST /tally Tallies an election, with the given input data. This involves communicating with the different election authorities to do the tally. Example request: POST /tally { "election_id": 111, "callback_url": "https://127.0.0.1:5000/public_api/receive_tally", "votes_url": "https://127.0.0.1:5000/public_data/vota4/encrypted_ciphertexts", "votes_hash": "ni:///sha-256;f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk" } On success, response is empty with status 202 Accepted and returns something like: { "task_id": "ba83ee09-aa83-1901-bb11-e645b52fc558", } When the election finally gets processed, the callback_url is called with POST similar to the following example: { "status": "finished", "reference": { "election_id": "d9e5ee09-03fa-4890-aa83-2fc558e645b5", "action": "POST /tally" }, "data": { "votes_url": "https://127.0.0.1:5000/public_data/vota4/tally.tar.bz2", "votes_hash": "ni:///sha-256;f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk" } } If there was an error, then the callback will be called following this example format: { "status": "error", "reference": { "election_id": "d9e5ee09-03fa-4890-aa83-2fc558e645b5", "action": "POST /tally" }, "data": { "message": "error message" } } ''' # first of all, parse input data data = request.get_json(force=True, silent=True) d = base64.b64encode(pickle.dumps(data)).decode('utf-8') queueid = queue_task(task='tally', data=d) return make_response(dumps(dict(queue_id=queueid)), 202) @public_api.route('/receive_election', methods=['POST']) def receive_election(): ''' This is a test route to be able to test that callbacks are correctly sent ''' print("ATTENTION received election callback: ") print(request.get_json(force=True, silent=True)) return make_response("", 202) @public_api.route('/receive_tally', methods=['POST']) def receive_tally(): ''' This is a test route to be able to test that callbacks are correctly sent ''' print("ATTENTION received tally callback: ") print(request.get_json(force=True, silent=True)) return make_response("", 202)
Java
class ReportsController < ApplicationController skip_load_and_authorize_resource def expenses @filter = params[:filter] if (@type = params[:by_type]) && (@group = params[:by_group]) @expenses = ExpenseReport.by(@type, @group).accessible_by(current_ability) if @filter @filter.each { |k,v| @expenses = @expenses.send(k, v) unless v.blank? } end @expenses = @expenses.order("sum_amount desc") respond_to do |format| format.html { init_form @expenses = @expenses.page(params[:page] || 1).per(20) } format.xlsx { render :xlsx => "expenses", :disposition => "attachment", :filename => "expenses.xlsx" } end else respond_to do |format| format.html { init_form } format.xlsx { redirect_to expenses_report_path(:format => :html) } end end end protected def init_form @by_type_options = %w(estimated approved total authorized) @by_group_options = ExpenseReport.groups.map(&:to_s) #@events = Event.order(:name) @request_states = Request.state_machines[:state].states.map {|s| [ s.value, s.human_name] } @reimbursement_states = Reimbursement.state_machines[:state].states.map {|s| [ s.value, s.human_name] } @countries = I18n.t(:countries).map {|k,v| [k.to_s,v]}.sort_by(&:last) end def set_breadcrumbs @breadcrumbs = [{:label => :breadcrumb_reports}] end end
Java
Network Firewall Setup Guide ============================ <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> **Table of Contents** *generated with [DocToc](http://doctoc.herokuapp.com/)* - [Before you begin](#before-you-begin) - [Initial Setup](#initial-setup) - [Assign interfaces](#assign-interfaces) - [Initial configuration](#initial-configuration) - [Connect to the pfSense WebGUI](#connect-to-the-pfsense-webgui) - [Setup Wizard](#setup-wizard) - [Connect Interfaces and Test Connectivity](#connect-interfaces-and-test-connectivity) - [SecureDrop-specific Configuration](#securedrop-specific-configuration) - [Set up OPT1](#set-up-opt1) - [Disable DHCP on the LAN](#disable-dhcp-on-the-lan) - [Disabling DHCP](#disabling-dhcp) - [Assigning a static IP address to the Admin Workstation](#assigning-a-static-ip-address-to-the-admin-workstation) - [Set up the network firewall rules](#set-up-the-network-firewall-rules) - [Example Screenshots](#example-screenshots) <!-- END doctoc generated TOC please keep comment here to allow auto update --> Unfortunately, due to the wide variety of firewalls that may be used, we do not provide specific instructions to cover every type or variation in software or hardware. This guide will focus on pfSense, and assumes your firewall has at least three interfaces: WAN, LAN, and OPT1. These are the default interfaces on the recommended Netgate firewall, and it should be easy to configure any pfSense firewall with 3 or more NICs this way. To avoid duplication, this guide refers to sections of the [pfSense Guide](http://data.sfb.bg.ac.rs/sftp/bojan.radic/Knjige/Guide_pfsense.pdf), so you will want to have that handy. Before you begin ---------------- First, consider how the firewall will be connected to the Internet. You need to be able to provision two unique subnets for SecureDrop: the app subnet and the monitor subnet. There are a number of possible ways to configure this, and the best way will depend on the network that you are connecting to. Note that many firewalls, including the recommended Netgate pfSense, automatically set up the LAN interface on 192.168.1.1/24. This is a very common subnet choice for home routers. If you are connecting the firewall to a router with the same subnet (common in a small office, home, or testing environment), you will probably be unable to connect to the network at first. However, you will be able to connect from the LAN to the pfSense WebGUI configuration wizard, and from there you will be able to configure the network so it is working correctly. The app subnet will need at least three IP addresses: one for the gateway, one for the app server, and one for the admin workstation. The monitor subnet will need at least two IP addresses: one for the gateway and one for the monitor server. We assume that you have examined your network configuration and have selected two appropriate subnets. We will refer to your chosen subnets as "App Subnet" and "Monitor Subnet" throughout the rest of the documentation. For the examples in the documentation, we have chosen: * App Subnet: 10.20.1.0/24 * App Gateway: 10.20.1.1 * App Server: 10.20.1.2 * Admin Workstation: 10.20.1.3 * Monitor Subnet: 10.20.2.0/24 * Monitor Gateway: 10.20.2.1 * Monitor Server: 10.20.2.2 Initial Setup ------------- Unpack the firewall, connect power, and power on. ### Assign interfaces Section 3.2.3, "Assigning Interfaces", of the pfSense Guide. Some firewalls, like the Netgate recommended in the Hardware Guide, have this set up already, in which case you can skip this step. ### Initial configuration We will use the pfSense WebGUI to do the initial configuration of the network firewall. #### Connect to the pfSense WebGUI 1. Boot the Admin Workstation into Tails from the Admin Live USB. 2. Connect the Admin Workstation to the switch on the LAN. After a few seconds, you should see a pop up notification saying "Connection established" in the top right corner of the screen. 3. Launch the Tor Browser, *Applications → Internet → Tor Browser*. 1. If there is a conflict between your WAN and the default LAN, you will not be able to connect to Tor, and may see a dialog that says "Tor is not ready. Start Tor Browser anyway?". Click "Start Tor Browser" to continue. 4. Navigate to the pfSense GUI in the Tor Browser: https://192.168.1.1 5. The firewall uses a self-signed certificate, so you will see a "This Connection Is Untrusted" warning when you connect. This is expected (see Section 4.5.6 of the pfSense Guide). You can safely continue by clicking "I Understand the Risks", "Add Exception...", and "Confirm Security Exception." 6. You should see the login page for the pfSense GUI. Log in with the default username and password (admin / pfsense). #### Setup Wizard If you're setting up a brand new (or recently factory reset) router, pfSense will start you on the Setup Wizard. Click next, then next again. Don't sign up for a pfSense Gold subscription. On the "General Information" page, we recommend leaving your hostname as the default (pfSense). There is no relevant domain for SecureDrop, so we recommend setting this to "securedrop.local" or something similar. Use whatever DNS servers you wish. If you don't know what DNS servers to use, we recommend using Google's DNS servers: `8.8.8.8` and `8.8.4.4`. Click Next. Leave the defaults for "Time Server Information". Click Next. On "Configure WAN Interface", enter the appropriate configuration for your network. Consult your local sysadmin if you are unsure what to enter here. For many environments, the default of DHCP will work and the rest of the fields can be left blank. Click Next. For "Configure LAN Interface", set the IP address and subnet mask of the Application Subnet for the LAN interface. Click Next. Set a strong admin password. We recommend generating a random password with KeePassX, and saving it in the Tails Persistent folder using the provided KeePassX database template. Click Next. Click Reload. If you changed the LAN Interface settings, you will no longer be able to connect after reloading the firewall and the next request will probably time out. This is not a problem - the firewall has reloaded and is working correctly. To connect to the new LAN interface, unplug and reconnect your network cable to have a new network address assigned to you via DHCP. Note that if you used a subnet with fewer addresses than `/24`, the default DHCP configuration in pfSense may not work. In this case, you should assign the Admin Workstation a static IP address that is known to be in the subnet to continue. Now the WebGUI will be available on the App Gateway address. Navigate to `https://<App Gateway IP>` in the Tor Browser, and do the same dance as before to log in to the pfSense WebGUI and continue configuring the firewall. #### Connect Interfaces and Test Connectivity Now that the initial configuration is completed, you can connect the WAN port without potentially conflicting with the default LAN settings (as explained earlier). Connect the WAN port to the external network. You can watch the WAN entry in the Interfaces table on the pfSense WebGUI homepage to see as it changes from down (red arrow pointing down) to up (green arrow pointing up). The WAN's IP address will be shown once it comes up. Finally, test connectivity to make sure you are able to connect to the Internet through the WAN. The easiest way to do this is to use ping (Diagnostics → Ping in the WebGUI). SecureDrop-specific Configuration --------------------------------- SecureDrop uses the firewall to achieve two primary goals: 1. Isolating SecureDrop from the existing network, which may be compromised (especially if it is a venerable network in a large organization like a newsroom). 2. Isolating the app and the monitor servers from each other as much as possible, to reduce attack surface. In order to use the firewall to isolate the app and monitor servers from each other, we need to connect them to separate interfaces, and then set up firewall rules that allow them to communicate. ### Set up OPT1 We set up the LAN interface during the initial configuration. We now need to set up the OPT1 interface. Start by connecting the Monitor Server to the OPT1 port. Then use the WebGUI to configure the OPT1 interface. Go to `Interfaces → OPT1`, and check the box to "Enable Interface". Use these settings: - IPv4 Configuration Type: Static IPv4 - IPv4 Address: Monitor Gateway Leave everything else as the default. Save and Apply Changes. ### Disable DHCP on the LAN pfSense runs a DHCP server on the LAN interface by default. At this stage in the documentation, the Admin Workstation has an IP address assigned via that DHCP server. You can easily check your current IP address by *right-clicking* the networking icon (a blue cable going in to a white jack) in the top right of the menu bar, and choosing "Connection Information". ![Connection Information](images/firewall/connection_information.png) In order to tighten the firewall rules as much as possible, we recommend disabling the DHCP server and assigning a static IP address to the Admin Workstation instead. #### Disabling DHCP To disable DHCP, navigate to "Services → DHCP Server". Uncheck the box to "Enable DHCP servers on LAN interface", scroll down, and click the Save button. #### Assigning a static IP address to the Admin Workstation Now you will need to assign a static IP to the Admin Workstation. Use the *Admin Workstation IP* that you selected earlier, and make sure you use the same IP when setting up the firewall rules later. Start by *right-clicking* the networking icon in the top right of the menu bar, and choosing "Edit Connections...". ![Edit Connections](images/firewall/edit_connections.png) Select "Wired connection" from the list and click the "Edit..." button. ![Edit Wired Connection](images/firewall/edit_wired_connection.png) Change to the "IPv4 Settings" tab. Change "Method:" from "Automatic (DHCP)" to "Manual". Click the Add button and fill in the static networking information for the Admin Workstation. ![Editing Wired Connection](images/firewall/editing_wired_connection.png) Click "Save...". If the network does not come up within 15 seconds or so, try disconnecting and reconnecting your network cable to trigger the change. You will need you have succeeded in connecting with your new static IP when you see a pop-up notification that says "Tor is ready. You can now access the Internet". ### Set up the network firewall rules Since there are a variety of firewalls with different configuration interfaces and underlying sets of software, we cannot provide a set of network firewall rules to match every use case. Instead, we provide a firewall rules template in `install_files/network_firewall/rules`. This template is written in the iptables format, which you will need to manually translate for your firewall and preferred configuration method. For pfSense, see Section 6 of the pfSense Guide for information on setting up firewall rules through the WebGUI. Here are some tips on interpreting the rules template for pfSense: 1. Create aliases for the repeated values (IPs and ports). 2. pfSense is a stateful firewall, which means that you don't need corresponding rules for the iptables rules that allow incoming traffic in response to outgoing traffic (`--state ESTABLISHED,RELATED`). pfSense does this for you automatically. 3. You should create the rules on the interface where the traffic originates from. The easy way to do this is look at the sources (`-s`) of each of the iptables rules, and create that rule on the corresponding interface: * `-s APP_IP` → `LAN` * `-s MONITOR_IP` → `OPT1` 4. Make sure you delete the default "allow all" rule on the LAN interface. Leave the "Anti-Lockout" rule enabled. 5. Any traffic that is not explicitly passed is logged and dropped by default in pfSense, so you don't need to add explicit rules (`LOGNDROP`) for that. 6. Since some of the rules are almost identical except for whether they allow traffic from the App Server or the Monitor Server (`-s MONITOR_IP,APP_IP`), you can use the "add a new rule based on this one" button to save time creating a copy of the rule on the other interface. 7. If you are having trouble with connections, the firewall logs can be very helpful. You can find them in the WebGUI in *Status → System Logs → Firewall*. We recognize that this process is cumbersome and may be difficult for people inexperienced in managing networks to understand. We are working on automating much of this for the next SecureDrop release. #### Example Screenshots Here are some example screenshots of a working pfSense firewall configuration: ![Firewall IP Aliases](images/firewall/ip_aliases.png) ![Firewall Port Aliases](images/firewall/port_aliases.png) ![Firewall LAN Rules](images/firewall/lan_rules.png) ![Firewall OPT1 Rules](images/firewall/opt1_rules.png) Once you've set up the firewall, continue with the instructions in the [Install Guide](/docs/install.md#set-up-the-servers).
Java
/* * Claudia Project * http://claudia.morfeo-project.org * * (C) Copyright 2010 Telefonica Investigacion y Desarrollo * S.A.Unipersonal (Telefonica I+D) * * See CREDITS file for info about members and contributors. * * This program is free software; you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License (AGPL) 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 Affero 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. * * If you want to use this software an plan to distribute a * proprietary application in any way, and you are not licensing and * distributing your source code under AGPL, you probably need to * purchase a commercial license of the product. Please contact * claudia-support@lists.morfeo-project.org for more information. */ package com.telefonica.claudia.smi.deployment; import java.io.IOException; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.log4j.Logger; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.data.Status; import org.restlet.resource.DomRepresentation; import org.restlet.resource.Representation; import org.restlet.resource.Resource; import org.restlet.resource.ResourceException; import org.restlet.resource.Variant; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.telefonica.claudia.smi.Main; import com.telefonica.claudia.smi.URICreation; public class ServiceItemResource extends Resource { private static Logger log = Logger.getLogger("com.telefonica.claudia.smi.ServiceItemResource"); String vdcId; String vappId; String orgId; public ServiceItemResource(Context context, Request request, Response response) { super(context, request, response); this.vappId = (String) getRequest().getAttributes().get("vapp-id"); this.vdcId = (String) getRequest().getAttributes().get("vdc-id"); this.orgId = (String) getRequest().getAttributes().get("org-id"); // Get the item directly from the "persistence layer". if (this.orgId != null && this.vdcId!=null && this.vappId!=null) { // Define the supported variant. getVariants().add(new Variant(MediaType.TEXT_XML)); // By default a resource cannot be updated. setModifiable(true); } else { // This resource is not available. setAvailable(false); } } /** * Handle GETS */ @Override public Representation represent(Variant variant) throws ResourceException { // Generate the right representation according to its media type. if (MediaType.TEXT_XML.equals(variant.getMediaType())) { try { DeploymentDriver actualDriver= (DeploymentDriver) getContext().getAttributes().get(DeploymentApplication.ATTR_PLUGIN_DEPLOYMENT); String serviceInfo = actualDriver.getService(URICreation.getFQN(orgId, vdcId, vappId)); // Substitute the macros in the description serviceInfo = serviceInfo.replace("@HOSTNAME", "http://" + Main.serverHost + ":" + Main.serverPort); if (serviceInfo==null) { log.error("Null response from the SM."); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); return null; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(serviceInfo)); Document doc = db.parse(is); DomRepresentation representation = new DomRepresentation( MediaType.TEXT_XML, doc); log.info("Data returned for service "+ URICreation.getFQN(orgId, vdcId, vappId) + ": \n\n" + serviceInfo); // Returns the XML representation of this document. return representation; } catch (IOException e) { log.error("Time out waiting for the Lifecycle Controller."); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); return null; } catch (SAXException e) { log.error("Retrieved data was not in XML format: " + e.getMessage()); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); return null; } catch (ParserConfigurationException e) { log.error("Error trying to configure parser."); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); return null; } } return null; } /** * Handle DELETE requests. */ @Override public void removeRepresentations() throws ResourceException { DeploymentDriver actualDriver= (DeploymentDriver) getContext().getAttributes().get(DeploymentApplication.ATTR_PLUGIN_DEPLOYMENT); try { actualDriver.undeploy(URICreation.getFQN(orgId, vdcId, vappId)); } catch (IOException e) { log.error("Time out waiting for the Lifecycle Controller."); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); return; } // Tells the client that the request has been successfully fulfilled. getResponse().setStatus(Status.SUCCESS_NO_CONTENT); } }
Java
--- layout: post title: "All Star Wars, all the time" date: 2013-04-15 00:00:00 +0900 categories: linux-foundation comics --- ![{{ page.title }}]({{ site.comicsurl }}69-all-star-wars-all-the-time.jpg) This comic originally appeared on [linux.com](https://www.linux.com) and was sponsored by [The Linux Foundation](https://www.linuxfoundation.org/). For those of you who have just come back from Antarctica and haven't seen the 6 Panel Star Wars yet, go take a look! It's almost worth having to sit through Jar Jar as you can just ignore that panel every time he comes on. Also, before any die hard fans point it out, we are aware that [Aqualish](http://starwars.wikia.com/wiki/Aqualish) only have 2 or 4 eyes, not 6, but 6 just fits the theme better.
Java
DELETE FROM `weenie` WHERE `class_Id` = 14289; INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`) VALUES (14289, 'portalvillalabar', 7, '2019-02-10 00:00:00') /* Portal */; INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`) VALUES (14289, 1, 65536) /* ItemType - Portal */ , (14289, 16, 32) /* ItemUseable - Remote */ , (14289, 93, 3084) /* PhysicsState - Ethereal, ReportCollisions, Gravity, LightingOn */ , (14289, 111, 1) /* PortalBitmask - Unrestricted */ , (14289, 133, 4) /* ShowableOnRadar - ShowAlways */ , (14289, 8007, 0) /* PCAPRecordedAutonomousMovement */; INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`) VALUES (14289, 1, True ) /* Stuck */; INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`) VALUES (14289, 54, -0.1) /* UseRadius */; INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`) VALUES (14289, 1, 'Villalabar Portal') /* Name */ , (14289, 8006, 'AAA9AAAAAAA=') /* PCAPRecordedCurrentMotionState */; INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`) VALUES (14289, 1, 0x020001B3) /* Setup */ , (14289, 2, 0x09000003) /* MotionTable */ , (14289, 8, 0x0600106B) /* Icon */ , (14289, 8001, 8388656) /* PCAPRecordedWeenieHeader - Usable, UseRadius, RadarBehavior */ , (14289, 8003, 262164) /* PCAPRecordedObjectDesc - Stuck, Attackable, Portal */ , (14289, 8005, 98307) /* PCAPRecordedPhysicsDesc - CSetup, MTable, Position, Movement */; INSERT INTO `weenie_properties_position` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`) VALUES (14289, 8040, 0x9521002F, 139.109, 166.067, 122.4202, 0.001375, 0, 0, -0.999999) /* PCAPRecordedLocation */ /* @teleloc 0x9521002F [139.109000 166.067000 122.420200] 0.001375 0.000000 0.000000 -0.999999 */; INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`) VALUES (14289, 8000, 0x79521002) /* PCAPRecordedObjectIID */;
Java
// Copyright 2014 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package v4_test import ( "encoding/json" "net/http" "time" jc "github.com/juju/testing/checkers" "github.com/juju/testing/httptesting" "github.com/juju/utils/debugstatus" gc "gopkg.in/check.v1" "gopkg.in/juju/charm.v5" "gopkg.in/juju/charmstore.v4/internal/mongodoc" "gopkg.in/juju/charmstore.v4/internal/router" "gopkg.in/juju/charmstore.v4/params" ) var zeroTimeStr = time.Time{}.Format(time.RFC3339) func (s *APISuite) TestStatus(c *gc.C) { for _, id := range []*router.ResolvedURL{ newResolvedURL("cs:~charmers/precise/wordpress-2", 2), newResolvedURL("cs:~charmers/precise/wordpress-3", 3), newResolvedURL("cs:~foo/precise/arble-9", -1), newResolvedURL("cs:~bar/utopic/arble-10", -1), newResolvedURL("cs:~charmers/bundle/oflaughs-3", 3), newResolvedURL("cs:~bar/bundle/oflaughs-4", -1), } { if id.URL.Series == "bundle" { s.addPublicBundle(c, "wordpress-simple", id) } else { s.addPublicCharm(c, "wordpress", id) } } now := time.Now() s.PatchValue(&debugstatus.StartTime, now) start := now.Add(-2 * time.Hour) s.addLog(c, &mongodoc.Log{ Data: []byte(`"ingestion started"`), Level: mongodoc.InfoLevel, Type: mongodoc.IngestionType, Time: start, }) end := now.Add(-1 * time.Hour) s.addLog(c, &mongodoc.Log{ Data: []byte(`"ingestion completed"`), Level: mongodoc.InfoLevel, Type: mongodoc.IngestionType, Time: end, }) statisticsStart := now.Add(-1*time.Hour - 30*time.Minute) s.addLog(c, &mongodoc.Log{ Data: []byte(`"legacy statistics import started"`), Level: mongodoc.InfoLevel, Type: mongodoc.LegacyStatisticsType, Time: statisticsStart, }) statisticsEnd := now.Add(-30 * time.Minute) s.addLog(c, &mongodoc.Log{ Data: []byte(`"legacy statistics import completed"`), Level: mongodoc.InfoLevel, Type: mongodoc.LegacyStatisticsType, Time: statisticsEnd, }) s.AssertDebugStatus(c, true, map[string]params.DebugStatus{ "mongo_connected": { Name: "MongoDB is connected", Value: "Connected", Passed: true, }, "mongo_collections": { Name: "MongoDB collections", Value: "All required collections exist", Passed: true, }, "elasticsearch": { Name: "Elastic search is running", Value: "Elastic search is not configured", Passed: true, }, "entities": { Name: "Entities in charm store", Value: "4 charms; 2 bundles; 3 promulgated", Passed: true, }, "base_entities": { Name: "Base entities in charm store", Value: "count: 5", Passed: true, }, "server_started": { Name: "Server started", Value: now.String(), Passed: true, }, "ingestion": { Name: "Ingestion", Value: "started: " + start.Format(time.RFC3339) + ", completed: " + end.Format(time.RFC3339), Passed: true, }, "legacy_statistics": { Name: "Legacy Statistics Load", Value: "started: " + statisticsStart.Format(time.RFC3339) + ", completed: " + statisticsEnd.Format(time.RFC3339), Passed: true, }, }) } func (s *APISuite) TestStatusWithoutCorrectCollections(c *gc.C) { s.store.DB.Entities().DropCollection() s.AssertDebugStatus(c, false, map[string]params.DebugStatus{ "mongo_collections": { Name: "MongoDB collections", Value: "Missing collections: [" + s.store.DB.Entities().Name + "]", Passed: false, }, }) } func (s *APISuite) TestStatusWithoutIngestion(c *gc.C) { s.AssertDebugStatus(c, false, map[string]params.DebugStatus{ "ingestion": { Name: "Ingestion", Value: "started: " + zeroTimeStr + ", completed: " + zeroTimeStr, Passed: false, }, }) } func (s *APISuite) TestStatusIngestionStarted(c *gc.C) { now := time.Now() start := now.Add(-1 * time.Hour) s.addLog(c, &mongodoc.Log{ Data: []byte(`"ingestion started"`), Level: mongodoc.InfoLevel, Type: mongodoc.IngestionType, Time: start, }) s.AssertDebugStatus(c, false, map[string]params.DebugStatus{ "ingestion": { Name: "Ingestion", Value: "started: " + start.Format(time.RFC3339) + ", completed: " + zeroTimeStr, Passed: false, }, }) } func (s *APISuite) TestStatusWithoutLegacyStatistics(c *gc.C) { s.AssertDebugStatus(c, false, map[string]params.DebugStatus{ "legacy_statistics": { Name: "Legacy Statistics Load", Value: "started: " + zeroTimeStr + ", completed: " + zeroTimeStr, Passed: false, }, }) } func (s *APISuite) TestStatusLegacyStatisticsStarted(c *gc.C) { now := time.Now() statisticsStart := now.Add(-1*time.Hour - 30*time.Minute) s.addLog(c, &mongodoc.Log{ Data: []byte(`"legacy statistics import started"`), Level: mongodoc.InfoLevel, Type: mongodoc.LegacyStatisticsType, Time: statisticsStart, }) s.AssertDebugStatus(c, false, map[string]params.DebugStatus{ "legacy_statistics": { Name: "Legacy Statistics Load", Value: "started: " + statisticsStart.Format(time.RFC3339) + ", completed: " + zeroTimeStr, Passed: false, }, }) } func (s *APISuite) TestStatusLegacyStatisticsMultipleLogs(c *gc.C) { now := time.Now() statisticsStart := now.Add(-1*time.Hour - 30*time.Minute) s.addLog(c, &mongodoc.Log{ Data: []byte(`"legacy statistics import started"`), Level: mongodoc.InfoLevel, Type: mongodoc.LegacyStatisticsType, Time: statisticsStart.Add(-1 * time.Hour), }) s.addLog(c, &mongodoc.Log{ Data: []byte(`"legacy statistics import started"`), Level: mongodoc.InfoLevel, Type: mongodoc.LegacyStatisticsType, Time: statisticsStart, }) statisticsEnd := now.Add(-30 * time.Minute) s.addLog(c, &mongodoc.Log{ Data: []byte(`"legacy statistics import completed"`), Level: mongodoc.InfoLevel, Type: mongodoc.LegacyStatisticsType, Time: statisticsEnd.Add(-1 * time.Hour), }) s.addLog(c, &mongodoc.Log{ Data: []byte(`"legacy statistics import completed"`), Level: mongodoc.InfoLevel, Type: mongodoc.LegacyStatisticsType, Time: statisticsEnd, }) s.AssertDebugStatus(c, false, map[string]params.DebugStatus{ "legacy_statistics": { Name: "Legacy Statistics Load", Value: "started: " + statisticsStart.Format(time.RFC3339) + ", completed: " + statisticsEnd.Format(time.RFC3339), Passed: true, }, }) } func (s *APISuite) TestStatusBaseEntitiesError(c *gc.C) { // Add a base entity without any corresponding entities. entity := &mongodoc.BaseEntity{ URL: charm.MustParseReference("django"), Name: "django", } err := s.store.DB.BaseEntities().Insert(entity) c.Assert(err, gc.IsNil) s.AssertDebugStatus(c, false, map[string]params.DebugStatus{ "base_entities": { Name: "Base entities in charm store", Value: "count: 1", Passed: false, }, }) } // AssertDebugStatus asserts that the current /debug/status endpoint // matches the given status, ignoring status duration. // If complete is true, it fails if the results contain // keys not mentioned in status. func (s *APISuite) AssertDebugStatus(c *gc.C, complete bool, status map[string]params.DebugStatus) { rec := httptesting.DoRequest(c, httptesting.DoRequestParams{ Handler: s.srv, URL: storeURL("debug/status"), }) c.Assert(rec.Code, gc.Equals, http.StatusOK, gc.Commentf("body: %s", rec.Body.Bytes())) c.Assert(rec.Header().Get("Content-Type"), gc.Equals, "application/json") var gotStatus map[string]params.DebugStatus err := json.Unmarshal(rec.Body.Bytes(), &gotStatus) c.Assert(err, gc.IsNil) for key, r := range gotStatus { if _, found := status[key]; !complete && !found { delete(gotStatus, key) continue } r.Duration = 0 gotStatus[key] = r } c.Assert(gotStatus, jc.DeepEquals, status) } type statusWithElasticSearchSuite struct { commonSuite } var _ = gc.Suite(&statusWithElasticSearchSuite{}) func (s *statusWithElasticSearchSuite) SetUpSuite(c *gc.C) { s.enableES = true s.commonSuite.SetUpSuite(c) } func (s *statusWithElasticSearchSuite) TestStatusWithElasticSearch(c *gc.C) { rec := httptesting.DoRequest(c, httptesting.DoRequestParams{ Handler: s.srv, URL: storeURL("debug/status"), }) var results map[string]params.DebugStatus err := json.Unmarshal(rec.Body.Bytes(), &results) c.Assert(err, gc.IsNil) c.Assert(results["elasticsearch"].Name, gc.Equals, "Elastic search is running") c.Assert(results["elasticsearch"].Value, jc.Contains, "cluster_name:") }
Java
// Copyright (c) 2012-present The upper.io/db authors. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package db import ( "reflect" "time" ) // Comparison defines methods for representing comparison operators in a // portable way across databases. type Comparison interface { Operator() ComparisonOperator Value() interface{} } // ComparisonOperator is a type we use to label comparison operators. type ComparisonOperator uint8 // Comparison operators const ( ComparisonOperatorNone ComparisonOperator = iota ComparisonOperatorEqual ComparisonOperatorNotEqual ComparisonOperatorLessThan ComparisonOperatorGreaterThan ComparisonOperatorLessThanOrEqualTo ComparisonOperatorGreaterThanOrEqualTo ComparisonOperatorBetween ComparisonOperatorNotBetween ComparisonOperatorIn ComparisonOperatorNotIn ComparisonOperatorIs ComparisonOperatorIsNot ComparisonOperatorLike ComparisonOperatorNotLike ComparisonOperatorRegExp ComparisonOperatorNotRegExp ComparisonOperatorAfter ComparisonOperatorBefore ComparisonOperatorOnOrAfter ComparisonOperatorOnOrBefore ) type dbComparisonOperator struct { t ComparisonOperator op string v interface{} } func (c *dbComparisonOperator) CustomOperator() string { return c.op } func (c *dbComparisonOperator) Operator() ComparisonOperator { return c.t } func (c *dbComparisonOperator) Value() interface{} { return c.v } // Gte indicates whether the reference is greater than or equal to the given // argument. func Gte(v interface{}) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorGreaterThanOrEqualTo, v: v, } } // Lte indicates whether the reference is less than or equal to the given // argument. func Lte(v interface{}) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorLessThanOrEqualTo, v: v, } } // Eq indicates whether the constraint is equal to the given argument. func Eq(v interface{}) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorEqual, v: v, } } // NotEq indicates whether the constraint is not equal to the given argument. func NotEq(v interface{}) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorNotEqual, v: v, } } // Gt indicates whether the constraint is greater than the given argument. func Gt(v interface{}) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorGreaterThan, v: v, } } // Lt indicates whether the constraint is less than the given argument. func Lt(v interface{}) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorLessThan, v: v, } } // In indicates whether the argument is part of the reference. func In(v interface{}) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorIn, v: toInterfaceArray(v), } } // NotIn indicates whether the argument is not part of the reference. func NotIn(v interface{}) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorNotIn, v: toInterfaceArray(v), } } // After indicates whether the reference is after the given time. func After(t time.Time) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorGreaterThan, v: t, } } // Before indicates whether the reference is before the given time. func Before(t time.Time) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorLessThan, v: t, } } // OnOrAfter indicater whether the reference is after or equal to the given // time value. func OnOrAfter(t time.Time) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorGreaterThanOrEqualTo, v: t, } } // OnOrBefore indicates whether the reference is before or equal to the given // time value. func OnOrBefore(t time.Time) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorLessThanOrEqualTo, v: t, } } // Between indicates whether the reference is contained between the two given // values. func Between(a interface{}, b interface{}) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorBetween, v: []interface{}{a, b}, } } // NotBetween indicates whether the reference is not contained between the two // given values. func NotBetween(a interface{}, b interface{}) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorNotBetween, v: []interface{}{a, b}, } } // Is indicates whether the reference is nil, true or false. func Is(v interface{}) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorIs, v: v, } } // IsNot indicates whether the reference is not nil, true nor false. func IsNot(v interface{}) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorIsNot, v: v, } } // IsNull indicates whether the reference is a NULL value. func IsNull() Comparison { return Is(nil) } // IsNotNull indicates whether the reference is a NULL value. func IsNotNull() Comparison { return IsNot(nil) } /* // IsDistinctFrom indicates whether the reference is different from // the given value, including NULL values. func IsDistinctFrom(v interface{}) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorIsDistinctFrom, v: v, } } // IsNotDistinctFrom indicates whether the reference is not different from the // given value, including NULL values. func IsNotDistinctFrom(v interface{}) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorIsNotDistinctFrom, v: v, } } */ // Like indicates whether the reference matches the wildcard value. func Like(v string) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorLike, v: v, } } // NotLike indicates whether the reference does not match the wildcard value. func NotLike(v string) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorNotLike, v: v, } } /* // ILike indicates whether the reference matches the wildcard value (case // insensitive). func ILike(v string) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorILike, v: v, } } // NotILike indicates whether the reference does not match the wildcard value // (case insensitive). func NotILike(v string) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorNotILike, v: v, } } */ // RegExp indicates whether the reference matches the regexp pattern. func RegExp(v string) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorRegExp, v: v, } } // NotRegExp indicates whether the reference does not match the regexp pattern. func NotRegExp(v string) Comparison { return &dbComparisonOperator{ t: ComparisonOperatorNotRegExp, v: v, } } // Op represents a custom comparison operator against the reference. func Op(customOperator string, v interface{}) Comparison { return &dbComparisonOperator{ op: customOperator, t: ComparisonOperatorNone, v: v, } } func toInterfaceArray(v interface{}) []interface{} { rv := reflect.ValueOf(v) switch rv.Type().Kind() { case reflect.Ptr: return toInterfaceArray(rv.Elem().Interface()) case reflect.Slice: elems := rv.Len() args := make([]interface{}, elems) for i := 0; i < elems; i++ { args[i] = rv.Index(i).Interface() } return args } return []interface{}{v} } var _ Comparison = &dbComparisonOperator{}
Java
<?php /** * plentymarkets shopware connector * Copyright © 2013-2014 plentymarkets GmbH * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License, supplemented by an additional * permission, and of our proprietary license can be found * in the LICENSE file you have received along with this program. * * 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. * * "plentymarkets" is a registered trademark of plentymarkets GmbH. * "shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, titles and interests in the * above trademarks remain entirely with the trademark owners. * * @copyright Copyright (c) 2014, plentymarkets GmbH (http://www.plentymarkets.com) * @author Daniel Bächtle <daniel.baechtle@plentymarkets.com> */ /** * I am a generated class and am required for communicating with plentymarkets. */ class PlentySoapObject_DeliveryRow { /** * @var int */ public $OrderRowID; /** * @var float */ public $Quantity; }
Java
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'UserProject.drive_auth' db.add_column(u'user_project', 'drive_auth', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False) def backwards(self, orm): # Deleting field 'UserProject.drive_auth' db.delete_column(u'user_project', 'drive_auth') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'home.category': { 'Meta': {'object_name': 'Category', 'db_table': "u'category'"}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '150'}) }, 'projects.project': { 'Meta': {'object_name': 'Project', 'db_table': "u'project'"}, 'categories': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['home.Category']", 'null': 'True', 'blank': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 27, 0, 0)', 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image_name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'null': 'True', 'blank': 'True'}), 'image_original_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'licence': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 27, 0, 0)', 'null': 'True', 'blank': 'True'}), 'tags': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'type_field': ('django.db.models.fields.IntegerField', [], {'default': '1', 'null': 'True', 'db_column': "'type'", 'blank': 'True'}) }, 'projects.projectpart': { 'Meta': {'object_name': 'ProjectPart', 'db_table': "u'project_part'"}, 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 27, 0, 0)', 'null': 'True', 'blank': 'True'}), 'created_user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'projectpart_created_user'", 'to': "orm['auth.User']"}), 'drive_id': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 27, 0, 0)', 'null': 'True', 'blank': 'True'}), 'modified_user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'projectpart_modified_user'", 'null': 'True', 'to': "orm['auth.User']"}), 'order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['projects.Project']"}), 'project_part': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['projects.ProjectPart']", 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'projects.userproject': { 'Meta': {'object_name': 'UserProject', 'db_table': "u'user_project'"}, 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 27, 0, 0)', 'null': 'True', 'blank': 'True'}), 'created_user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'userproject_created_user'", 'to': "orm['auth.User']"}), 'drive_auth': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'modified_user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'userproject_modified_user'", 'null': 'True', 'to': "orm['auth.User']"}), 'permission': ('django.db.models.fields.CharField', [], {'default': '0', 'max_length': '255'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['projects.Project']", 'db_column': "'project_id'"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) } } complete_apps = ['projects']
Java
ace.define("ace/mode/jsx", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text", "ace/tokenizer", "ace/mode/jsx_highlight_rules", "ace/mode/matching_brace_outdent", "ace/mode/behaviour/cstyle", "ace/mode/folding/cstyle"], function (e, t, n) { function l() { this.HighlightRules = o, this.$outdent = new u, this.$behaviour = new a, this.foldingRules = new f } var r = e("../lib/oop"), i = e("./text").Mode, s = e("../tokenizer").Tokenizer, o = e("./jsx_highlight_rules").JsxHighlightRules, u = e("./matching_brace_outdent").MatchingBraceOutdent, a = e("./behaviour/cstyle").CstyleBehaviour, f = e("./folding/cstyle").FoldMode; r.inherits(l, i), function () { this.lineCommentStart = "//", this.blockComment = {start: "/*", end: "*/"}, this.getNextLineIndent = function (e, t, n) { var r = this.$getIndent(t), i = this.getTokenizer().getLineTokens(t, e), s = i.tokens; if (s.length && s[s.length - 1].type == "comment")return r; if (e == "start") { var o = t.match(/^.*[\{\(\[]\s*$/); o && (r += n) } return r }, this.checkOutdent = function (e, t, n) { return this.$outdent.checkOutdent(t, n) }, this.autoOutdent = function (e, t, n) { this.$outdent.autoOutdent(t, n) }, this.$id = "ace/mode/jsx" }.call(l.prototype), t.Mode = l }), ace.define("ace/mode/jsx_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/lib/lang", "ace/mode/doc_comment_highlight_rules", "ace/mode/text_highlight_rules"], function (e, t, n) { var r = e("../lib/oop"), i = e("../lib/lang"), s = e("./doc_comment_highlight_rules").DocCommentHighlightRules, o = e("./text_highlight_rules").TextHighlightRules, u = function () { var e = i.arrayToMap("break|do|instanceof|typeof|case|else|new|var|catch|finally|return|void|continue|for|switch|default|while|function|this|if|throw|delete|in|try|class|extends|super|import|from|into|implements|interface|static|mixin|override|abstract|final|number|int|string|boolean|variant|log|assert".split("|")), t = i.arrayToMap("null|true|false|NaN|Infinity|__FILE__|__LINE__|undefined".split("|")), n = i.arrayToMap("debugger|with|const|export|let|private|public|yield|protected|extern|native|as|operator|__fake__|__readonly__".split("|")), r = "[a-zA-Z_][a-zA-Z0-9_]*\\b"; this.$rules = {start: [ {token: "comment", regex: "\\/\\/.*$"}, s.getStartRule("doc-start"), {token: "comment", regex: "\\/\\*", next: "comment"}, {token: "string.regexp", regex: "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"}, {token: "string", regex: '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'}, {token: "string", regex: "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"}, {token: "constant.numeric", regex: "0[xX][0-9a-fA-F]+\\b"}, {token: "constant.numeric", regex: "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"}, {token: "constant.language.boolean", regex: "(?:true|false)\\b"}, {token: ["storage.type", "text", "entity.name.function"], regex: "(function)(\\s+)(" + r + ")"}, {token: function (r) { return r == "this" ? "variable.language" : r == "function" ? "storage.type" : e.hasOwnProperty(r) || n.hasOwnProperty(r) ? "keyword" : t.hasOwnProperty(r) ? "constant.language" : /^_?[A-Z][a-zA-Z0-9_]*$/.test(r) ? "language.support.class" : "identifier" }, regex: r}, {token: "keyword.operator", regex: "!|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|==|=|!=|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"}, {token: "punctuation.operator", regex: "\\?|\\:|\\,|\\;|\\."}, {token: "paren.lparen", regex: "[[({<]"}, {token: "paren.rparen", regex: "[\\])}>]"}, {token: "text", regex: "\\s+"} ], comment: [ {token: "comment", regex: ".*?\\*\\/", next: "start"}, {token: "comment", regex: ".+"} ]}, this.embedRules(s, "doc-", [s.getEndRule("start")]) }; r.inherits(u, o), t.JsxHighlightRules = u }), ace.define("ace/mode/doc_comment_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function (e, t, n) { var r = e("../lib/oop"), i = e("./text_highlight_rules").TextHighlightRules, s = function () { this.$rules = {start: [ {token: "comment.doc.tag", regex: "@[\\w\\d_]+"}, {token: "comment.doc.tag", regex: "\\bTODO\\b"}, {defaultToken: "comment.doc"} ]} }; r.inherits(s, i), s.getStartRule = function (e) { return{token: "comment.doc", regex: "\\/\\*(?=\\*)", next: e} }, s.getEndRule = function (e) { return{token: "comment.doc", regex: "\\*\\/", next: e} }, t.DocCommentHighlightRules = s }), ace.define("ace/mode/matching_brace_outdent", ["require", "exports", "module", "ace/range"], function (e, t, n) { var r = e("../range").Range, i = function () { }; (function () { this.checkOutdent = function (e, t) { return/^\s+$/.test(e) ? /^\s*\}/.test(t) : !1 }, this.autoOutdent = function (e, t) { var n = e.getLine(t), i = n.match(/^(\s*\})/); if (!i)return 0; var s = i[1].length, o = e.findMatchingBracket({row: t, column: s}); if (!o || o.row == t)return 0; var u = this.$getIndent(e.getLine(o.row)); e.replace(new r(t, 0, t, s - 1), u) }, this.$getIndent = function (e) { return e.match(/^\s*/)[0] } }).call(i.prototype), t.MatchingBraceOutdent = i }), ace.define("ace/mode/behaviour/cstyle", ["require", "exports", "module", "ace/lib/oop", "ace/mode/behaviour", "ace/token_iterator", "ace/lib/lang"], function (e, t, n) { var r = e("../../lib/oop"), i = e("../behaviour").Behaviour, s = e("../../token_iterator").TokenIterator, o = e("../../lib/lang"), u = ["text", "paren.rparen", "punctuation.operator"], a = ["text", "paren.rparen", "punctuation.operator", "comment"], f, l = {}, c = function (e) { var t = -1; e.multiSelect && (t = e.selection.id, l.rangeCount != e.multiSelect.rangeCount && (l = {rangeCount: e.multiSelect.rangeCount})); if (l[t])return f = l[t]; f = l[t] = {autoInsertedBrackets: 0, autoInsertedRow: -1, autoInsertedLineEnd: "", maybeInsertedBrackets: 0, maybeInsertedRow: -1, maybeInsertedLineStart: "", maybeInsertedLineEnd: ""} }, h = function () { this.add("braces", "insertion", function (e, t, n, r, i) { var s = n.getCursorPosition(), u = r.doc.getLine(s.row); if (i == "{") { c(n); var a = n.getSelectionRange(), l = r.doc.getTextRange(a); if (l !== "" && l !== "{" && n.getWrapBehavioursEnabled())return{text: "{" + l + "}", selection: !1}; if (h.isSaneInsertion(n, r))return/[\]\}\)]/.test(u[s.column]) || n.inMultiSelectMode ? (h.recordAutoInsert(n, r, "}"), {text: "{}", selection: [1, 1]}) : (h.recordMaybeInsert(n, r, "{"), {text: "{", selection: [1, 1]}) } else if (i == "}") { c(n); var p = u.substring(s.column, s.column + 1); if (p == "}") { var d = r.$findOpeningBracket("}", {column: s.column + 1, row: s.row}); if (d !== null && h.isAutoInsertedClosing(s, u, i))return h.popAutoInsertedClosing(), {text: "", selection: [1, 1]} } } else { if (i == "\n" || i == "\r\n") { c(n); var v = ""; h.isMaybeInsertedClosing(s, u) && (v = o.stringRepeat("}", f.maybeInsertedBrackets), h.clearMaybeInsertedClosing()); var p = u.substring(s.column, s.column + 1); if (p === "}") { var m = r.findMatchingBracket({row: s.row, column: s.column + 1}, "}"); if (!m)return null; var g = this.$getIndent(r.getLine(m.row)) } else { if (!v) { h.clearMaybeInsertedClosing(); return } var g = this.$getIndent(u) } var y = g + r.getTabString(); return{text: "\n" + y + "\n" + g + v, selection: [1, y.length, 1, y.length]} } h.clearMaybeInsertedClosing() } }), this.add("braces", "deletion", function (e, t, n, r, i) { var s = r.doc.getTextRange(i); if (!i.isMultiLine() && s == "{") { c(n); var o = r.doc.getLine(i.start.row), u = o.substring(i.end.column, i.end.column + 1); if (u == "}")return i.end.column++, i; f.maybeInsertedBrackets-- } }), this.add("parens", "insertion", function (e, t, n, r, i) { if (i == "(") { c(n); var s = n.getSelectionRange(), o = r.doc.getTextRange(s); if (o !== "" && n.getWrapBehavioursEnabled())return{text: "(" + o + ")", selection: !1}; if (h.isSaneInsertion(n, r))return h.recordAutoInsert(n, r, ")"), {text: "()", selection: [1, 1]} } else if (i == ")") { c(n); var u = n.getCursorPosition(), a = r.doc.getLine(u.row), f = a.substring(u.column, u.column + 1); if (f == ")") { var l = r.$findOpeningBracket(")", {column: u.column + 1, row: u.row}); if (l !== null && h.isAutoInsertedClosing(u, a, i))return h.popAutoInsertedClosing(), {text: "", selection: [1, 1]} } } }), this.add("parens", "deletion", function (e, t, n, r, i) { var s = r.doc.getTextRange(i); if (!i.isMultiLine() && s == "(") { c(n); var o = r.doc.getLine(i.start.row), u = o.substring(i.start.column + 1, i.start.column + 2); if (u == ")")return i.end.column++, i } }), this.add("brackets", "insertion", function (e, t, n, r, i) { if (i == "[") { c(n); var s = n.getSelectionRange(), o = r.doc.getTextRange(s); if (o !== "" && n.getWrapBehavioursEnabled())return{text: "[" + o + "]", selection: !1}; if (h.isSaneInsertion(n, r))return h.recordAutoInsert(n, r, "]"), {text: "[]", selection: [1, 1]} } else if (i == "]") { c(n); var u = n.getCursorPosition(), a = r.doc.getLine(u.row), f = a.substring(u.column, u.column + 1); if (f == "]") { var l = r.$findOpeningBracket("]", {column: u.column + 1, row: u.row}); if (l !== null && h.isAutoInsertedClosing(u, a, i))return h.popAutoInsertedClosing(), {text: "", selection: [1, 1]} } } }), this.add("brackets", "deletion", function (e, t, n, r, i) { var s = r.doc.getTextRange(i); if (!i.isMultiLine() && s == "[") { c(n); var o = r.doc.getLine(i.start.row), u = o.substring(i.start.column + 1, i.start.column + 2); if (u == "]")return i.end.column++, i } }), this.add("string_dquotes", "insertion", function (e, t, n, r, i) { if (i == '"' || i == "'") { c(n); var s = i, o = n.getSelectionRange(), u = r.doc.getTextRange(o); if (u !== "" && u !== "'" && u != '"' && n.getWrapBehavioursEnabled())return{text: s + u + s, selection: !1}; var a = n.getCursorPosition(), f = r.doc.getLine(a.row), l = f.substring(a.column - 1, a.column); if (l == "\\")return null; var p = r.getTokens(o.start.row), d = 0, v, m = -1; for (var g = 0; g < p.length; g++) { v = p[g], v.type == "string" ? m = -1 : m < 0 && (m = v.value.indexOf(s)); if (v.value.length + d > o.start.column)break; d += p[g].value.length } if (!v || m < 0 && v.type !== "comment" && (v.type !== "string" || o.start.column !== v.value.length + d - 1 && v.value.lastIndexOf(s) === v.value.length - 1)) { if (!h.isSaneInsertion(n, r))return; return{text: s + s, selection: [1, 1]} } if (v && v.type === "string") { var y = f.substring(a.column, a.column + 1); if (y == s)return{text: "", selection: [1, 1]} } } }), this.add("string_dquotes", "deletion", function (e, t, n, r, i) { var s = r.doc.getTextRange(i); if (!i.isMultiLine() && (s == '"' || s == "'")) { c(n); var o = r.doc.getLine(i.start.row), u = o.substring(i.start.column + 1, i.start.column + 2); if (u == s)return i.end.column++, i } }) }; h.isSaneInsertion = function (e, t) { var n = e.getCursorPosition(), r = new s(t, n.row, n.column); if (!this.$matchTokenType(r.getCurrentToken() || "text", u)) { var i = new s(t, n.row, n.column + 1); if (!this.$matchTokenType(i.getCurrentToken() || "text", u))return!1 } return r.stepForward(), r.getCurrentTokenRow() !== n.row || this.$matchTokenType(r.getCurrentToken() || "text", a) }, h.$matchTokenType = function (e, t) { return t.indexOf(e.type || e) > -1 }, h.recordAutoInsert = function (e, t, n) { var r = e.getCursorPosition(), i = t.doc.getLine(r.row); this.isAutoInsertedClosing(r, i, f.autoInsertedLineEnd[0]) || (f.autoInsertedBrackets = 0), f.autoInsertedRow = r.row, f.autoInsertedLineEnd = n + i.substr(r.column), f.autoInsertedBrackets++ }, h.recordMaybeInsert = function (e, t, n) { var r = e.getCursorPosition(), i = t.doc.getLine(r.row); this.isMaybeInsertedClosing(r, i) || (f.maybeInsertedBrackets = 0), f.maybeInsertedRow = r.row, f.maybeInsertedLineStart = i.substr(0, r.column) + n, f.maybeInsertedLineEnd = i.substr(r.column), f.maybeInsertedBrackets++ }, h.isAutoInsertedClosing = function (e, t, n) { return f.autoInsertedBrackets > 0 && e.row === f.autoInsertedRow && n === f.autoInsertedLineEnd[0] && t.substr(e.column) === f.autoInsertedLineEnd }, h.isMaybeInsertedClosing = function (e, t) { return f.maybeInsertedBrackets > 0 && e.row === f.maybeInsertedRow && t.substr(e.column) === f.maybeInsertedLineEnd && t.substr(0, e.column) == f.maybeInsertedLineStart }, h.popAutoInsertedClosing = function () { f.autoInsertedLineEnd = f.autoInsertedLineEnd.substr(1), f.autoInsertedBrackets-- }, h.clearMaybeInsertedClosing = function () { f && (f.maybeInsertedBrackets = 0, f.maybeInsertedRow = -1) }, r.inherits(h, i), t.CstyleBehaviour = h }), ace.define("ace/mode/folding/cstyle", ["require", "exports", "module", "ace/lib/oop", "ace/range", "ace/mode/folding/fold_mode"], function (e, t, n) { var r = e("../../lib/oop"), i = e("../../range").Range, s = e("./fold_mode").FoldMode, o = t.FoldMode = function (e) { e && (this.foldingStartMarker = new RegExp(this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + e.start)), this.foldingStopMarker = new RegExp(this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + e.end))) }; r.inherits(o, s), function () { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/, this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/, this.getFoldWidgetRange = function (e, t, n, r) { var i = e.getLine(n), s = i.match(this.foldingStartMarker); if (s) { var o = s.index; if (s[1])return this.openingBracketBlock(e, s[1], n, o); var u = e.getCommentFoldRange(n, o + s[0].length, 1); return u && !u.isMultiLine() && (r ? u = this.getSectionRange(e, n) : t != "all" && (u = null)), u } if (t === "markbegin")return; var s = i.match(this.foldingStopMarker); if (s) { var o = s.index + s[0].length; return s[1] ? this.closingBracketBlock(e, s[1], n, o) : e.getCommentFoldRange(n, o, -1) } }, this.getSectionRange = function (e, t) { var n = e.getLine(t), r = n.search(/\S/), s = t, o = n.length; t += 1; var u = t, a = e.getLength(); while (++t < a) { n = e.getLine(t); var f = n.search(/\S/); if (f === -1)continue; if (r > f)break; var l = this.getFoldWidgetRange(e, "all", t); if (l) { if (l.start.row <= s)break; if (l.isMultiLine())t = l.end.row; else if (r == f)break } u = t } return new i(s, o, u, e.getLine(u).length) } }.call(o.prototype) })
Java
<?php class TreeNode { public $text = ""; public $id = ""; public $iconCls = ""; public $leaf = true; public $draggable = false; public $href = "#"; public $hrefTarget = ""; function __construct($id,$text,$iconCls,$leaf,$draggable,$href,$hrefTarget) { $this->id = $id; $this->text = $text; $this->iconCls = $iconCls; $this->leaf = $leaf; $this->draggable = $draggable; $this->href = $href; $this->hrefTarget = $hrefTarget; } function toJson() { return G::json_encode($this); } } class ExtJsTreeNode extends TreeNode { public $children = array(); function add($object) { $this->children[] = $object; } function toJson() { return G::json_encode($this); } } G::LoadClass('case'); $o = new Cases(); $PRO_UID = $_SESSION['PROCESS']; $treeArray = array(); //if (isset($_GET['action'])&&$_GET['action']=='test'){ echo "["; // dynaforms assemble $extTreeDynaforms = new ExtJsTreeNode("node-dynaforms", G::loadtranslation('ID_DYNAFORMS'), "", false, false, "", ""); $i = 0; $APP_UID = $_GET['APP_UID']; $DEL_INDEX = $_GET['DEL_INDEX']; $steps = $o->getAllDynaformsStepsToRevise($_GET['APP_UID']); $steps->next(); while ($step = $steps->getRow()) { require_once 'classes/model/Dynaform.php'; $od = new Dynaform(); $dynaformF = $od->Load($step['STEP_UID_OBJ']); $n = $step['STEP_POSITION']; $TITLE = " - ".$dynaformF['DYN_TITLE']; $DYN_UID = $dynaformF['DYN_UID']; $href = "cases_StepToRevise?type=DYNAFORM&ex=$i&PRO_UID=$PRO_UID&DYN_UID=$DYN_UID&APP_UID=$APP_UID&position=".$step['STEP_POSITION']."&DEL_INDEX=$DEL_INDEX"; $extTreeDynaforms->add(new TreeNode($DYN_UID,$TITLE,"datasource",true,false,$href,"openCaseFrame")); $i++; $steps->next(); } echo $extTreeDynaforms->toJson(); // end the dynaforms tree menu echo ","; // assembling the input documents tree menu $extTreeInputDocs = new ExtJsTreeNode("node-input-documents", G::loadtranslation('ID_REQUEST_DOCUMENTS'), "", false, false, "", ""); $i = 0; $APP_UID = $_GET['APP_UID']; $DEL_INDEX = $_GET['DEL_INDEX']; $steps = $o->getAllInputsStepsToRevise($_GET['APP_UID']); $steps->next(); while ($step = $steps->getRow()) { require_once 'classes/model/InputDocument.php'; $od = new InputDocument(); $IDF = $od->Load($step['STEP_UID_OBJ']); $n = $step['STEP_POSITION']; $TITLE = " - ".$IDF['INP_DOC_TITLE']; $INP_DOC_UID = $IDF['INP_DOC_UID']; $href = "cases_StepToReviseInputs?type=INPUT_DOCUMENT&ex=$i&PRO_UID=$PRO_UID&INP_DOC_UID=$INP_DOC_UID&APP_UID=$APP_UID&position=".$step['STEP_POSITION']."&DEL_INDEX=$DEL_INDEX"; $extTreeInputDocs->add(new TreeNode($INP_DOC_UID,$TITLE,"datasource",true,false,$href,"openCaseFrame")); $i++; $steps->next(); } echo $extTreeInputDocs->toJson(); echo "]";
Java
# Northerner Cyril # Welcome to the Northerner! This is the reference implementation for a server-client, token-based online architecture of the game Carcassonne. You may want to look into our [Wiki][] or jump to the [Protocol][] [Wiki]: https://github.com/BenWiederhake/northerner-cyril/wiki [Protocol]: https://github.com/BenWiederhake/northerner-cyril/wiki/Protocol
Java
<?php namespace CloudDataService\NHSNumberValidation\Test; use CloudDataService\NHSNumberValidation\Test\TestCase; use CloudDataService\NHSNumberValidation\Validator; class ValidatorTest extends TestCase { public function testInit() { $validator = new Validator; $this->assertTrue(is_object($validator)); } public function testHasFunction() { $validator = new Validator; $this->assertTrue( method_exists($validator, 'validate'), 'Class does not have method validate' ); } public function testValidateNoNumber() { $validator = new Validator; $this->assertTrue(is_object($validator)); try { $valid = $validator->validate(); } catch (\CloudDataService\NHSNumberValidation\InvalidNumberException $e) { return; } } public function testValidateNumberTooShort() { $validator = new Validator; $this->assertTrue(is_object($validator)); try { $valid = $validator->validate(0123); } catch (\CloudDataService\NHSNumberValidation\InvalidNumberException $e) { return; } } public function testValidateNumberTooLong() { $validator = new Validator; $this->assertTrue(is_object($validator)); try { $valid = $validator->validate('01234567890'); } catch (\CloudDataService\NHSNumberValidation\InvalidNumberException $e) { return; } } public function testValidNumber() { $validator = new Validator; $this->assertTrue(is_object($validator)); try { $valid = $validator->validate(4010232137); } catch (\CloudDataService\NHSNumberValidation\InvalidNumberException $e) { return false; } $this->assertEquals(4010232137, $valid); } public function testValidNumberWithBadChecksum() { $validator = new Validator; $this->assertTrue(is_object($validator)); try { $valid = $validator->validate(4010232138); } catch (\CloudDataService\NHSNumberValidation\InvalidNumberException $e) { return false; } } public function testValidNumberWithBadChecksumEqualsTen() { $validator = new Validator; $this->assertTrue(is_object($validator)); try { $valid = $validator->validate(1000000010); } catch (\CloudDataService\NHSNumberValidation\InvalidNumberException $e) { return false; } } public function testValidNumberWithBadChecksumEqualsEleven() { $validator = new Validator; $this->assertTrue(is_object($validator)); try { $valid = $validator->validate(1000000060); } catch (\CloudDataService\NHSNumberValidation\InvalidNumberException $e) { return false; } } public function testValidNumberWithSpaces() { $validator = new Validator; $this->assertTrue(is_object($validator)); try { $valid = $validator->validate("401 023 2137"); } catch (\CloudDataService\NHSNumberValidation\InvalidNumberException $e) { return false; } $this->assertEquals(4010232137, $valid); } public function testValidNumberWithNonAlphaNumeric() { $validator = new Validator; $this->assertTrue(is_object($validator)); try { $valid = $validator->validate("401-023-2137"); } catch (\CloudDataService\NHSNumberValidation\InvalidNumberException $e) { return false; } $this->assertEquals(4010232137, $valid); } }
Java
# Copyright (C) 2021 OpenMotics BV # # 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/>. """ apartment controller manages the apartment objects that are known in the system """ import logging from gateway.events import EsafeEvent, EventError from gateway.exceptions import ItemDoesNotExistException, StateException from gateway.models import Apartment, Database from gateway.mappers import ApartmentMapper from gateway.dto import ApartmentDTO from gateway.pubsub import PubSub from ioc import INJECTED, Inject, Injectable, Singleton if False: # MyPy from typing import List, Optional, Dict, Any from esafe.rebus import RebusController logger = logging.getLogger(__name__) @Injectable.named('apartment_controller') @Singleton class ApartmentController(object): def __init__(self): self.rebus_controller = None # type: Optional[RebusController] def set_rebus_controller(self, rebus_controller): self.rebus_controller = rebus_controller @staticmethod @Inject def send_config_change_event(msg, error=EventError.ErrorTypes.NO_ERROR, pubsub=INJECTED): # type: (str, Dict[str, Any], PubSub) -> None event = EsafeEvent(EsafeEvent.Types.CONFIG_CHANGE, {'type': 'apartment', 'msg': msg}, error=error) pubsub.publish_esafe_event(PubSub.EsafeTopics.CONFIG, event) @staticmethod def load_apartment(apartment_id): # type: (int) -> Optional[ApartmentDTO] apartment_orm = Apartment.select().where(Apartment.id == apartment_id).first() if apartment_orm is None: return None apartment_dto = ApartmentMapper.orm_to_dto(apartment_orm) return apartment_dto @staticmethod def load_apartment_by_mailbox_id(mailbox_id): # type: (int) -> Optional[ApartmentDTO] apartment_orm = Apartment.select().where(Apartment.mailbox_rebus_id == mailbox_id).first() if apartment_orm is None: return None apartment_dto = ApartmentMapper.orm_to_dto(apartment_orm) return apartment_dto @staticmethod def load_apartment_by_doorbell_id(doorbell_id): # type: (int) -> Optional[ApartmentDTO] apartment_orm = Apartment.select().where(Apartment.doorbell_rebus_id == doorbell_id).first() if apartment_orm is None: return None apartment_dto = ApartmentMapper.orm_to_dto(apartment_orm) return apartment_dto @staticmethod def load_apartments(): # type: () -> List[ApartmentDTO] apartments = [] for apartment_orm in Apartment.select(): apartment_dto = ApartmentMapper.orm_to_dto(apartment_orm) apartments.append(apartment_dto) return apartments @staticmethod def get_apartment_count(): # type: () -> int return Apartment.select().count() @staticmethod def apartment_id_exists(apartment_id): # type: (int) -> bool apartments = ApartmentController.load_apartments() ids = (x.id for x in apartments) return apartment_id in ids def _check_rebus_ids(self, apartment_dto): if self.rebus_controller is None: raise StateException("Cannot save apartment: Rebus Controller is None") if 'doorbell_rebus_id' in apartment_dto.loaded_fields and \ not self.rebus_controller.verify_device_exists(apartment_dto.doorbell_rebus_id): raise ItemDoesNotExistException("Cannot save apartment: doorbell ({}) does not exists".format(apartment_dto.doorbell_rebus_id)) if 'mailbox_rebus_id' in apartment_dto.loaded_fields and \ not self.rebus_controller.verify_device_exists(apartment_dto.mailbox_rebus_id): raise ItemDoesNotExistException("Cannot save apartment: mailbox ({}) does not exists".format(apartment_dto.mailbox_rebus_id)) def save_apartment(self, apartment_dto, send_event=True): # type: (ApartmentDTO, bool) -> ApartmentDTO self._check_rebus_ids(apartment_dto) apartment_orm = ApartmentMapper.dto_to_orm(apartment_dto) apartment_orm.save() if send_event: ApartmentController.send_config_change_event('save') return ApartmentMapper.orm_to_dto(apartment_orm) def save_apartments(self, apartments_dto): apartments_dtos = [] for apartment in apartments_dto: apartment_saved = self.save_apartment(apartment, send_event=False) apartments_dtos.append(apartment_saved) self.send_config_change_event('save') return apartments_dtos def update_apartment(self, apartment_dto, send_event=True): # type: (ApartmentDTO, bool) -> ApartmentDTO self._check_rebus_ids(apartment_dto) if 'id' not in apartment_dto.loaded_fields or apartment_dto.id is None: raise RuntimeError('cannot update an apartment without the id being set') try: apartment_orm = Apartment.get_by_id(apartment_dto.id) loaded_apartment_dto = ApartmentMapper.orm_to_dto(apartment_orm) for field in apartment_dto.loaded_fields: if field == 'id': continue if hasattr(apartment_dto, field): setattr(loaded_apartment_dto, field, getattr(apartment_dto, field)) apartment_orm = ApartmentMapper.dto_to_orm(loaded_apartment_dto) apartment_orm.save() if send_event: ApartmentController.send_config_change_event('update') return ApartmentMapper.orm_to_dto(apartment_orm) except Exception as e: raise RuntimeError('Could not update the user: {}'.format(e)) def update_apartments(self, apartment_dtos): # type: (List[ApartmentDTO]) -> Optional[List[ApartmentDTO]] apartments = [] with Database.get_db().transaction() as transaction: try: # First clear all the rebus fields in order to be able to swap 2 fields for apartment in apartment_dtos: apartment_orm = Apartment.get_by_id(apartment.id) # type: Apartment if 'mailbox_rebus_id' in apartment.loaded_fields: apartment_orm.mailbox_rebus_id = None if 'doorbell_rebus_id' in apartment.loaded_fields: apartment_orm.doorbell_rebus_id = None apartment_orm.save() # Then check if there is already an apartment with an mailbox or doorbell rebus id that is passed # This is needed for when an doorbell or mailbox gets assigned to another apartment. Then the first assignment needs to be deleted. for apartment_orm in Apartment.select(): for apartment_dto in apartment_dtos: if apartment_orm.mailbox_rebus_id == apartment_dto.mailbox_rebus_id and apartment_orm.mailbox_rebus_id is not None: apartment_orm.mailbox_rebus_id = None apartment_orm.save() if apartment_orm.doorbell_rebus_id == apartment_dto.doorbell_rebus_id and apartment_orm.doorbell_rebus_id is not None: apartment_orm.doorbell_rebus_id = None apartment_orm.save() for apartment in apartment_dtos: updated = self.update_apartment(apartment, send_event=False) if updated is not None: apartments.append(updated) self.send_config_change_event('update') except Exception as ex: logger.error('Could not update apartments: {}: {}'.format(type(ex).__name__, ex)) transaction.rollback() return None return apartments @staticmethod def delete_apartment(apartment_dto): # type: (ApartmentDTO) -> None if "id" in apartment_dto.loaded_fields and apartment_dto.id is not None: Apartment.delete_by_id(apartment_dto.id) elif "name" in apartment_dto.loaded_fields: # First check if there is only one: if Apartment.select().where(Apartment.name == apartment_dto.name).count() <= 1: Apartment.delete().where(Apartment.name == apartment_dto.name).execute() ApartmentController.send_config_change_event('delete') else: raise RuntimeError('More than one apartment with the given name: {}'.format(apartment_dto.name)) else: raise RuntimeError('Could not find an apartment with the name {} to delete'.format(apartment_dto.name))
Java
<?php /** * BaseContact class * * @author Carlos Palma <chonwil@gmail.com> */ abstract class BaseContact extends ContentDataObject { // ------------------------------------------------------- // Access methods // ------------------------------------------------------- /** * Return value of 'id' field * * @access public * @param void * @return integer */ function getObjectId() { return $this->getColumnValue('object_id'); } // getObjectId() /** * Set value of 'id' field * * @access public * @param integer $value * @return boolean */ function setObjectId($value) { return $this->setColumnValue('object_id', $value); } // setObjectId() /** * Return value of 'first_name' field * * @access public * @param void * @return string */ function getFirstName() { return $this->getColumnValue('first_name'); } // getFirstName() /** * Set value of 'first_name' field * * @access public * @param string $value * @return boolean */ function setFirstName($value) { return $this->setColumnValue('first_name', $value); } // setFirstName() /** * Return value of 'surname' field * * @access public * @param void * @return string */ function getSurname() { return $this->getColumnValue('surname'); } // getSurname() /** * Set value of 'surname' field * * @access public * @param string $value * @return boolean */ function setSurname($value) { return $this->setColumnValue('surname', $value); } // setSurname() /** * Return value of 'company_id' field * * @access public * @param void * @return integer */ function getCompanyId() { return $this->getColumnValue('company_id'); } // getCompanyId() /** * Set value of 'company_id' field * * @access public * @param integer $value * @return boolean */ function setCompanyId($value) { return $this->setColumnValue('company_id', $value); } // setCompanyId() /** * Return value of 'is_company' field * * @access public * @param void * @return boolean */ function getIsCompany() { return $this->getColumnValue('is_company'); } // getIsCompany() /** * Set value of 'is_company' field * * @access public * @param boolean $value * @return boolean */ function setIsCompany($value) { return $this->setColumnValue('is_company', $value); } // setIsCompany() /** * Return value of 'user_type' field * * @access public * @param void * @return boolean */ function getUserType() { return $this->getColumnValue('user_type'); } // getUserType() /** * Set value of 'user_type' field * * @access public * @param boolean $value * @return boolean */ function setUserType($value) { return $this->setColumnValue('user_type', $value); } // setUserType() /** * Return value of 'birthday' field * * @access public * @param void * @return datetimevalue */ function getBirthday() { return $this->getColumnValue('birthday'); } // getBirthday() /** * Set value of 'birthday' field * * @access public * @param datetimevalue $value * @return boolean */ function setBirthday($value) { return $this->setColumnValue('birthday', $value); } // setBirthday() /** * Return value of 'department' field * * @access public * @param void * @return string */ function getDepartment() { return $this->getColumnValue('department'); } // getDepartment() /** * Set value of 'department' field * * @access public * @param string $value * @return boolean */ function setDepartment($value) { return $this->setColumnValue('department', $value); } // setDepartment() /** * Return value of 'job_title' field * * @access public * @param void * @return string */ function getJobTitle() { return $this->getColumnValue('job_title'); } // getJobTitle() /** * Set value of 'job_title' field * * @access public * @param string $value * @return boolean */ function setJobTitle($value) { return $this->setColumnValue('job_title', $value); } // setJobTitle() /** * Return value of 'timezone' field * * @access public * @param void * @return float */ function getTimezone() { return $this->getColumnValue('timezone'); } // getTimezone() /** * Set value of 'timezone' field * * @access public * @param float $value * @return boolean */ function setTimezone($value) { return $this->setColumnValue('timezone', $value); } // setTimezone() /** * Return value of 'is_active_user' field * * @access public * @param void * @return boolean */ function getIsActiveUser() { return $this->getColumnValue('is_active_user'); } // getIsActiveUser() /** * Set value of 'is_active_user' field * * @access public * @param boolean $value * @return boolean */ function setIsActiveUser($value) { return $this->setColumnValue('is_active_user', $value); } // setIsActiveUser() /** * Return value of 'token' field * * @access public * @param void * @return string */ function getToken() { return $this->getColumnValue('token'); } // getToken() /** * Set value of 'token' field * * @access public * @param string $value * @return boolean */ function setToken($value) { return $this->setColumnValue('token', $value); } // setToken() /** * Return value of 'salt' field * * @access public * @param void * @return string */ function getSalt() { return $this->getColumnValue('salt'); } // getSalt() /** * Set value of 'salt' field * * @access public * @param string $value * @return boolean */ function setSalt($value) { return $this->setColumnValue('salt', $value); } // setSalt() /** * Return value of 'twister' field * * @access public * @param void * @return string */ function getTwister() { return $this->getColumnValue('twister'); } // getTwister() /** * Set value of 'twister' field * * @access public * @param string $value * @return boolean */ function setTwister($value) { return $this->setColumnValue('twister', $value); } // setTwister() /** * Return value of 'display_name' field * * @access public * @param void * @return string */ function getDisplayName() { return $this->getColumnValue('display_name'); } // getDisplayName() /** * Set value of 'display_name' field * * @access public * @param string $value * @return boolean */ function setDisplayName($value) { return $this->setColumnValue('display_name', $value); } // setDisplayName() /** * Return value of 'permission_group_id' field * * @access public * @param void * @return integer */ function getPermissionGroupId() { return $this->getColumnValue('permission_group_id'); } // getPermissionGroupId() /** * Set value of 'permission_group_id' field * * @access public * @param integer $value * @return boolean */ function setPermissionGroupId($value) { return $this->setColumnValue('permission_group_id', $value); } // setPermissionGroupId() /** * Return value of 'username' field * * @access public * @param void * @return string */ function getUsername() { return $this->getColumnValue('username'); } // getUsername() /** * Set value of 'username' field * * @access public * @param string $value * @return boolean */ function setUsername($value) { return $this->setColumnValue('username', $value); } // setUsername() /** * Return value of 'contact_passwords_id' field * * @access public * @param void * @return string */ function getContactPasswordsId() { return $this->getColumnValue('contact_passwords_id'); } // getContactPasswordsId() /** * Set value of 'contact_passwords_id' field * * @access public * @param string $value * @return boolean */ function setContactPasswordsId($value) { return $this->setColumnValue('contact_passwords_id', $value); } // setContactPasswordsId() /** * Return value of 'comments' field * * @access public * @param void * @return string */ function getCommentsField() { return $this->getColumnValue('comments'); } // getCommentsField() /** * Set value of 'comments' field * * @access public * @param string $value * @return boolean */ function setCommentsField($value) { return $this->setColumnValue('comments', $value); } // setCommentsField() /** * Return value of 'picture_file' field * * @access public * @param void * @return string */ function getPictureFile() { return $this->getColumnValue('picture_file'); } // getPictureFile() /** * Set value of 'picture_file' field * * @access public * @param string $value * @return boolean */ function setPictureFile($value) { return $this->setColumnValue('picture_file', $value); } // setPictureFile() function getPictureFileSmall() { return $this->getColumnValue('picture_file_small'); } function setPictureFileSmall($value) { return $this->setColumnValue('picture_file_small', $value); } function getPictureFileMedium() { return $this->getColumnValue('picture_file_medium'); } function setPictureFileMedium($value) { return $this->setColumnValue('picture_file_medium', $value); } /** * Return value of 'avatar_file' field * * @access public * @param void * @return string */ function getAvatarFile() { return $this->getColumnValue('avatar_file'); } // getAvatarFile() /** * Set value of 'avatar_file' field * * @access public * @param string $value * @return boolean */ function setAvatarFile($value) { return $this->setColumnValue('avatar_file', $value); } // setAvatarFile() /** * Return value of 'last_login' field * * @access public * @param void * @return DateTimeValue */ function getLastLogin() { return $this->getColumnValue('last_login'); } // getLastLogin() /** * Set value of 'last_login' field * * @access public * @param DateTimeValue $value * @return boolean */ function setLastLogin(DateTimeValue $value) { return $this->setColumnValue('last_login', $value); } // setLastLogin() /** * Return value of 'last_visit' field * * @access public * @param void * @return DateTimeValue */ function getLastVisit() { return $this->getColumnValue('last_visit'); } // getLastVisit() /** * Set value of 'last_visit' field * * @access public * @param DateTimeValue $value * @return boolean */ function setLastVisit($value) { return $this->setColumnValue('last_visit', $value); } // setLastVisit() /** * Return value of 'last_activity' field * * @access public * @param void * @return DateTimeValue */ function getLastActivity() { return $this->getColumnValue('last_activity'); } // getLastActivity() /** * Set value of 'last_activity' field * * @access public * @param DateTimeValue $value * @return boolean */ function setLastActivity($value) { return $this->setColumnValue('last_activity', $value); } // setLastActivity() /** * Return value of 'personal_member_id' field * * @access public * @param void * @return integer */ function getPersonalMemberId() { return $this->getColumnValue('personal_member_id'); } // getPersonalMemberId() /** * Set value of 'personal_member_id' field * * @access public * @param integer $value * @return boolean */ function setPersonalMemberId($value) { return $this->setColumnValue('personal_member_id', $value); } // setPersonalMemberId() /** * Return value of 'disabled' field * * @access public * @param void * @return integer */ function getDisabled() { return $this->getColumnValue('disabled'); } // getDisabled() /** * Set value of 'disabled' field * * @access public * @param integer $value * @return boolean */ function setDisabled($value) { return $this->setColumnValue('disabled', $value); } // setDisabled() /** * Return value of 'token_disabled' field * * @access public * @param void * @return string */ function getTokenDisabled() { return $this->getColumnValue('token_disabled'); } // getTokenDisabled() /** * Set value of 'token_disabled' field * * @access public * @param string $value * @return boolean */ function setTokenDisabled($value) { return $this->setColumnValue('token_disabled', $value); } // setTokenDisabled() /** * Return value of 'default_billing_id' field * * @access public * @param void * @return integer */ function getDefaultBillingId() { return $this->getColumnValue('default_billing_id'); } // getDefaultBillingId() /** * Set value of 'default_billing_id' field * * @access public * @param integer $value * @return boolean */ function setDefaultBillingId($value) { return $this->setColumnValue('default_billing_id', $value); } // setDefaultBillingId() function getUserTimezoneId() { return $this->getColumnValue('user_timezone_id'); } function setUserTimezoneId($value) { return $this->setColumnValue('user_timezone_id', $value); } /** * Return manager instance * * @access protected * @param void * @return Contacts */ function manager() { if(!($this->manager instanceof Contacts)) $this->manager = Contacts::instance(); return $this->manager; } // manager } // BaseContact ?>
Java
<?php /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ require_once('data/SugarBean.php'); require_once('modules/Contacts/Contact.php'); require_once('include/SubPanel/SubPanelDefinitions.php'); class Bug41738Test extends Sugar_PHPUnit_Framework_TestCase { protected $bean; public function setUp() { global $moduleList, $beanList, $beanFiles; require('include/modules.php'); $GLOBALS['current_user'] = SugarTestUserUtilities::createAnonymousUser(); $GLOBALS['modListHeader'] = query_module_access_list($GLOBALS['current_user']); $GLOBALS['modules_exempt_from_availability_check']['Calls']='Calls'; $GLOBALS['modules_exempt_from_availability_check']['Meetings']='Meetings'; $this->bean = new Opportunity(); } public function tearDown() { SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); unset($GLOBALS['current_user']); } public function testSubpanelCollectionWithSpecificQuery() { $subpanel = array( 'order' => 20, 'sort_order' => 'desc', 'sort_by' => 'date_entered', 'type' => 'collection', 'subpanel_name' => 'history', //this values is not associated with a physical file. 'top_buttons' => array(), 'collection_list' => array( 'meetings' => array( 'module' => 'Meetings', 'subpanel_name' => 'ForHistory', 'get_subpanel_data' => 'function:subpanelCollectionWithSpecificQueryMeetings', 'generate_select'=>false, 'function_parameters' => array( 'bean_id'=>$this->bean->id, 'import_function_file' => __FILE__ ), ), 'tasks' => array( 'module' => 'Tasks', 'subpanel_name' => 'ForHistory', 'get_subpanel_data' => 'function:subpanelCollectionWithSpecificQueryTasks', 'generate_select'=>false, 'function_parameters' => array( 'bean_id'=>$this->bean->id, 'import_function_file' => __FILE__ ), ), ) ); $subpanel_def = new aSubPanel("testpanel", $subpanel, $this->bean); $query = $this->bean->get_union_related_list($this->bean, "", '', "", 0, 5, -1, 0, $subpanel_def); $result = $this->bean->db->query($query["query"]); $this->assertTrue($result != false, "Bad query: {$query['query']}"); } } function subpanelCollectionWithSpecificQueryMeetings($params) { $query = "SELECT meetings.id , meetings.name , meetings.status , 0 reply_to_status , ' ' contact_name , ' ' contact_id , ' ' contact_name_owner , ' ' contact_name_mod , meetings.parent_id , meetings.parent_type , meetings.date_modified , jt1.user_name assigned_user_name , jt1.created_by assigned_user_name_owner , 'Users' assigned_user_name_mod, ' ' filename , meetings.assigned_user_id , 'meetings' panel_name FROM meetings LEFT JOIN users jt1 ON jt1.id= meetings.assigned_user_id AND jt1.deleted=0 AND jt1.deleted=0 WHERE ( meetings.parent_type = 'Opportunities' AND meetings.deleted=0 AND (meetings.status='Held' OR meetings.status='Not Held') AND meetings.parent_id IN( SELECT o.id FROM opportunities o INNER JOIN opportunities_contacts oc on o.id = oc.opportunity_id AND oc.contact_id = '".$params['bean_id']."') )"; return $query ; } function subpanelCollectionWithSpecificQueryTasks($params) { $query = "SELECT tasks.id , tasks.name , tasks.status , 0 reply_to_status , ' ' contact_name , ' ' contact_id , ' ' contact_name_owner , ' ' contact_name_mod , tasks.parent_id , tasks.parent_type , tasks.date_modified , jt1.user_name assigned_user_name , jt1.created_by assigned_user_name_owner , 'Users' assigned_user_name_mod, ' ' filename , tasks.assigned_user_id , 'tasks' panel_name FROM tasks LEFT JOIN users jt1 ON jt1.id= tasks.assigned_user_id AND jt1.deleted=0 AND jt1.deleted=0 WHERE ( tasks.parent_type = 'Opportunities' AND tasks.deleted=0 AND (tasks.status='Completed' OR tasks.status='Deferred') AND tasks.parent_id IN( SELECT o.id FROM opportunities o INNER JOIN opportunities_contacts oc on o.id = oc.opportunity_id AND oc.contact_id = '".$params['bean_id']."') )"; return $query ; }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="es"> <head> <!-- Generated by javadoc (1.8.0_122-ea) on Thu Jan 19 17:37:21 CET 2017 --> <title>Uses of Class me.Bn32w.Bn32wEngine.entity.collision.CollisionBox</title> <meta name="date" content="2017-01-19"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class me.Bn32w.Bn32wEngine.entity.collision.CollisionBox"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <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="../../../../../../me/Bn32w/Bn32wEngine/entity/collision/CollisionBox.html" title="class in me.Bn32w.Bn32wEngine.entity.collision">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-files/index-1.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?me/Bn32w/Bn32wEngine/entity/collision/class-use/CollisionBox.html" target="_top">Frames</a></li> <li><a href="CollisionBox.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;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 me.Bn32w.Bn32wEngine.entity.collision.CollisionBox" class="title">Uses of Class<br>me.Bn32w.Bn32wEngine.entity.collision.CollisionBox</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../me/Bn32w/Bn32wEngine/entity/collision/CollisionBox.html" title="class in me.Bn32w.Bn32wEngine.entity.collision">CollisionBox</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#me.Bn32w.Bn32wEngine.entity">me.Bn32w.Bn32wEngine.entity</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="me.Bn32w.Bn32wEngine.entity"> <!-- --> </a> <h3>Uses of <a href="../../../../../../me/Bn32w/Bn32wEngine/entity/collision/CollisionBox.html" title="class in me.Bn32w.Bn32wEngine.entity.collision">CollisionBox</a> in <a href="../../../../../../me/Bn32w/Bn32wEngine/entity/package-summary.html">me.Bn32w.Bn32wEngine.entity</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation"> <caption><span>Constructors in <a href="../../../../../../me/Bn32w/Bn32wEngine/entity/package-summary.html">me.Bn32w.Bn32wEngine.entity</a> with parameters of type <a href="../../../../../../me/Bn32w/Bn32wEngine/entity/collision/CollisionBox.html" title="class in me.Bn32w.Bn32wEngine.entity.collision">CollisionBox</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../me/Bn32w/Bn32wEngine/entity/Entity.html#Entity-me.Bn32w.Bn32wEngine.entity.collision.CollisionBox-java.lang.String-me.Bn32w.Bn32wEngine.states.State-boolean-">Entity</a></span>(<a href="../../../../../../me/Bn32w/Bn32wEngine/entity/collision/CollisionBox.html" title="class in me.Bn32w.Bn32wEngine.entity.collision">CollisionBox</a>&nbsp;pCollisionBox, java.lang.String&nbsp;identifier, <a href="../../../../../../me/Bn32w/Bn32wEngine/states/State.html" title="class in me.Bn32w.Bn32wEngine.states">State</a>&nbsp;state, boolean&nbsp;solid)</code> <div class="block">Creates a new entity, initializing all the bounds data by the information given in the parameter, the speed and acceleration is 0.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <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="../../../../../../me/Bn32w/Bn32wEngine/entity/collision/CollisionBox.html" title="class in me.Bn32w.Bn32wEngine.entity.collision">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-files/index-1.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?me/Bn32w/Bn32wEngine/entity/collision/class-use/CollisionBox.html" target="_top">Frames</a></li> <li><a href="CollisionBox.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;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 ======= --> </body> </html>
Java
<div class="split-content"> <div class="header"> <h2 translate>Templates</h2> <div class="pull-right"> <div class="sortbar pull-left"> <span class="lab" translate>Filter:</span> <div class="dropdown" dropdown sd-dropdown-position> <button id="order_button" class="dropdown-toggle" dropdown-toggle>{{ filters[activeFilter].label | translate }} <b class="caret"></b> </button> <ul class="dropdown-menu left-submenu" id="order_selector"> <li ng-repeat="f in filters track by $index" ng-class="{active: activeFilter === $index}"> <a href="" ng-click="filterBy($index)">{{ f.label | translate }}</a> </li> </ul> </div> </div> <button class="btn btn-info" ng-click="edit()"> <i class="icon-plus-sign icon-white"></i> <span translate>Add New Template</span> </button> </div> </div> <div class="content"> <div class="flex-grid box wrap-items small-2 medium-4 large-6"> <div class="flex-item card-box template-card" ng-repeat="template in content_templates._items | templatesBy:filters[activeFilter]" ng-if="desks"> <div class="card-box__header" ng-class="{'card-box__header--dark': !template.is_public}" > <div class="dropdown" dropdown> <button class="dropdown-toggle" dropdown-toggle> <i class="icon-dots-vertical"></i> </button> <ul class="dropdown-menu more-activity-menu pull-right"> <li><div class="menu-label" translate>Actions</div></li> <li class="divider"></li> <li><button ng-click="edit(template)" title="{{:: 'Edit Template' | translate }}"><i class="icon-pencil"></i>{{:: 'Edit'| translate}}</button></li> <li ng-if="template.template_type !== 'kill'"><button ng-click="remove(template)" title="{{:: 'Remove Template' | translate }}"><i class="icon-trash"></i>{{:: 'Remove'| translate}}</button></li> </ul> </div> <div class="card-box__heading">{{ template.template_name }}</div> </div> <div class="card-box__content"> <ul class="card-box__content-list"> <li> <h4 class="with-value">{{ :: 'Template type' | translate }} <span class="value-label">{{ template.template_type }}</span></h4> </li> <li ng-if="getTemplateDesk(template).name"> <h4>{{ :: 'Desk / Stage' | translate }}</h4> <span>{{getTemplateDesk(template).name}} / {{getTemplateStage(template).name}}</span> </li> <li ng-if="template.schedule.is_active"> <h4>{{ :: 'Automated item creation' | translate }}</h4> <span ng-repeat="day in template.schedule.day_of_week"> {{ :: weekdays[day] }} <span ng-if="$index < template.schedule.day_of_week.length-1">, </span> </span> <span class="creation-time"> <i class="icon-time"></i> at {{ template.schedule.create_at | time }}<span> </li> </ul> </div> </div> </div> </div> </div> <div sd-modal data-model="template" class="modal-responsive"> <div class="modal-header template-header"> <a href="" class="close" ng-click="cancel()"><i class="icon-close-small"></i></a> <h3 ng-show="template._id"><span translate>Edit Template</span><span>"{{ origTemplate.template_name }}"</span></h3> <h3 translate ng-hide="template._id" translate>Add New Template</h3> </div> <div class="modal-body"> <form name="templateForm"> <div class="main-article"> <div class="fieldset"> <div class="field"> <label for="template-name" translate>Template Name</label> <input id="template-name" required ng-model="template.template_name"> </div> <div class="field"> <label for="template-type" translate>Template Type</label> <select id="template-type" required ng-model="template.template_type" ng-options="type._id as type.label for type in types | filter:templatesFilter"></select> </div> <div class="field"> <label for="template-is-private" translate>Desk Template</label> <div class="control"> <span sd-switch ng-model="template.is_public"></span> </div> </div> <div class="field" ng-if="template.template_type !== 'kill' && content_types.length"> <label for="template-profile" translate>Content Profile</label> <div class="control"> <select id="template-profile" ng-model="item.profile" ng-options="type._id as type.label for type in content_types"></select> </div> </div> <div class="field" ng-if="template.template_type !== 'kill' && !content_types.length"> <label for="template-profile" translate>Content Profile</label> <div class="control"> <input type="text" id="template-profile" ng-model="item.profile"> </div> </div> <div class="field" ng-if="template.template_type !== 'kill' && template.is_public"> <label for="template-desk" translate>Desk</label> <div class="control"> <select id="template-desk" ng-model="template.template_desk" ng-change="updateStages(template.template_desk)"> <option value="" translate>None</option> <option ng-repeat="desk in desks._items track by desk._id" value="{{ desk._id }}" ng-selected="desk._id === template.template_desk">{{ :: desk.name }}</option> </select> </div> </div> <div class="field" ng-if="template.template_desk && stages && template.template_type !== 'kill' && template.is_public"> <label for="template-stage" translate>Stage</label> <div class="control"> <select id="template-stage" ng-model="template.template_stage"> <option ng-repeat="stage in stages track by stage._id" value="{{ stage._id }}" ng-selected="stage._id === template.template_stage">{{ :: stage.name }}</option> </select> </div> </div> <div class="field" ng-if="template.template_desk && template.template_type !== 'kill' && template.is_public"> <label for="schedule-toggle" translate>Automatically create item</label> <div class="control"> <span sd-switch ng-model="template.schedule.is_active"></span> </div> </div> <div class="field" ng-if="template.schedule.is_active && template.template_type !== 'kill'"> <label translate>On</label> <div class="day-filter-box clearfix" sd-weekday-picker data-model="template.schedule.day_of_week"></div> </div> <div class="field" ng-if="template.schedule.is_active && template.template_type !== 'kill'"> <label translate>At</label> <span sd-timepicker ng-model="template.schedule.create_at"></span> <div sd-timezone data-timezone="template.schedule.time_zone"></div> </div> </div> <div class="fieldset" sd-article-edit></div> </div> </form> </div> <div class="modal-footer"> <button class="btn btn-default" ng-click="cancel()" translate>Cancel</button> <button class="btn btn-primary" ng-click="save()" ng-disabled="templateForm.$invalid || (!templateForm.$invalid && !validSchedule())" translate>Save</button> </div> </div>
Java
<?php class MetadataPlugin extends KalturaPlugin { const PLUGIN_NAME = 'metadata'; const METADATA_FLOW_MANAGER_CLASS = 'kMetadataFlowManager'; const METADATA_COPY_HANDLER_CLASS = 'kMetadataObjectCopiedHandler'; const METADATA_DELETE_HANDLER_CLASS = 'kMetadataObjectDeletedHandler'; const BULK_UPLOAD_COLUMN_PROFILE_ID = 'metadataProfileId'; const BULK_UPLOAD_COLUMN_XML = 'metadataXml'; const BULK_UPLOAD_COLUMN_URL = 'metadataUrl'; const BULK_UPLOAD_COLUMN_FIELD_PREFIX = 'metadataField_'; const BULK_UPLOAD_MULTI_VALUES_DELIMITER = '|,|'; const BULK_UPLOAD_DATE_FORMAT = '%Y-%m-%dT%H:%i:%s'; /** * @return array<string,string> in the form array[serviceName] = serviceClass */ public static function getServicesMap() { $map = array( 'metadata' => 'MetadataService', 'metadataProfile' => 'MetadataProfileService', 'metadataBatch' => 'MetadataBatchService', ); return $map; } /** * @return string - the path to services.ct */ public static function getServiceConfig() { return realpath(dirname(__FILE__).'/config/metadata.ct'); } /** * @return array */ public static function getEventConsumers() { return array( self::METADATA_FLOW_MANAGER_CLASS, self::METADATA_COPY_HANDLER_CLASS, self::METADATA_DELETE_HANDLER_CLASS, ); } /** * @param KalturaPluginManager::OBJECT_TYPE $objectType * @param string $enumValue * @param array $constructorArgs * @return object */ public static function loadObject($objectType, $enumValue, array $constructorArgs = null) { if($objectType != KalturaPluginManager::OBJECT_TYPE_SYNCABLE) return null; if(!isset($constructorArgs['objectId'])) return null; $objectId = $constructorArgs['objectId']; switch($enumValue) { case FileSync::FILE_SYNC_OBJECT_TYPE_METADATA: MetadataPeer::setUseCriteriaFilter ( false ); $object = MetadataPeer::retrieveByPK( $objectId ); MetadataPeer::setUseCriteriaFilter ( true ); return $object; case FileSync::FILE_SYNC_OBJECT_TYPE_METADATA_PROFILE: MetadataProfilePeer::setUseCriteriaFilter ( false ); $object = MetadataProfilePeer::retrieveByPK( $objectId ); MetadataProfilePeer::setUseCriteriaFilter ( true ); return $object; } return null; } /** * @param array $fields * @return string */ private static function getDateFormatRegex(&$fields = null) { $replace = array( '%Y' => '([1-2][0-9]{3})', '%m' => '([0-1][0-9])', '%d' => '([0-3][0-9])', '%H' => '([0-2][0-9])', '%i' => '([0-5][0-9])', '%s' => '([0-5][0-9])', // '%T' => '([A-Z]{3})', ); $fields = array(); $arr = null; // if(!preg_match_all('/%([YmdTHis])/', self::BULK_UPLOAD_DATE_FORMAT, $arr)) if(!preg_match_all('/%([YmdHis])/', self::BULK_UPLOAD_DATE_FORMAT, $arr)) return false; $fields = $arr[1]; return '/' . str_replace(array_keys($replace), $replace, self::BULK_UPLOAD_DATE_FORMAT) . '/'; } /** * @param string $str * @return int */ private static function parseFormatedDate($str) { KalturaLog::debug("parseFormatedDate($str)"); if(function_exists('strptime')) { $ret = strptime($str, self::BULK_UPLOAD_DATE_FORMAT); if($ret) { KalturaLog::debug("Formated Date [$ret] " . date('Y-m-d\TH:i:s', $ret)); return $ret; } } $fields = null; $regex = self::getDateFormatRegex($fields); $values = null; if(!preg_match($regex, $str, $values)) return null; $hour = 0; $minute = 0; $second = 0; $month = 0; $day = 0; $year = 0; $is_dst = 0; foreach($fields as $index => $field) { $value = $values[$index + 1]; switch($field) { case 'Y': $year = intval($value); break; case 'm': $month = intval($value); break; case 'd': $day = intval($value); break; case 'H': $hour = intval($value); break; case 'i': $minute = intval($value); break; case 's': $second = intval($value); break; // case 'T': // $date = date_parse($value); // $hour -= ($date['zone'] / 60); // break; } } KalturaLog::debug("gmmktime($hour, $minute, $second, $month, $day, $year)"); $ret = gmmktime($hour, $minute, $second, $month, $day, $year); if($ret) { KalturaLog::debug("Formated Date [$ret] " . date('Y-m-d\TH:i:s', $ret)); return $ret; } KalturaLog::debug("Formated Date [null]"); return null; } /** * @param string $entryId the new created entry * @param array $data key => value pairs */ public static function handleBulkUploadData($entryId, array $data) { KalturaLog::debug("Handle metadata bulk upload data:\n" . print_r($data, true)); if(!isset($data[self::BULK_UPLOAD_COLUMN_PROFILE_ID])) return; $metadataProfileId = $data[self::BULK_UPLOAD_COLUMN_PROFILE_ID]; $xmlData = null; $entry = entryPeer::retrieveByPK($entryId); if(!$entry) return; $metadataProfile = MetadataProfilePeer::retrieveById($metadataProfileId); if(!$metadataProfile) { KalturaLog::info("Metadata profile [$metadataProfileId] not found"); return; } if(isset($data[self::BULK_UPLOAD_COLUMN_URL])) { try{ $xmlData = file_get_contents($data[self::BULK_UPLOAD_COLUMN_URL]); KalturaLog::debug("Metadata downloaded [" . $data[self::BULK_UPLOAD_COLUMN_URL] . "]"); } catch(Exception $e) { KalturaLog::err("Download metadata[" . $data[self::BULK_UPLOAD_COLUMN_URL] . "] error: " . $e->getMessage()); $xmlData = null; } } elseif(isset($data[self::BULK_UPLOAD_COLUMN_XML])) { $xmlData = $data[self::BULK_UPLOAD_COLUMN_XML]; } else { $metadataProfileFields = array(); MetadataProfileFieldPeer::setUseCriteriaFilter(false); $tmpMetadataProfileFields = MetadataProfileFieldPeer::retrieveByMetadataProfileId($metadataProfileId); MetadataProfileFieldPeer::setUseCriteriaFilter(true); foreach($tmpMetadataProfileFields as $metadataProfileField) $metadataProfileFields[$metadataProfileField->getKey()] = $metadataProfileField; KalturaLog::debug("Found fields [" . count($metadataProfileFields) . "] for metadata profile [$metadataProfileId]"); $xml = new DOMDocument(); $dataFound = false; foreach($data as $key => $value) { if(!$value || !strlen($value)) continue; if(!preg_match('/^' . self::BULK_UPLOAD_COLUMN_FIELD_PREFIX . '(.+)$/', $key, $matches)) continue; $key = $matches[1]; if(!isset($metadataProfileFields[$key])) { KalturaLog::debug("No field found for key[$key]"); continue; } $metadataProfileField = $metadataProfileFields[$key]; KalturaLog::debug("Found field [" . $metadataProfileField->getXpath() . "] for value [$value]"); if($metadataProfileField->getType() == MetadataSearchFilter::KMC_FIELD_TYPE_DATE && !is_numeric($value)) { $value = self::parseFormatedDate($value); if(!$value || !strlen($value)) continue; } $fieldValues = explode(self::BULK_UPLOAD_MULTI_VALUES_DELIMITER, $value); foreach($fieldValues as $fieldValue) self::addXpath($xml, $metadataProfileField->getXpath(), $fieldValue); $dataFound = true; } if($dataFound) { $xmlData = $xml->saveXML($xml->firstChild); $xmlData = trim($xmlData, " \n\r\t"); } } if(!$xmlData) return; $dbMetadata = new Metadata(); $dbMetadata->setPartnerId($entry->getPartnerId()); $dbMetadata->setMetadataProfileId($metadataProfileId); $dbMetadata->setMetadataProfileVersion($metadataProfile->getVersion()); $dbMetadata->setObjectType(Metadata::TYPE_ENTRY); $dbMetadata->setObjectId($entryId); $dbMetadata->setStatus(Metadata::STATUS_INVALID); $dbMetadata->save(); KalturaLog::debug("Metadata [" . $dbMetadata->getId() . "] saved [$xmlData]"); $key = $dbMetadata->getSyncKey(Metadata::FILE_SYNC_METADATA_DATA); kFileSyncUtils::file_put_contents($key, $xmlData); $errorMessage = ''; $status = kMetadataManager::validateMetadata($dbMetadata, $errorMessage); if($status == Metadata::STATUS_VALID) { kMetadataManager::updateSearchIndex($dbMetadata); } else { $bulkUploadResult = BulkUploadResultPeer::retrieveByEntryId($entryId, $entry->getBulkUploadId()); if($bulkUploadResult) { $msg = $bulkUploadResult->getDescription(); if($msg) $msg .= "\n"; $msg .= $errorMessage; $bulkUploadResult->setDescription($msg); $bulkUploadResult->save(); } } } protected static function addXpath(DOMDocument &$xml, $xPath, $value) { KalturaLog::debug("add value [$value] to xPath [$xPath]"); $xPaths = explode('/', $xPath); $currentNode = $xml; $currentXPath = ''; foreach($xPaths as $index => $xPath) { if(!strlen($xPath)) { KalturaLog::debug("xPath [/] already exists"); continue; } $currentXPath .= "/$xPath"; $domXPath = new DOMXPath($xml); $nodeList = $domXPath->query($currentXPath); if($nodeList && $nodeList->length) { $currentNode = $nodeList->item(0); KalturaLog::debug("xPath [$xPath] already exists"); continue; } if(!preg_match('/\*\[\s*local-name\(\)\s*=\s*\'([^\']+)\'\s*\]/', $xPath, $matches)) { KalturaLog::err("Xpath [$xPath] doesn't match"); return false; } $nodeName = $matches[1]; if($index + 1 == count($xPaths)) { KalturaLog::debug("Creating node [$nodeName] xPath [$xPath] with value [$value]"); $valueNode = $xml->createElement($nodeName, $value); } else { KalturaLog::debug("Creating node [$nodeName] xPath [$xPath]"); $valueNode = $xml->createElement($nodeName); } KalturaLog::debug("Appending node [$nodeName] to current node [$currentNode->localName]"); $currentNode->appendChild($valueNode); $currentNode = $valueNode; } } // /** // * @return array<KalturaAdminConsolePlugin> // */ // public static function getAdminConsolePages() // { // $metadata = new MetadataProfilesAction('Metadata', 'metadata'); // $metadataProfiles = new MetadataProfilesAction('Profiles Management', 'profiles', 'Metadata'); // $metadataObjects = new MetadataObjectsAction('Objects Management', 'objects', 'Metadata'); // return array($metadata, $metadataProfiles, $metadataObjects); // } }
Java
import React from 'react'; import PropTypes from 'prop-types'; import ManaUsageGraph from './ManaUsageGraph'; class HealingDoneGraph extends React.PureComponent { static propTypes = { start: PropTypes.number.isRequired, end: PropTypes.number.isRequired, offset: PropTypes.number.isRequired, healingBySecond: PropTypes.object.isRequired, manaUpdates: PropTypes.array.isRequired, }; groupHealingBySeconds(healingBySecond, interval) { return Object.keys(healingBySecond) .reduce((obj, second) => { const healing = healingBySecond[second]; const index = Math.floor(second / interval); if (obj[index]) { obj[index] = obj[index].add(healing.regular, healing.absorbed, healing.overheal); } else { obj[index] = healing; } return obj; }, {}); } render() { const { start, end, offset, healingBySecond, manaUpdates } = this.props; // TODO: move this to vega-lite window transform // e.g. { window: [{op: 'mean', field: 'hps', as: 'hps'}], frame: [-2, 2] } const interval = 5; const healingPerFrame = this.groupHealingBySeconds(healingBySecond, interval); let max = 0; Object.keys(healingPerFrame) .map(k => healingPerFrame[k]) .forEach((healingDone) => { const current = healingDone.effective; if (current > max) { max = current; } }); max /= interval; const manaUsagePerFrame = { 0: 0, }; const manaLevelPerFrame = { 0: 1, }; manaUpdates.forEach((item) => { const frame = Math.floor((item.timestamp - start) / 1000 / interval); manaUsagePerFrame[frame] = (manaUsagePerFrame[frame] || 0) + item.used / item.max; manaLevelPerFrame[frame] = item.current / item.max; // use the lowest value of the frame; likely to be more accurate }); const fightDurationSec = Math.ceil((end - start) / 1000); const labels = []; for (let i = 0; i <= fightDurationSec / interval; i += 1) { labels.push(Math.ceil(offset/1000) + i * interval); healingPerFrame[i] = healingPerFrame[i] !== undefined ? healingPerFrame[i].effective : 0; manaUsagePerFrame[i] = manaUsagePerFrame[i] !== undefined ? manaUsagePerFrame[i] : 0; manaLevelPerFrame[i] = manaLevelPerFrame[i] !== undefined ? manaLevelPerFrame[i] : null; } let lastKnown = null; const mana = Object.values(manaLevelPerFrame).map((value, i) => { if (value !== null) { lastKnown = value; } return { x: labels[i], y: lastKnown * max, }; }); const healing = Object.values(healingPerFrame).map((value, i) => ({ x: labels[i], y: value / interval })); const manaUsed = Object.values(manaUsagePerFrame).map((value, i) => ({ x: labels[i], y: value * max })); return ( <div className="graph-container" style={{ marginBottom: 20 }}> <ManaUsageGraph mana={mana} healing={healing} manaUsed={manaUsed} /> </div> ); } } export default HealingDoneGraph;
Java
<!doctype html> <html lang="en" class="no-js"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="shortcut icon" href="../../../../assets/images/dasch-favicon.ico"> <meta name="generator" content="mkdocs-1.1.2, mkdocs-material-6.2.8"> <title>API v2 Design Overview - Knora Documentation</title> <link rel="stylesheet" href="../../../../assets/stylesheets/main.cb6bc1d0.min.css"> <link rel="stylesheet" href="../../../../assets/stylesheets/palette.39b8e14a.min.css"> <meta name="theme-color" content="#7e56c2"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700%7CRoboto+Mono&display=fallback"> <style>body,input{font-family:"Roboto",-apple-system,BlinkMacSystemFont,Helvetica,Arial,sans-serif}code,kbd,pre{font-family:"Roboto Mono",SFMono-Regular,Consolas,Menlo,monospace}</style> <link rel="stylesheet" href="../../../../assets/style/theme.css"> </head> <body dir="ltr" data-md-color-scheme="" data-md-color-primary="deep-purple" data-md-color-accent="deep-purple"> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer" autocomplete="off"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search" autocomplete="off"> <label class="md-overlay" for="__drawer"></label> <div data-md-component="skip"> <a href="#api-v2-design-overview" class="md-skip"> Skip to content </a> </div> <div data-md-component="announce"> </div> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid" aria-label="Header"> <a href="../../../.." title="Knora Documentation" class="md-header-nav__button md-logo" aria-label="Knora Documentation"> <img src="../../../../assets/images/dasch-icon-white.svg" alt="logo"> </a> <label class="md-header-nav__button md-icon" for="__drawer"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M3 6h18v2H3V6m0 5h18v2H3v-2m0 5h18v2H3v-2z"/></svg> </label> <div class="md-header-nav__title" data-md-component="header-title"> <div class="md-header-nav__ellipsis"> <div class="md-header-nav__topic"> <span class="md-ellipsis"> Knora Documentation </span> </div> <div class="md-header-nav__topic"> <span class="md-ellipsis"> API v2 Design Overview </span> </div> </div> </div> <label class="md-header-nav__button md-icon" for="__search"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M9.5 3A6.5 6.5 0 0116 9.5c0 1.61-.59 3.09-1.56 4.23l.27.27h.79l5 5-1.5 1.5-5-5v-.79l-.27-.27A6.516 6.516 0 019.5 16 6.5 6.5 0 013 9.5 6.5 6.5 0 019.5 3m0 2C7 5 5 7 5 9.5S7 14 9.5 14 14 12 14 9.5 12 5 9.5 5z"/></svg> </label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" name="search"> <input type="text" class="md-search__input" name="query" aria-label="Search" placeholder="Search" autocapitalize="off" autocorrect="off" autocomplete="off" spellcheck="false" data-md-component="search-query" data-md-state="active" required> <label class="md-search__icon md-icon" for="__search"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M9.5 3A6.5 6.5 0 0116 9.5c0 1.61-.59 3.09-1.56 4.23l.27.27h.79l5 5-1.5 1.5-5-5v-.79l-.27-.27A6.516 6.516 0 019.5 16 6.5 6.5 0 013 9.5 6.5 6.5 0 019.5 3m0 2C7 5 5 7 5 9.5S7 14 9.5 14 14 12 14 9.5 12 5 9.5 5z"/></svg> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M20 11v2H8l5.5 5.5-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5 8 11h12z"/></svg> </label> <button type="reset" class="md-search__icon md-icon" aria-label="Clear" data-md-component="search-reset" tabindex="-1"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"/></svg> </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="search-result"> <div class="md-search-result__meta"> Initializing search </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </nav> </header> <div class="md-container" data-md-component="container"> <nav class="md-tabs" aria-label="Tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"> <a href="../../../.." class="md-tabs__link"> Home </a> </li> <li class="md-tabs__item"> <a href="../../../../01-introduction/" class="md-tabs__link"> Introduction </a> </li> <li class="md-tabs__item"> <a href="../../../../02-knora-ontologies/" class="md-tabs__link"> Knora Ontologies </a> </li> <li class="md-tabs__item"> <a href="../../../../03-apis/" class="md-tabs__link"> APIs </a> </li> <li class="md-tabs__item"> <a href="../../../../04-publishing-deployment/" class="md-tabs__link"> Publishing and Deployment </a> </li> <li class="md-tabs__item"> <a href="../../principles/" class="md-tabs__link md-tabs__link--active"> Knora Internals </a> </li> <li class="md-tabs__item"> <a href="../../../../06-salsah/index.md" class="md-tabs__link"> Salsah </a> </li> <li class="md-tabs__item"> <a href="../../../../07-sipi/" class="md-tabs__link"> SIPI </a> </li> <li class="md-tabs__item"> <a href="../../../../08-lucene/" class="md-tabs__link"> Lucene </a> </li> <li class="md-tabs__item"> <a href="../../../../faq/" class="md-tabs__link"> Frequently Asked Questions </a> </li> <li class="md-tabs__item"> <a href="../../../../00-release-notes/" class="md-tabs__link"> Release Notes </a> </li> </ul> </div> </nav> <main class="md-main" data-md-component="main"> <div class="md-main__inner md-grid"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation" > <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary md-nav--lifted" aria-label="Navigation" data-md-level="0"> <label class="md-nav__title" for="__drawer"> <a href="../../../.." title="Knora Documentation" class="md-nav__button md-logo" aria-label="Knora Documentation"> <img src="../../../../assets/images/dasch-icon-white.svg" alt="logo"> </a> Knora Documentation </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item"> <a href="../../../.." class="md-nav__link"> Home </a> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle="nav-2" type="checkbox" id="nav-2" > <label class="md-nav__link" for="nav-2"> Introduction <span class="md-nav__icon md-icon"></span> </label> <nav class="md-nav" aria-label="Introduction" data-md-level="1"> <label class="md-nav__title" for="nav-2"> <span class="md-nav__icon md-icon"></span> Introduction </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item"> <a href="../../../../01-introduction/" class="md-nav__link"> Index </a> </li> <li class="md-nav__item"> <a href="../../../../01-introduction/what-is-knora/" class="md-nav__link"> What is Knora? </a> </li> <li class="md-nav__item"> <a href="../../../../01-introduction/data-formats/" class="md-nav__link"> Data Formats in Knora </a> </li> <li class="md-nav__item"> <a href="../../../../01-introduction/standoff-rdf/" class="md-nav__link"> Standoff/RDF Text Markup </a> </li> <li class="md-nav__item"> <a href="../../../../01-introduction/example-project/" class="md-nav__link"> An Example Project </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle="nav-3" type="checkbox" id="nav-3" > <label class="md-nav__link" for="nav-3"> Knora Ontologies <span class="md-nav__icon md-icon"></span> </label> <nav class="md-nav" aria-label="Knora Ontologies" data-md-level="1"> <label class="md-nav__title" for="nav-3"> <span class="md-nav__icon md-icon"></span> Knora Ontologies </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item"> <a href="../../../../02-knora-ontologies/" class="md-nav__link"> Index </a> </li> <li class="md-nav__item"> <a href="../../../../02-knora-ontologies/introduction/" class="md-nav__link"> Introduction </a> </li> <li class="md-nav__item"> <a href="../../../../02-knora-ontologies/knora-base/" class="md-nav__link"> The Knora Base Ontology </a> </li> <li class="md-nav__item"> <a href="../../../../02-knora-ontologies/salsah-gui/" class="md-nav__link"> The SALSAH GUI Ontology </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle="nav-4" type="checkbox" id="nav-4" > <label class="md-nav__link" for="nav-4"> APIs <span class="md-nav__icon md-icon"></span> </label> <nav class="md-nav" aria-label="APIs" data-md-level="1"> <label class="md-nav__title" for="nav-4"> <span class="md-nav__icon md-icon"></span> APIs </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle="nav-4-1" type="checkbox" id="nav-4-1" > <label class="md-nav__link" for="nav-4-1"> The Knora APIs <span class="md-nav__icon md-icon"></span> </label> <nav class="md-nav" aria-label="The Knora APIs" data-md-level="2"> <label class="md-nav__title" for="nav-4-1"> <span class="md-nav__icon md-icon"></span> The Knora APIs </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item"> <a href="../../../../03-apis/" class="md-nav__link"> Index </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/feature-toggles/" class="md-nav__link"> Feature Toggles </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle="nav-4-2" type="checkbox" id="nav-4-2" > <label class="md-nav__link" for="nav-4-2"> API V1 <span class="md-nav__icon md-icon"></span> </label> <nav class="md-nav" aria-label="API V1" data-md-level="2"> <label class="md-nav__title" for="nav-4-2"> <span class="md-nav__icon md-icon"></span> API V1 </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item"> <a href="../../../../03-apis/api-v1/" class="md-nav__link"> Index </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v1/introduction/" class="md-nav__link"> Introduction </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v1/authentication/" class="md-nav__link"> Authentication </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v1/reading-and-searching-resources/" class="md-nav__link"> Reading and Searching Resources </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v1/xml-to-standoff-mapping/" class="md-nav__link"> XML to Standoff Mapping </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v1/adding-resources/" class="md-nav__link"> Adding Resources </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v1/reading-and-searching-resources/" class="md-nav__link"> Reading and Searching Resources </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v1/reading-values/" class="md-nav__link"> Reading Values </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v1/adding-values/" class="md-nav__link"> Adding Values </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v1/changing-values/" class="md-nav__link"> Changing Values </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v1/delete-resources-and-values/" class="md-nav__link"> Deleting Resources and Values </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle="nav-4-3" type="checkbox" id="nav-4-3" > <label class="md-nav__link" for="nav-4-3"> API V2 <span class="md-nav__icon md-icon"></span> </label> <nav class="md-nav" aria-label="API V2" data-md-level="2"> <label class="md-nav__title" for="nav-4-3"> <span class="md-nav__icon md-icon"></span> API V2 </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item"> <a href="../../../../03-apis/api-v2/" class="md-nav__link"> Index </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v2/introduction/" class="md-nav__link"> Introduction </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v2/authentication/" class="md-nav__link"> Authentication </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v2/knora-iris/" class="md-nav__link"> Knora IRIs </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v2/metadata/" class="md-nav__link"> Metadata </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v2/reading-and-searching-resources/" class="md-nav__link"> Reading and Searching Resources </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v2/reading-user-permissions/" class="md-nav__link"> Reading the User's Permissions on Resources and Values </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v2/getting-lists/" class="md-nav__link"> Getting Lists </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v2/xml-to-standoff-mapping/" class="md-nav__link"> XML to Standoff Mapping </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v2/query-language/" class="md-nav__link"> Gravsearch - Virtual Graph Search </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v2/editing-resources/" class="md-nav__link"> Editing Resources </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v2/editing-values/" class="md-nav__link"> Editing Values </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v2/ontology-information/" class="md-nav__link"> Querying, Creating, and Updating Ontologies </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v2/tei-xml/" class="md-nav__link"> TEI/XML </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-v2/permalinks/" class="md-nav__link"> Permalinks </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle="nav-4-4" type="checkbox" id="nav-4-4" > <label class="md-nav__link" for="nav-4-4"> Admin API <span class="md-nav__icon md-icon"></span> </label> <nav class="md-nav" aria-label="Admin API" data-md-level="2"> <label class="md-nav__title" for="nav-4-4"> <span class="md-nav__icon md-icon"></span> Admin API </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item"> <a href="../../../../03-apis/api-admin/" class="md-nav__link"> Index </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-admin/introduction/" class="md-nav__link"> Introduction </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-admin/overview/" class="md-nav__link"> Overview </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-admin/users/" class="md-nav__link"> Users Endpoint </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-admin/projects/" class="md-nav__link"> Projects Endpoint </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-admin/groups/" class="md-nav__link"> Groups Endpoint </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-admin/lists/" class="md-nav__link"> Lists Endpoint </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-admin/lists_new-list-admin-routes_v1/" class="md-nav__link"> New Lists Endpoint </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-admin/permissions/" class="md-nav__link"> Permissions Endpoint </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-admin/stores/" class="md-nav__link"> Stores Endpoint </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle="nav-4-5" type="checkbox" id="nav-4-5" > <label class="md-nav__link" for="nav-4-5"> Util API <span class="md-nav__icon md-icon"></span> </label> <nav class="md-nav" aria-label="Util API" data-md-level="2"> <label class="md-nav__title" for="nav-4-5"> <span class="md-nav__icon md-icon"></span> Util API </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item"> <a href="../../../../03-apis/api-util/" class="md-nav__link"> Index </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-util/health/" class="md-nav__link"> Health </a> </li> <li class="md-nav__item"> <a href="../../../../03-apis/api-util/version/" class="md-nav__link"> Version </a> </li> </ul> </nav> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle="nav-5" type="checkbox" id="nav-5" > <label class="md-nav__link" for="nav-5"> Publishing and Deployment <span class="md-nav__icon md-icon"></span> </label> <nav class="md-nav" aria-label="Publishing and Deployment" data-md-level="1"> <label class="md-nav__title" for="nav-5"> <span class="md-nav__icon md-icon"></span> Publishing and Deployment </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item"> <a href="../../../../04-publishing-deployment/" class="md-nav__link"> Index </a> </li> <li class="md-nav__item"> <a href="../../../../04-publishing-deployment/publishing/" class="md-nav__link"> Publishing </a> </li> <li class="md-nav__item"> <a href="../../../../04-publishing-deployment/getting-started/" class="md-nav__link"> Getting Started with Knora </a> </li> <li class="md-nav__item"> <a href="../../../../04-publishing-deployment/configuration/" class="md-nav__link"> Configuration </a> </li> <li class="md-nav__item"> <a href="../../../../04-publishing-deployment/updates/" class="md-nav__link"> Updating Repositories when Upgrading Knora </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--active md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle="nav-6" type="checkbox" id="nav-6" checked> <label class="md-nav__link" for="nav-6"> Knora Internals <span class="md-nav__icon md-icon"></span> </label> <nav class="md-nav" aria-label="Knora Internals" data-md-level="1"> <label class="md-nav__title" for="nav-6"> <span class="md-nav__icon md-icon"></span> Knora Internals </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item md-nav__item--active md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle="nav-6-1" type="checkbox" id="nav-6-1" checked> <label class="md-nav__link" for="nav-6-1"> Design <span class="md-nav__icon md-icon"></span> </label> <nav class="md-nav" aria-label="Design" data-md-level="2"> <label class="md-nav__title" for="nav-6-1"> <span class="md-nav__icon md-icon"></span> Design </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle="nav-6-1-1" type="checkbox" id="nav-6-1-1" > <label class="md-nav__link" for="nav-6-1-1"> Knora Design Principles <span class="md-nav__icon md-icon"></span> </label> <nav class="md-nav" aria-label="Knora Design Principles" data-md-level="3"> <label class="md-nav__title" for="nav-6-1-1"> <span class="md-nav__icon md-icon"></span> Knora Design Principles </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item"> <a href="../../principles/" class="md-nav__link"> Index </a> </li> <li class="md-nav__item"> <a href="../../principles/design-overview/" class="md-nav__link"> Design Overview </a> </li> <li class="md-nav__item"> <a href="../../principles/futures-with-akka/" class="md-nav__link"> Futures with Akka </a> </li> <li class="md-nav__item"> <a href="../../principles/http-module/" class="md-nav__link"> HTTP Module </a> </li> <li class="md-nav__item"> <a href="../../principles/store-module/" class="md-nav__link"> Store Module </a> </li> <li class="md-nav__item"> <a href="../../principles/triplestore-updates/" class="md-nav__link"> Triplestore Updates </a> </li> <li class="md-nav__item"> <a href="../../principles/consistency-checking/" class="md-nav__link"> Consistency Checking </a> </li> <li class="md-nav__item"> <a href="../../principles/authentication/" class="md-nav__link"> Authentication </a> </li> <li class="md-nav__item"> <a href="../../principles/feature-toggles/" class="md-nav__link"> Feature Toggles </a> </li> <li class="md-nav__item"> <a href="../../principles/rdf-api/" class="md-nav__link"> RDF Processing API </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle="nav-6-1-2" type="checkbox" id="nav-6-1-2" > <label class="md-nav__link" for="nav-6-1-2"> API V1 Design <span class="md-nav__icon md-icon"></span> </label> <nav class="md-nav" aria-label="API V1 Design" data-md-level="3"> <label class="md-nav__title" for="nav-6-1-2"> <span class="md-nav__icon md-icon"></span> API V1 Design </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item"> <a href="../../api-v1/" class="md-nav__link"> Index </a> </li> <li class="md-nav__item"> <a href="../../api-v1/how-to-add-a-route/" class="md-nav__link"> How to Add an API v1 Route </a> </li> <li class="md-nav__item"> <a href="../../api-v1/json/" class="md-nav__link"> JSON in API v1 </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--active md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle="nav-6-1-3" type="checkbox" id="nav-6-1-3" checked> <label class="md-nav__link" for="nav-6-1-3"> API V2 Design <span class="md-nav__icon md-icon"></span> </label> <nav class="md-nav" aria-label="API V2 Design" data-md-level="3"> <label class="md-nav__title" for="nav-6-1-3"> <span class="md-nav__icon md-icon"></span> API V2 Design </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item"> <a href="../" class="md-nav__link"> Index </a> </li> <li class="md-nav__item md-nav__item--active"> <input class="md-nav__toggle md-toggle" data-md-toggle="toc" type="checkbox" id="__toc"> <label class="md-nav__link md-nav__link--active" for="__toc"> API v2 Design Overview <span class="md-nav__icon md-icon"></span> </label> <a href="./" class="md-nav__link md-nav__link--active"> API v2 Design Overview </a> <nav class="md-nav md-nav--secondary" aria-label="Table of contents"> <label class="md-nav__title" for="__toc"> <span class="md-nav__icon md-icon"></span> Table of contents </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item"> <a href="#general-principles" class="md-nav__link"> General Principles </a> </li> <li class="md-nav__item"> <a href="#api-schemas" class="md-nav__link"> API Schemas </a> </li> <li class="md-nav__item"> <a href="#implementation" class="md-nav__link"> Implementation </a> <nav class="md-nav" aria-label="Implementation"> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="#json-ld-parsing-and-formatting" class="md-nav__link"> JSON-LD Parsing and Formatting </a> </li> <li class="md-nav__item"> <a href="#generation-of-other-rdf-formats" class="md-nav__link"> Generation of Other RDF Formats </a> </li> <li class="md-nav__item"> <a href="#operation-wrappers" class="md-nav__link"> Operation Wrappers </a> </li> <li class="md-nav__item"> <a href="#smart-iris" class="md-nav__link"> Smart IRIs </a> <nav class="md-nav" aria-label="Smart IRIs"> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="#usage" class="md-nav__link"> Usage </a> </li> <li class="md-nav__item"> <a href="#implementation_1" class="md-nav__link"> Implementation </a> </li> </ul> </nav> </li> </ul> </nav> </li> </ul> </nav> </li> <li class="md-nav__item"> <a href="../ontology-schemas/" class="md-nav__link"> Ontology Schemas </a> </li> <li class="md-nav__item"> <a href="../smart-iris/" class="md-nav__link"> Smart IRIs </a> </li> <li class="md-nav__item"> <a href="../content-wrappers/" class="md-nav__link"> Content Wrappers </a> </li> <li class="md-nav__item"> <a href="../how-to-add-a-route/" class="md-nav__link"> How to Add an API v2 Route </a> </li> <li class="md-nav__item"> <a href="../json-ld/" class="md-nav__link"> JSON-LD Parsing and Formatting </a> </li> <li class="md-nav__item"> <a href="../ontology-management/" class="md-nav__link"> Ontology Management </a> </li> <li class="md-nav__item"> <a href="../sipi/" class="md-nav__link"> Knora and Sipi </a> </li> <li class="md-nav__item"> <a href="../gravsearch/" class="md-nav__link"> Gravsearch Design </a> </li> <li class="md-nav__item"> <a href="../standoff/" class="md-nav__link"> Standoff Markup </a> </li> <li class="md-nav__item"> <a href="../ark/" class="md-nav__link"> Archival Resource Key (ARK) Identifiers </a> </li> <li class="md-nav__item"> <a href="../query-design/" class="md-nav__link"> SPARQL Query Design </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle="nav-6-1-4" type="checkbox" id="nav-6-1-4" > <label class="md-nav__link" for="nav-6-1-4"> Admin API Design <span class="md-nav__icon md-icon"></span> </label> <nav class="md-nav" aria-label="Admin API Design" data-md-level="3"> <label class="md-nav__title" for="nav-6-1-4"> <span class="md-nav__icon md-icon"></span> Admin API Design </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item"> <a href="../../api-admin/" class="md-nav__link"> Index </a> </li> <li class="md-nav__item"> <a href="../../api-admin/administration/" class="md-nav__link"> Administration </a> </li> </ul> </nav> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle="nav-6-2" type="checkbox" id="nav-6-2" > <label class="md-nav__link" for="nav-6-2"> Development <span class="md-nav__icon md-icon"></span> </label> <nav class="md-nav" aria-label="Development" data-md-level="2"> <label class="md-nav__title" for="nav-6-2"> <span class="md-nav__icon md-icon"></span> Development </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item"> <a href="../../../development/" class="md-nav__link"> Index </a> </li> <li class="md-nav__item"> <a href="../../../development/overview/" class="md-nav__link"> Overview </a> </li> <li class="md-nav__item"> <a href="../../../development/building-and-running/" class="md-nav__link"> Build and Running </a> </li> <li class="md-nav__item"> <a href="../../../development/intellij-config/" class="md-nav__link"> Setup IntelliJ for development of Knora </a> </li> <li class="md-nav__item"> <a href="../../../development/bazel/" class="md-nav__link"> Bazel Notes </a> </li> <li class="md-nav__item"> <a href="../../../development/testing/" class="md-nav__link"> Testing </a> </li> <li class="md-nav__item"> <a href="../../../development/docker-cheat-sheet/" class="md-nav__link"> Docker Cheat Sheet </a> </li> <li class="md-nav__item"> <a href="../../../development/monitoring/" class="md-nav__link"> Monitoring Knora </a> </li> <li class="md-nav__item"> <a href="../../../development/profiling/" class="md-nav__link"> Profiling Knora </a> </li> <li class="md-nav__item"> <a href="../../../development/docker-compose/" class="md-nav__link"> Starting the Knora-Stack inside Docker Container </a> </li> <li class="md-nav__item"> <a href="../../../development/updating-repositories/" class="md-nav__link"> Updating Repositories </a> </li> <li class="md-nav__item"> <a href="../../../development/generating-client-test-data/" class="md-nav__link"> Generating Client Test Data </a> </li> <li class="md-nav__item"> <a href="../../../development/graphdb/" class="md-nav__link"> Starting GraphDB </a> </li> <li class="md-nav__item"> <a href="../../../development/third-party/" class="md-nav__link"> Third-Party Dependencies </a> </li> </ul> </nav> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle="nav-7" type="checkbox" id="nav-7" > <label class="md-nav__link" for="nav-7"> Salsah <span class="md-nav__icon md-icon"></span> </label> <nav class="md-nav" aria-label="Salsah" data-md-level="1"> <label class="md-nav__title" for="nav-7"> <span class="md-nav__icon md-icon"></span> Salsah </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item"> <a href="../../../../06-salsah/index.md" class="md-nav__link"> Index </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle="nav-8" type="checkbox" id="nav-8" > <label class="md-nav__link" for="nav-8"> SIPI <span class="md-nav__icon md-icon"></span> </label> <nav class="md-nav" aria-label="SIPI" data-md-level="1"> <label class="md-nav__title" for="nav-8"> <span class="md-nav__icon md-icon"></span> SIPI </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item"> <a href="../../../../07-sipi/" class="md-nav__link"> Index </a> </li> <li class="md-nav__item"> <a href="../../../../07-sipi/setup-sipi-for-knora/" class="md-nav__link"> Setting Up Sipi for Knora </a> </li> <li class="md-nav__item"> <a href="../../../../07-sipi/sipi-and-knora/" class="md-nav__link"> Interaction between Sipi and Knora </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle="nav-9" type="checkbox" id="nav-9" > <label class="md-nav__link" for="nav-9"> Lucene <span class="md-nav__icon md-icon"></span> </label> <nav class="md-nav" aria-label="Lucene" data-md-level="1"> <label class="md-nav__title" for="nav-9"> <span class="md-nav__icon md-icon"></span> Lucene </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item"> <a href="../../../../08-lucene/" class="md-nav__link"> Overview </a> </li> <li class="md-nav__item"> <a href="../../../../08-lucene/lucene-query-parser-syntax/" class="md-nav__link"> Lucene Query Parser Syntax </a> </li> </ul> </nav> </li> <li class="md-nav__item"> <a href="../../../../faq/" class="md-nav__link"> Frequently Asked Questions </a> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle="nav-11" type="checkbox" id="nav-11" > <label class="md-nav__link" for="nav-11"> Release Notes <span class="md-nav__icon md-icon"></span> </label> <nav class="md-nav" aria-label="Release Notes" data-md-level="1"> <label class="md-nav__title" for="nav-11"> <span class="md-nav__icon md-icon"></span> Release Notes </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item"> <a href="../../../../00-release-notes/" class="md-nav__link"> Overview </a> </li> <li class="md-nav__item"> <a href="../../../../00-release-notes/migration/" class="md-nav__link"> Migration Notes </a> </li> <li class="md-nav__item"> <a href="../../../../00-release-notes/next/" class="md-nav__link"> Next Release </a> </li> <li class="md-nav__item"> <a href="../../../../00-release-notes/v1.1.0/" class="md-nav__link"> v1.1.0 </a> </li> <li class="md-nav__item"> <a href="../../../../00-release-notes/v1.2.0/" class="md-nav__link"> v1.2.0 </a> </li> <li class="md-nav__item"> <a href="../../../../00-release-notes/v1.3.0/" class="md-nav__link"> v1.3.0 </a> </li> <li class="md-nav__item"> <a href="../../../../00-release-notes/v1.4.0/" class="md-nav__link"> v1.4.0 </a> </li> <li class="md-nav__item"> <a href="../../../../00-release-notes/v1.5.0/" class="md-nav__link"> v1.5.0 </a> </li> <li class="md-nav__item"> <a href="../../../../00-release-notes/v1.6.0/" class="md-nav__link"> v1.6.0 </a> </li> <li class="md-nav__item"> <a href="../../../../00-release-notes/v1.7.0/" class="md-nav__link"> v1.7.0 </a> </li> <li class="md-nav__item"> <a href="../../../../00-release-notes/v2.x.x/" class="md-nav__link"> v2.x.x </a> </li> <li class="md-nav__item"> <a href="../../../../00-release-notes/v3.x.x/" class="md-nav__link"> v3.x.x </a> </li> <li class="md-nav__item"> <a href="../../../../00-release-notes/v4.x.x/" class="md-nav__link"> v4.x.x </a> </li> <li class="md-nav__item"> <a href="../../../../00-release-notes/v5.x.x/" class="md-nav__link"> v5.x.x </a> </li> <li class="md-nav__item"> <a href="../../../../00-release-notes/v6.x.x/" class="md-nav__link"> v6.x.x </a> </li> </ul> </nav> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc" > <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary" aria-label="Table of contents"> <label class="md-nav__title" for="__toc"> <span class="md-nav__icon md-icon"></span> Table of contents </label> <ul class="md-nav__list" data-md-scrollfix> <li class="md-nav__item"> <a href="#general-principles" class="md-nav__link"> General Principles </a> </li> <li class="md-nav__item"> <a href="#api-schemas" class="md-nav__link"> API Schemas </a> </li> <li class="md-nav__item"> <a href="#implementation" class="md-nav__link"> Implementation </a> <nav class="md-nav" aria-label="Implementation"> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="#json-ld-parsing-and-formatting" class="md-nav__link"> JSON-LD Parsing and Formatting </a> </li> <li class="md-nav__item"> <a href="#generation-of-other-rdf-formats" class="md-nav__link"> Generation of Other RDF Formats </a> </li> <li class="md-nav__item"> <a href="#operation-wrappers" class="md-nav__link"> Operation Wrappers </a> </li> <li class="md-nav__item"> <a href="#smart-iris" class="md-nav__link"> Smart IRIs </a> <nav class="md-nav" aria-label="Smart IRIs"> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="#usage" class="md-nav__link"> Usage </a> </li> <li class="md-nav__item"> <a href="#implementation_1" class="md-nav__link"> Implementation </a> </li> </ul> </nav> </li> </ul> </nav> </li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset"> <!--- Copyright © 2015-2021 the contributors (see Contributors.md). This file is part of Knora. Knora 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. Knora 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 Knora. If not, see <http://www.gnu.org/licenses/>. --> <h1 id="api-v2-design-overview">API v2 Design Overview</h1> <h2 id="general-principles">General Principles</h2> <ul> <li>Knora API v2 requests and responses are RDF documents. Any API v2 response can be returned as <a href="https://json-ld.org/spec/latest/json-ld/">JSON-LD</a>, <a href="https://www.w3.org/TR/turtle/">Turtle</a>, or <a href="https://www.w3.org/TR/rdf-syntax-grammar/">RDF/XML</a>.</li> <li>Each class or property used in a request or response has a definition in an ontology, which Knora can serve.</li> <li>Response formats are reused for different requests whenever possible, to minimise the number of different response formats a client has to handle. For example, any request for one or more resources (such as a search result, or a request for one specific resource) returns a response in the same format.</li> <li>Response size is limited by design. Large amounts of data must be retrieved by requesting small pages of data, one after the other.</li> <li>Responses that provide data are distinct from responses that provide definitions (i.e. ontology entities). Data responses indicate which types are used, and the client can request information about these types separately.</li> </ul> <h2 id="api-schemas">API Schemas</h2> <p>The types used in the triplestore are not exposed directly in the API. Instead, they are mapped onto API 'schemas'. Two schemas are currently provided.</p> <ul> <li>A complex schema, which is suitable both for reading and for editing data. The complex schema represents values primarily as complex objects.</li> <li>A simple schema, which is suitable for reading data but not for editing it. The simple schema facilitates interoperability between Knora ontologies and non-Knora ontologies, since it represents values primarily as literals.</li> </ul> <p>Each schema has its own type IRIs, which are derived from the ones used in the triplestore. For details of these different IRI formats, see <a href="../../../../03-apis/api-v2/knora-iris/">Knora IRIs</a>.</p> <h2 id="implementation">Implementation</h2> <h3 id="json-ld-parsing-and-formatting">JSON-LD Parsing and Formatting</h3> <p>Each API response is represented by a class that extends <code>KnoraResponseV2</code>, which has a method <code>toJsonLDDocument</code> that specifies the target schema. It is currently up to each route to determine what the appropriate response schema should be. Some routes will support only one response schema. Others will allow the client to choose, and there will be one or more standard ways for the client to specify the desired response schema.</p> <p>A route calls <code>RouteUtilV2.runRdfRoute</code>, passing a request message and a response schema. When <code>RouteUtilV2</code> gets the response message from the responder, it calls <code>toJsonLDDocument</code> on it, specifying that schema. The response message returns a <code>JsonLDDocument</code>, which is a simple data structure that is then converted to Java objects and passed to the JSON-LD Java library for formatting. In general, <code>toJsonLDDocument</code> is implemented in two stages: first the object converts itself to the target schema, and then the resulting object is converted to a <code>JsonLDDocument</code>.</p> <p>A route that receives JSON-LD requests should use <code>JsonLDUtil.parseJsonLD</code> to convert each request to a <code>JsonLDDocument</code>.</p> <h3 id="generation-of-other-rdf-formats">Generation of Other RDF Formats</h3> <p><code>RouteUtilV2.runRdfRoute</code> implements <a href="https://tools.ietf.org/html/rfc7231#section-5.3.2">HTTP content negotiation</a>, and converts JSON-LD responses into <a href="https://www.w3.org/TR/turtle/">Turtle</a> or <a href="https://www.w3.org/TR/rdf-syntax-grammar/">RDF/XML</a> as appropriate.</p> <h3 id="operation-wrappers">Operation Wrappers</h3> <p>Whenever possible, the same data structures are used for input and output. Often more data is available in output than in input. For example, when a value is read from the triplestore, its IRI is available, but when it is being created, it does not yet have an IRI. In such cases, there is a class like <code>ValueContentV2</code>, which represents the data that is used both for input and for output. When a value is read, a <code>ValueContentV2</code> is wrapped in a <code>ReadValueV2</code>, which additionally contains the value's IRI. When a value is created, it is wrapped in a <code>CreateValueV2</code>, which has the resource IRI and the property IRI, but not the value IRI.</p> <p>A <code>Read*</code> wrapper can be wrapped in another <code>Read*</code> wrapper; for example, a <code>ReadResourceV2</code> contains <code>ReadValueV2</code> objects.</p> <p>Each <code>*Content*</code> class should extend <code>KnoraContentV2</code> and thus have a <code>toOntologySchema</code> method or converting itself between internal and external schemas, in either direction.</p> <p>Each <code>Read*</code> wrapper class should have a method for converting itself to JSON-LD in a particular external schema. If the <code>Read*</code> wrapper is a <code>KnoraResponseV2</code>, this method is <code>toJsonLDDocument</code>.</p> <h3 id="smart-iris">Smart IRIs</h3> <h4 id="usage">Usage</h4> <p>The <code>SmartIri</code> trait can be used to parse and validate IRIs, and in particular for converting Knora type IRIs between internal and external schemas. It validates each IRI it parses. To use it, import the following:</p> <pre><code class="language-scala">import org.knora.webapi.messages.{SmartIri, StringFormatter} import org.knora.webapi.messages.IriConversions._ </code></pre> <p>Ensure that an implicit instance of <code>StringFormatter</code> is in scope:</p> <pre><code class="language-scala">implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance </code></pre> <p>Then, if <code>iriStr</code> is a string representing an IRI, you can can convert it to a <code>SmartIri</code> like this:</p> <pre><code class="language-scala">val iri: SmartIri = iriStr.toSmartIri </code></pre> <p>If the IRI came from a request, use this method to throw a specific exception if the IRI is invalid:</p> <pre><code class="language-scala">val iri: SmartIri = iriStr.toSmartIriWithErr( () =&gt; throw BadRequestException(s&quot;Invalid IRI: $iriStr&quot;) ) </code></pre> <p>You can then use methods such as <code>SmartIri.isKnoraApiV2EntityIri</code> and <code>SmartIri.getProjectCode</code> to obtain information about the IRI. To convert it to another schema, call <code>SmartIri.toOntologySchema</code>. Converting a non-Knora IRI returns the same IRI.</p> <p>If the IRI represents a Knora internal value class such as <code>knora-base:TextValue</code>, converting it to the <code>ApiV2Simple</code> schema will return the corresponding simplified type, such as <code>xsd:string</code>. But this conversion is not performed in the other direction (external to internal), since this would require knowledge of the context in which the IRI is being used.</p> <p>The performance penalty for using a <code>SmartIri</code> instead of a string is very small. Instances are automatically cached once they are constructed. Parsing and caching a <code>SmartIri</code> instance takes about 10-20 µs, and retrieving a cached <code>SmartIri</code> takes about 1 µs.</p> <p>There is no advantage to using <code>SmartIri</code> for data IRIs, since they are not schema-specific (and are not cached). If a data IRI has been received from a client request, it is better just to validate it using <code>StringFormatter.validateAndEscapeIri</code>.</p> <h4 id="implementation_1">Implementation</h4> <p>The smart IRI implementation, <code>SmartIriImpl</code>, is nested in the <code>StringFormatter</code> class, because it uses Knora's hostname, which isn't available until the Akka ActorSystem has started. However, this means that the type of a <code>SmartIriImpl</code> instance is dependent on the instance of <code>StringFormatter</code> that constructed it. Therefore, instances of <code>SmartIriImpl</code> created by different instances of <code>StringFormatter</code> can't be compared directly.</p> <p>There are in fact two instances of <code>StringFormatter</code>:</p> <ul> <li>one returned by <code>StringFormatter.getGeneralInstance</code> which is available after Akka has started and has the API server's hostname (and can therefore provide <code>SmartIri</code> instances capable of parsing IRIs containing that hostname). This instance is used throughout the Knora API server.</li> <li>one returned by <code>StringFormatter.getInstanceForConstantOntologies</code>, which is available before Akka has started, and is used only by the hard-coded constant <code>knora-api</code> ontologies.</li> </ul> <p>This is the reason for the existence of the <code>SmartIri</code> trait, which is a top-level definition and has its own <code>equals</code> and <code>hashCode</code> methods. Instances of <code>SmartIri</code> can thus be compared (e.g. to use them as unique keys in collections), regardless of which instance of <code>StringFormatter</code> created them.</p> </article> </div> </div> </main> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid" aria-label="Footer"> <a href="../" class="md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-footer-nav__button md-icon"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M20 11v2H8l5.5 5.5-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5 8 11h12z"/></svg> </div> <div class="md-footer-nav__title"> <div class="md-ellipsis"> <span class="md-footer-nav__direction"> Previous </span> Index </div> </div> </a> <a href="../ontology-schemas/" class="md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-footer-nav__title"> <div class="md-ellipsis"> <span class="md-footer-nav__direction"> Next </span> Ontology Schemas </div> </div> <div class="md-footer-nav__button md-icon"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M4 11v2h12l-5.5 5.5 1.42 1.42L19.84 12l-7.92-7.92L10.5 5.5 16 11H4z"/></svg> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> Made with <a href="https://squidfunk.github.io/mkdocs-material/" target="_blank" rel="noopener"> Material for MkDocs </a> </div> </div> </div> </footer> </div> <script src="../../../../assets/javascripts/vendor.18f0862e.min.js"></script> <script src="../../../../assets/javascripts/bundle.994580cf.min.js"></script><script id="__lang" type="application/json">{"clipboard.copy": "Copy to clipboard", "clipboard.copied": "Copied to clipboard", "search.config.lang": "en", "search.config.pipeline": "trimmer, stopWordFilter", "search.config.separator": "[\\s\\-]+", "search.placeholder": "Search", "search.result.placeholder": "Type to start searching", "search.result.none": "No matching documents", "search.result.one": "1 matching document", "search.result.other": "# matching documents", "search.result.more.one": "1 more on this page", "search.result.more.other": "# more on this page", "search.result.term.missing": "Missing"}</script> <script> app = initialize({ base: "../../../..", features: ['navigation.tabs'], search: Object.assign({ worker: "../../../../assets/javascripts/worker/search.9c0e82ba.min.js" }, typeof search !== "undefined" && search) }) </script> </body> </html>
Java
/* * Copyright (c) 2015 - 2016 Memorial Sloan-Kettering Cancer Center. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS * FOR A PARTICULAR PURPOSE. The software and documentation provided hereunder * is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no * obligations to provide maintenance, support, updates, enhancements or * modifications. In no event shall Memorial Sloan-Kettering Cancer Center be * liable to any party for direct, indirect, special, incidental or * consequential damages, including lost profits, arising out of the use of this * software and its documentation, even if Memorial Sloan-Kettering Cancer * Center has been advised of the possibility of such damage. */ /* * This file is part of cBioPortal. * * cBioPortal 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. * * 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/>. */ package org.mskcc.cbio.portal.util; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import org.cbioportal.persistence.GenePanelRepository; import org.cbioportal.model.GenePanel; import org.mskcc.cbio.portal.model.GeneticAlterationType; import org.mskcc.cbio.portal.model.GeneticProfile; /** * Genetic Profile Util Class. * */ public class GeneticProfileUtil { /** * Gets the GeneticProfile with the Specified GeneticProfile ID. * @param profileId GeneticProfile ID. * @param profileList List of Genetic Profiles. * @return GeneticProfile or null. */ public static GeneticProfile getProfile(String profileId, ArrayList<GeneticProfile> profileList) { for (GeneticProfile profile : profileList) { if (profile.getStableId().equals(profileId)) { return profile; } } return null; } /** * Returns true if Any of the Profiles Selected by the User Refer to mRNA Expression * outlier profiles. * * @param geneticProfileIdSet Set of Chosen Profiles IDs. * @param profileList List of Genetic Profiles. * @return true or false. */ public static boolean outlierExpressionSelected(HashSet<String> geneticProfileIdSet, ArrayList<GeneticProfile> profileList) { Iterator<String> geneticProfileIdIterator = geneticProfileIdSet.iterator(); while (geneticProfileIdIterator.hasNext()) { String geneticProfileId = geneticProfileIdIterator.next(); GeneticProfile geneticProfile = getProfile (geneticProfileId, profileList); if (geneticProfile != null && geneticProfile.getGeneticAlterationType() == GeneticAlterationType.MRNA_EXPRESSION) { String profileName = geneticProfile.getProfileName(); if (profileName != null) { if (profileName.toLowerCase().contains("outlier")) { return true; } } } } return false; } public static int getGenePanelId(String panelId) { GenePanelRepository genePanelRepository = SpringUtil.getGenePanelRepository(); GenePanel genePanel = genePanelRepository.getGenePanelByStableId(panelId).get(0); return genePanel.getInternalId(); } }
Java
odoo.define('web_editor.field_html_tests', function (require) { "use strict"; var ajax = require('web.ajax'); var FormView = require('web.FormView'); var testUtils = require('web.test_utils'); var weTestUtils = require('web_editor.test_utils'); var core = require('web.core'); var Wysiwyg = require('web_editor.wysiwyg'); var MediaDialog = require('wysiwyg.widgets.MediaDialog'); var _t = core._t; QUnit.module('web_editor', {}, function () { QUnit.module('field html', { beforeEach: function () { this.data = weTestUtils.wysiwygData({ 'note.note': { fields: { display_name: { string: "Displayed name", type: "char" }, header: { string: "Header", type: "html", required: true, }, body: { string: "Message", type: "html" }, }, records: [{ id: 1, display_name: "first record", header: "<p> &nbsp;&nbsp; <br> </p>", body: "<p>toto toto toto</p><p>tata</p>", }], }, 'mass.mailing': { fields: { display_name: { string: "Displayed name", type: "char" }, body_html: { string: "Message Body inline (to send)", type: "html" }, body_arch: { string: "Message Body for edition", type: "html" }, }, records: [{ id: 1, display_name: "first record", body_html: "<div class='field_body' style='background-color: red;'>yep</div>", body_arch: "<div class='field_body'>yep</div>", }], }, "ir.translation": { fields: { lang_code: {type: "char"}, value: {type: "char"}, res_id: {type: "integer"} }, records: [{ id: 99, res_id: 12, value: '', lang_code: 'en_US' }] }, }); testUtils.mock.patch(ajax, { loadAsset: function (xmlId) { if (xmlId === 'template.assets') { return Promise.resolve({ cssLibs: [], cssContents: ['body {background-color: red;}'] }); } if (xmlId === 'template.assets_all_style') { return Promise.resolve({ cssLibs: $('link[href]:not([type="image/x-icon"])').map(function () { return $(this).attr('href'); }).get(), cssContents: ['body {background-color: red;}'] }); } throw 'Wrong template'; }, }); }, afterEach: function () { testUtils.mock.unpatch(ajax); }, }, function () { QUnit.module('basic'); QUnit.test('simple rendering', async function (assert) { assert.expect(3); var form = await testUtils.createView({ View: FormView, model: 'note.note', data: this.data, arch: '<form>' + '<field name="body" widget="html" style="height: 100px"/>' + '</form>', res_id: 1, }); var $field = form.$('.oe_form_field[name="body"]'); assert.strictEqual($field.children('.o_readonly').html(), '<p>toto toto toto</p><p>tata</p>', "should have rendered a div with correct content in readonly"); assert.strictEqual($field.attr('style'), 'height: 100px', "should have applied the style correctly"); await testUtils.form.clickEdit(form); await testUtils.nextTick(); $field = form.$('.oe_form_field[name="body"]'); assert.strictEqual($field.find('.note-editable').html(), '<p>toto toto toto</p><p>tata</p>', "should have rendered the field correctly in edit"); form.destroy(); }); QUnit.test('check if required field is set', async function (assert) { assert.expect(1); var form = await testUtils.createView({ View: FormView, model: 'note.note', data: this.data, arch: '<form>' + '<field name="header" widget="html" style="height: 100px" />' + '</form>', res_id: 1, }); testUtils.mock.intercept(form, 'call_service', function (ev) { if (ev.data.service === 'notification') { assert.deepEqual(ev.data.args[0], { "className": undefined, "message": "<ul><li>Header</li></ul>", "sticky": undefined, "title": "Invalid fields:", "type": "danger" }); } }, true); await testUtils.form.clickEdit(form); await testUtils.nextTick(); await testUtils.dom.click(form.$('.o_form_button_save')); form.destroy(); }); QUnit.test('colorpicker', async function (assert) { assert.expect(6); var form = await testUtils.createView({ View: FormView, model: 'note.note', data: this.data, arch: '<form>' + '<field name="body" widget="html" style="height: 100px"/>' + '</form>', res_id: 1, }); // Summernote needs a RootWidget to set as parent of the ColorPaletteWidget. In the // tests, there is no RootWidget, so we set it here to the parent of the form view, which // can act as RootWidget, as it will honor rpc requests correctly (to the MockServer). const rootWidget = odoo.__DEBUG__.services['root.widget']; odoo.__DEBUG__.services['root.widget'] = form.getParent(); await testUtils.form.clickEdit(form); var $field = form.$('.oe_form_field[name="body"]'); // select the text var pText = $field.find('.note-editable p').first().contents()[0]; Wysiwyg.setRange(pText, 1, pText, 10); // text is selected var range = Wysiwyg.getRange($field[0]); assert.strictEqual(range.sc, pText, "should select the text"); async function openColorpicker(selector) { const $colorpicker = $field.find(selector); const openingProm = new Promise(resolve => { $colorpicker.one('shown.bs.dropdown', () => resolve()); }); await testUtils.dom.click($colorpicker.find('button:first')); return openingProm; } await openColorpicker('.note-toolbar .note-back-color-preview'); assert.ok($field.find('.note-back-color-preview').hasClass('show'), "should display the color picker"); await testUtils.dom.click($field.find('.note-toolbar .note-back-color-preview .o_we_color_btn[style="background-color:#00FFFF;"]')); assert.ok(!$field.find('.note-back-color-preview').hasClass('show'), "should close the color picker"); assert.strictEqual($field.find('.note-editable').html(), '<p>t<font style="background-color: rgb(0, 255, 255);">oto toto&nbsp;</font>toto</p><p>tata</p>', "should have rendered the field correctly in edit"); var fontContent = $field.find('.note-editable font').contents()[0]; var rangeControl = { sc: fontContent, so: 0, ec: fontContent, eo: fontContent.length, }; range = Wysiwyg.getRange($field[0]); assert.deepEqual(_.pick(range, 'sc', 'so', 'ec', 'eo'), rangeControl, "should select the text after color change"); // select the text pText = $field.find('.note-editable p').first().contents()[2]; Wysiwyg.setRange(fontContent, 5, pText, 2); // text is selected await openColorpicker('.note-toolbar .note-back-color-preview'); await testUtils.dom.click($field.find('.note-toolbar .note-back-color-preview .o_we_color_btn.bg-o-color-3')); assert.strictEqual($field.find('.note-editable').html(), '<p>t<font style="background-color: rgb(0, 255, 255);">oto t</font><font style="" class="bg-o-color-3">oto&nbsp;</font><font class="bg-o-color-3" style="">to</font>to</p><p>tata</p>', "should have rendered the field correctly in edit"); odoo.__DEBUG__.services['root.widget'] = rootWidget; form.destroy(); }); QUnit.test('media dialog: image', async function (assert) { assert.expect(1); var form = await testUtils.createView({ View: FormView, model: 'note.note', data: this.data, arch: '<form>' + '<field name="body" widget="html" style="height: 100px"/>' + '</form>', res_id: 1, mockRPC: function (route, args) { if (args.model === 'ir.attachment') { if (args.method === "generate_access_token") { return Promise.resolve(); } } if (route.indexOf('/web/image/123/transparent.png') === 0) { return Promise.resolve(); } if (route.indexOf('/web_unsplash/fetch_images') === 0) { return Promise.resolve(); } if (route.indexOf('/web_editor/media_library_search') === 0) { return Promise.resolve(); } return this._super(route, args); }, }); await testUtils.form.clickEdit(form); var $field = form.$('.oe_form_field[name="body"]'); // the dialog load some xml assets var defMediaDialog = testUtils.makeTestPromise(); testUtils.mock.patch(MediaDialog, { init: function () { this._super.apply(this, arguments); this.opened(defMediaDialog.resolve.bind(defMediaDialog)); } }); var pText = $field.find('.note-editable p').first().contents()[0]; Wysiwyg.setRange(pText, 1); await testUtils.dom.click($field.find('.note-toolbar .note-insert button:has(.fa-file-image-o)')); // load static xml file (dialog, media dialog, unsplash image widget) await defMediaDialog; await testUtils.dom.click($('.modal #editor-media-image .o_existing_attachment_cell:first').removeClass('d-none')); var $editable = form.$('.oe_form_field[name="body"] .note-editable'); assert.ok($editable.find('img')[0].dataset.src.includes('/web/image/123/transparent.png'), "should have the image in the dom"); testUtils.mock.unpatch(MediaDialog); form.destroy(); }); QUnit.test('media dialog: icon', async function (assert) { assert.expect(1); var form = await testUtils.createView({ View: FormView, model: 'note.note', data: this.data, arch: '<form>' + '<field name="body" widget="html" style="height: 100px"/>' + '</form>', res_id: 1, mockRPC: function (route, args) { if (args.model === 'ir.attachment') { return Promise.resolve([]); } if (route.indexOf('/web_unsplash/fetch_images') === 0) { return Promise.resolve(); } return this._super(route, args); }, }); await testUtils.form.clickEdit(form); var $field = form.$('.oe_form_field[name="body"]'); // the dialog load some xml assets var defMediaDialog = testUtils.makeTestPromise(); testUtils.mock.patch(MediaDialog, { init: function () { this._super.apply(this, arguments); this.opened(defMediaDialog.resolve.bind(defMediaDialog)); } }); var pText = $field.find('.note-editable p').first().contents()[0]; Wysiwyg.setRange(pText, 1); await testUtils.dom.click($field.find('.note-toolbar .note-insert button:has(.fa-file-image-o)')); // load static xml file (dialog, media dialog, unsplash image widget) await defMediaDialog; $('.modal .tab-content .tab-pane').removeClass('fade'); // to be sync in test await testUtils.dom.click($('.modal a[aria-controls="editor-media-icon"]')); await testUtils.dom.click($('.modal #editor-media-icon .font-icons-icon.fa-glass')); var $editable = form.$('.oe_form_field[name="body"] .note-editable'); assert.strictEqual($editable.data('wysiwyg').getValue(), '<p>t<span class="fa fa-glass"></span>oto toto toto</p><p>tata</p>', "should have the image in the dom"); testUtils.mock.unpatch(MediaDialog); form.destroy(); }); QUnit.test('save', async function (assert) { assert.expect(1); var form = await testUtils.createView({ View: FormView, model: 'note.note', data: this.data, arch: '<form>' + '<field name="body" widget="html" style="height: 100px"/>' + '</form>', res_id: 1, mockRPC: function (route, args) { if (args.method === "write") { assert.strictEqual(args.args[1].body, '<p>t<font class="bg-o-color-3">oto toto&nbsp;</font>toto</p><p>tata</p>', "should save the content"); } return this._super.apply(this, arguments); }, }); await testUtils.form.clickEdit(form); var $field = form.$('.oe_form_field[name="body"]'); // select the text var pText = $field.find('.note-editable p').first().contents()[0]; Wysiwyg.setRange(pText, 1, pText, 10); // text is selected async function openColorpicker(selector) { const $colorpicker = $field.find(selector); const openingProm = new Promise(resolve => { $colorpicker.one('shown.bs.dropdown', () => resolve()); }); await testUtils.dom.click($colorpicker.find('button:first')); return openingProm; } await openColorpicker('.note-toolbar .note-back-color-preview'); await testUtils.dom.click($field.find('.note-toolbar .note-back-color-preview .o_we_color_btn.bg-o-color-3')); await testUtils.form.clickSave(form); form.destroy(); }); QUnit.module('cssReadonly'); QUnit.test('rendering with iframe for readonly mode', async function (assert) { assert.expect(3); var form = await testUtils.createView({ View: FormView, model: 'note.note', data: this.data, arch: '<form>' + '<field name="body" widget="html" style="height: 100px" options="{\'cssReadonly\': \'template.assets\'}"/>' + '</form>', res_id: 1, }); var $field = form.$('.oe_form_field[name="body"]'); var $iframe = $field.find('iframe.o_readonly'); await $iframe.data('loadDef'); var doc = $iframe.contents()[0]; assert.strictEqual($(doc).find('#iframe_target').html(), '<p>toto toto toto</p><p>tata</p>', "should have rendered a div with correct content in readonly"); assert.strictEqual(doc.defaultView.getComputedStyle(doc.body).backgroundColor, 'rgb(255, 0, 0)', "should load the asset css"); await testUtils.form.clickEdit(form); $field = form.$('.oe_form_field[name="body"]'); assert.strictEqual($field.find('.note-editable').html(), '<p>toto toto toto</p><p>tata</p>', "should have rendered the field correctly in edit"); form.destroy(); }); QUnit.module('translation'); QUnit.test('field html translatable', async function (assert) { assert.expect(4); var multiLang = _t.database.multi_lang; _t.database.multi_lang = true; this.data['note.note'].fields.body.translate = true; var form = await testUtils.createView({ View: FormView, model: 'note.note', data: this.data, arch: '<form string="Partners">' + '<field name="body" widget="html"/>' + '</form>', res_id: 1, mockRPC: function (route, args) { if (route === '/web/dataset/call_button' && args.method === 'translate_fields') { assert.deepEqual(args.args, ['note.note', 1, 'body'], "should call 'call_button' route"); return Promise.resolve({ domain: [], context: {search_default_name: 'partnes,foo'}, }); } if (route === "/web/dataset/call_kw/res.lang/get_installed") { return Promise.resolve([["en_US"], ["fr_BE"]]); } return this._super.apply(this, arguments); }, }); assert.strictEqual(form.$('.oe_form_field_html .o_field_translate').length, 0, "should not have a translate button in readonly mode"); await testUtils.form.clickEdit(form); var $button = form.$('.oe_form_field_html .o_field_translate'); assert.strictEqual($button.length, 1, "should have a translate button"); await testUtils.dom.click($button); assert.containsOnce($(document), '.o_translation_dialog', 'should have a modal to translate'); form.destroy(); _t.database.multi_lang = multiLang; }); }); }); });
Java
"use strict"; require("./setup"); var exchange = require("../src/exchange"), assert = require("assert"), config = require("config"), async = require("async"); describe("Exchange", function () { describe("rounding", function () { it("should round as expected", function() { assert.equal( exchange.round("USD", 33.38 + 10.74), 44.12); }); }); describe("Load and keep fresh the exchange rates", function () { it("should be using test path", function () { // check it is faked out for tests var stubbedPath = "config/initial_exchange_rates.json"; assert.equal( exchange.pathToLatestJSON(), stubbedPath); // check it is normally correct exchange.pathToLatestJSON.restore(); assert.notEqual( exchange.pathToLatestJSON(), stubbedPath); }); it("fx object should convert correctly", function () { assert.equal(exchange.convert(100, "GBP", "USD"), 153.85 ); // 2 dp assert.equal(exchange.convert(100, "GBP", "JPY"), 15083 ); // 0 dp assert.equal(exchange.convert(100, "GBP", "LYD"), 195.385 ); // 3 dp assert.equal(exchange.convert(100, "GBP", "XAG"), 6.15 ); // null dp }); it("should reload exchange rates periodically", function (done) { var fx = exchange.fx; var clock = this.sandbox.clock; // change one of the exchange rates to test for the reload var originalGBP = fx.rates.GBP; fx.rates.GBP = 123.456; // start the delayAndReload exchange.initiateDelayAndReload(); // work out how long to wait var delay = exchange.calculateDelayUntilNextReload(); // go almost to the roll over and check no change clock.tick( delay-10 ); assert.equal(fx.rates.GBP, 123.456); async.series([ function (cb) { // go past rollover and check for change exchange.hub.once("reloaded", function () { assert.equal(fx.rates.GBP, originalGBP); cb(); }); clock.tick( 20 ); }, function (cb) { // reset it again and go ahead another interval and check for change fx.rates.GBP = 123.456; exchange.hub.once("reloaded", function () { assert.equal(fx.rates.GBP, originalGBP); cb(); }); clock.tick( config.exchangeReloadIntervalSeconds * 1000 ); } ], done); }); it.skip("should handle bad exchange rates JSON"); }); });
Java
<?php require_once __BASE__.'/model/Storable.php'; class AccountSMTP extends Storable { public $id = MYSQL_PRIMARY_KEY; public $code = ''; public $created = MYSQL_DATETIME; public $last_edit = MYSQL_DATETIME; public $name = ''; public $host = ''; public $port = ''; public $connection = ''; public $username = ''; public $password = ''; public $sender_name = ''; public $sender_mail = ''; public $replyTo = ''; public $max_mail = 0; public $ever = ['day', 'week', 'month', 'year', 'onetime']; public $max_mail_day = 0; public $send = 0; public $last_send = MYSQL_DATETIME; public $perc = 0.0; public $total_send = 0; public $active = 1; ## public static function findServer() { $servers = self::query( [ 'active' => 1, ]); $perc = 110; foreach ($servers as $server) { if ($server->perc < $perc) { //trova quello più saturo $use = $server; } if ($server->perc == 0) { return $use; } } return $use; } ## public static function getMaxMail($account = 'all') { $append = $account != 'all' ? ' WHERE id = "'.$account.'"' : ' '; $sql = 'SELECT SUM(max_mail_day) AS maxmail FROM '.self::table().$append; $res = schemadb::execute('row', $sql); return $res['maxmail']; } ## public static function getSenderMail($account = 'all') { $append = $account != 'all' ? ' WHERE id = "'.$account.'"' : ' '; $sql = 'SELECT SUM(total_send) AS mailtotali FROM '.self::table().$append; $res = schemadb::execute('row', $sql); return $res['mailtotali']; } ## public static function getInviateMail($account = 'all') { $append = $account != 'all' ? ' WHERE id = "'.$account.'"' : ' '; $sql = 'SELECT SUM(send) AS inviate FROM '.self::table().$append; $res = schemadb::execute('row', $sql); return $res['inviate']; } ## public static function getRemainMail($account = 'all') { $remain = self::getMaxMail() - self::getInviateMail(); return $remain; } } AccountSMTP::schemadb_update();
Java
# frozen_string_literal: true require "spec_helper" describe "Edit initiative", type: :system do let(:organization) { create(:organization) } let(:user) { create(:user, :confirmed, organization: organization) } let(:initiative_title) { translated(initiative.title) } let(:new_title) { "This is my initiative new title" } let!(:initiative_type) { create(:initiatives_type, :online_signature_enabled, organization: organization) } let!(:scoped_type) { create(:initiatives_type_scope, type: initiative_type) } let!(:other_initiative_type) { create(:initiatives_type, organization: organization) } let!(:other_scoped_type) { create(:initiatives_type_scope, type: initiative_type) } let(:initiative_path) { decidim_initiatives.initiative_path(initiative) } let(:edit_initiative_path) { decidim_initiatives.edit_initiative_path(initiative) } shared_examples "manage update" do it "can be updated" do visit initiative_path click_link("Edit", href: edit_initiative_path) expect(page).to have_content "EDIT INITIATIVE" within "form.edit_initiative" do fill_in :initiative_title, with: new_title click_button "Update" end expect(page).to have_content(new_title) end end before do switch_to_host(organization.host) login_as user, scope: :user end describe "when user is initiative author" do let(:initiative) { create(:initiative, :created, author: user, scoped_type: scoped_type, organization: organization) } it_behaves_like "manage update" context "when initiative is published" do let(:initiative) { create(:initiative, author: user, scoped_type: scoped_type, organization: organization) } it "can't be updated" do visit decidim_initiatives.initiative_path(initiative) expect(page).not_to have_content "Edit initiative" visit edit_initiative_path expect(page).to have_content("not authorized") end end end describe "when author is a committee member" do let(:initiative) { create(:initiative, :created, scoped_type: scoped_type, organization: organization) } before do create(:initiatives_committee_member, user: user, initiative: initiative) end it_behaves_like "manage update" end describe "when user is admin" do let(:user) { create(:user, :confirmed, :admin, organization: organization) } let(:initiative) { create(:initiative, :created, scoped_type: scoped_type, organization: organization) } it_behaves_like "manage update" end describe "when author is not a committee member" do let(:initiative) { create(:initiative, :created, scoped_type: scoped_type, organization: organization) } it "renders an error" do visit decidim_initiatives.initiative_path(initiative) expect(page).to have_no_content("Edit initiative") visit edit_initiative_path expect(page).to have_content("not authorized") end end end
Java
from odoo import fields, models class Job(models.Model): _inherit = "crm.team" survey_id = fields.Many2one( 'survey.survey', "Interview Form", help="Choose an interview form") def action_print_survey(self): return self.survey_id.action_print_survey()
Java
package com.alessiodp.parties.bukkit.addons.external.skript.expressions; import ch.njol.skript.classes.Changer; import ch.njol.skript.doc.Description; import ch.njol.skript.doc.Examples; import ch.njol.skript.doc.Name; import ch.njol.skript.doc.Since; import ch.njol.skript.expressions.base.SimplePropertyExpression; import ch.njol.util.coll.CollectionUtils; import com.alessiodp.parties.api.interfaces.Party; import org.bukkit.event.Event; @Name("Party Name") @Description("Get the name of the given party.") @Examples({"send \"%name of party with name \"test\"%\"", "send \"%name of event-party%\""}) @Since("3.0.0") public class ExprPartyName extends SimplePropertyExpression<Party, String> { static { register(ExprPartyName.class, String.class, "name", "party"); } @Override public Class<? extends String> getReturnType() { return String.class; } @Override protected String getPropertyName() { return "name"; } @Override public String convert(Party party) { return party.getName(); } @Override public void change(Event e, Object[] delta, Changer.ChangeMode mode){ if (delta != null) { Party party = getExpr().getSingle(e); String newName = (String) delta[0]; switch (mode) { case SET: party.rename(newName); break; case DELETE: party.rename(null); break; default: break; } } } @Override public Class<?>[] acceptChange(final Changer.ChangeMode mode) { return (mode == Changer.ChangeMode.SET || mode == Changer.ChangeMode.DELETE) ? CollectionUtils.array(String.class) : null; } }
Java
//Copyright (c) 2018 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef INFILL_SUBDIVCUBE_H #define INFILL_SUBDIVCUBE_H #include "../settings/types/Ratio.h" #include "../utils/IntPoint.h" #include "../utils/Point3.h" namespace cura { struct LayerIndex; class Polygons; class SliceMeshStorage; class SubDivCube { public: /*! * Constructor for SubDivCube. Recursively calls itself eight times to flesh out the octree. * \param mesh contains infill layer data and settings * \param my_center the center of the cube * \param depth the recursion depth of the cube (0 is most recursed) */ SubDivCube(SliceMeshStorage& mesh, Point3& center, size_t depth); ~SubDivCube(); //!< destructor (also destroys children) /*! * Precompute the octree of subdivided cubes * \param mesh contains infill layer data and settings */ static void precomputeOctree(SliceMeshStorage& mesh, const Point& infill_origin); /*! * Generates the lines of subdivision of the specific cube at the specific layer. It recursively calls itself, so it ends up drawing all the subdivision lines of sub-cubes too. * \param z the specified layer height * \param result (output) The resulting lines */ void generateSubdivisionLines(const coord_t z, Polygons& result); private: /*! * Generates the lines of subdivision of the specific cube at the specific layer. It recursively calls itself, so it ends up drawing all the subdivision lines of sub-cubes too. * \param z the specified layer height * \param result (output) The resulting lines * \param directional_line_groups Array of 3 times a polylines. Used to keep track of line segments that are all pointing the same direction for line segment combining */ void generateSubdivisionLines(const coord_t z, Polygons (&directional_line_groups)[3]); struct CubeProperties { coord_t side_length; //!< side length of cubes coord_t height; //!< height of cubes based. This is the distance from one point of a cube to its 3d opposite. coord_t square_height; //!< square cut across lengths. This is the diagonal distance across a face of the cube. coord_t max_draw_z_diff; //!< maximum draw z differences. This is the maximum difference in z at which lines need to be drawn. coord_t max_line_offset; //!< maximum line offsets. This is the maximum distance at which subdivision lines should be drawn from the 2d cube center. }; /*! * Rotates a point 120 degrees about the origin. * \param target the point to rotate. */ static void rotatePoint120(Point& target); /*! * Rotates a point to align it with the orientation of the infill. * \param target the point to rotate. */ static void rotatePointInitial(Point& target); /*! * Determines if a described theoretical cube should be subdivided based on if a sphere that encloses the cube touches the infill mesh. * \param mesh contains infill layer data and settings * \param center the center of the described cube * \param radius the radius of the enclosing sphere * \return the described cube should be subdivided */ static bool isValidSubdivision(SliceMeshStorage& mesh, Point3& center, coord_t radius); /*! * Finds the distance to the infill border at the specified layer from the specified point. * \param mesh contains infill layer data and settings * \param layer_nr the number of the specified layer * \param location the location of the specified point * \param[out] distance2 the squared distance to the infill border * \return Code 0: outside, 1: inside, 2: boundary does not exist at specified layer */ static coord_t distanceFromPointToMesh(SliceMeshStorage& mesh, const LayerIndex layer_nr, Point& location, coord_t* distance2); /*! * Adds the defined line to the specified polygons. It assumes that the specified polygons are all parallel lines. Combines line segments with touching ends closer than epsilon. * \param[out] group the polygons to add the line to * \param from the first endpoint of the line * \param to the second endpoint of the line */ void addLineAndCombine(Polygons& group, Point from, Point to); size_t depth; //!< the recursion depth of the cube (0 is most recursed) Point3 center; //!< center location of the cube in absolute coordinates SubDivCube* children[8] = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}; //!< pointers to this cube's eight octree children static std::vector<CubeProperties> cube_properties_per_recursion_step; //!< precomputed array of basic properties of cubes based on recursion depth. static Ratio radius_multiplier; //!< multiplier for the bounding radius when determining if a cube should be subdivided static Point3Matrix rotation_matrix; //!< The rotation matrix to get from axis aligned cubes to cubes standing on a corner point aligned with the infill_angle static PointMatrix infill_rotation_matrix; //!< Horizontal rotation applied to infill static coord_t radius_addition; //!< addition to the bounding radius when determining if a cube should be subdivided }; } #endif //INFILL_SUBDIVCUBE_H
Java
class CreateColorMappings < ActiveRecord::Migration def self.up create_table :color_mappings do |t| t.references :collage t.references :tag t.string :hex t.timestamps end end def self.down drop_table :color_mappings end end
Java
############################################################################## # For copyright and license notices, see __manifest__.py file in module root # directory ############################################################################## from . import account_move from . import account_move_line from . import account_master_port
Java
/** * Copyright (C) 2001-2020 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * 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/. */ package com.rapidminer.gui.new_plotter.configuration; import com.rapidminer.gui.new_plotter.listener.events.LineFormatChangeEvent; import com.rapidminer.gui.new_plotter.utility.DataStructureUtils; import com.rapidminer.tools.I18N; import java.awt.BasicStroke; import java.awt.Color; import java.lang.ref.WeakReference; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * @author Marius Helf * @deprecated since 9.2.0 */ @Deprecated public class LineFormat implements Cloneable { private static class StrokeFactory { static public BasicStroke getSolidStroke() { return new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); } static public BasicStroke getDottedStroke() { return new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, new float[] { 1f, 1f }, 0.0f); } static public BasicStroke getShortDashedStroke() { return new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, new float[] { 4f, 2f }, 0.0f); } static public BasicStroke getLongDashedStroke() { return new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, new float[] { 7f, 3f }, 0.0f); } static public BasicStroke getDashDotStroke() { return new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, new float[] { 6f, 2f, 1f, 2f }, 0.0f); } static public BasicStroke getStripedStroke() { return new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, new float[] { 0.2f, 0.2f }, 0.0f); } } public enum LineStyle { NONE(null, I18N.getGUILabel("plotter.linestyle.NONE.label")), SOLID(StrokeFactory.getSolidStroke(), I18N .getGUILabel("plotter.linestyle.SOLID.label")), DOTS(StrokeFactory.getDottedStroke(), I18N .getGUILabel("plotter.linestyle.DOTS.label")), SHORT_DASHES(StrokeFactory.getShortDashedStroke(), I18N .getGUILabel("plotter.linestyle.SHORT_DASHES.label")), LONG_DASHES(StrokeFactory.getLongDashedStroke(), I18N .getGUILabel("plotter.linestyle.LONG_DASHES.label")), DASH_DOT(StrokeFactory.getDashDotStroke(), I18N .getGUILabel("plotter.linestyle.DASH_DOT.label")), STRIPES(StrokeFactory.getStripedStroke(), I18N .getGUILabel("plotter.linestyle.STRIPES.label")); private final BasicStroke stroke; private final String name; public BasicStroke getStroke() { return stroke; } public String getName() { return name; } private LineStyle(BasicStroke stroke, String name) { this.stroke = stroke; this.name = name; } } private List<WeakReference<LineFormatListener>> listeners = new LinkedList<WeakReference<LineFormatListener>>(); private LineStyle style = LineStyle.NONE; // dashed, solid... private Color color = Color.GRAY; private float width = 1.0f; public LineStyle getStyle() { return style; } public void setStyle(LineStyle style) { if (style != this.style) { this.style = style; fireStyleChanged(); } } public Color getColor() { return color; } public void setColor(Color color) { if (color == null ? this.color != null : !color.equals(this.color)) { this.color = color; fireColorChanged(); } } public float getWidth() { return width; } public void setWidth(float width) { if (width != this.width) { this.width = width; fireWidthChanged(); } } private void fireWidthChanged() { fireLineFormatChanged(new LineFormatChangeEvent(this, width)); } private void fireColorChanged() { fireLineFormatChanged(new LineFormatChangeEvent(this, color)); } private void fireStyleChanged() { fireLineFormatChanged(new LineFormatChangeEvent(this, style)); } private void fireLineFormatChanged(LineFormatChangeEvent e) { Iterator<WeakReference<LineFormatListener>> it = listeners.iterator(); while (it.hasNext()) { LineFormatListener l = it.next().get(); if (l != null) { l.lineFormatChanged(e); } else { it.remove(); } } } @Override public LineFormat clone() { LineFormat clone = new LineFormat(); clone.color = new Color(color.getRGB(), true); clone.style = style; clone.width = width; return clone; } public BasicStroke getStroke() { BasicStroke stroke = style.getStroke(); if (stroke != null) { float[] scaledDashArray = getScaledDashArray(); BasicStroke scaledStroke = new BasicStroke(this.getWidth(), stroke.getEndCap(), stroke.getLineJoin(), stroke.getMiterLimit(), scaledDashArray, stroke.getDashPhase()); return scaledStroke; } else { return null; } } float[] getScaledDashArray() { BasicStroke stroke = getStyle().getStroke(); if (stroke == null) { return null; } float[] dashArray = stroke.getDashArray(); float[] scaledDashArray; if (dashArray != null) { float scalingFactor = getWidth(); if (scalingFactor <= 0) { scalingFactor = 1; } if (scalingFactor != 1) { scaledDashArray = DataStructureUtils.cloneAndMultiplyArray(dashArray, scalingFactor); } else { scaledDashArray = dashArray; } } else { scaledDashArray = dashArray; } return scaledDashArray; } public void addLineFormatListener(LineFormatListener l) { listeners.add(new WeakReference<LineFormatListener>(l)); } public void removeLineFormatListener(LineFormatListener l) { Iterator<WeakReference<LineFormatListener>> it = listeners.iterator(); while (it.hasNext()) { LineFormatListener listener = it.next().get(); if (l != null) { if (listener != null && listener.equals(l)) { it.remove(); } } else { it.remove(); } } } }
Java
package com.nexusplay.containers; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.math.BigInteger; import java.sql.SQLException; import org.apache.commons.io.IOUtils; import com.nexusplay.db.SubtitlesDatabase; import com.nexusplay.security.RandomContainer; /** * Contains a proposed change (to a subtitle). * @author alex * */ public class Change { private String targetID, changedContent, id, originalContent, votes; private int nrVotes; /** * Constructor for creating new objects, prior to storing them in the database. * @param changedContent The change's original data * @param originalContent The change's new data * @param targetID The object targeted by the change * @param votes The user IDs that voted this change */ public Change(String changedContent, String originalContent, String targetID, String votes){ this.changedContent = changedContent; this.originalContent = originalContent; this.targetID = targetID; this.votes = votes; nrVotes = votes.length() - votes.replace(";", "").length(); generateId(); } /** * This constructor should only be used for recreating a stored object. * @param changedContent The change's original data * @param originalContent The change's new data * @param targetID The object targeted by the change * @param votes The user IDs that voted this change * @param id The change's unique ID */ public Change(String changedContent, String originalContent, String targetID, String votes, String id){ this.changedContent = changedContent; this.originalContent = originalContent; this.targetID = targetID; this.votes = votes; nrVotes = votes.length() - votes.replace(";", "").length(); this.id = id; } /** * Commits a change to disk. * @throws SQLException Thrown if the database is not accessible to us for whatever reason * @throws FileNotFoundException Thrown if we're denied access to the subtitle file * @throws IOException Thrown if an error appears while writing the file */ public void commitChange() throws SQLException, FileNotFoundException, IOException{ Subtitle sub = SubtitlesDatabase.getSubtitleByID(targetID); FileInputStream input = new FileInputStream(SettingsContainer.getAbsoluteSubtitlePath() + File.separator + sub.getId() + ".vtt"); String content = IOUtils.toString(input, "UTF-8"); content = content.replaceAll(originalContent, changedContent); content = content.replaceAll(originalContent.replaceAll("\n", "\r\n"), changedContent.replaceAll("\n", "\r\n")); FileOutputStream output = new FileOutputStream(SettingsContainer.getAbsoluteSubtitlePath() + File.separator + sub.getId() + ".vtt"); IOUtils.write(content, output, "UTF-8"); output.close(); input.close(); } /** * Generates a new unique ID for the item */ public void generateId() { id = (new BigInteger(130, RandomContainer.getRandom())).toString(32); } /** * @return The ID of the Media element associated to this object */ public String getTargetID() { return targetID; } /** * @param targetID The new ID of the Media element associated to this object */ public void setTargetID(String targetID) { this.targetID = targetID; } /** * @return The change itself */ public String getChangedContent() { return changedContent; } /** * @param content The new data to change */ public void setChangedContent(String content) { this.changedContent = content; } /** * @return The change's unique ID */ public String getId() { return id; } /** * @param id The change's new unique ID */ public void setId(String id) { this.id = id; } /** * @return The user IDs who voted for this change */ public String getVotes() { return votes; } /** * @param votes The new user IDs who voted for this change */ public void setVotes(String votes) { this.votes = votes; nrVotes = votes.length() - votes.replace(";", "").length(); } /** * @return The original content prior to changing */ public String getOriginalContent() { return originalContent; } /** * @param originalContent The new original content prior to changing */ public void setOriginalContent(String originalContent) { this.originalContent = originalContent; } /** * @return the nrVotes */ public int getNrVotes() { return nrVotes; } /** * @param nrVotes the nrVotes to set */ public void setNrVotes(int nrVotes) { this.nrVotes = nrVotes; } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_20) on Tue May 04 10:00:19 CEST 2010 --> <TITLE> Uses of Class mx.database.table.Query </TITLE> <META NAME="date" CONTENT="2010-05-04"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class mx.database.table.Query"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../mx/database/table/Query.html" title="class in mx.database.table"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?mx/database/table/\class-useQuery.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Query.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>mx.database.table.Query</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../mx/database/table/Query.html" title="class in mx.database.table">Query</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#mx.database.navigator"><B>mx.database.navigator</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#mx.database.table.test"><B>mx.database.table.test</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="mx.database.navigator"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../mx/database/table/Query.html" title="class in mx.database.table">Query</A> in <A HREF="../../../../mx/database/navigator/package-summary.html">mx.database.navigator</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../mx/database/table/Query.html" title="class in mx.database.table">Query</A> in <A HREF="../../../../mx/database/navigator/package-summary.html">mx.database.navigator</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../mx/database/navigator/QueryNavigator.html" title="class in mx.database.navigator">QueryNavigator</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Questa classe viene utilizzata per la gestione della navigazione delle tabelle</TD> </TR> </TABLE> &nbsp; <P> <A NAME="mx.database.table.test"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../mx/database/table/Query.html" title="class in mx.database.table">Query</A> in <A HREF="../../../../mx/database/table/test/package-summary.html">mx.database.table.test</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../mx/database/table/Query.html" title="class in mx.database.table">Query</A> in <A HREF="../../../../mx/database/table/test/package-summary.html">mx.database.table.test</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../mx/database/table/test/CalcID.html" title="class in mx.database.table.test">CalcID</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../../../mx/database/table/test/package-summary.html">mx.database.table.test</A> declared as <A HREF="../../../../mx/database/table/Query.html" title="class in mx.database.table">Query</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>private &nbsp;<A HREF="../../../../mx/database/table/Query.html" title="class in mx.database.table">Query</A></CODE></FONT></TD> <TD><CODE><B>QueryTest.</B><B><A HREF="../../../../mx/database/table/test/QueryTest.html#query">query</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../mx/database/table/Query.html" title="class in mx.database.table"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?mx/database/table/\class-useQuery.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Query.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
Java
from ctypes import * import ctypes.util import threading import os import sys from warnings import warn from functools import partial import collections import re import traceback # vim: ts=4 sw=4 et if os.name == 'nt': backend = CDLL('mpv-1.dll') fs_enc = 'utf-8' else: import locale lc, enc = locale.getlocale(locale.LC_NUMERIC) # libmpv requires LC_NUMERIC to be set to "C". Since messing with global variables everyone else relies upon is # still better than segfaulting, we are setting LC_NUMERIC to "C". locale.setlocale(locale.LC_NUMERIC, 'C') sofile = ctypes.util.find_library('mpv') if sofile is None: raise OSError("Cannot find libmpv in the usual places. Depending on your distro, you may try installing an " "mpv-devel or mpv-libs package. If you have libmpv around but this script can't find it, maybe consult " "the documentation for ctypes.util.find_library which this script uses to look up the library " "filename.") backend = CDLL(sofile) fs_enc = sys.getfilesystemencoding() class MpvHandle(c_void_p): pass class MpvOpenGLCbContext(c_void_p): pass class PropertyUnavailableError(AttributeError): pass class ErrorCode(object): """ For documentation on these, see mpv's libmpv/client.h """ SUCCESS = 0 EVENT_QUEUE_FULL = -1 NOMEM = -2 UNINITIALIZED = -3 INVALID_PARAMETER = -4 OPTION_NOT_FOUND = -5 OPTION_FORMAT = -6 OPTION_ERROR = -7 PROPERTY_NOT_FOUND = -8 PROPERTY_FORMAT = -9 PROPERTY_UNAVAILABLE = -10 PROPERTY_ERROR = -11 COMMAND = -12 EXCEPTION_DICT = { 0: None, -1: lambda *a: MemoryError('mpv event queue full', *a), -2: lambda *a: MemoryError('mpv cannot allocate memory', *a), -3: lambda *a: ValueError('Uninitialized mpv handle used', *a), -4: lambda *a: ValueError('Invalid value for mpv parameter', *a), -5: lambda *a: AttributeError('mpv option does not exist', *a), -6: lambda *a: TypeError('Tried to set mpv option using wrong format', *a), -7: lambda *a: ValueError('Invalid value for mpv option', *a), -8: lambda *a: AttributeError('mpv property does not exist', *a), # Currently (mpv 0.18.1) there is a bug causing a PROPERTY_FORMAT error to be returned instead of # INVALID_PARAMETER when setting a property-mapped option to an invalid value. -9: lambda *a: TypeError('Tried to get/set mpv property using wrong format, or passed invalid value', *a), -10: lambda *a: PropertyUnavailableError('mpv property is not available', *a), -11: lambda *a: RuntimeError('Generic error getting or setting mpv property', *a), -12: lambda *a: SystemError('Error running mpv command', *a) } @staticmethod def default_error_handler(ec, *args): return ValueError(_mpv_error_string(ec).decode('utf-8'), ec, *args) @classmethod def raise_for_ec(kls, ec, func, *args): ec = 0 if ec > 0 else ec ex = kls.EXCEPTION_DICT.get(ec , kls.default_error_handler) if ex: raise ex(ec, *args) class MpvFormat(c_int): NONE = 0 STRING = 1 OSD_STRING = 2 FLAG = 3 INT64 = 4 DOUBLE = 5 NODE = 6 NODE_ARRAY = 7 NODE_MAP = 8 BYTE_ARRAY = 9 def __eq__(self, other): return self is other or self.value == other or self.value == int(other) def __repr__(self): return ['NONE', 'STRING', 'OSD_STRING', 'FLAG', 'INT64', 'DOUBLE', 'NODE', 'NODE_ARRAY', 'NODE_MAP', 'BYTE_ARRAY'][self.value] class MpvEventID(c_int): NONE = 0 SHUTDOWN = 1 LOG_MESSAGE = 2 GET_PROPERTY_REPLY = 3 SET_PROPERTY_REPLY = 4 COMMAND_REPLY = 5 START_FILE = 6 END_FILE = 7 FILE_LOADED = 8 TRACKS_CHANGED = 9 TRACK_SWITCHED = 10 IDLE = 11 PAUSE = 12 UNPAUSE = 13 TICK = 14 SCRIPT_INPUT_DISPATCH = 15 CLIENT_MESSAGE = 16 VIDEO_RECONFIG = 17 AUDIO_RECONFIG = 18 METADATA_UPDATE = 19 SEEK = 20 PLAYBACK_RESTART = 21 PROPERTY_CHANGE = 22 CHAPTER_CHANGE = 23 ANY = ( SHUTDOWN, LOG_MESSAGE, GET_PROPERTY_REPLY, SET_PROPERTY_REPLY, COMMAND_REPLY, START_FILE, END_FILE, FILE_LOADED, TRACKS_CHANGED, TRACK_SWITCHED, IDLE, PAUSE, UNPAUSE, TICK, SCRIPT_INPUT_DISPATCH, CLIENT_MESSAGE, VIDEO_RECONFIG, AUDIO_RECONFIG, METADATA_UPDATE, SEEK, PLAYBACK_RESTART, PROPERTY_CHANGE, CHAPTER_CHANGE ) def __repr__(self): return ['NONE', 'SHUTDOWN', 'LOG_MESSAGE', 'GET_PROPERTY_REPLY', 'SET_PROPERTY_REPLY', 'COMMAND_REPLY', 'START_FILE', 'END_FILE', 'FILE_LOADED', 'TRACKS_CHANGED', 'TRACK_SWITCHED', 'IDLE', 'PAUSE', 'UNPAUSE', 'TICK', 'SCRIPT_INPUT_DISPATCH', 'CLIENT_MESSAGE', 'VIDEO_RECONFIG', 'AUDIO_RECONFIG', 'METADATA_UPDATE', 'SEEK', 'PLAYBACK_RESTART', 'PROPERTY_CHANGE', 'CHAPTER_CHANGE'][self.value] class MpvNodeList(Structure): def array_value(self, decode_str=False): return [ self.values[i].node_value(decode_str) for i in range(self.num) ] def dict_value(self, decode_str=False): return { self.keys[i].decode('utf-8'): self.values[i].node_value(decode_str) for i in range(self.num) } class MpvNode(Structure): _fields_ = [('val', c_longlong), ('format', MpvFormat)] def node_value(self, decode_str=False): return MpvNode.node_cast_value(byref(c_void_p(self.val)), self.format.value, decode_str) @staticmethod def node_cast_value(v, fmt, decode_str=False): dwrap = lambda s: s.decode('utf-8') if decode_str else s return { MpvFormat.NONE: lambda v: None, MpvFormat.STRING: lambda v: dwrap(cast(v, POINTER(c_char_p)).contents.value), MpvFormat.OSD_STRING: lambda v: cast(v, POINTER(c_char_p)).contents.value.decode('utf-8'), MpvFormat.FLAG: lambda v: bool(cast(v, POINTER(c_int)).contents.value), MpvFormat.INT64: lambda v: cast(v, POINTER(c_longlong)).contents.value, MpvFormat.DOUBLE: lambda v: cast(v, POINTER(c_double)).contents.value, MpvFormat.NODE: lambda v: cast(v, POINTER(MpvNode)).contents.node_value(decode_str), MpvFormat.NODE_ARRAY: lambda v: cast(v, POINTER(POINTER(MpvNodeList))).contents.contents.array_value(decode_str), MpvFormat.NODE_MAP: lambda v: cast(v, POINTER(POINTER(MpvNodeList))).contents.contents.dict_value(decode_str), MpvFormat.BYTE_ARRAY: lambda v: cast(v, POINTER(c_char_p)).contents.value, }[fmt](v) MpvNodeList._fields_ = [('num', c_int), ('values', POINTER(MpvNode)), ('keys', POINTER(c_char_p))] class MpvSubApi(c_int): MPV_SUB_API_OPENGL_CB = 1 class MpvEvent(Structure): _fields_ = [('event_id', MpvEventID), ('error', c_int), ('reply_userdata', c_ulonglong), ('data', c_void_p)] def as_dict(self): dtype = {MpvEventID.END_FILE: MpvEventEndFile, MpvEventID.PROPERTY_CHANGE: MpvEventProperty, MpvEventID.GET_PROPERTY_REPLY: MpvEventProperty, MpvEventID.LOG_MESSAGE: MpvEventLogMessage, MpvEventID.SCRIPT_INPUT_DISPATCH: MpvEventScriptInputDispatch, MpvEventID.CLIENT_MESSAGE: MpvEventClientMessage }.get(self.event_id.value, None) return {'event_id': self.event_id.value, 'error': self.error, 'reply_userdata': self.reply_userdata, 'event': cast(self.data, POINTER(dtype)).contents.as_dict() if dtype else None} class MpvEventProperty(Structure): _fields_ = [('name', c_char_p), ('format', MpvFormat), ('data', c_void_p)] def as_dict(self): if self.format.value == MpvFormat.STRING: proptype, _access = ALL_PROPERTIES.get(self.name, (str, None)) return {'name': self.name.decode('utf-8'), 'format': self.format, 'data': self.data, 'value': proptype(cast(self.data, POINTER(c_char_p)).contents.value.decode('utf-8'))} else: return {'name': self.name.decode('utf-8'), 'format': self.format, 'data': self.data} class MpvEventLogMessage(Structure): _fields_ = [('prefix', c_char_p), ('level', c_char_p), ('text', c_char_p)] def as_dict(self): return { 'prefix': self.prefix.decode('utf-8'), 'level': self.level.decode('utf-8'), 'text': self.text.decode('utf-8').rstrip() } class MpvEventEndFile(c_int): EOF_OR_INIT_FAILURE = 0 RESTARTED = 1 ABORTED = 2 QUIT = 3 def as_dict(self): return {'reason': self.value} class MpvEventScriptInputDispatch(Structure): _fields_ = [('arg0', c_int), ('type', c_char_p)] def as_dict(self): pass # TODO class MpvEventClientMessage(Structure): _fields_ = [('num_args', c_int), ('args', POINTER(c_char_p))] def as_dict(self): return { 'args': [ self.args[i].decode('utf-8') for i in range(self.num_args) ] } WakeupCallback = CFUNCTYPE(None, c_void_p) OpenGlCbUpdateFn = CFUNCTYPE(None, c_void_p) OpenGlCbGetProcAddrFn = CFUNCTYPE(None, c_void_p, c_char_p) def _handle_func(name, args, restype, errcheck, ctx=MpvHandle): func = getattr(backend, name) func.argtypes = [ctx] + args if ctx else args if restype is not None: func.restype = restype if errcheck is not None: func.errcheck = errcheck globals()['_'+name] = func def bytes_free_errcheck(res, func, *args): notnull_errcheck(res, func, *args) rv = cast(res, c_void_p).value _mpv_free(res) return rv def notnull_errcheck(res, func, *args): if res is None: raise RuntimeError('Underspecified error in MPV when calling {} with args {!r}: NULL pointer returned.'\ 'Please consult your local debugger.'.format(func.__name__, args)) return res ec_errcheck = ErrorCode.raise_for_ec def _handle_gl_func(name, args=[], restype=None): _handle_func(name, args, restype, errcheck=None, ctx=MpvOpenGLCbContext) backend.mpv_client_api_version.restype = c_ulong def _mpv_client_api_version(): ver = backend.mpv_client_api_version() return ver>>16, ver&0xFFFF backend.mpv_free.argtypes = [c_void_p] _mpv_free = backend.mpv_free backend.mpv_free_node_contents.argtypes = [c_void_p] _mpv_free_node_contents = backend.mpv_free_node_contents backend.mpv_create.restype = MpvHandle _mpv_create = backend.mpv_create _handle_func('mpv_create_client', [c_char_p], MpvHandle, notnull_errcheck) _handle_func('mpv_client_name', [], c_char_p, errcheck=None) _handle_func('mpv_initialize', [], c_int, ec_errcheck) _handle_func('mpv_detach_destroy', [], None, errcheck=None) _handle_func('mpv_terminate_destroy', [], None, errcheck=None) _handle_func('mpv_load_config_file', [c_char_p], c_int, ec_errcheck) _handle_func('mpv_suspend', [], None, errcheck=None) _handle_func('mpv_resume', [], None, errcheck=None) _handle_func('mpv_get_time_us', [], c_ulonglong, errcheck=None) _handle_func('mpv_set_option', [c_char_p, MpvFormat, c_void_p], c_int, ec_errcheck) _handle_func('mpv_set_option_string', [c_char_p, c_char_p], c_int, ec_errcheck) _handle_func('mpv_command', [POINTER(c_char_p)], c_int, ec_errcheck) _handle_func('mpv_command_string', [c_char_p, c_char_p], c_int, ec_errcheck) _handle_func('mpv_command_async', [c_ulonglong, POINTER(c_char_p)], c_int, ec_errcheck) _handle_func('mpv_set_property', [c_char_p, MpvFormat, c_void_p], c_int, ec_errcheck) _handle_func('mpv_set_property_string', [c_char_p, c_char_p], c_int, ec_errcheck) _handle_func('mpv_set_property_async', [c_ulonglong, c_char_p, MpvFormat,c_void_p],c_int, ec_errcheck) _handle_func('mpv_get_property', [c_char_p, MpvFormat, c_void_p], c_int, ec_errcheck) _handle_func('mpv_get_property_string', [c_char_p], c_void_p, bytes_free_errcheck) _handle_func('mpv_get_property_osd_string', [c_char_p], c_void_p, bytes_free_errcheck) _handle_func('mpv_get_property_async', [c_ulonglong, c_char_p, MpvFormat], c_int, ec_errcheck) _handle_func('mpv_observe_property', [c_ulonglong, c_char_p, MpvFormat], c_int, ec_errcheck) _handle_func('mpv_unobserve_property', [c_ulonglong], c_int, ec_errcheck) _handle_func('mpv_event_name', [c_int], c_char_p, errcheck=None, ctx=None) _handle_func('mpv_error_string', [c_int], c_char_p, errcheck=None, ctx=None) _handle_func('mpv_request_event', [MpvEventID, c_int], c_int, ec_errcheck) _handle_func('mpv_request_log_messages', [c_char_p], c_int, ec_errcheck) _handle_func('mpv_wait_event', [c_double], POINTER(MpvEvent), errcheck=None) _handle_func('mpv_wakeup', [], None, errcheck=None) _handle_func('mpv_set_wakeup_callback', [WakeupCallback, c_void_p], None, errcheck=None) _handle_func('mpv_get_wakeup_pipe', [], c_int, errcheck=None) _handle_func('mpv_get_sub_api', [MpvSubApi], c_void_p, notnull_errcheck) _handle_gl_func('mpv_opengl_cb_set_update_callback', [OpenGlCbUpdateFn, c_void_p]) _handle_gl_func('mpv_opengl_cb_init_gl', [c_char_p, OpenGlCbGetProcAddrFn, c_void_p], c_int) _handle_gl_func('mpv_opengl_cb_draw', [c_int, c_int, c_int], c_int) _handle_gl_func('mpv_opengl_cb_render', [c_int, c_int], c_int) _handle_gl_func('mpv_opengl_cb_report_flip', [c_ulonglong], c_int) _handle_gl_func('mpv_opengl_cb_uninit_gl', [], c_int) def _ensure_encoding(possibly_bytes): return possibly_bytes.decode('utf-8') if type(possibly_bytes) is bytes else possibly_bytes def _event_generator(handle): while True: event = _mpv_wait_event(handle, -1).contents if event.event_id.value == MpvEventID.NONE: raise StopIteration() yield event def load_lua(): """ Use this function if you intend to use mpv's built-in lua interpreter. This is e.g. needed for playback of youtube urls. """ CDLL('liblua.so', mode=RTLD_GLOBAL) def _event_loop(event_handle, playback_cond, event_callbacks, message_handlers, property_handlers, log_handler): for event in _event_generator(event_handle): try: devent = event.as_dict() # copy data from ctypes eid = devent['event_id'] for callback in event_callbacks: callback(devent) if eid in (MpvEventID.SHUTDOWN, MpvEventID.END_FILE): with playback_cond: playback_cond.notify_all() if eid == MpvEventID.PROPERTY_CHANGE: pc = devent['event'] name = pc['name'] if 'value' in pc: proptype, _access = ALL_PROPERTIES[name] if proptype is bytes: args = (pc['value'],) else: args = (proptype(_ensure_encoding(pc['value'])),) elif pc['format'] == MpvFormat.NONE: args = (None,) else: args = (pc['data'], pc['format']) for handler in property_handlers[name]: handler(*args) if eid == MpvEventID.LOG_MESSAGE and log_handler is not None: ev = devent['event'] log_handler(ev['level'], ev['prefix'], ev['text']) if eid == MpvEventID.CLIENT_MESSAGE: # {'event': {'args': ['key-binding', 'foo', 'u-', 'g']}, 'reply_userdata': 0, 'error': 0, 'event_id': 16} target, *args = devent['event']['args'] if target in message_handlers: message_handlers[target](*args) if eid == MpvEventID.SHUTDOWN: _mpv_detach_destroy(event_handle) return except Exception as e: traceback.print_exc() class MPV(object): """ See man mpv(1) for the details of the implemented commands. """ def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, **extra_mpv_opts): """ Create an MPV instance. Extra arguments and extra keyword arguments will be passed to mpv as options. """ self._event_thread = None self.handle = _mpv_create() _mpv_set_option_string(self.handle, b'audio-display', b'no') istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o) try: for flag in extra_mpv_flags: _mpv_set_option_string(self.handle, flag.encode('utf-8'), b'') for k,v in extra_mpv_opts.items(): _mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8')) except AttributeError as e: _mpv_initialize(self.handle) raise e _mpv_initialize(self.handle) self._event_callbacks = [] self._property_handlers = collections.defaultdict(lambda: []) self._message_handlers = {} self._key_binding_handlers = {} self._playback_cond = threading.Condition() self._event_handle = _mpv_create_client(self.handle, b'py_event_handler') self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks, self._message_handlers, self._property_handlers, log_handler) if start_event_thread: self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread') self._event_thread.setDaemon(True) self._event_thread.start() else: self._event_thread = None if log_handler is not None: self.set_loglevel('terminal-default') def wait_for_playback(self): """ Waits until playback of the current title is paused or done """ with self._playback_cond: self._playback_cond.wait() def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True): sema = threading.Semaphore(value=0) def observer(val): if cond(val): sema.release() self.observe_property(name, observer) if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))): sema.acquire() self.unobserve_property(name, observer) def __del__(self): if self.handle: self.terminate() def terminate(self): self.handle, handle = None, self.handle if threading.current_thread() is self._event_thread: # Handle special case to allow event handle to be detached. # This is necessary since otherwise the event thread would deadlock itself. grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle)) grim_reaper.start() else: _mpv_terminate_destroy(handle) if self._event_thread: self._event_thread.join() def set_loglevel(self, level): _mpv_request_log_messages(self._event_handle, level.encode('utf-8')) def command(self, name, *args): """ Execute a raw command """ args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8')) for arg in args if arg is not None ] + [None] _mpv_command(self.handle, (c_char_p*len(args))(*args)) def seek(self, amount, reference="relative", precision="default-precise"): self.command('seek', amount, reference, precision) def revert_seek(self): self.command('revert_seek'); def frame_step(self): self.command('frame_step') def frame_back_step(self): self.command('frame_back_step') def _add_property(self, name, value=None): self.command('add_property', name, value) def _cycle_property(self, name, direction='up'): self.command('cycle_property', name, direction) def _multiply_property(self, name, factor): self.command('multiply_property', name, factor) def screenshot(self, includes='subtitles', mode='single'): self.command('screenshot', includes, mode) def screenshot_to_file(self, filename, includes='subtitles'): self.command('screenshot_to_file', filename.encode(fs_enc), includes) def playlist_next(self, mode='weak'): self.command('playlist_next', mode) def playlist_prev(self, mode='weak'): self.command('playlist_prev', mode) @staticmethod def _encode_options(options): return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items()) def loadfile(self, filename, mode='replace', **options): self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options)) def loadlist(self, playlist, mode='replace'): self.command('loadlist', playlist.encode(fs_enc), mode) def playlist_clear(self): self.command('playlist_clear') def playlist_remove(self, index='current'): self.command('playlist_remove', index) def playlist_move(self, index1, index2): self.command('playlist_move', index1, index2) def run(self, command, *args): self.command('run', command, *args) def quit(self, code=None): self.command('quit', code) def quit_watch_later(self, code=None): self.command('quit_watch_later', code) def sub_add(self, filename): self.command('sub_add', filename.encode(fs_enc)) def sub_remove(self, sub_id=None): self.command('sub_remove', sub_id) def sub_reload(self, sub_id=None): self.command('sub_reload', sub_id) def sub_step(self, skip): self.command('sub_step', skip) def sub_seek(self, skip): self.command('sub_seek', skip) def toggle_osd(self): self.command('osd') def show_text(self, string, duration='-', level=None): self.command('show_text', string, duration, level) def show_progress(self): self.command('show_progress') def discnav(self, command): self.command('discnav', command) def write_watch_later_config(self): self.command('write_watch_later_config') def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride): self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride) def overlay_remove(self, overlay_id): self.command('overlay_remove', overlay_id) def script_message(self, *args): self.command('script_message', *args) def script_message_to(self, target, *args): self.command('script_message_to', target, *args) def observe_property(self, name, handler): self._property_handlers[name].append(handler) _mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.STRING) def unobserve_property(self, name, handler): handlers = self._property_handlers[name] handlers.remove(handler) if not handlers: _mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff) def register_message_handler(self, target, handler): self._message_handlers[target] = handler def unregister_message_handler(self, target): del self._message_handlers[target] def register_event_callback(self, callback): self._event_callbacks.append(callback) def unregister_event_callback(self, callback): self._event_callbacks.remove(callback) @staticmethod def _binding_name(callback_or_cmd): return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff) def register_key_binding(self, keydef, callback_or_cmd, mode='force'): """ BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether this is secure in your case. """ if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef): raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n' '<key> is either the literal character the key produces (ASCII or Unicode character), or a ' 'symbolic name (as printed by --input-keylist') binding_name = MPV._binding_name(keydef) if callable(callback_or_cmd): self._key_binding_handlers[binding_name] = callback_or_cmd self.register_message_handler('key-binding', self._handle_key_binding_message) self.command('define-section', binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode) elif isinstance(callback_or_cmd, str): self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode) else: raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.') self.command('enable-section', binding_name) def _handle_key_binding_message(self, binding_name, key_state, key_name): self._key_binding_handlers[binding_name](key_state, key_name) def unregister_key_binding(self, keydef): binding_name = MPV._binding_name(keydef) self.command('disable-section', binding_name) self.command('define-section', binding_name, '') if callable(callback): del self._key_binding_handlers[binding_name] if not self._key_binding_handlers: self.unregister_message_handler('key-binding') # Convenience functions def play(self, filename): self.loadfile(filename) # Property accessors def _get_property(self, name, proptype=str, decode_str=False): fmt = {int: MpvFormat.INT64, float: MpvFormat.DOUBLE, bool: MpvFormat.FLAG, str: MpvFormat.STRING, bytes: MpvFormat.STRING, commalist: MpvFormat.STRING, MpvFormat.NODE: MpvFormat.NODE}[proptype] out = cast(create_string_buffer(sizeof(c_void_p)), c_void_p) outptr = byref(out) try: cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, outptr) rv = MpvNode.node_cast_value(outptr, fmt, decode_str or proptype in (str, commalist)) if proptype is commalist: rv = proptype(rv) if proptype is str: _mpv_free(out) elif proptype is MpvFormat.NODE: _mpv_free_node_contents(outptr) return rv except PropertyUnavailableError as ex: return None def _set_property(self, name, value, proptype=str): ename = name.encode('utf-8') if type(value) is bytes: _mpv_set_property_string(self.handle, ename, value) elif type(value) is bool: _mpv_set_property_string(self.handle, ename, b'yes' if value else b'no') elif proptype in (str, int, float): _mpv_set_property_string(self.handle, ename, str(proptype(value)).encode('utf-8')) else: raise TypeError('Cannot set {} property {} to value of type {}'.format(proptype, name, type(value))) # Dict-like option access def __getitem__(self, name, file_local=False): """ Get an option value """ prefix = 'file-local-options/' if file_local else 'options/' return self._get_property(prefix+name) def __setitem__(self, name, value, file_local=False): """ Get an option value """ prefix = 'file-local-options/' if file_local else 'options/' return self._set_property(prefix+name, value) def __iter__(self): return iter(self.options) def option_info(self, name): return self._get_property('option-info/'+name) def commalist(propval=''): return str(propval).split(',') node = MpvFormat.NODE ALL_PROPERTIES = { 'osd-level': (int, 'rw'), 'osd-scale': (float, 'rw'), 'loop': (str, 'rw'), 'loop-file': (str, 'rw'), 'speed': (float, 'rw'), 'filename': (bytes, 'r'), 'file-size': (int, 'r'), 'path': (bytes, 'r'), 'media-title': (bytes, 'r'), 'stream-pos': (int, 'rw'), 'stream-end': (int, 'r'), 'length': (float, 'r'), # deprecated for ages now 'duration': (float, 'r'), 'avsync': (float, 'r'), 'total-avsync-change': (float, 'r'), 'drop-frame-count': (int, 'r'), 'percent-pos': (float, 'rw'), # 'ratio-pos': (float, 'rw'), 'time-pos': (float, 'rw'), 'time-start': (float, 'r'), 'time-remaining': (float, 'r'), 'playtime-remaining': (float, 'r'), 'chapter': (int, 'rw'), 'edition': (int, 'rw'), 'disc-titles': (int, 'r'), 'disc-title': (str, 'rw'), # 'disc-menu-active': (bool, 'r'), 'chapters': (int, 'r'), 'editions': (int, 'r'), 'angle': (int, 'rw'), 'pause': (bool, 'rw'), 'core-idle': (bool, 'r'), 'cache': (int, 'r'), 'cache-size': (int, 'rw'), 'cache-free': (int, 'r'), 'cache-used': (int, 'r'), 'cache-speed': (int, 'r'), 'cache-idle': (bool, 'r'), 'cache-buffering-state': (int, 'r'), 'paused-for-cache': (bool, 'r'), # 'pause-for-cache': (bool, 'r'), 'eof-reached': (bool, 'r'), # 'pts-association-mode': (str, 'rw'), 'hr-seek': (str, 'rw'), 'volume': (float, 'rw'), 'volume-max': (int, 'rw'), 'ao-volume': (float, 'rw'), 'mute': (bool, 'rw'), 'ao-mute': (bool, 'rw'), 'audio-speed-correction': (float, 'r'), 'audio-delay': (float, 'rw'), 'audio-format': (str, 'r'), 'audio-codec': (str, 'r'), 'audio-codec-name': (str, 'r'), 'audio-bitrate': (float, 'r'), 'packet-audio-bitrate': (float, 'r'), 'audio-samplerate': (int, 'r'), 'audio-channels': (str, 'r'), 'aid': (str, 'rw'), 'audio': (str, 'rw'), # alias for aid 'balance': (int, 'rw'), 'fullscreen': (bool, 'rw'), 'deinterlace': (str, 'rw'), 'colormatrix': (str, 'rw'), 'colormatrix-input-range': (str, 'rw'), # 'colormatrix-output-range': (str, 'rw'), 'colormatrix-primaries': (str, 'rw'), 'ontop': (bool, 'rw'), 'border': (bool, 'rw'), 'framedrop': (str, 'rw'), 'gamma': (float, 'rw'), 'brightness': (int, 'rw'), 'contrast': (int, 'rw'), 'saturation': (int, 'rw'), 'hue': (int, 'rw'), 'hwdec': (str, 'rw'), 'panscan': (float, 'rw'), 'video-format': (str, 'r'), 'video-codec': (str, 'r'), 'video-bitrate': (float, 'r'), 'packet-video-bitrate': (float, 'r'), 'width': (int, 'r'), 'height': (int, 'r'), 'dwidth': (int, 'r'), 'dheight': (int, 'r'), 'fps': (float, 'r'), 'estimated-vf-fps': (float, 'r'), 'window-scale': (float, 'rw'), 'video-aspect': (str, 'rw'), 'osd-width': (int, 'r'), 'osd-height': (int, 'r'), 'osd-par': (float, 'r'), 'vid': (str, 'rw'), 'video': (str, 'rw'), # alias for vid 'video-align-x': (float, 'rw'), 'video-align-y': (float, 'rw'), 'video-pan-x': (float, 'rw'), 'video-pan-y': (float, 'rw'), 'video-zoom': (float, 'rw'), 'video-unscaled': (bool, 'w'), 'video-speed-correction': (float, 'r'), 'program': (int, 'w'), 'sid': (str, 'rw'), 'sub': (str, 'rw'), # alias for sid 'secondary-sid': (str, 'rw'), 'sub-delay': (float, 'rw'), 'sub-pos': (int, 'rw'), 'sub-visibility': (bool, 'rw'), 'sub-forced-only': (bool, 'rw'), 'sub-scale': (float, 'rw'), 'sub-bitrate': (float, 'r'), 'packet-sub-bitrate': (float, 'r'), # 'ass-use-margins': (bool, 'rw'), 'ass-vsfilter-aspect-compat': (bool, 'rw'), 'ass-style-override': (bool, 'rw'), 'stream-capture': (str, 'rw'), 'tv-brightness': (int, 'rw'), 'tv-contrast': (int, 'rw'), 'tv-saturation': (int, 'rw'), 'tv-hue': (int, 'rw'), 'playlist-pos': (int, 'rw'), 'playlist-pos-1': (int, 'rw'), # ugh. 'playlist-count': (int, 'r'), # 'quvi-format': (str, 'rw'), 'seekable': (bool, 'r'), 'seeking': (bool, 'r'), 'partially-seekable': (bool, 'r'), 'playback-abort': (bool, 'r'), 'cursor-autohide': (str, 'rw'), 'audio-device': (str, 'rw'), 'current-vo': (str, 'r'), 'current-ao': (str, 'r'), 'audio-out-detected-device': (str, 'r'), 'protocol-list': (str, 'r'), 'mpv-version': (str, 'r'), 'mpv-configuration': (str, 'r'), 'ffmpeg-version': (str, 'r'), 'display-sync-active': (bool, 'r'), 'stream-open-filename': (bytes, 'rw'), # Undocumented 'file-format': (commalist,'r'), # Be careful with this one. 'mistimed-frame-count': (int, 'r'), 'vsync-ratio': (float, 'r'), 'vo-drop-frame-count': (int, 'r'), 'vo-delayed-frame-count': (int, 'r'), 'playback-time': (float, 'rw'), 'demuxer-cache-duration': (float, 'r'), 'demuxer-cache-time': (float, 'r'), 'demuxer-cache-idle': (bool, 'r'), 'idle': (bool, 'r'), 'disc-title-list': (commalist,'r'), 'field-dominance': (str, 'rw'), 'taskbar-progress': (bool, 'rw'), 'on-all-workspaces': (bool, 'rw'), 'video-output-levels': (str, 'r'), 'vo-configured': (bool, 'r'), 'hwdec-current': (str, 'r'), 'hwdec-interop': (str, 'r'), 'estimated-frame-count': (int, 'r'), 'estimated-frame-number': (int, 'r'), 'sub-use-margins': (bool, 'rw'), 'ass-force-margins': (bool, 'rw'), 'video-rotate': (str, 'rw'), 'video-stereo-mode': (str, 'rw'), 'ab-loop-a': (str, 'r'), # What a mess... 'ab-loop-b': (str, 'r'), 'dvb-channel': (str, 'w'), 'dvb-channel-name': (str, 'rw'), 'window-minimized': (bool, 'r'), 'display-names': (commalist, 'r'), 'display-fps': (float, 'r'), # access apparently misdocumented in the manpage 'estimated-display-fps': (float, 'r'), 'vsync-jitter': (float, 'r'), 'video-params': (node, 'r', True), 'video-out-params': (node, 'r', True), 'track-list': (node, 'r', False), 'playlist': (node, 'r', False), 'chapter-list': (node, 'r', False), 'vo-performance': (node, 'r', True), 'filtered-metadata': (node, 'r', False), 'metadata': (node, 'r', False), 'chapter-metadata': (node, 'r', False), 'vf-metadata': (node, 'r', False), 'af-metadata': (node, 'r', False), 'edition-list': (node, 'r', False), 'disc-titles': (node, 'r', False), 'audio-params': (node, 'r', True), 'audio-out-params': (node, 'r', True), 'audio-device-list': (node, 'r', True), 'video-frame-info': (node, 'r', True), 'decoder-list': (node, 'r', True), 'encoder-list': (node, 'r', True), 'vf': (node, 'r', True), 'af': (node, 'r', True), 'options': (node, 'r', True), 'file-local-options': (node, 'r', True), 'property-list': (commalist,'r')} def bindproperty(MPV, name, proptype, access, decode_str=False): getter = lambda self: self._get_property(name, proptype, decode_str) setter = lambda self, value: self._set_property(name, value, proptype) def barf(*args): raise NotImplementedError('Access denied') setattr(MPV, name.replace('-', '_'), property(getter if 'r' in access else barf, setter if 'w' in access else barf)) for name, (proptype, access, *args) in ALL_PROPERTIES.items(): bindproperty(MPV, name, proptype, access, *args)
Java
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2017 Kuali, Inc. * * 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/>. */ package org.kuali.kfs.module.purap.document.validation.impl; import org.kuali.kfs.coreservice.framework.parameter.ParameterService; import org.kuali.kfs.module.purap.PurapConstants; import org.kuali.kfs.module.purap.PurapParameterConstants; import org.kuali.kfs.module.purap.PurapRuleConstants; import org.kuali.kfs.module.purap.document.RequisitionDocument; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.kfs.sys.document.validation.event.AttributedDocumentEvent; public class RequisitionNewIndividualItemValidation extends PurchasingNewIndividualItemValidation { public boolean validate(AttributedDocumentEvent event) { return super.validate(event); } @Override protected boolean commodityCodeIsRequired() { //if the ENABLE_COMMODITY_CODE_IND parameter is N then we don't //need to check for the ITEMS_REQUIRE_COMMODITY_CODE_IND parameter anymore, just return false. boolean enableCommodityCode = SpringContext.getBean(ParameterService.class).getParameterValueAsBoolean(PurapConstants.PURAP_NAMESPACE, "Document", PurapParameterConstants.ENABLE_COMMODITY_CODE_IND); if (!enableCommodityCode) { return false; } else { return super.getParameterService().getParameterValueAsBoolean(RequisitionDocument.class, PurapRuleConstants.ITEMS_REQUIRE_COMMODITY_CODE_IND); } } }
Java
// License: MIT #pragma once //\brief: TypeFlags, mostly used to define updatePackets. //\note: check out class inheritance. it is not true that every unit is "just" a creature. /* object - unit - - player - - creature - - - pet <- probably wrong inheritance from summon not from creature - - - totem <- probably wrong inheritance from summon not from creature - - - vehicle - - - summon (pets and totems are always summons) - - - - pet - - - - totem - gameobject - dynamicobject - corpse - item - - container */ enum TYPE { TYPE_OBJECT = 1, TYPE_ITEM = 2, TYPE_CONTAINER = 4, TYPE_UNIT = 8, TYPE_PLAYER = 16, TYPE_GAMEOBJECT = 32, TYPE_DYNAMICOBJECT = 64, TYPE_CORPSE = 128, //TYPE_AIGROUP = 256, not used //TYPE_AREATRIGGER = 512, not used //TYPE_IN_GUILD = 1024 not used }; //\todo: remove these typeIds and use flags instead. No reason to use two different enums to define a object type. enum TYPEID { TYPEID_OBJECT = 0, TYPEID_ITEM = 1, TYPEID_CONTAINER = 2, TYPEID_UNIT = 3, TYPEID_PLAYER = 4, TYPEID_GAMEOBJECT = 5, TYPEID_DYNAMICOBJECT = 6, TYPEID_CORPSE = 7, //TYPEID_AIGROUP = 8, not used //TYPEID_AREATRIGGER = 9 not used (WoWTrigger is a thing on Cata) }; #ifdef AE_CATA enum OBJECT_UPDATE_TYPE { UPDATETYPE_VALUES = 0, UPDATETYPE_CREATE_OBJECT = 1, UPDATETYPE_CREATE_OBJECT2 = 2, UPDATETYPE_OUT_OF_RANGE_OBJECTS = 3 }; #else enum OBJECT_UPDATE_TYPE { UPDATETYPE_VALUES = 0, UPDATETYPE_MOVEMENT = 1, UPDATETYPE_CREATE_OBJECT = 2, UPDATETYPE_CREATE_YOURSELF = 3, UPDATETYPE_OUT_OF_RANGE_OBJECTS = 4 }; #endif enum PHASECOMMANDS { PHASE_SET = 0, /// overwrites the phase value with the supplied one PHASE_ADD = 1, /// adds the new bits to the current phase value PHASE_DEL = 2, /// removes the given bits from the current phase value PHASE_RESET = 3 /// sets the default phase of 1, same as PHASE_SET with 1 as the new value };
Java
<?php declare(strict_types=1); /** * @copyright Copyright (c) 2020, Morris Jobke <hey@morrisjobke.de> * * @author Morris Jobke <hey@morrisjobke.de> * * @license GNU AGPL version 3 or any later version * * 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 OC\Files\Mount; use OC\Files\ObjectStore\AppdataPreviewObjectStoreStorage; use OC\Files\ObjectStore\ObjectStoreStorage; use OC\Files\Storage\Wrapper\Jail; use OCP\Files\Config\IRootMountProvider; use OCP\Files\Storage\IStorageFactory; use OCP\IConfig; use OCP\ILogger; /** * Mount provider for object store app data folder for previews */ class ObjectStorePreviewCacheMountProvider implements IRootMountProvider { /** @var ILogger */ private $logger; /** @var IConfig */ private $config; public function __construct(ILogger $logger, IConfig $config) { $this->logger = $logger; $this->config = $config; } /** * @return MountPoint[] * @throws \Exception */ public function getRootMounts(IStorageFactory $loader): array { if (!is_array($this->config->getSystemValue('objectstore_multibucket'))) { return []; } if ($this->config->getSystemValue('objectstore.multibucket.preview-distribution', false) !== true) { return []; } $instanceId = $this->config->getSystemValueString('instanceid', ''); $mountPoints = []; $directoryRange = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; $i = 0; foreach ($directoryRange as $parent) { foreach ($directoryRange as $child) { $mountPoints[] = new MountPoint( AppdataPreviewObjectStoreStorage::class, '/appdata_' . $instanceId . '/preview/' . $parent . '/' . $child, $this->getMultiBucketObjectStore($i), $loader ); $i++; } } $rootStorageArguments = $this->getMultiBucketObjectStoreForRoot(); $fakeRootStorage = new ObjectStoreStorage($rootStorageArguments); $fakeRootStorageJail = new Jail([ 'storage' => $fakeRootStorage, 'root' => '/appdata_' . $instanceId . '/preview', ]); // add a fallback location to be able to fetch existing previews from the old bucket $mountPoints[] = new MountPoint( $fakeRootStorageJail, '/appdata_' . $instanceId . '/preview/old-multibucket', null, $loader ); return $mountPoints; } protected function getMultiBucketObjectStore(int $number): array { $config = $this->config->getSystemValue('objectstore_multibucket'); // sanity checks if (empty($config['class'])) { $this->logger->error('No class given for objectstore', ['app' => 'files']); } if (!isset($config['arguments'])) { $config['arguments'] = []; } /* * Use any provided bucket argument as prefix * and add the mapping from parent/child => bucket */ if (!isset($config['arguments']['bucket'])) { $config['arguments']['bucket'] = ''; } $config['arguments']['bucket'] .= "-preview-$number"; // instantiate object store implementation $config['arguments']['objectstore'] = new $config['class']($config['arguments']); $config['arguments']['internal-id'] = $number; return $config['arguments']; } protected function getMultiBucketObjectStoreForRoot(): array { $config = $this->config->getSystemValue('objectstore_multibucket'); // sanity checks if (empty($config['class'])) { $this->logger->error('No class given for objectstore', ['app' => 'files']); } if (!isset($config['arguments'])) { $config['arguments'] = []; } /* * Use any provided bucket argument as prefix * and add the mapping from parent/child => bucket */ if (!isset($config['arguments']['bucket'])) { $config['arguments']['bucket'] = ''; } $config['arguments']['bucket'] .= '0'; // instantiate object store implementation $config['arguments']['objectstore'] = new $config['class']($config['arguments']); return $config['arguments']; } }
Java
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../../../../../img/clover.ico" /> <link rel="stylesheet" href="../../../../../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../../../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../../../../../style.css'); @import url('../../../../../../../tree.css'); </style> <script src="../../../../../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../../../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../../../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../../../../../clover-tree.js" type="text/javascript"></script> <script src="../../../../../../../clover.js" type="text/javascript"></script> <script src="../../../../../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../../../../../cloud.js" type="text/javascript"></script> <title>rapidminer-studio-core 转换结果 </title> </head> <body > <div id="page"> <header id="header" role="banner"> <nav class="aui-header aui-dropdown2-trigger-group" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo aui-header-logo-clover"> <a href="http://www.atlassian.com/clover" title="Open Atlassian Clover home page"><span class="aui-header-logo-device">Clover</span></a> </h1> </div> <div class="aui-header-secondary"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online Clover documentation" target="_blank" href="https://confluence.atlassian.com/display/CLOVER/Clover+Documentation+Home"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="aui-page-panel-inner"> <div class="aui-page-panel-nav aui-page-panel-nav-clover"> <div class="aui-page-header-inner" style="margin-bottom: 20px;"> <div class="aui-page-header-image"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../../../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </div> <div class="aui-page-header-main" > <h1> rapidminer-studio-core 转换结果 </h1> </div> </div> <nav class="aui-navgroup aui-navgroup-vertical"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../../../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading packages-nav-heading"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui package-filter-container"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="package-filter-no-results-message hidden"> <small>No results found.</small> </p> <div class="packages-tree-wrapper" data-root-relative="../../../../../../../" data-package-name="com.rapidminer.tools.expression.internal.function.bitwise"> <div class="packages-tree-container"></div> <div class="clover-packages-lozenges"></div> </div> </div> </div> </nav> </div> <section class="aui-page-panel-content"> <div class="aui-page-panel-content-clover"> <ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../../../../../dashboard.html">Project Clover database 星期二 九月 5 2017 16:40:29 CST</a></li> </ol> <h1 class="aui-h2-clover"> Package com.rapidminer.tools.expression.internal.function.bitwise </h1> <div class="aui-tabs horizontal-tabs"> <ul class="tabs-menu"> <li class="menu-item "> <a href="pkg-summary.html"><strong>Application code</strong></a> </li> <li class="menu-item active-tab"> <a href="top-risks.html"><strong>Top risks</strong></a> </li> <li class="menu-item "> <a href="quick-wins.html"><strong>Quick wins</strong></a> </li> </ul> <div class="tabs-pane active-pane" id="tabs-first"> <div>&#160;</div> <div class="aui-message aui-message-warning"> <p class="title"> <strong>Evaluation License</strong> </p> <p> This report was generated with an evaluation server license. <a href="http://www.atlassian.com/software/clover">Purchase Clover</a> or <a href="http://confluence.atlassian.com/x/JAgQCQ">configure your license.</a> </p> </div> <div style="text-align: right; margin-bottom: 10px"> <button class="aui-button aui-button-subtle" id="popupHelp"> <span class="aui-icon aui-icon-small aui-iconfont-help"></span>&#160;How to read this chart </button> <script> AJS.InlineDialog(AJS.$("#popupHelp"), "helpDialog", function (content, trigger, showPopup) { var description = topRisksDescription(); var title = 'Top Risks'; content.css({"padding": "20px"}).html( '<h2>' + title + '</h2>' + description); showPopup(); return false; }, { width: 600 } ); </script> </div> <div style="padding: 20px; border: 1px solid #cccccc; background-color: #f5f5f5; border-radius: 3px"> <div id="shallowPackageCloud" > </div> </div> </div> <!-- tabs-pane active-pane --> </div> <!-- aui-tabs horizontal-tabs --> </div> <!-- class="aui-page-panel-content-clover" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://www.atlassian.com/software/clover">Atlassian Clover</a> v 4.1.2 on 星期二 九月 5 2017 17:24:16 CST using coverage data from 星期四 一月 1 1970 08:00:00 CST. </li> </ul> <ul> <li>Clover Evaluation License registered to Clover Plugin. You have 29 day(s) before your license expires.</li> </ul> <div id="footer-logo"> <a target="_blank" href="http://www.atlassian.com/"> Atlassian </a> </div> </section> </footer> </section> <!-- class="aui-page-panel-content" --> </div> <!-- class="aui-page-panel-inner" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
Java
# -- # Kernel/GenericInterface/Operation/Session/SessionCreate.pm - GenericInterface SessionCreate operation backend # Copyright (C) 2001-2014 OTRS AG, http://otrs.com/ # -- # This software comes with ABSOLUTELY NO WARRANTY. For details, see # the enclosed file COPYING for license information (AGPL). If you # did not receive this file, see http://www.gnu.org/licenses/agpl.txt. # -- package Kernel::GenericInterface::Operation::Session::SessionCreate; use strict; use warnings; use Kernel::GenericInterface::Operation::Common; use Kernel::GenericInterface::Operation::Session::Common; use Kernel::System::VariableCheck qw(IsStringWithData IsHashRefWithData); use vars qw(@ISA); =head1 NAME Kernel::GenericInterface::Operation::Ticket::SessionCreate - GenericInterface Session Create Operation backend =head1 SYNOPSIS =head1 PUBLIC INTERFACE =over 4 =cut =item new() usually, you want to create an instance of this by using Kernel::GenericInterface::Operation->new(); =cut sub new { my ( $Type, %Param ) = @_; my $Self = {}; bless( $Self, $Type ); # check needed objects for my $Needed ( qw(DebuggerObject ConfigObject MainObject LogObject TimeObject DBObject EncodeObject WebserviceID) ) { if ( !$Param{$Needed} ) { return { Success => 0, ErrorMessage => "Got no $Needed!" }; } $Self->{$Needed} = $Param{$Needed}; } # create additional objects $Self->{CommonObject} = Kernel::GenericInterface::Operation::Common->new( %{$Self} ); $Self->{SessionCommonObject} = Kernel::GenericInterface::Operation::Session::Common->new( %{$Self} ); return $Self; } =item Run() Retrieve a new session id value. my $Result = $OperationObject->Run( Data => { UserLogin => 'Agent1', CustomerUserLogin => 'Customer1', # optional, provide UserLogin or CustomerUserLogin Password => 'some password', # plain text password }, ); $Result = { Success => 1, # 0 or 1 ErrorMessage => '', # In case of an error Data => { SessionID => $SessionID, }, }; =cut sub Run { my ( $Self, %Param ) = @_; # check needed stuff if ( !IsHashRefWithData( $Param{Data} ) ) { return $Self->{CommonObject}->ReturnError( ErrorCode => 'SessionCreate.MissingParameter', ErrorMessage => "SessionCreate: The request is empty!", ); } for my $Needed (qw( Password )) { if ( !$Param{Data}->{$Needed} ) { return $Self->{CommonObject}->ReturnError( ErrorCode => 'SessionCreate.MissingParameter', ErrorMessage => "SessionCreate: $Needed parameter is missing!", ); } } my $SessionID = $Self->{SessionCommonObject}->CreateSessionID( %Param, ); if ( !$SessionID ) { return $Self->{CommonObject}->ReturnError( ErrorCode => 'SessionCreate.AuthFail', ErrorMessage => "SessionCreate: Authorization failing!", ); } return { Success => 1, Data => { SessionID => $SessionID, }, }; } 1; =back =head1 TERMS AND CONDITIONS This software is part of the OTRS project (L<http://otrs.org/>). This software comes with ABSOLUTELY NO WARRANTY. For details, see the enclosed file COPYING for license information (AGPL). If you did not receive this file, see L<http://www.gnu.org/licenses/agpl.txt>. =cut
Java
<?php /** * plentymarkets shopware connector * Copyright © 2013 plentymarkets GmbH * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License, supplemented by an additional * permission, and of our proprietary license can be found * in the LICENSE file you have received along with this program. * * 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. * * "plentymarkets" is a registered trademark of plentymarkets GmbH. * "shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, titles and interests in the * above trademarks remain entirely with the trademark owners. * * @copyright Copyright (c) 2013, plentymarkets GmbH (http://www.plentymarkets.com) * @author Daniel Bächtle <daniel.baechtle@plentymarkets.com> */ /** * I am a generated class and am required for communicating with plentymarkets. */ class PlentySoapObject_ItemBase { /** * @var ArrayOfPlentysoapobject_itemattributevalueset */ public $AttributeValueSets; /** * @var PlentySoapObject_ItemAvailability */ public $Availability; /** * @var string */ public $BundleType; /** * @var ArrayOfPlentysoapobject_itemcategory */ public $Categories; /** * @var int */ public $Condition; /** * @var string */ public $CustomsTariffNumber; /** * @var string */ public $DeepLink; /** * @var string */ public $EAN1; /** * @var string */ public $EAN2; /** * @var string */ public $EAN3; /** * @var string */ public $EAN4; /** * @var string */ public $ExternalItemID; /** * @var int */ public $FSK; /** * @var PlentySoapObject_ItemFreeTextFields */ public $FreeTextFields; /** * @var int */ public $HasAttributes; /** * @var string */ public $ISBN; /** * @var int */ public $Inserted; /** * @var ArrayOfPlentysoapobject_itemattributemarkup */ public $ItemAttributeMarkup; /** * @var int */ public $ItemID; /** * @var string */ public $ItemNo; /** * @var ArrayOfPlentysoapobject_itemproperty */ public $ItemProperties; /** * @var ArrayOfPlentysoapobject_itemsupplier */ public $ItemSuppliers; /** * @var string */ public $ItemURL; /** * @var int */ public $LastUpdate; /** * @var int */ public $Marking1ID; /** * @var int */ public $Marking2ID; /** * @var string */ public $Model; /** * @var PlentySoapObject_ItemOthers */ public $Others; /** * @var ArrayOfPlentysoapobject_integer */ public $ParcelServicePresetIDs; /** * @var string */ public $Position; /** * @var PlentySoapObject_ItemPriceSet */ public $PriceSet; /** * @var int */ public $ProducerID; /** * @var string */ public $ProducerName; /** * @var int */ public $ProducingCountryID; /** * @var int */ public $Published; /** * @var PlentySoapObject_ItemStock */ public $Stock; /** * @var int */ public $StorageLocation; /** * @var PlentySoapObject_ItemTexts */ public $Texts; /** * @var int */ public $Type; /** * @var int */ public $VATInternalID; /** * @var string */ public $WebShopSpecial; }
Java