code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/******************************************************************************* * Copyright (c) 2006, 2009 David A Carlson * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * David A Carlson (XMLmodeling.com) - initial API and implementation *******************************************************************************/ package org.openhealthtools.mdht.emf.w3c.xhtml; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Q</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link org.openhealthtools.mdht.emf.w3c.xhtml.Q#getCite1 <em>Cite1</em>}</li> * <li>{@link org.openhealthtools.mdht.emf.w3c.xhtml.Q#getClass_ <em>Class</em>}</li> * <li>{@link org.openhealthtools.mdht.emf.w3c.xhtml.Q#getLang <em>Lang</em>}</li> * <li>{@link org.openhealthtools.mdht.emf.w3c.xhtml.Q#getStyle <em>Style</em>}</li> * </ul> * </p> * * @see org.openhealthtools.mdht.emf.w3c.xhtml.XhtmlPackage#getQ() * @model extendedMetaData="name='Q' kind='mixed'" * @generated */ public interface Q extends Inline { /** * Returns the value of the '<em><b>Cite1</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * Provides a reference to the external source from which the quote is extracted. * <!-- end-model-doc --> * @return the value of the '<em>Cite1</em>' attribute. * @see #setCite1(String) * @see org.openhealthtools.mdht.emf.w3c.xhtml.XhtmlPackage#getQ_Cite1() * @model dataType="org.openhealthtools.mdht.emf.w3c.xhtml.URI" * extendedMetaData="kind='attribute' name='cite'" * @generated */ String getCite1(); /** * Sets the value of the '{@link org.openhealthtools.mdht.emf.w3c.xhtml.Q#getCite1 <em>Cite1</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Cite1</em>' attribute. * @see #getCite1() * @generated */ void setCite1(String value); /** * Returns the value of the '<em><b>Class</b></em>' attribute. * The literals are from the enumeration {@link org.openhealthtools.mdht.emf.w3c.xhtml.MifClassType}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * space separated list of classes * <!-- end-model-doc --> * @return the value of the '<em>Class</em>' attribute. * @see org.openhealthtools.mdht.emf.w3c.xhtml.MifClassType * @see #isSetClass() * @see #unsetClass() * @see #setClass(MifClassType) * @see org.openhealthtools.mdht.emf.w3c.xhtml.XhtmlPackage#getQ_Class() * @model unsettable="true" * extendedMetaData="kind='attribute' name='class'" * @generated */ MifClassType getClass_(); /** * Sets the value of the '{@link org.openhealthtools.mdht.emf.w3c.xhtml.Q#getClass_ <em>Class</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Class</em>' attribute. * @see org.openhealthtools.mdht.emf.w3c.xhtml.MifClassType * @see #isSetClass() * @see #unsetClass() * @see #getClass_() * @generated */ void setClass(MifClassType value); /** * Unsets the value of the '{@link org.openhealthtools.mdht.emf.w3c.xhtml.Q#getClass_ <em>Class</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetClass() * @see #getClass_() * @see #setClass(MifClassType) * @generated */ void unsetClass(); /** * Returns whether the value of the '{@link org.openhealthtools.mdht.emf.w3c.xhtml.Q#getClass_ <em>Class</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Class</em>' attribute is set. * @see #unsetClass() * @see #getClass_() * @see #setClass(MifClassType) * @generated */ boolean isSetClass(); /** * Returns the value of the '<em><b>Lang</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * language code (as per XML 1.0 spec) * <!-- end-model-doc --> * @return the value of the '<em>Lang</em>' attribute. * @see #setLang(String) * @see org.openhealthtools.mdht.emf.w3c.xhtml.XhtmlPackage#getQ_Lang() * @model dataType="org.eclipse.emf.ecore.xml.namespace.LangType" * extendedMetaData="kind='attribute' name='lang' namespace='http://www.w3.org/XML/1998/namespace'" * @generated */ String getLang(); /** * Sets the value of the '{@link org.openhealthtools.mdht.emf.w3c.xhtml.Q#getLang <em>Lang</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Lang</em>' attribute. * @see #getLang() * @generated */ void setLang(String value); /** * Returns the value of the '<em><b>Style</b></em>' attribute. * The literals are from the enumeration {@link org.openhealthtools.mdht.emf.w3c.xhtml.StyleSheet}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * associated style info * <!-- end-model-doc --> * @return the value of the '<em>Style</em>' attribute. * @see org.openhealthtools.mdht.emf.w3c.xhtml.StyleSheet * @see #isSetStyle() * @see #unsetStyle() * @see #setStyle(StyleSheet) * @see org.openhealthtools.mdht.emf.w3c.xhtml.XhtmlPackage#getQ_Style() * @model unsettable="true" * extendedMetaData="kind='attribute' name='style'" * @generated */ StyleSheet getStyle(); /** * Sets the value of the '{@link org.openhealthtools.mdht.emf.w3c.xhtml.Q#getStyle <em>Style</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Style</em>' attribute. * @see org.openhealthtools.mdht.emf.w3c.xhtml.StyleSheet * @see #isSetStyle() * @see #unsetStyle() * @see #getStyle() * @generated */ void setStyle(StyleSheet value); /** * Unsets the value of the '{@link org.openhealthtools.mdht.emf.w3c.xhtml.Q#getStyle <em>Style</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetStyle() * @see #getStyle() * @see #setStyle(StyleSheet) * @generated */ void unsetStyle(); /** * Returns whether the value of the '{@link org.openhealthtools.mdht.emf.w3c.xhtml.Q#getStyle <em>Style</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Style</em>' attribute is set. * @see #unsetStyle() * @see #getStyle() * @see #setStyle(StyleSheet) * @generated */ boolean isSetStyle(); } // Q
drbgfc/mdht
hl7/plugins/org.openhealthtools.mdht.emf.hl7.mif2/src/org/openhealthtools/mdht/emf/w3c/xhtml/Q.java
Java
epl-1.0
6,922
/******************************************************************************* * Copyright (c) 2010-present Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Stuart McCulloch (Sonatype, Inc.) - initial API and implementation *******************************************************************************/ package org.eclipse.sisu.plexus; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.List; import org.codehaus.plexus.component.annotations.Requirement; import org.eclipse.sisu.inject.DeferredClass; import org.eclipse.sisu.space.LoadedClass; /** * Runtime implementation of Plexus @{@link Requirement} annotation. */ public final class RequirementImpl implements Requirement { // ---------------------------------------------------------------------- // Implementation fields // ---------------------------------------------------------------------- private final DeferredClass<?> role; private final boolean optional; private final String hint; private final String[] hints; // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- public RequirementImpl( final DeferredClass<?> role, final boolean optional, final List<String> hints ) { if ( null == role || null == hints || hints.contains( null ) ) { throw new IllegalArgumentException( "@Requirement cannot contain null values" ); } this.role = role; this.optional = optional; final int length = hints.size(); if ( length == 0 ) { hint = ""; this.hints = Hints.NO_HINTS; } else if ( length == 1 ) { hint = hints.get( 0 ); this.hints = Hints.NO_HINTS; } else { hint = ""; this.hints = hints.toArray( new String[length] ); } } /** * For testing purposes only. */ @Deprecated public RequirementImpl( final Class<?> role, final boolean optional, final String... hints ) { this( new LoadedClass<Object>( role ), optional, Arrays.asList( hints ) ); } // ---------------------------------------------------------------------- // Annotation properties // ---------------------------------------------------------------------- public Class<?> role() { return role.load(); } public boolean optional() { return optional; } public String hint() { return hint; } public String[] hints() { return hints.clone(); } // ---------------------------------------------------------------------- // Standard annotation behaviour // ---------------------------------------------------------------------- @Override public boolean equals( final Object rhs ) { if ( this == rhs ) { return true; } if ( rhs instanceof Requirement ) { final Requirement req = (Requirement) rhs; return role().equals( req.role() ) && optional == req.optional() && hint.equals( req.hint() ) && Arrays.equals( hints, req.hints() ); } return false; } @Override public int hashCode() { return ( 127 * "role".hashCode() ^ role().hashCode() ) + ( 127 * "optional".hashCode() ^ Boolean.valueOf( optional ).hashCode() ) + ( 127 * "hint".hashCode() ^ hint.hashCode() ) + ( 127 * "hints".hashCode() ^ Arrays.hashCode( hints ) ); } @Override public String toString() { return String.format( "@%s(hints=%s, optional=%b, role=%s, hint=%s)", Requirement.class.getName(), Arrays.toString( hints ), Boolean.valueOf( optional ), role(), hint ); } public Class<? extends Annotation> annotationType() { return Requirement.class; } }
mcculls/sisu.plexus
org.eclipse.sisu.plexus/src/org/eclipse/sisu/plexus/RequirementImpl.java
Java
epl-1.0
4,280
/** * Copyright 2005-2010 Noelios Technologies. * * The contents of this file are subject to the terms of one of the following * open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the * "Licenses"). You can select the license that you prefer but you may not use * this file except in compliance with one of these Licenses. * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0.html * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1.php * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1.php * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0.php * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.noelios.com/products/restlet-engine * * Restlet is a registered trademark of Noelios Technologies. */ package org.restlet.ext.xml.internal; import java.io.IOException; import java.util.logging.Level; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import javax.xml.transform.stream.StreamSource; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Method; import org.restlet.data.Reference; /** * URI resolver based on a Restlet Context instance. * * @author Jerome Louvel */ public class ContextResolver implements URIResolver { /** The Restlet context. */ private final Context context; /** * Constructor. * * @param context * The Restlet context. */ public ContextResolver(Context context) { this.context = context; } /** * Resolves a target reference into a Source document. * * @see javax.xml.transform.URIResolver#resolve(java.lang.String, * java.lang.String) */ public Source resolve(String href, String base) throws TransformerException { Source result = null; if (this.context != null) { Reference targetRef = null; if ((base != null) && !base.equals("")) { // Potentially a relative reference Reference baseRef = new Reference(base); targetRef = new Reference(baseRef, href); } else { // No base, assume "href" is an absolute URI targetRef = new Reference(href); } String targetUri = targetRef.getTargetRef().toString(); Response response = this.context.getClientDispatcher().handle( new Request(Method.GET, targetUri)); if (response.getStatus().isSuccess() && response.isEntityAvailable()) { try { result = new StreamSource(response.getEntity().getStream()); result.setSystemId(targetUri); } catch (IOException e) { this.context.getLogger().log(Level.WARNING, "I/O error while getting the response stream", e); } } } return result; } }
alastrina123/debrief
org.mwc.asset.comms/docs/restlet_src/org.restlet.ext.xml/org/restlet/ext/xml/internal/ContextResolver.java
Java
epl-1.0
3,540
from gettext import gettext as _ import traceback from pulp.client.commands.repo.sync_publish import StatusRenderer from pulp.client.extensions.core import COLOR_FAILURE from pulp_puppet.common import constants from pulp_puppet.common.publish_progress import PublishProgressReport from pulp_puppet.common.sync_progress import SyncProgressReport class PuppetStatusRenderer(StatusRenderer): def __init__(self, context): super(PuppetStatusRenderer, self).__init__(context) # Sync Steps self.sync_metadata_last_state = constants.STATE_NOT_STARTED self.sync_modules_last_state = constants.STATE_NOT_STARTED # Publish Steps self.publish_modules_last_state = constants.STATE_NOT_STARTED self.publish_metadata_last_state = constants.STATE_NOT_STARTED self.publish_http_last_state = constants.STATE_NOT_STARTED self.publish_https_last_state = constants.STATE_NOT_STARTED # UI Widgets self.sync_metadata_bar = self.prompt.create_progress_bar() self.sync_modules_bar = self.prompt.create_progress_bar() self.publish_modules_bar = self.prompt.create_progress_bar() self.publish_metadata_spinner = self.prompt.create_spinner() def display_report(self, progress_report): # Sync Steps if constants.IMPORTER_ID in progress_report: sync_report = SyncProgressReport.from_progress_dict(progress_report[constants.IMPORTER_ID]) self._display_sync_metadata_step(sync_report) self._display_sync_modules_step(sync_report) # Publish Steps if constants.DISTRIBUTOR_ID in progress_report: publish_report = PublishProgressReport.from_progress_dict(progress_report[constants.DISTRIBUTOR_ID]) self._display_publish_modules_step(publish_report) self._display_publish_metadata_step(publish_report) self._display_publish_http_https_step(publish_report) def _display_sync_metadata_step(self, sync_report): # Do nothing if it hasn't started yet or has already finished if sync_report.metadata_state == constants.STATE_NOT_STARTED or \ self.sync_metadata_last_state in constants.COMPLETE_STATES: return # Only render this on the first non-not-started state if self.sync_metadata_last_state == constants.STATE_NOT_STARTED: self.prompt.write(_('Downloading metadata...'), tag='download-metadata') # Same behavior for running or success if sync_report.metadata_state in (constants.STATE_RUNNING, constants.STATE_SUCCESS): items_done = sync_report.metadata_query_finished_count items_total = sync_report.metadata_query_total_count item_type = _('Metadata Query') self._render_itemized_in_progress_state(items_done, items_total, item_type, self.sync_metadata_bar, sync_report.metadata_state) # The only state left to handle is if it failed else: self.prompt.render_failure_message(_('... failed')) self.prompt.render_spacer() self._render_error(sync_report.metadata_error_message, sync_report.metadata_exception, sync_report.metadata_traceback) # Before finishing update the state self.sync_metadata_last_state = sync_report.metadata_state def _display_sync_modules_step(self, sync_report): # Do nothing if it hasn't started yet or has already finished if sync_report.modules_state == constants.STATE_NOT_STARTED or \ self.sync_modules_last_state in constants.COMPLETE_STATES: return # Only render this on the first non-not-started state if self.sync_modules_last_state == constants.STATE_NOT_STARTED: self.prompt.write(_('Downloading new modules...'), tag='downloading') # Same behavior for running or success if sync_report.modules_state in (constants.STATE_RUNNING, constants.STATE_SUCCESS): items_done = sync_report.modules_finished_count + sync_report.modules_error_count items_total = sync_report.modules_total_count item_type = _('Module') self._render_itemized_in_progress_state(items_done, items_total, item_type, self.sync_modules_bar, sync_report.modules_state) # The only state left to handle is if it failed else: self.prompt.render_failure_message(_('... failed')) self.prompt.render_spacer() self._render_error(sync_report.modules_error_message, sync_report.modules_exception, sync_report.modules_traceback) # Regardless of success or failure, display any individual module errors # if the new state is complete if sync_report.modules_state in constants.COMPLETE_STATES: self._render_module_errors(sync_report.modules_individual_errors) # Before finishing update the state self.sync_modules_last_state = sync_report.modules_state def _display_publish_modules_step(self, publish_report): # Do nothing if it hasn't started yet or has already finished if publish_report.modules_state == constants.STATE_NOT_STARTED or \ self.publish_modules_last_state in constants.COMPLETE_STATES: return # Only render this on the first non-not-started state if self.publish_modules_last_state == constants.STATE_NOT_STARTED: self.prompt.write(_('Publishing modules...'), tag='publishing') # Same behavior for running or success if publish_report.modules_state in (constants.STATE_RUNNING, constants.STATE_SUCCESS): items_done = publish_report.modules_finished_count + publish_report.modules_error_count items_total = publish_report.modules_total_count item_type = _('Module') self._render_itemized_in_progress_state(items_done, items_total, item_type, self.publish_modules_bar, publish_report.modules_state) # The only state left to handle is if it failed else: self.prompt.render_failure_message(_('... failed')) self.prompt.render_spacer() self._render_error(publish_report.modules_error_message, publish_report.modules_exception, publish_report.modules_traceback) # Regardless of success or failure, display any individual module errors # if the new state is complete if publish_report.modules_state in constants.COMPLETE_STATES: self._render_module_errors(publish_report.modules_individual_errors) # Before finishing update the state self.publish_modules_last_state = publish_report.modules_state def _display_publish_metadata_step(self, publish_report): # Do nothing if it hasn't started yet or has already finished if publish_report.metadata_state == constants.STATE_NOT_STARTED or \ self.publish_metadata_last_state in constants.COMPLETE_STATES: return # Only render this on the first non-not-started state if self.publish_metadata_last_state == constants.STATE_NOT_STARTED: self.prompt.write(_('Generating repository metadata...'), tag='generating') if publish_report.metadata_state == constants.STATE_RUNNING: self.publish_metadata_spinner.next() elif publish_report.metadata_state == constants.STATE_SUCCESS: self.publish_metadata_spinner.next(finished=True) self.prompt.write(_('... completed'), tag='completed') self.prompt.render_spacer() elif publish_report.metadata_state == constants.STATE_FAILED: self.publish_metadata_spinner.next(finished=True) self.prompt.render_failure_message(_('... failed')) self.prompt.render_spacer() self._render_error(publish_report.modules_error_message, publish_report.modules_exception, publish_report.modules_traceback) self.publish_metadata_last_state = publish_report.metadata_state def _display_publish_http_https_step(self, publish_report): # -- HTTP -------- if publish_report.publish_http != constants.STATE_NOT_STARTED and \ self.publish_http_last_state not in constants.COMPLETE_STATES: self.prompt.write(_('Publishing repository over HTTP...')) if publish_report.publish_http == constants.STATE_SUCCESS: self.prompt.write(_('... completed'), tag='http-completed') elif publish_report.publish_http == constants.STATE_SKIPPED: self.prompt.write(_('... skipped'), tag='http-skipped') else: self.prompt.write(_('... unknown'), tag='http-unknown') self.publish_http_last_state = publish_report.publish_http self.prompt.render_spacer() # -- HTTPS -------- if publish_report.publish_https != constants.STATE_NOT_STARTED and \ self.publish_https_last_state not in constants.COMPLETE_STATES: self.prompt.write(_('Publishing repository over HTTPS...')) if publish_report.publish_https == constants.STATE_SUCCESS: self.prompt.write(_('... completed'), tag='https-completed') elif publish_report.publish_https == constants.STATE_SKIPPED: self.prompt.write(_('... skipped'), tag='https-skipped') else: self.prompt.write(_('... unknown'), tag='https-unknown') self.publish_https_last_state = publish_report.publish_https def _render_itemized_in_progress_state(self, items_done, items_total, type_name, progress_bar, current_state): """ This is a pretty ugly way of reusing similar code between the publish steps for packages and distributions. There might be a cleaner way but I was having trouble updating the correct state variable and frankly I'm out of time. Feel free to fix this if you are inspired. """ # For the progress bar to work, we can't write anything after it until # we're completely finished with it. Assemble the download summary into # a string and let the progress bar render it. message_data = { 'name' : type_name.title(), 'items_done' : items_done, 'items_total' : items_total, } template = _('%(name)s: %(items_done)s/%(items_total)s items') bar_message = template % message_data # If there's nothing to download in this step, flag the bar as complete if items_total is 0: items_total = items_done = 1 progress_bar.render(items_done, items_total, message=bar_message) if current_state == constants.STATE_SUCCESS: self.prompt.write(_('... completed')) self.prompt.render_spacer() def _render_module_errors(self, individual_errors): """ :param individual_errors: dictionary where keys are module names and values are dicts with keys 'exception' and 'traceback'. :type individual_errors: dict """ if individual_errors: # TODO: read this from config display_error_count = 20 self.prompt.render_failure_message(_('Could not import the following modules:')) for module_error in individual_errors[:display_error_count]: msg = _(' %(module)s: %(error)s') msg = msg % {'module': module_error['module'], 'error': module_error['exception']} self.prompt.write(msg, color=COLOR_FAILURE) self.prompt.render_spacer() def _render_error(self, error_message, exception, traceback): msg = _('The following error was encountered during the previous ' 'step. More information can be found by passing -v flag one or more times') self.prompt.render_failure_message(msg) self.prompt.render_spacer() self.prompt.render_failure_message(' %s' % error_message) self.context.logger.error(error_message) self.context.logger.error(exception) self.context.logger.error(traceback)
dkliban/pulp_puppet
pulp_puppet_extensions_admin/pulp_puppet/extensions/admin/repo/status.py
Python
gpl-2.0
12,614
<?php Class Automattic_Readme { function Automattic_Readme() { // This space intentially blank } function parse_readme( $file ) { $file_contents = @implode('', @file($file)); return $this->parse_readme_contents( $file_contents ); } function parse_readme_contents( $file_contents ) { $file_contents = str_replace(array("\r\n", "\r"), "\n", $file_contents); $file_contents = trim($file_contents); if ( 0 === strpos( $file_contents, "\xEF\xBB\xBF" ) ) $file_contents = substr( $file_contents, 3 ); // === Plugin Name === // Must be the very first thing. if ( !preg_match('|^===(.*)===|', $file_contents, $_name) ) return array(); // require a name $name = trim($_name[1], '='); $name = $this->sanitize_text( $name ); $file_contents = $this->chop_string( $file_contents, $_name[0] ); // Requires at least: 1.5 if ( preg_match('|Requires at least:(.*)|i', $file_contents, $_requires_at_least) ) $requires_at_least = $this->sanitize_text($_requires_at_least[1]); else $requires_at_least = NULL; // Tested up to: 2.1 if ( preg_match('|Tested up to:(.*)|i', $file_contents, $_tested_up_to) ) $tested_up_to = $this->sanitize_text( $_tested_up_to[1] ); else $tested_up_to = NULL; // Stable tag: 10.4-ride-the-fire-eagle-danger-day if ( preg_match('|Stable tag:(.*)|i', $file_contents, $_stable_tag) ) $stable_tag = $this->sanitize_text( $_stable_tag[1] ); else $stable_tag = NULL; // we assume trunk, but don't set it here to tell the difference between specified trunk and default trunk // Tags: some tag, another tag, we like tags if ( preg_match('|Tags:(.*)|i', $file_contents, $_tags) ) { $tags = preg_split('|,[\s]*?|', trim($_tags[1])); foreach ( array_keys($tags) as $t ) $tags[$t] = $this->sanitize_text( $tags[$t] ); } else { $tags = array(); } // Contributors: markjaquith, mdawaffe, zefrank $contributors = array(); if ( preg_match('|Contributors:(.*)|i', $file_contents, $_contributors) ) { $temp_contributors = preg_split('|,[\s]*|', trim($_contributors[1])); foreach ( array_keys($temp_contributors) as $c ) { $tmp_sanitized = $this->user_sanitize( $temp_contributors[$c] ); if ( strlen(trim($tmp_sanitized)) > 0 ) $contributors[$c] = $tmp_sanitized; unset($tmp_sanitized); } } // Donate Link: URL if ( preg_match('|Donate link:\s+(.*)|i', $file_contents, $_donate_link) ) $donate_link = esc_url( $_donate_link[1] ); else $donate_link = NULL; // License: GPLv2 (Lots of plugins have this, so lets pull it out so it doesn't get into our short description) if ( preg_match('|License:(.*)|i', $file_contents, $_license) ) $license = $this->sanitize_text( $_license[1] ); else $license = NULL; // License URI: URL if ( preg_match( '|License URI:\s+(.*)|i', $file_contents, $_license_uri ) ) $license_uri = esc_url( $_license_uri[1] ); else $license_uri = null; // togs, conts, etc are optional and order shouldn't matter. So we chop them only after we've grabbed their values. foreach ( array('tags', 'contributors', 'requires_at_least', 'tested_up_to', 'stable_tag', 'donate_link', 'license', 'license_uri') as $chop ) { if ( $$chop ) { $_chop = '_' . $chop; $file_contents = $this->chop_string( $file_contents, ${$_chop}[0] ); } } $file_contents = trim($file_contents); // short-description fu if ( !preg_match('/(^(.*?))^[\s]*=+?[\s]*.+?[\s]*=+?/ms', $file_contents, $_short_description) ) $_short_description = array( 1 => &$file_contents, 2 => &$file_contents ); $short_desc_filtered = $this->sanitize_text( $_short_description[2] ); $short_desc_length = strlen($short_desc_filtered); $short_description = substr($short_desc_filtered, 0, 150); if ( $short_desc_length > strlen($short_description) ) $truncated = true; else $truncated = false; if ( $_short_description[1] ) $file_contents = $this->chop_string( $file_contents, $_short_description[1] ); // yes, the [1] is intentional // == Section == // Break into sections // $_sections[0] will be the title of the first section, $_sections[1] will be the content of the first section // the array alternates from there: title2, content2, title3, content3... and so forth $_sections = preg_split('/^[\s]*==[\s]*(.+?)[\s]*==/m', $file_contents, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY); $sections = array(); for ( $i=1; $i <= count($_sections); $i +=2 ) { $_sections[$i] = preg_replace('/^[\s]*=[\s]+(.+?)[\s]+=/m', '<h4>$1</h4>', $_sections[$i]); $_sections[$i] = $this->filter_text( $_sections[$i], true ); $title = $this->sanitize_text( $_sections[$i-1] ); $sections[str_replace(' ', '_', strtolower($title))] = array('title' => $title, 'content' => $_sections[$i]); } // Special sections // This is where we nab our special sections, so we can enforce their order and treat them differently, if needed // upgrade_notice is not a section, but parse it like it is for now $final_sections = array(); foreach ( array('description', 'installation', 'frequently_asked_questions', 'screenshots', 'changelog', 'change_log', 'upgrade_notice') as $special_section ) { if ( isset($sections[$special_section]) ) { $final_sections[$special_section] = $sections[$special_section]['content']; unset($sections[$special_section]); } } if ( isset($final_sections['change_log']) && empty($final_sections['changelog']) ) $final_sections['changelog'] = $final_sections['change_log']; $final_screenshots = array(); if ( isset($final_sections['screenshots']) ) { preg_match_all('|<li>(.*?)</li>|s', $final_sections['screenshots'], $screenshots, PREG_SET_ORDER); if ( $screenshots ) { foreach ( (array) $screenshots as $ss ) $final_screenshots[] = $ss[1]; } } // Parse the upgrade_notice section specially: // 1.0 => blah, 1.1 => fnord $upgrade_notice = array(); if ( isset($final_sections['upgrade_notice']) ) { $split = preg_split( '#<h4>(.*?)</h4>#', $final_sections['upgrade_notice'], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY ); for ( $i = 0; $i < count( $split ); $i += 2 ) { if ( empty( $split[$i + 1] ) ) { break; } $upgrade_notice[$this->sanitize_text( $split[$i] )] = substr( $this->sanitize_text( $split[$i + 1] ), 0, 300 ); } unset( $final_sections['upgrade_notice'] ); } // No description? // No problem... we'll just fall back to the old style of description // We'll even let you use markup this time! $excerpt = false; if ( !isset($final_sections['description']) ) { $final_sections = array_merge(array('description' => $this->filter_text( $_short_description[2], true )), $final_sections); $excerpt = true; } // dump the non-special sections into $remaining_content // their order will be determined by their original order in the readme.txt $remaining_content = ''; foreach ( $sections as $s_name => $s_data ) { $title_id = esc_attr($s_data['title']); $title_id = str_replace(' ','-',$title_id); $remaining_content .= "\n<h3 id='{$title_id}'>{$s_data['title']}</h3>\n{$s_data['content']}"; } $remaining_content = trim($remaining_content); // All done! // $r['tags'] and $r['contributors'] are simple arrays // $r['sections'] is an array with named elements $r = array( 'name' => $name, 'tags' => $tags, 'requires_at_least' => $requires_at_least, 'tested_up_to' => $tested_up_to, 'stable_tag' => $stable_tag, 'contributors' => $contributors, 'donate_link' => $donate_link, 'license' => $license, 'license_uri' => $license_uri, 'short_description' => $short_description, 'screenshots' => $final_screenshots, 'is_excerpt' => $excerpt, 'is_truncated' => $truncated, 'sections' => $final_sections, 'remaining_content' => $remaining_content, 'upgrade_notice' => $upgrade_notice ); return $r; } function chop_string( $string, $chop ) { // chop a "prefix" from a string: Agressive! uses strstr not 0 === strpos if ( $_string = strstr($string, $chop) ) { $_string = substr($_string, strlen($chop)); return trim($_string); } else { return trim($string); } } function user_sanitize( $text, $strict = false ) { // whitelisted chars if ( function_exists('user_sanitize') ) // bbPress native return user_sanitize( $text, $strict ); if ( $strict ) { $text = preg_replace('/[^a-z0-9-]/i', '', $text); $text = preg_replace('|-+|', '-', $text); } else { $text = preg_replace('/[^a-z0-9_-]/i', '', $text); } return $text; } function sanitize_text( $text ) { // not fancy $text = strip_tags($text); $text = esc_html($text); $text = trim($text); return $text; } function filter_text( $text, $markdown = false ) { // fancy, Markdown $text = trim($text); $text = call_user_func( array( __CLASS__, 'code_trick' ), $text, $markdown ); // A better parser than Markdown's for: backticks -> CODE if ( $markdown ) { // Parse markdown. if ( !function_exists('Markdown') ) require( AUTOMATTIC_README_MARKDOWN ); $text = Markdown($text); } $allowed = array( 'a' => array( 'href' => array(), 'title' => array(), 'rel' => array()), 'blockquote' => array('cite' => array()), 'br' => array(), 'cite' => array(), 'p' => array(), 'code' => array(), 'pre' => array(), 'em' => array(), 'strong' => array(), 'ul' => array(), 'ol' => array(), 'li' => array(), 'h3' => array(), 'h4' => array() ); $text = balanceTags($text); $text = wp_kses( $text, $allowed ); $text = trim($text); return $text; } function code_trick( $text, $markdown ) { // Don't use bbPress native function - it's incompatible with Markdown // If doing markdown, first take any user formatted code blocks and turn them into backticks so that // markdown will preserve things like underscores in code blocks if ( $markdown ) $text = preg_replace_callback("!(<pre><code>|<code>)(.*?)(</code></pre>|</code>)!s", array( __CLASS__,'decodeit'), $text); $text = str_replace(array("\r\n", "\r"), "\n", $text); if ( !$markdown ) { // This gets the "inline" code blocks, but can't be used with Markdown. $text = preg_replace_callback("|(`)(.*?)`|", array( __CLASS__, 'encodeit'), $text); // This gets the "block level" code blocks and converts them to PRE CODE $text = preg_replace_callback("!(^|\n)`(.*?)`!s", array( __CLASS__, 'encodeit'), $text); } else { // // Markdown can do inline code, we convert bbPress style block level code to Markdown style // $text = preg_replace_callback("!(^|\n)([ \t]*?)`(.*?)`!s", array( __CLASS__, 'indent'), $text); // Markdown seems to be choking on block level stuff too. Let's just encode it and be done with it. $text = preg_replace_callback("!(^|\n)`(.*?)`!s", array( __CLASS__, 'encodeit'), $text); } return $text; } function indent( $matches ) { $text = $matches[3]; $text = preg_replace('|^|m', $matches[2] . ' ', $text); return $matches[1] . $text; } function encodeit( $matches ) { if ( function_exists('encodeit') ) // bbPress native return encodeit( $matches ); $text = trim($matches[2]); $text = htmlspecialchars($text, ENT_QUOTES); $text = str_replace(array("\r\n", "\r"), "\n", $text); $text = preg_replace("|\n\n\n+|", "\n\n", $text); $text = str_replace('&amp;lt;', '&lt;', $text); $text = str_replace('&amp;gt;', '&gt;', $text); $text = "<code>$text</code>"; if ( "`" != $matches[1] ) $text = "<pre>$text</pre>"; return $text; } function decodeit( $matches ) { if ( function_exists('decodeit') ) // bbPress native return decodeit( $matches ); $text = $matches[2]; $trans_table = array_flip(get_html_translation_table(HTML_ENTITIES)); $text = strtr($text, $trans_table); $text = str_replace('<br />', '', $text); $text = str_replace('&#38;', '&', $text); $text = str_replace('&#39;', "'", $text); if ( '<pre><code>' == $matches[1] ) $text = "\n$text\n"; return "`$text`"; } } // end class
jonasbelcina/palmonade
wp-content/plugins/github-updater-5.3.4/vendor/parse-readme.php
PHP
gpl-2.0
12,074
<?php $guid = elgg_extract('guid', $vars); elgg_entity_gatekeeper($guid, 'object', 'blog'); $entity = get_entity($guid); elgg_push_entity_breadcrumbs($entity, false); $content = elgg_view_entity($entity, [ 'full_view' => true, 'show_responses' => true, ]); echo elgg_view_page($entity->getDisplayName(), [ 'content' => $content, 'filter_id' => 'blog/view', 'entity' => $entity, 'sidebar' => elgg_view('object/blog/elements/sidebar', [ 'entity' => $entity, ]), ], 'default', [ 'entity' => $entity, ]);
mrclay/Elgg-leaf
mod/blog/views/default/resources/blog/view.php
PHP
gpl-2.0
516
<?php /* ------------------------------------- * MISSING WORDPRESS FUNCTIONS * ------------------------------------- */ /** * Retrieve the date that the first post/page was published. * * The server timezone is the default and is the difference between GMT and * server time. The 'blog' value is the date when the last post was posted. The * 'gmt' is when the last post was posted in GMT formatted date. * * @uses apply_filters() Calls 'get_firstdate' filter * * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'. * @param string $post_type Post type to check. * @return string The date of the last post. */ if( !function_exists('get_firstdate') ) { function get_firstdate($timezone = 'server', $post_type = 'any') { return apply_filters( 'get_firstdate', _get_time( $timezone, 'date', $post_type, 'first' ), $timezone ); } } /** * Retrieve the date that the last post/page was published. * * The server timezone is the default and is the difference between GMT and * server time. The 'blog' value is the date when the last post was posted. The * 'gmt' is when the last post was posted in GMT formatted date. * * @uses apply_filters() Calls 'get_lastdate' filter * * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'. * @param $post_types The post type(s). Can be string or array. * @return string The date of the last post. */ if( !function_exists('get_lastdate') ) { function get_lastdate($timezone = 'server', $post_types = 'any', $m = false) { if (!is_array($post_types)) $post_types = array($post_types); $lastmodified = array(); foreach ($post_types as $post_type) $lastmodified[] = _get_time( $timezone, 'date', $post_type, 'last', $m ); sort($lastmodified); $lastmodified = array_filter($lastmodified); return apply_filters( 'get_lastdate', end($lastmodified), $timezone ); } } /** * Retrieve last post/page modified date depending on timezone. * * The server timezone is the default and is the difference between GMT and * server time. The 'blog' value is the date when the last post was posted. The * 'gmt' is when the last post was posted in GMT formatted date. * * @uses apply_filters() Calls 'get_lastmodified' filter * * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'. * @return string The date of the oldest modified post. */ if( !function_exists('get_lastmodified') ) { function get_lastmodified($timezone = 'server', $post_type = 'any', $m = false) { return apply_filters( 'get_lastmodified', _get_time( $timezone, 'modified', $post_type, 'last', $m ), $timezone ); } } /** * Retrieve first or last post type date data based on timezone. * Variation of function _get_last_post_time * * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'. * @param string $field Field to check. Can be 'date' or 'modified'. * @param string $post_type Post type to check. Defaults to 'any'. * @param string $which Which to check. Can be 'first' or 'last'. Defaults to 'last'. * @return string The date. */ if( !function_exists('_get_time') ) { function _get_time( $timezone, $field, $post_type = 'any', $which = 'last', $m = 0 ) { global $wpdb; if ( !in_array( $field, array( 'date', 'modified' ) ) ) return false; $timezone = strtolower( $timezone ); $order = ( $which == 'last' ) ? 'DESC' : 'ASC'; $key = ( $post_type == 'any' ) ? "{$which}post{$field}{$m}:$timezone" : "{$which}posttype{$post_type}{$field}{$m}:$timezone"; $date = wp_cache_get( $key, 'timeinfo' ); if ( !$date ) { $add_seconds_server = date('Z'); if ( $post_type == 'any' ) { $post_types = get_post_types( array( 'public' => true ) ); array_walk( $post_types, array( &$wpdb, 'escape_by_ref' ) ); $post_types = "'" . implode( "', '", $post_types ) . "'"; } elseif ( is_array($post_type) ) { $types = get_post_types( array( 'public' => true ) ); foreach ( $post_type as $type ) if ( !in_array( $type, $types ) ) return false; array_walk( $post_type, array( &$wpdb, 'escape_by_ref' ) ); $post_types = "'" . implode( "', '", $post_type ) . "'"; } else { if ( !in_array( $post_type, get_post_types( array( 'public' => true ) ) ) ) return false; $post_types = "'" . addslashes($post_type) . "'"; } $where = "$wpdb->posts.post_status='publish' AND $wpdb->posts.post_type IN ({$post_types}) AND $wpdb->posts.post_date_gmt "; // If a month is specified in the querystring, load that month $m = preg_replace('|[^0-9]|', '', $m); if ( !empty($m) ) { $where .= " AND YEAR($wpdb->posts.post_date)=" . substr($m, 0, 4); if ( strlen($m) > 5 ) $where .= " AND MONTH($wpdb->posts.post_date)=" . substr($m, 4, 2); } switch ( $timezone ) { case 'gmt': $date = $wpdb->get_var("SELECT post_{$field}_gmt FROM $wpdb->posts WHERE $where ORDER BY $wpdb->posts.post_{$field}_gmt {$order} LIMIT 1"); break; case 'blog': $date = $wpdb->get_var("SELECT post_{$field} FROM $wpdb->posts WHERE $where ORDER BY $wpdb->posts.post_{$field}_gmt {$order} LIMIT 1"); break; case 'server': $date = $wpdb->get_var("SELECT DATE_ADD(post_{$field}_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE $where ORDER BY $wpdb->posts.post_{$field}_gmt {$order} LIMIT 1"); break; } if ( $date ) wp_cache_set( $key, $date, 'timeinfo' ); } return $date; } }
jolay/maga2.0
wp-content/plugins/xml-sitemap-feed/hacks.php
PHP
gpl-2.0
5,493
// start the popup specefic scripts // safe to use $ jQuery(document).ready(function($) { var vibes = { loadVals: function() { var shortcode = $('#_vibe_shortcode').text(), uShortcode = shortcode; // fill in the gaps eg {{param}} $('.vibe-input').each(function() { var input = $(this), id = input.attr('id'), id = id.replace('vibe_', ''), // gets rid of the vibe_ prefix re = new RegExp("{{"+id+"}}","g"); uShortcode = uShortcode.replace(re, input.val()); }); // adds the filled-in shortcode as hidden input $('#_vibe_ushortcode').remove(); $('#vibe-sc-form-table').prepend('<div id="_vibe_ushortcode" class="hidden">' + uShortcode + '</div>'); }, cLoadVals: function() { var shortcode = $('#_vibe_cshortcode').text(), pShortcode = ''; shortcodes = ''; // fill in the gaps eg {{param}} $('.child-clone-row').each(function() { var row = $(this), rShortcode = shortcode; $('.vibe-cinput', this).each(function() { var input = $(this), id = input.attr('id'), id = id.replace('vibe_', '') // gets rid of the vibe_ prefix re = new RegExp("{{"+id+"}}","g"); rShortcode = rShortcode.replace(re, input.val()); }); shortcodes = shortcodes + rShortcode + "\n"; }); // adds the filled-in shortcode as hidden input $('#_vibe_cshortcodes').remove(); $('.child-clone-rows').prepend('<div id="_vibe_cshortcodes" class="hidden">' + shortcodes + '</div>'); // add to parent shortcode this.loadVals(); pShortcode = $('#_vibe_ushortcode').text().replace('{{child_shortcode}}', shortcodes); // add updated parent shortcode $('#_vibe_ushortcode').remove(); $('#vibe-sc-form-table').prepend('<div id="_vibe_ushortcode" class="hidden">' + pShortcode + '</div>'); }, children: function() { // assign the cloning plugin $('.child-clone-rows').appendo({ subSelect: '> div.child-clone-row:last-child', allowDelete: false, focusFirst: false }); // remove button $('.child-clone-row-remove').live('click', function() { var btn = $(this), row = btn.parent(); if( $('.child-clone-row').size() > 1 ) { row.remove(); } else { alert('You need a minimum of one row'); } return false; }); // assign jUI sortable $( ".child-clone-rows" ).sortable({ placeholder: "sortable-placeholder", items: '.child-clone-row' }); }, resizeTB: function() { var ajaxCont = $('#TB_ajaxContent'), tbWindow = $('#TB_window'), vibePopup = $('#vibe-popup'); tbWindow.css({ height: vibePopup.outerHeight(), width: vibePopup.outerWidth(), marginLeft: -(vibePopup.outerWidth()/2) }); ajaxCont.css({ paddingTop: 0, paddingLeft: 0, paddingRight: 0, height: (tbWindow.outerHeight()-0), overflow: 'auto', // IMPORTANT width: vibePopup.outerWidth() }); $('#vibe-popup').addClass('no_preview'); }, load: function() { var vibes = this, popup = $('#vibe-popup'), form = $('#vibe-sc-form', popup), shortcode = $('#_vibe_shortcode', form).text(), popupType = $('#_vibe_popup', form).text(), uShortcode = ''; //Call special fx $(".popup-colorpicker").iris({ change: function( event, ui ) { var hexcolor =ui.color.toString(); $(this).attr('value',hexcolor); $(this).trigger('change'); } }); // resize TB vibes.resizeTB(); $(window).resize(function() {vibes.resizeTB()}); // initialise vibes.loadVals(); vibes.children(); vibes.cLoadVals(); // update on children value change $('.vibe-cinput', form).live('change', function() { vibes.cLoadVals(); }); // update on value change $('.vibe-input', form).change(function() { vibes.loadVals(); }); // when insert is clicked $('.vibe-insert', form).click(function(event) {event.preventDefault(); if(parent.tinyMCE) { parent.tinyMCE.execCommand('mceInsertContent', false, $('#_vibe_ushortcode', form).html()); tb_remove(); } }); } } // run $('#vibe-popup').livequery( function() {vibes.load();} ); $('.the-icons i').live('click', function() { var inputvalue=$(this).parent().parent().parent().find('.capture-input'); inputvalue.val($(this).attr('class')); $(this).parent().parent().find('.clicked').removeClass('clicked'); $(this).addClass('clicked'); inputvalue.trigger("change"); }); $('.popup-colorpicker').live('click', function() { var iris =$(this).parent().find('.iris-picker'); if(iris.hasClass('show')){ iris.hide(); iris.removeClass('show'); }else{ iris.show(); iris.addClass('show'); } }); //Generating Live Preview $('#vibe-sc-form-live-preview').livequery( function() { $(this).hide(); var shortcode = $(this).html(); var $this = $(this); $('.refresh').live('click', function(e) { shortcode_html=shortcode; var regex = /{{(\w*)}}/gi; if(regex.test(shortcode)) { var matches = shortcode.match(regex); for(var match in matches) { var fthis=matches[match].replace('{{',''); fthis=fthis.replace('}}',''); fthis='#vibe_'+fthis; var repl =$(fthis).val(); if(repl != '0px'){ shortcode_html=shortcode_html.replace(matches[match],repl); } } } $this.html(shortcode_html); }); }); $( ".popup-slider" ).livequery( function() { var slide_val = $(this).next(); var $this = $(this); var std=parseInt(slide_val.attr('data-std')); var min=parseInt(slide_val.attr('data-min')); var max=parseInt(slide_val.attr('data-max')); slide_val.slider({ range: "min", value: std, min: min, max: max, slide: function( event, ui ) { var val=ui.value; $this.attr('value', val +'px'); $this.trigger("change"); } }); $(this).val( slide_val.slider( "value" ) +'px'); $(this).trigger('change'); }); $( ".vibe-form-select-hide" ).livequery( function() { $('#vibe-sc-form-live-preview').show(); var hide_val = parseInt($(this).attr('rel-hide')); var parent = $(this).parent().parent().parent(); var nextall= parent.nextAll("tbody").slice(0, hide_val); if($(this).val() == 'other'){ nextall.show(); }else{ nextall.hide(); } $(this).change(function(){ if($(this).val() == 'other'){ nextall.show(); $('#vibe-popup').css('height','120%'); }else{ nextall.hide(); } }); }) $( "#vibe_options" ).livequery( function() { $(this).parent().parent().hide(); }); $('#vibe_type').live('change', function() { var crow=$(this).parent().parent().next(); if($(this).val() == 'select'){ crow.show(); crow.find('#vibe_options').show(); }else{ crow.hide(); } }); });
songlequang/myclass
wp-content/plugins/vibe-shortcodes/tinymce/js/popup.js
JavaScript
gpl-2.0
8,606
<?php /** * A unique identifier is defined to store the options in the database and reference them from the theme. * By default it uses the theme name, in lowercase and without spaces, but this can be changed if needed. * If the identifier changes, it'll appear as if the options have been reset. * */ function optionsframework_option_name() { return 'unite'; } /** * Defines an array of options that will be used to generate the settings page and be saved in the database. * When creating the 'id' fields, make sure to use all lowercase and no spaces. * */ function optionsframework_options() { // Option to switch between the_excerpt and the_content $blog_layout = array('1' => __('Display full content for each post', 'unite'),'2' => __('Display excerpt for each post', 'unite')); // Color schemes $site_layout = array('pull-left' => __('Right Sidebar', 'unite'),'pull-right' => __('Left Sidebar', 'unite')); // Test data $test_array = array( 'one' => __('One', 'options_framework_theme'), 'two' => __('Two', 'options_framework_theme'), 'three' => __('Three', 'options_framework_theme'), 'four' => __('Four', 'options_framework_theme'), 'five' => __('Five', 'options_framework_theme') ); // Multicheck Array $multicheck_array = array( 'one' => __('French Toast', 'options_framework_theme'), 'two' => __('Pancake', 'options_framework_theme'), 'three' => __('Omelette', 'options_framework_theme'), 'four' => __('Crepe', 'options_framework_theme'), 'five' => __('Waffle', 'options_framework_theme') ); // Multicheck Defaults $multicheck_defaults = array( 'one' => '1', 'five' => '1' ); // Typography Defaults $typography_defaults = array( 'size' => '15px', 'face' => 'Helvetica Neue', 'style' => 'normal', 'color' => '#6B6B6B' ); // Typography Options $typography_options = array( 'sizes' => array( '6','10','12','14','15','16','18','20','24','28','32','36','42','48' ), 'faces' => array( 'arial' => 'Arial', 'verdana' => 'Verdana, Geneva', 'trebuchet' => 'Trebuchet', 'georgia' => 'Georgia', 'times' => 'Times New Roman', 'tahoma' => 'Tahoma, Geneva', 'palatino' => 'Palatino', 'helvetica' => 'Helvetica', 'Helvetica Neue' => 'Helvetica Neue' ), 'styles' => array( 'normal' => 'Normal','bold' => 'Bold' ), 'color' => true ); // Pull all the categories into an array $options_categories = array(); $options_categories_obj = get_categories(); foreach ($options_categories_obj as $category) { $options_categories[$category->cat_ID] = $category->cat_name; } // Pull all tags into an array $options_tags = array(); $options_tags_obj = get_tags(); foreach ( $options_tags_obj as $tag ) { $options_tags[$tag->term_id] = $tag->name; } // Pull all the pages into an array $options_pages = array(); $options_pages_obj = get_pages('sort_column=post_parent,menu_order'); $options_pages[''] = 'Select a page:'; foreach ($options_pages_obj as $page) { $options_pages[$page->ID] = $page->post_title; } // If using image radio buttons, define a directory path $imagepath = get_template_directory_uri() . '/images/'; // fixed or scroll position $fixed_scroll = array('scroll' => 'Scroll', 'fixed' => 'Fixed'); $options = array(); $options[] = array( 'name' => __('Main', 'unite'), 'type' => 'heading' ); $options[] = array( 'name' => __('Home Page Settings', 'unite'), 'id' => 'blog_settings', 'std' => '1', 'type' => 'select', 'options' => $blog_layout ); $options[] = array( "name" => __('Website Layout Options', 'unite'), "desc" => __('Choose between Left and Right sidebar options to be used as default', 'unite'), "id" => "site_layout", "std" => "pull-left", "type" => "select", "class" => "mini", "options" => $site_layout ); $options[] = array( 'name' => __('Element color', 'unite'), 'desc' => __('Default used if no color is selected', 'unite'), 'id' => 'element_color', 'std' => '', 'type' => 'color' ); $options[] = array( 'name' => __('Element color on hover', 'unite'), 'desc' => __('Default used if no color is selected', 'unite'), 'id' => 'element_color_hover', 'std' => '', 'type' => 'color' ); $options[] = array( 'name' => __('Custom Favicon', 'unite'), 'desc' => __('Upload a 32px x 32px PNG/GIF image that will represent your websites favicon', 'unite'), 'id' => 'custom_favicon', 'std' => '', 'type' => 'upload' ); $options[] = array( 'name' => __('Typography', 'unite'), 'type' => 'heading' ); $options[] = array( 'name' => __('Main Body Text', 'unite'), 'desc' => __('Used in P tags', 'unite'), 'id' => 'main_body_typography', 'std' => $typography_defaults, 'type' => 'typography', 'options' => $typography_options ); $options[] = array( 'name' => __('Heading Color', 'unite'), 'desc' => __('Default used if no color is selected', 'unite'), 'id' => 'heading_color', 'std' => '', 'type' => 'color' ); $options[] = array( 'name' => __('Link Color', 'unite'), 'desc' => __('Default used if no color is selected', 'unite'), 'id' => 'link_color', 'std' => '', 'type' => 'color' ); $options[] = array( 'name' => __('Link:hover Color', 'unite'), 'desc' => __('Default used if no color is selected', 'unite'), 'id' => 'link_hover_color', 'std' => '', 'type' => 'color' ); $options[] = array( 'name' => __('Link:active Color', 'unite'), 'desc' => __('Default used if no color is selected', 'unite'), 'id' => 'link_active_color', 'std' => '', 'type' => 'color' ); $options[] = array( 'name' => __('Header', 'unite'), 'type' => 'heading' ); $options[] = array( 'name' => __('Top nav background color', 'unite'), 'desc' => __('Default used if no color is selected.', 'unite'), 'id' => 'top_nav_bg_color', 'std' => '', 'type' => 'color' ); $options[] = array( 'name' => __('Top nav item color', 'unite'), 'desc' => __('Link color', 'unite'), 'id' => 'top_nav_link_color', 'std' => '', 'type' => 'color' ); $options[] = array( 'name' => __('Top nav dropdown background color', 'unite'), 'desc' => __('Background of dropdown item hover color', 'unite'), 'id' => 'top_nav_dropdown_bg', 'std' => '', 'type' => 'color' ); $options[] = array( 'name' => __('Top nav dropdown item color', 'unite'), 'desc' => __('Dropdown item color', 'unite'), 'id' => 'top_nav_dropdown_item', 'std' => '', 'type' => 'color' ); $options[] = array( 'name' => __('Footer', 'unite'), 'type' => 'heading' ); $options[] = array( 'name' => __('Footer Background Color', 'unite'), 'id' => 'footer_bg_color', 'std' => '', 'type' => 'color' ); $options[] = array( 'name' => __('Footer Text Color', 'unite'), 'id' => 'footer_text_color', 'std' => '', 'type' => 'color' ); $options[] = array( 'name' => __('Footer Link Color', 'unite'), 'id' => 'footer_link_color', 'std' => '', 'type' => 'color' ); $options[] = array( 'name' => __('Footer information', 'unite'), 'desc' => __('Copyright text in footer', 'unite'), 'id' => 'custom_footer_text', 'std' => '<a href="' . esc_url( home_url( '/' ) ) . '" title="' . esc_attr( get_bloginfo( 'name', 'display' ) ) . '" >' . get_bloginfo( 'name', 'display' ) . '</a>. All rights reserved.', 'type' => 'textarea' ); $options[] = array( 'name' => __('Social', 'unite'), 'type' => 'heading' ); $options[] = array( 'name' => __('Social Icon Color', 'unite'), 'desc' => __('Default used if no color is selected', 'unite'), 'id' => 'social_color', 'std' => '', 'type' => 'color' ); $options[] = array( 'name' => __('Social Icon:hover Color', 'unite'), 'desc' => __('Default used if no color is selected', 'unite'), 'id' => 'social_hover_color', 'std' => '', 'type' => 'color' ); $options[] = array( 'name' => __('Add full URL for your social network profiles', 'unite'), 'desc' => __('Facebook', 'unite'), 'id' => 'social_facebook', 'std' => '', 'class' => 'mini', 'type' => 'text' ); $options[] = array( 'id' => 'social_twitter', 'desc' => __('Twitter', 'unite'), 'std' => '', 'class' => 'mini', 'type' => 'text' ); $options[] = array( 'id' => 'social_google', 'desc' => __('Google+', 'unite'), 'std' => '', 'class' => 'mini', 'type' => 'text' ); $options[] = array( 'id' => 'social_youtube', 'desc' => __('Youtube', 'unite'), 'std' => '', 'class' => 'mini', 'type' => 'text' ); $options[] = array( 'id' => 'social_linkedin', 'desc' => __('LinkedIn', 'unite'), 'std' => '', 'class' => 'mini', 'type' => 'text' ); $options[] = array( 'id' => 'social_pinterest', 'desc' => __('Pinterest', 'unite'), 'std' => '', 'class' => 'mini', 'type' => 'text' ); $options[] = array( 'id' => 'social_feed', 'desc' => __('RSS Feed', 'unite'), 'std' => '', 'class' => 'mini', 'type' => 'text' ); $options[] = array( 'id' => 'social_tumblr', 'desc' => __('Tumblr', 'unite'), 'std' => '', 'class' => 'mini', 'type' => 'text' ); $options[] = array( 'id' => 'social_flickr', 'desc' => __('Flickr', 'unite'), 'std' => '', 'class' => 'mini', 'type' => 'text' ); $options[] = array( 'id' => 'social_instagram', 'desc' => __('Instagram', 'unite'), 'std' => '', 'class' => 'mini', 'type' => 'text' ); $options[] = array( 'id' => 'social_dribbble', 'desc' => __('Dribbble', 'unite'), 'std' => '', 'class' => 'mini', 'type' => 'text' ); $options[] = array( 'id' => 'social_skype', 'desc' => __('Skype', 'unite'), 'std' => '', 'class' => 'mini', 'type' => 'text' ); $options[] = array( 'id' => 'social_vimeo', 'desc' => __('Vimeo', 'unite'), 'std' => '', 'class' => 'mini', 'type' => 'text' ); $options[] = array( 'name' => __('Other', 'unite'), 'type' => 'heading' ); $options[] = array( 'name' => __('Custom CSS', 'unite'), 'desc' => __('Additional CSS', 'unite'), 'id' => 'custom_css', 'std' => '', 'type' => 'textarea' ); return $options; }
haithan/11b5
wp-content/themes/unite/options.php
PHP
gpl-2.0
10,316
#include <Arduino.h> #include <IRSender.h> // Send IR using the IR Blaster. The IR Blaster generates the 38 kHz carrier frequency IRSenderBlaster::IRSenderBlaster(uint8_t pin) : IRSender(pin) { pinMode(_pin, OUTPUT); } void IRSenderBlaster::setFrequency(int frequency) { (void)frequency; } // Send an IR 'mark' symbol, i.e. transmitter ON void IRSenderBlaster::mark(int markLength) { digitalWrite(_pin, HIGH); if (markLength < 16383) { delayMicroseconds(markLength); } else { delay(markLength/1000); } } // Send an IR 'space' symbol, i.e. transmitter OFF void IRSenderBlaster::space(int spaceLength) { digitalWrite(_pin, LOW); if (spaceLength < 16383) { delayMicroseconds(spaceLength); } else { delay(spaceLength/1000); } }
Marthin-/MySecureSensors
libraries/HeatpumpIR/IRSenderBlaster.cpp
C++
gpl-2.0
770
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * (c)Copyright 2006 Hewlett-Packard Development Company, LP. * */ #ifndef _GENERIC_METHODS_HPP_ #define _GENERIC_METHODS_HPP_ #include "C_ProtocolFrame.hpp" extern "C" int sys_time_secs (T_pValueData P_msgPart, T_pValueData P_args, T_pValueData P_result); extern "C" int sys_time_unsig_sec (T_pValueData P_msgPart, T_pValueData P_args, T_pValueData P_result); #endif // _GENERIC_METHODS_HPP_
hamzasheikh/Seagull
seagull/trunk/src/library-general-methods/generic_methods.hpp
C++
gpl-2.0
1,259
using System; using System.Collections; using Server.Engines.XmlSpawner2; using Server.Items; using Server.Network; using Server.Targeting; /* ** TeamLMSGump ** ArteGordon ** updated 12/06/04 ** */ namespace Server.Gumps { public class TeamLMSGump : Gump { private const int textentrybackground = 0x24A8; private readonly int y_inc = 25; private readonly int PlayersPerPage = 10; private readonly int MaxTeamSize = 0;// zero means unlimited number of players private readonly TeamLMSGauntlet m_gauntlet; private readonly ArrayList m_WorkingList; private readonly int viewpage; public TeamLMSGump(TeamLMSGauntlet gauntlet, Mobile from) : this(gauntlet, from, 0) { } public TeamLMSGump(TeamLMSGauntlet gauntlet, Mobile from, int page) : base(20, 30) { if (from == null || gauntlet == null || gauntlet.Deleted || gauntlet.Challenger == null) return; from.CloseGump(typeof(TeamLMSGump)); this.m_gauntlet = gauntlet; this.viewpage = page; int height = 500; this.AddBackground(0, 0, 350, height, 0xDAC); //AddAlphaRegion( 0, 0, 340, height ); this.AddLabel(100, 10, 0, XmlPoints.GetText(from, 200610)); // "Team LMS Challenge" this.AddLabel(20, 30, 0, String.Format(XmlPoints.GetText(from, 200501), gauntlet.Challenger.Name)); // "Organized by: {0}" this.AddLabel(20, 50, 0, String.Format(XmlPoints.GetText(from, 200502), this.m_gauntlet.EntryFee)); // "Entry Fee: {0}" this.AddLabel(20, 70, 0, String.Format(XmlPoints.GetText(from, 200503), this.m_gauntlet.ArenaSize)); // "Arena Size: {0}" this.AddImageTiled(15, 110, 320, 20, 0xdb3); // display all of the current team members if (gauntlet.Participants != null) { // copy the master list to a temporary working list this.m_WorkingList = (ArrayList)gauntlet.Participants.Clone(); this.AddLabel(150, 50, 0, String.Format(XmlPoints.GetText(from, 200504), this.m_WorkingList.Count * this.m_gauntlet.EntryFee)); // "Total Purse: {0}" this.AddLabel(150, 70, 0, String.Format(XmlPoints.GetText(from, 200505), this.m_gauntlet.Location, this.m_gauntlet.Map)); // "Loc: {0} {1}" this.AddLabel(20, 90, 0, String.Format(XmlPoints.GetText(from, 200506), gauntlet.Participants.Count)); // "Players: {0}" this.AddLabel(150, 90, 0, String.Format(XmlPoints.GetText(from, 200507), gauntlet.ActivePlayers())); // "Active: {0}" int yoffset = 135; // page up and down buttons this.AddButton(300, 110, 0x15E0, 0x15E4, 13, GumpButtonType.Reply, 0); this.AddButton(320, 110, 0x15E2, 0x15E6, 12, GumpButtonType.Reply, 0); // find the players entry to determine the viewing page for (int i = 0; i < this.m_WorkingList.Count; i++) { TeamLMSGauntlet.ChallengeEntry entry = (TeamLMSGauntlet.ChallengeEntry)this.m_WorkingList[i]; if (entry == null) continue; if (entry.Participant == from) { this.viewpage = entry.PageBeingViewed; break; } } this.AddLabel(220, 110, 0, String.Format(XmlPoints.GetText(from, 200508), this.viewpage + 1, (int)(this.m_WorkingList.Count / this.PlayersPerPage) + 1)); // "Page: {0}/{1}" this.AddLabel(155, 110, 0, XmlPoints.GetText(from, 200591)); // "Team" for (int i = 0; i < this.m_WorkingList.Count; i++) { // determine which page is being viewed if ((int)(i / this.PlayersPerPage) != this.viewpage) continue; TeamLMSGauntlet.ChallengeEntry entry = (TeamLMSGauntlet.ChallengeEntry)this.m_WorkingList[i]; if (entry == null) continue; // display the entry with a color indicating whether they have accepted or not Mobile m = entry.Participant; string statusmsg = XmlPoints.GetText(from, 200509); // "Waiting" int texthue = 0; // this section is available during game setup if (!this.m_gauntlet.GameLocked) { statusmsg = XmlPoints.GetText(from, 200509); // "Waiting" if (entry.Accepted) { texthue = 68; statusmsg = XmlPoints.GetText(from, 200510); // "Accepted" } // check to see if they have the Entry fee if (!this.m_gauntlet.HasEntryFee(m)) { texthue = 33; statusmsg = XmlPoints.GetText(from, 200511); // "Insufficient funds" } // if the game is still open then enable these buttons // if this is the participant then add the accept button to the entry if (m == from) { this.AddButton(15, yoffset, entry.Accepted ? 0xd1 : 0xd0, entry.Accepted ? 0xd0 : 0xd1, 1000 + i, GumpButtonType.Reply, 0); } // if this is the organizer then add the kick button and the team assignment to each entry if (from == this.m_gauntlet.Challenger) { this.AddImageTiled(223, yoffset, 20, 19, textentrybackground); this.AddTextEntry(225, yoffset, 20, 19, 0, 500 + i, entry.Team.ToString()); } if (from == this.m_gauntlet.Challenger || from == entry.Participant) { this.AddButton(190, yoffset, 0xFB1, 0xFB3, 2000 + i, GumpButtonType.Reply, 0); } } else { // this section is active after the game has started // enable the forfeit button if (m == from && entry.Status == ChallengeStatus.Active && !this.m_gauntlet.GameCompleted) { this.AddButton(190, yoffset, 0xFB1, 0xFB3, 4000 + i, GumpButtonType.Reply, 0); } if (entry.Status == ChallengeStatus.Forfeit) { texthue = 33; statusmsg = XmlPoints.GetText(from, 200520); // "Forfeit" } else if (entry.Caution == ChallengeStatus.Hidden && entry.Status == ChallengeStatus.Active) { texthue = 53; statusmsg = XmlPoints.GetText(from, 200521); // "Hidden" } else if (entry.Caution == ChallengeStatus.OutOfBounds && entry.Status == ChallengeStatus.Active) { texthue = 53; statusmsg = XmlPoints.GetText(from, 200522); // "Out of Bounds" } else if (entry.Caution == ChallengeStatus.Offline && entry.Status == ChallengeStatus.Active) { texthue = 53; statusmsg = XmlPoints.GetText(from, 200523); // "Offline" } else if (entry.Status == ChallengeStatus.Active) { texthue = 68; if (gauntlet.Winner == entry.Team) statusmsg = XmlPoints.GetText(from, 200524); // "Winner" else statusmsg = XmlPoints.GetText(from, 200525); // "Active" } else if (entry.Status == ChallengeStatus.Dead) { texthue = 33; statusmsg = XmlPoints.GetText(from, 200526); // "Dead" } else if (entry.Status == ChallengeStatus.Disqualified) { texthue = 33; statusmsg = XmlPoints.GetText(from, 200527); // "Disqualified" } } if (m != null) { int teamhue = 0; if (entry.Team > 0) { teamhue = BaseChallengeGame.TeamColor(entry.Team); } this.AddLabel(40, yoffset, teamhue, m.Name); this.AddLabel(165, yoffset, teamhue, entry.Team.ToString()); this.AddLabel(255, yoffset, texthue, statusmsg); } yoffset += this.y_inc; } } // the challenger gets additional options if (from == gauntlet.Challenger && !this.m_gauntlet.GameLocked) { this.AddImageTiled(15, height - 110, 320, 20, 0xdb3); this.AddButton(130, height - 35, 0xFA8, 0xFAA, 100, GumpButtonType.Reply, 0); this.AddLabel(170, height - 35, 0, XmlPoints.GetText(from, 200528)); // "Add" this.AddButton(230, height - 35, 0xFB7, 0xFB9, 300, GumpButtonType.Reply, 0); this.AddLabel(270, height - 35, 0, XmlPoints.GetText(from, 200529)); // "Start" // set teams this.AddButton(230, height - 85, 0xFAE, 0xFAF, 11, GumpButtonType.Reply, 0); this.AddLabel(270, height - 85, 0, XmlPoints.GetText(from, 200592)); // "Set Teams" // set entry fee this.AddButton(20, height - 85, 0xFAE, 0xFAF, 10, GumpButtonType.Reply, 0); this.AddImageTiled(160, height - 85, 60, 19, textentrybackground); this.AddTextEntry(160, height - 85, 60, 25, 0, 10, this.m_gauntlet.EntryFee.ToString()); this.AddLabel(60, height - 85, 0, XmlPoints.GetText(from, 200530)); // "Set Entry Fee: " // set arena size this.AddButton(20, height - 60, 0xFAE, 0xFAF, 20, GumpButtonType.Reply, 0); this.AddImageTiled(160, height - 60, 30, 19, textentrybackground); this.AddTextEntry(160, height - 60, 30, 25, 0, 20, this.m_gauntlet.ArenaSize.ToString()); this.AddLabel(60, height - 60, 0, XmlPoints.GetText(from, 200531)); // "Set Arena Size: " } else { this.AddImageTiled(15, height - 60, 320, 20, 0xdb3); } this.AddButton(20, height - 35, 0xFAB, 0xFAD, 1, GumpButtonType.Reply, 0); this.AddLabel(60, height - 35, 0, XmlPoints.GetText(from, 200532)); // "Refresh" if (gauntlet.GameInProgress) { this.AddLabel(150, height - 35, 68, XmlPoints.GetText(from, 200533)); // "Game is in progress!" } else if (gauntlet.Winner != 0) { this.AddLabel(130, height - 35, 68, String.Format(XmlPoints.GetText(from, 200593), gauntlet.Winner)); // "Team {0} is the winner!" } //AddButton( 30, height - 35, 0xFB7, 0xFB9, 0, GumpButtonType.Reply, 0 ); //AddLabel( 70, height - 35, 0, "Close" ); // display the teams gump from.CloseGump(typeof(TeamsGump)); from.SendGump(new TeamsGump(this.m_gauntlet, from)); } public static void RefreshAllGumps(TeamLMSGauntlet gauntlet, bool force) { if (gauntlet.Participants != null) { foreach (TeamLMSGauntlet.ChallengeEntry entry in gauntlet.Participants) { if (entry.Participant != null) { if (force || entry.Participant.HasGump(typeof(TeamLMSGump))) { entry.Participant.SendGump(new TeamLMSGump(gauntlet, entry.Participant)); } } } } // update for the organizer if (gauntlet.Challenger != null) { if (force || gauntlet.Challenger.HasGump(typeof(TeamLMSGump))) { gauntlet.Challenger.SendGump(new TeamLMSGump(gauntlet, gauntlet.Challenger)); } } } public override void OnResponse(NetState state, RelayInfo info) { if (state == null || info == null || state.Mobile == null || this.m_gauntlet == null || this.m_gauntlet.Challenger == null) return; XmlPoints afrom = (XmlPoints)XmlAttach.FindAttachment(state.Mobile, typeof(XmlPoints)); switch ( info.ButtonID ) { case 1: // refresh //m_gauntlet.CheckForDisqualification(); state.Mobile.SendGump(new TeamLMSGump(this.m_gauntlet, state.Mobile, this.viewpage)); break; case 10: // Entry fee int val = 0; TextRelay tr = info.GetTextEntry(10); if (tr != null) { try { val = int.Parse(tr.Text); } catch { } } this.m_gauntlet.EntryFee = val; this.m_gauntlet.ResetAcceptance(); // update all the gumps RefreshAllGumps(this.m_gauntlet, true); state.Mobile.SendGump(new TeamLMSGump(this.m_gauntlet, state.Mobile, this.viewpage)); break; case 11: // update teams if (this.m_WorkingList != null) for (int i = 0; i < this.m_WorkingList.Count; i++) { // is this on the visible page? if ((int)(i / this.PlayersPerPage) != this.viewpage) continue; TeamLMSGauntlet.ChallengeEntry entry = (TeamLMSGauntlet.ChallengeEntry)this.m_WorkingList[i]; if (entry != null) { int tval = 0; tr = info.GetTextEntry(500 + i); if (tr != null) { try { tval = int.Parse(tr.Text); } catch { } } entry.Team = tval; } } this.m_gauntlet.ResetAcceptance(); // update all the gumps RefreshAllGumps(this.m_gauntlet, true); state.Mobile.SendGump(new TeamLMSGump(this.m_gauntlet, state.Mobile, this.viewpage)); break; case 12: // page up // try doing the default for non-participants int nplayers = 0; if (this.m_gauntlet.Participants != null) nplayers = this.m_gauntlet.Participants.Count; int page = this.viewpage + 1; if (page > (int)(nplayers / this.PlayersPerPage)) { page = (int)(nplayers / this.PlayersPerPage); } if (this.m_WorkingList != null) for (int i = 0; i < this.m_WorkingList.Count; i++) { TeamLMSGauntlet.ChallengeEntry entry = (TeamLMSGauntlet.ChallengeEntry)this.m_WorkingList[i]; if (entry != null) { if (entry.Participant == state.Mobile) { entry.PageBeingViewed++; if (entry.PageBeingViewed > (int)(nplayers / this.PlayersPerPage)) entry.PageBeingViewed = (int)(nplayers / this.PlayersPerPage); page = entry.PageBeingViewed; //break; } } } state.Mobile.SendGump(new TeamLMSGump(this.m_gauntlet, state.Mobile, page)); break; case 13: // page down // try doing the default for non-participants page = this.viewpage - 1; if (page < 0) { page = 0; } if (this.m_WorkingList != null) for (int i = 0; i < this.m_WorkingList.Count; i++) { TeamLMSGauntlet.ChallengeEntry entry = (TeamLMSGauntlet.ChallengeEntry)this.m_WorkingList[i]; if (entry != null) { if (entry.Participant == state.Mobile) { entry.PageBeingViewed--; if (entry.PageBeingViewed < 0) entry.PageBeingViewed = 0; page = entry.PageBeingViewed; //break; } } } state.Mobile.SendGump(new TeamLMSGump(this.m_gauntlet, state.Mobile, page)); break; case 20: // arena size val = 0; tr = info.GetTextEntry(20); if (tr != null) { try { val = int.Parse(tr.Text); } catch { } } this.m_gauntlet.ArenaSize = val; this.m_gauntlet.ResetAcceptance(); // update all the gumps RefreshAllGumps(this.m_gauntlet, true); state.Mobile.SendGump(new TeamLMSGump(this.m_gauntlet, state.Mobile, this.viewpage)); break; case 100: // add to Participants if (this.m_gauntlet.Participants == null) this.m_gauntlet.Participants = new ArrayList(); if (this.MaxTeamSize > 0 && this.m_gauntlet.Participants.Count >= this.MaxTeamSize) { XmlPoints.SendText(state.Mobile, 100535); // "Challenge is full!" } else { state.Mobile.Target = new MemberTarget(this.m_gauntlet, this.m_gauntlet.Participants); } state.Mobile.SendGump(new TeamLMSGump(this.m_gauntlet, state.Mobile, this.viewpage)); break; case 300: // Start game if (this.m_WorkingList == null) return; bool complete = true; foreach (TeamLMSGauntlet.ChallengeEntry entry in this.m_WorkingList) { if (entry != null) { Mobile m = entry.Participant; if (m == null) continue; if (!this.m_gauntlet.CheckQualify(m)) { complete = false; break; } if (!entry.Accepted) { XmlPoints.SendText(this.m_gauntlet.Challenger, 100539, m.Name); // "{0} has not accepted yet." complete = false; break; } // and they have a team if (entry.Team <= 0) { XmlPoints.SendText(this.m_gauntlet.Challenger, 100594, m.Name); // "{0} has not been assigned a team." complete = false; } } } if (this.m_WorkingList.Count < 2) { XmlPoints.SendText(this.m_gauntlet.Challenger, 100540); // "Insufficient number of players." complete = false; } // copy all of the accepted entries to the final participants list if (complete) { this.m_gauntlet.Participants = new ArrayList(); foreach (TeamLMSGauntlet.ChallengeEntry entry in this.m_WorkingList) { if (entry != null) { Mobile m = entry.Participant; if (m == null) continue; // try to collect any entry fee if (!this.m_gauntlet.CollectEntryFee(m, this.m_gauntlet.EntryFee)) continue; // set up the challenge on each player XmlPoints a = (XmlPoints)XmlAttach.FindAttachment(m, typeof(XmlPoints)); if (a != null) { a.ChallengeGame = this.m_gauntlet; } entry.Status = ChallengeStatus.Active; this.m_gauntlet.Participants.Add(entry); } } // and lock the game this.m_gauntlet.StartGame(); // refresh all gumps RefreshAllGumps(this.m_gauntlet, true); } else { state.Mobile.SendGump(new TeamLMSGump(this.m_gauntlet, state.Mobile, this.viewpage)); } break; default: { // forfeit buttons if (info.ButtonID >= 4000) { int selection = info.ButtonID - 4000; if (selection < this.m_WorkingList.Count) { TeamLMSGauntlet.ChallengeEntry entry = (TeamLMSGauntlet.ChallengeEntry)this.m_WorkingList[selection]; // find the master participants list entry with the same participant if (this.m_gauntlet.Participants != null) { TeamLMSGauntlet.ChallengeEntry forfeitentry = null; foreach (TeamLMSGauntlet.ChallengeEntry masterentry in this.m_gauntlet.Participants) { if (entry == masterentry) { forfeitentry = masterentry; break; } } // and remove it if (forfeitentry != null) { forfeitentry.Status = ChallengeStatus.Forfeit; // inform him that he has been kicked this.m_gauntlet.Forfeit(forfeitentry.Participant); } } } } // kick buttons if (info.ButtonID >= 2000) { int selection = info.ButtonID - 2000; if (selection < this.m_WorkingList.Count) { TeamLMSGauntlet.ChallengeEntry entry = (TeamLMSGauntlet.ChallengeEntry)this.m_WorkingList[selection]; // find the master participants list entry with the same participant if (this.m_gauntlet.Participants != null) { TeamLMSGauntlet.ChallengeEntry kickentry = null; foreach (TeamLMSGauntlet.ChallengeEntry masterentry in this.m_gauntlet.Participants) { if (entry == masterentry) { kickentry = masterentry; break; } } // and remove it if (kickentry != null) { this.m_gauntlet.Participants.Remove(kickentry); // refresh his gump and inform him that he has been kicked if (kickentry.Participant != null) { XmlPoints.SendText(kickentry.Participant, 100545, this.m_gauntlet.ChallengeName); // "You have been kicked from {0}" kickentry.Participant.SendGump(new TeamLMSGump(this.m_gauntlet, kickentry.Participant, this.viewpage)); } } } this.m_gauntlet.ResetAcceptance(); } // refresh all gumps RefreshAllGumps(this.m_gauntlet, true); //state.Mobile.SendGump( new TeamLMSGump( m_gauntlet, state.Mobile)); } else if (info.ButtonID >= 1000) { int selection = info.ButtonID - 1000; // set the acceptance flag of the participant if (selection < this.m_WorkingList.Count) { TeamLMSGauntlet.ChallengeEntry entry = (TeamLMSGauntlet.ChallengeEntry)this.m_WorkingList[selection]; entry.Accepted = !entry.Accepted; } // refresh all gumps RefreshAllGumps(this.m_gauntlet, true); //state.Mobile.SendGump( new TeamLMSGump( m_gauntlet, state.Mobile)); } break; } } } public class TeamsGump : Gump { public TeamsGump(TeamLMSGauntlet gauntlet, Mobile from) : base(350,30) { if (gauntlet == null || from == null) return; int yinc = 25; ArrayList Teams = gauntlet.GetTeams(); // gump height determined by number of teams int height = Teams.Count * yinc + 80; this.AddBackground(0, 0, 210, height, 0xDAC); //AddAlphaRegion( 0, 0, 340, height ); this.AddLabel(50, 10, 0, XmlPoints.GetText(from, 200611)); // "LMS Team Status" this.AddLabel(20, 40, 0, XmlPoints.GetText(from, 200591)); // "Team" this.AddLabel(75, 40, 0, XmlPoints.GetText(from, 200596)); // "Members" this.AddLabel(135, 40, 0, XmlPoints.GetText(from, 200597)); // "Active" int yoffset = 60; // list all of the teams and their status foreach (TeamInfo t in Teams) { int teamhue = 0; if (t.ID > 0) { teamhue = BaseChallengeGame.TeamColor(t.ID); } this.AddLabel(20, yoffset, teamhue, t.ID.ToString()); this.AddLabel(75, yoffset, teamhue, t.Members.Count.ToString()); this.AddLabel(135, yoffset, teamhue, t.NActive.ToString()); yoffset += yinc; } } } private class MemberTarget : Target { private readonly ArrayList m_list; private readonly TeamLMSGauntlet m_gauntlet; public MemberTarget(TeamLMSGauntlet gauntlet, ArrayList list) : base(30, false, TargetFlags.None) { this.m_list = list; this.m_gauntlet = gauntlet; } protected override void OnTarget(Mobile from, object targeted) { if (from == null || targeted == null || this.m_gauntlet == null || this.m_list == null) return; if (targeted is Mobile && ((Mobile)targeted).Player) { Mobile pm = targeted as Mobile; // make sure they qualify if (!this.m_gauntlet.CheckQualify(pm)) { return; } // see if they are already in the game if (this.m_gauntlet.Participants != null) { foreach (TeamLMSGauntlet.ChallengeEntry entry in this.m_gauntlet.Participants) { if (pm == entry.Participant) { XmlPoints.SendText(from, 100548, pm.Name); // "{0} has already been added to the game." return; } } } this.m_list.Add(new TeamLMSGauntlet.ChallengeEntry(pm)); XmlPoints.SendText(from, 100549, pm.Name); // "You have added {0} to the challenge." XmlPoints.SendText(pm, 100550, this.m_gauntlet.Name); // "You have been invited to participate in {0}." // clear all acceptances this.m_gauntlet.ResetAcceptance(); // refresh all gumps RefreshAllGumps(this.m_gauntlet, true); // refresh the gump with the new member //from.SendGump( new TeamLMSGump( m_gauntlet, from)); } } } } }
jasegiffin/ServUO
Scripts/Services/XmlSpawner 2/XmlEngines/XmlPoints/ChallengeGames/TeamLMSGump.cs
C#
gpl-2.0
33,127
<?php /* * @version $Id$ ------------------------------------------------------------------------- GLPI - Gestionnaire Libre de Parc Informatique Copyright (C) 2015-2016 Teclib'. http://glpi-project.org based on GLPI - Gestionnaire Libre de Parc Informatique Copyright (C) 2003-2014 by the INDEPNET Development Team. ------------------------------------------------------------------------- LICENSE This file is part of GLPI. GLPI is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief */ if (!defined('GLPI_ROOT')) { die("Sorry. You can't access this file directly"); } /** * Relation between item and devices **/ class Item_DeviceDrive extends Item_Devices { static public $itemtype_2 = 'DeviceDrive'; static public $items_id_2 = 'devicedrives_id'; static protected $notable = false; /** * @since version 0.85 **/ static function getSpecificities($specif='') { return array('serial' => parent::getSpecificities('serial'), 'busID' => parent::getSpecificities('busID')); } } ?>
Diegoromeropanes/glpi
inc/item_devicedrive.class.php
PHP
gpl-2.0
1,694
/* * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "Chat.h" #include "DB2Stores.h" #include "Language.h" #include "ObjectMgr.h" #include "Player.h" #include "RBAC.h" #include "WorldSession.h" class scene_commandscript : public CommandScript { public: scene_commandscript() : CommandScript("scene_commandscript") { } std::vector<ChatCommand> GetCommands() const override { static std::vector<ChatCommand> sceneCommandTable = { { "debug", rbac::RBAC_PERM_COMMAND_SCENE_DEBUG, false, &HandleDebugSceneCommand, "" }, { "play", rbac::RBAC_PERM_COMMAND_SCENE_PLAY, false, &HandlePlaySceneCommand, "" }, { "playpackage", rbac::RBAC_PERM_COMMAND_SCENE_PLAY_PACKAGE, false, &HandlePlayScenePackageCommand, "" }, { "cancel", rbac::RBAC_PERM_COMMAND_SCENE_CANCEL, false, &HandleCancelSceneCommand, "" } }; static std::vector<ChatCommand> commandTable = { { "scene", rbac::RBAC_PERM_COMMAND_SCENE, true, NULL, "", sceneCommandTable } }; return commandTable; } static bool HandleDebugSceneCommand(ChatHandler* handler, char const* /*args*/) { if (Player* player = handler->GetSession()->GetPlayer()) { player->GetSceneMgr().ToggleDebugSceneMode(); handler->PSendSysMessage(player->GetSceneMgr().IsInDebugSceneMode() ? LANG_COMMAND_SCENE_DEBUG_ON : LANG_COMMAND_SCENE_DEBUG_OFF); } return true; } static bool HandlePlaySceneCommand(ChatHandler* handler, char const* args) { if (!*args) return false; char const* sceneIdStr = strtok((char*)args, " "); if (!sceneIdStr) return false; uint32 sceneId = atoi(sceneIdStr); Player* target = handler->getSelectedPlayerOrSelf(); if (!target) { handler->SendSysMessage(LANG_PLAYER_NOT_FOUND); handler->SetSentErrorMessage(true); return false; } if (!sObjectMgr->GetSceneTemplate(sceneId)) return false; target->GetSceneMgr().PlayScene(sceneId); return true; } static bool HandlePlayScenePackageCommand(ChatHandler* handler, char const* args) { if (!*args) return false; char const* scenePackageIdStr = strtok((char*)args, " "); char const* flagsStr = strtok(NULL, ""); if (!scenePackageIdStr) return false; uint32 scenePackageId = atoi(scenePackageIdStr); uint32 flags = flagsStr ? atoi(flagsStr) : SCENEFLAG_UNK16; Player* target = handler->getSelectedPlayerOrSelf(); if (!target) { handler->SendSysMessage(LANG_PLAYER_NOT_FOUND); handler->SetSentErrorMessage(true); return false; } if (!sSceneScriptPackageStore.HasRecord(scenePackageId)) return false; target->GetSceneMgr().PlaySceneByPackageId(scenePackageId, flags); return true; } static bool HandleCancelSceneCommand(ChatHandler* handler, char const* args) { if (!*args) return false; Player* target = handler->getSelectedPlayerOrSelf(); if (!target) { handler->SendSysMessage(LANG_PLAYER_NOT_FOUND); handler->SetSentErrorMessage(true); return false; } uint32 id = atoi((char*)args); if (!sSceneScriptPackageStore.HasRecord(id)) return false; target->GetSceneMgr().CancelSceneByPackageId(id); return true; } }; void AddSC_scene_commandscript() { new scene_commandscript(); }
Regigicas/TrinityCore
src/server/scripts/Commands/cs_scene.cpp
C++
gpl-2.0
4,542
#include "SDRDeviceInfo.h" SDRDeviceInfo::SDRDeviceInfo() : name(""), serial(""), available(false) { } std::string SDRDeviceInfo::getDeviceId() { std::string deviceId; deviceId.append(getName()); deviceId.append(" :: "); deviceId.append(getSerial()); return deviceId; } bool SDRDeviceInfo::isAvailable() const { return available; } void SDRDeviceInfo::setAvailable(bool available) { this->available = available; } const std::string& SDRDeviceInfo::getName() const { return name; } void SDRDeviceInfo::setName(const std::string& name) { this->name = name; } const std::string& SDRDeviceInfo::getSerial() const { return serial; } void SDRDeviceInfo::setSerial(const std::string& serial) { this->serial = serial; } const std::string& SDRDeviceInfo::getTuner() const { return tuner; } void SDRDeviceInfo::setTuner(const std::string& tuner) { this->tuner = tuner; } const std::string& SDRDeviceInfo::getManufacturer() const { return manufacturer; } void SDRDeviceInfo::setManufacturer(const std::string& manufacturer) { this->manufacturer = manufacturer; } const std::string& SDRDeviceInfo::getProduct() const { return product; } void SDRDeviceInfo::setProduct(const std::string& product) { this->product = product; }
hugewave/CubicSDR
src/sdr/SDRDeviceInfo.cpp
C++
gpl-2.0
1,308
<?php require_once($root_path.'include/care_api_classes/class_core.php'); global $page_funct, $Headline; class page_funct extends Core { function page_funct(){ return true; } function Display_Header(){ global $URL_APPEND, $LDBillingInsurance; echo '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 3.0//EN" "html.dtd"> <HTML> <HEAD> <TITLE> <?php echo $LDBillingInsurance; ?> </TITLE> <meta name="Description" content="Hospital and Healthcare Integrated Information System - CARE2x"> <meta name="Author" content="Robert Meggle"> <meta name="Generator" content="various: Quanta, AceHTML 4 Freeware, NuSphere, PHP Coder"> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <script language="javascript"> <!-- function gethelp(x,s,x1,x2,x3,x4) { if (!x) x=""; urlholder="../../main/help-router.php<?php echo URL_APPEND; ?>&helpidx="+x+"&src="+s+"&x1="+x1+"&x2="+x2+"&x3="+x3+"&x4="+x4; helpwin=window.open(urlholder,"helpwin","width=790,height=540,menubar=no,resizable=yes,scrollbars=yes"); window.helpwin.moveTo(0,0); } // --> </script> <link rel="stylesheet" href="../../css/themes/default/default.css" type="text/css"> <script language="javascript" src="../../js/hilitebu.js"></script> <STYLE TYPE="text/css"> A:link {color: #000066;} A:hover {color: #cc0033;} A:active {color: #cc0000;} A:visited {color: #000066;} A:visited:active {color: #cc0000;} A:visited:hover {color: #cc0033;} </style> <script language="JavaScript"> <!-- function popPic(pid,nm){ if(pid!="") regpicwindow = window.open("../../main/pop_reg_pic.php?sid=<?php echo $sid."&lang=".$lang; ?>&pid="+pid+"&nm="+nm,"regpicwin","toolbar=no,scrollbars,width=180,height=250"); } // --> </script> <script language="javascript"> <!-- function closewin() { location.href=\'startframe.php?sid="<?php echo $sid."&lang=".$lang; ?>"\'; } // --> </script> </HEAD>'; return true; } function Display_Headline($Headline){ echo '<table cellspacing="0" class="titlebar" border=0 height="35" width="100%"> <tr valign=top class="titlebar"> <td bgcolor="#99ccff"> &nbsp;&nbsp;<font color="#330066">'.$Headline.'</font> </td> <td bgcolor="#99ccff" align=right><a href="javascript:window.history.back()"><img src="../../gui/img/control/default/en/en_back2.gif" border=0 width="110" height="24" alt="" style="filter:alpha(opacity=70)" onMouseover="hilite(this,1)" onMouseOut="hilite(this,0)" ></a><a href="javascript:gethelp(\'insurance_companies_edit.php','Administrative Companies :: Setup\')"><img src="../../gui/img/control/default/en/en_hilfe-r.gif" border=0 width="75" height="24" alt="" style="filter:alpha(opacity=70)" onMouseover="hilite(this,1)" onMouseOut="hilite(this,0)"></a><a href="insurance_tz.php?ntid=false&lang=$lang" ><img src="../../gui/img/control/default/en/en_close2.gif" border=0 width="103" height="24" alt="" style="filter:alpha(opacity=70)" onMouseover="hilite(this,1)" onMouseOut="hilite(this,0)"></a> </td> </tr> </table> <table width=100% border=0 cellspacing=0 height=80%> <tbody class="main"> <tr> <td>'; return true; } function Display_Footer($Headline){ echo '</td><tr></table></<table cellspacing="0" class="titlebar" border=0 height="35" width="100%"> <tr valign=top class="titlebar"> <td bgcolor="#99ccff"> &nbsp;&nbsp;<font color="#330066">'.$Headline.'</font> </td> <td bgcolor="#99ccff" align=right><a href="javascript:window.history.back()"><img src="../../gui/img/control/default/en/en_back2.gif" border=0 width="110" height="24" alt="" style="filter:alpha(opacity=70)" onMouseover="hilite(this,1)" onMouseOut="hilite(this,0)" ></a><a href="javascript:gethelp(\'insurance_companies_edit.php\',\'Administrative Companies :: Setup\')"><img src="../../gui/img/control/default/en/en_hilfe-r.gif" border=0 width="75" height="24" alt="" style="filter:alpha(opacity=70)" onMouseover="hilite(this,1)" onMouseOut="hilite(this,0)"></a><a href="insurance_tz.php?ntid=false&lang=$lang" ><img src="../../gui/img/control/default/en/en_close2.gif" border=0 width="103" height="24" alt="" style="filter:alpha(opacity=70)" onMouseover="hilite(this,1)" onMouseOut="hilite(this,0)"></a> </td> </tr> </table>'; return true; } function Display_Credits(){ echo '<table width="100%" border="0" cellspacing="0" cellpadding="1" bgcolor="#cfcfcf"> <tr> <td align="center"> <table width="100%" bgcolor="#ffffff" cellspacing=0 cellpadding=5> <tr> <td> <div class="copyright"> <script language="JavaScript"> <!-- function openCreditsWindow() { urlholder="../../language/$lang/$lang_credits.php?lang=$lang"; creditswin=window.open(urlholder,"creditswin","width=500,height=600,menubar=no,resizable=yes,scrollbars=yes"); // --> } </script> <a href="http://www.care2x.org" target=_new>CARE2X 2nd Generation pre-deployment 2.0.2</a> :: <a href="../../legal_gnu_gpl.htm" target=_new> License</a> :: <a href=mailto:info@care2x.org>Contact</a> :: <a href="../../language/en/en_privacy.htm" target="pp"> Our Privacy Policy </a> :: <a href="../../docs/show_legal.php?lang=$lang" target="lgl"> Legal </a> :: <a href="javascript:openCreditsWindow()"> Credits </a> ::.<br> </div> </td> <tr> </table> </td> </tr> </table> </BODY> </HTML>'; return true; } } ?>
victorkagimu/khl-care2x
include/inc_page_functions.php
PHP
gpl-2.0
5,535
<?php /** * Copyright © 2015 Magento. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Bundle\Test\Unit\Block\Adminhtml\Sales\Order\View\Items; class RendererTest extends \PHPUnit_Framework_TestCase { /** @var \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject */ protected $orderItem; /** @var \Magento\Bundle\Block\Adminhtml\Sales\Order\View\Items\Renderer $model */ protected $model; protected function setUp() { $this->orderItem = $this->getMock( 'Magento\Sales\Model\Order\Item', ['getProductOptions', '__wakeup', 'getParentItem', 'getOrderItem'], [], '', false ); $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->model = $objectManager->getObject('Magento\Bundle\Block\Adminhtml\Sales\Order\View\Items\Renderer'); } /** * @dataProvider isShipmentSeparatelyWithoutItemDataProvider */ public function testIsShipmentSeparatelyWithoutItem($productOptions, $result) { $this->model->setItem($this->orderItem); $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); $this->assertSame($result, $this->model->isShipmentSeparately()); } public function isShipmentSeparatelyWithoutItemDataProvider() { return [ [['shipment_type' => 1], true], [['shipment_type' => 0], false], [[], false] ]; } /** * @dataProvider isShipmentSeparatelyWithItemDataProvider */ public function testIsShipmentSeparatelyWithItem($productOptions, $result, $parentItem) { if ($parentItem) { $parentItem = $this->getMock('Magento\Sales\Model\Order\Item', ['getProductOptions', '__wakeup'], [], '', false); $parentItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); } else { $this->orderItem->expects($this->any())->method('getProductOptions') ->will($this->returnValue($productOptions)); } $this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem)); $this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf()); $this->assertSame($result, $this->model->isShipmentSeparately($this->orderItem)); } public function isShipmentSeparatelyWithItemDataProvider() { return [ [['shipment_type' => 1], false, false], [['shipment_type' => 0], true, false], [['shipment_type' => 1], true, true], [['shipment_type' => 0], false, true], ]; } /** * @dataProvider isChildCalculatedWithoutItemDataProvider */ public function testIsChildCalculatedWithoutItem($productOptions, $result) { $this->model->setItem($this->orderItem); $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); $this->assertSame($result, $this->model->isChildCalculated()); } public function isChildCalculatedWithoutItemDataProvider() { return [ [['product_calculations' => 0], true], [['product_calculations' => 1], false], [[], false], ]; } /** * @dataProvider isChildCalculatedWithItemDataProvider */ public function testIsChildCalculatedWithItem($productOptions, $result, $parentItem) { if ($parentItem) { $parentItem = $this->getMock('Magento\Sales\Model\Order\Item', ['getProductOptions', '__wakeup'], [], '', false); $parentItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); } else { $this->orderItem->expects($this->any())->method('getProductOptions') ->will($this->returnValue($productOptions)); } $this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem)); $this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf()); $this->assertSame($result, $this->model->isChildCalculated($this->orderItem)); } public function isChildCalculatedWithItemDataProvider() { return [ [['product_calculations' => 0], false, false], [['product_calculations' => 1], true, false], [['product_calculations' => 0], true, true], [['product_calculations' => 1], false, true], ]; } /** * @dataProvider getSelectionAttributesDataProvider */ public function testGetSelectionAttributes($productOptions, $result) { $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); $this->assertSame($result, $this->model->getSelectionAttributes($this->orderItem)); } public function getSelectionAttributesDataProvider() { return [ [[], null], [['bundle_selection_attributes' => 'a:1:{i:0;i:1;}'], [0 => 1]], ]; } public function testGetOrderOptions() { $productOptions = [ 'options' => ['options'], 'additional_options' => ['additional_options'], 'attributes_info' => ['attributes_info'], ]; $this->model->setItem($this->orderItem); $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); $this->assertEquals(['attributes_info', 'options', 'additional_options'], $this->model->getOrderOptions()); } /** * @dataProvider canShowPriceInfoDataProvider */ public function testCanShowPriceInfo($parentItem, $productOptions, $result) { $this->model->setItem($this->orderItem); $this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf()); $this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem)); $this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions)); $this->assertSame($result, $this->model->canShowPriceInfo($this->orderItem)); } public function canShowPriceInfoDataProvider() { return [ [true, ['product_calculations' => 0], true], [false, [], true], [false, ['product_calculations' => 0], false], ]; } }
FPLD/project0
vendor/magento/module-bundle/Test/Unit/Block/Adminhtml/Sales/Order/View/Items/RendererTest.php
PHP
gpl-2.0
6,729
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "common/config-manager.h" #include "common/file.h" #include "common/substream.h" #include "common/macresman.h" #include "common/memstream.h" #include "director/director.h" #include "director/archive.h" #include "director/window.h" #include "director/util.h" namespace Director { // Base Archive code Archive::Archive() { _stream = 0; _isBigEndian = true; } Archive::~Archive() { close(); } Common::String Archive::getFileName() const { return Director::getFileName(_pathName); } bool Archive::openFile(const Common::String &fileName) { Common::File *file = new Common::File(); if (!file->open(Common::Path(fileName, g_director->_dirSeparator))) { warning("Archive::openFile(): Error opening file %s", fileName.c_str()); delete file; return false; } _pathName = fileName; if (!openStream(file)) { warning("Archive::openFile(): Error loading stream from file %s", fileName.c_str()); close(); return false; } return true; } void Archive::close() { _types.clear(); if (_stream) delete _stream; _stream = 0; } int Archive::getFileSize() { if (!_stream) return 0; return _stream->size(); } bool Archive::hasResource(uint32 tag, int id) const { if (!_types.contains(tag)) return false; if (id == -1) return true; return _types[tag].contains(id); } bool Archive::hasResource(uint32 tag, const Common::String &resName) const { if (!_types.contains(tag) || resName.empty()) return false; const ResourceMap &resMap = _types[tag]; for (ResourceMap::const_iterator it = resMap.begin(); it != resMap.end(); it++) if (it->_value.name.matchString(resName)) return true; return false; } Common::SeekableReadStreamEndian *Archive::getFirstResource(uint32 tag) { return getResource(tag, getResourceIDList(tag)[0]); } Common::SeekableReadStreamEndian *Archive::getResource(uint32 tag, uint16 id) { if (!_types.contains(tag)) error("Archive::getResource(): Archive does not contain '%s' %d", tag2str(tag), id); const ResourceMap &resMap = _types[tag]; if (!resMap.contains(id)) error("Archive::getResource(): Archive does not contain '%s' %d", tag2str(tag), id); const Resource &res = resMap[id]; return new Common::SeekableSubReadStreamEndian(_stream, res.offset, res.offset + res.size, _isBigEndian, DisposeAfterUse::NO); } Resource Archive::getResourceDetail(uint32 tag, uint16 id) { if (!_types.contains(tag)) error("Archive::getResourceDetail(): Archive does not contain '%s' %d", tag2str(tag), id); const ResourceMap &resMap = _types[tag]; if (!resMap.contains(id)) error("Archive::getResourceDetail(): Archive does not contain '%s' %d", tag2str(tag), id); return resMap[id]; } uint32 Archive::getOffset(uint32 tag, uint16 id) const { if (!_types.contains(tag)) error("Archive::getOffset(): Archive does not contain '%s' %d", tag2str(tag), id); const ResourceMap &resMap = _types[tag]; if (!resMap.contains(id)) error("Archive::getOffset(): Archive does not contain '%s' %d", tag2str(tag), id); return resMap[id].offset; } uint16 Archive::findResourceID(uint32 tag, const Common::String &resName, bool ignoreCase) const { if (!_types.contains(tag) || resName.empty()) return 0xFFFF; const ResourceMap &resMap = _types[tag]; for (ResourceMap::const_iterator it = resMap.begin(); it != resMap.end(); it++) if (it->_value.name.matchString(resName, ignoreCase)) return it->_key; return 0xFFFF; } Common::String Archive::getName(uint32 tag, uint16 id) const { if (!_types.contains(tag)) error("Archive::getName(): Archive does not contain '%s' %d", tag2str(tag), id); const ResourceMap &resMap = _types[tag]; if (!resMap.contains(id)) error("Archive::getName(): Archive does not contain '%s' %d", tag2str(tag), id); return resMap[id].name; } Common::Array<uint32> Archive::getResourceTypeList() const { Common::Array<uint32> typeList; for (TypeMap::const_iterator it = _types.begin(); it != _types.end(); it++) typeList.push_back(it->_key); return typeList; } Common::Array<uint16> Archive::getResourceIDList(uint32 type) const { Common::Array<uint16> idList; if (!_types.contains(type)) return idList; const ResourceMap &resMap = _types[type]; for (ResourceMap::const_iterator it = resMap.begin(); it != resMap.end(); it++) idList.push_back(it->_key); return idList; } uint32 Archive::convertTagToUppercase(uint32 tag) { uint32 newTag = toupper(tag >> 24) << 24; newTag |= toupper((tag >> 16) & 0xFF) << 16; newTag |= toupper((tag >> 8) & 0xFF) << 8; return newTag | toupper(tag & 0xFF); } // Mac Archive code MacArchive::MacArchive() : Archive(), _resFork(0) { } MacArchive::~MacArchive() { delete _resFork; } void MacArchive::close() { Archive::close(); delete _resFork; _resFork = 0; } bool MacArchive::openFile(const Common::String &fileName) { close(); _resFork = new Common::MacResManager(); Common::String fName = fileName; if (!_resFork->open(Common::Path(fName, g_director->_dirSeparator)) || !_resFork->hasResFork()) { close(); return false; } _pathName = _resFork->getBaseFileName().toString(g_director->_dirSeparator); if (_pathName.hasSuffix(".bin")) { for (int i = 0; i < 4; i++) _pathName.deleteLastChar(); } readTags(); return true; } bool MacArchive::openStream(Common::SeekableReadStream *stream, uint32 startOffset) { close(); if (startOffset) error("MacArchive::openStream(): startOffset > 0 is not yet implemented"); _resFork = new Common::MacResManager(); stream->seek(startOffset); if (!_resFork->loadFromMacBinary(*stream)) { warning("MacArchive::openStream(): Error loading Mac Binary"); close(); return false; } _pathName = "<stream>"; _resFork->setBaseFileName(_pathName); readTags(); return true; } void MacArchive::readTags() { Common::MacResTagArray tagArray = _resFork->getResTagArray(); for (uint32 i = 0; i < tagArray.size(); i++) { ResourceMap &resMap = _types[tagArray[i]]; Common::MacResIDArray idArray = _resFork->getResIDArray(tagArray[i]); for (uint32 j = 0; j < idArray.size(); j++) { Resource &res = resMap[idArray[j]]; res.offset = res.size = 0; // unused res.name = _resFork->getResName(tagArray[i], idArray[j]); debug(3, "Found MacArchive resource '%s' %d: %s", tag2str(tagArray[i]), idArray[j], res.name.c_str()); } } } Common::SeekableReadStreamEndian *MacArchive::getResource(uint32 tag, uint16 id) { assert(_resFork); Common::SeekableReadStream *stream = _resFork->getResource(tag, id); if (stream == nullptr) { warning("MacArchive::getResource('%s', %d): Resource doesn't exit", tag2str(tag), id); return nullptr; } return new Common::SeekableSubReadStreamEndian(stream, 0, stream->size(), true, DisposeAfterUse::YES); } // RIFF Archive code bool RIFFArchive::openStream(Common::SeekableReadStream *stream, uint32 startOffset) { close(); _startOffset = startOffset; stream->seek(startOffset); if (convertTagToUppercase(stream->readUint32BE()) != MKTAG('R', 'I', 'F', 'F')) { warning("RIFFArchive::openStream(): RIFF expected but not found"); return false; } stream->readUint32LE(); // size if (convertTagToUppercase(stream->readUint32BE()) != MKTAG('R', 'M', 'M', 'P')) { warning("RIFFArchive::openStream(): RMMP expected but not found"); return false; } if (convertTagToUppercase(stream->readUint32BE()) != MKTAG('C', 'F', 'T', 'C')) { warning("RIFFArchive::openStream(): CFTC expected but not found"); return false; } uint32 cftcSize = stream->readUint32LE(); uint32 startPos = stream->pos(); stream->readUint32LE(); // unknown (always 0?) while ((uint32)stream->pos() < startPos + cftcSize) { uint32 tag = convertTagToUppercase(stream->readUint32BE()); uint32 size = stream->readUint32LE(); uint32 id = stream->readUint32LE(); uint32 offset = stream->readUint32LE(); if (tag == 0) break; uint32 startResPos = stream->pos(); stream->seek(startOffset + offset + 12); Common::String name = ""; byte nameSize = stream->readByte(); if (nameSize) { bool skip = false; for (uint8 i = 0; i < nameSize; i++) { byte b = stream->readByte(); if (!b) skip = true; if (!skip) name += b; } } stream->seek(startResPos); debug(3, "Found RIFF resource '%s' %d: %d @ 0x%08x (0x%08x)", tag2str(tag), id, size, offset, startOffset + offset); ResourceMap &resMap = _types[tag]; Resource &res = resMap[id]; res.offset = offset; res.size = size; res.name = name; res.tag = tag; } _stream = stream; return true; } Common::SeekableReadStreamEndian *RIFFArchive::getResource(uint32 tag, uint16 id) { if (!_types.contains(tag)) error("RIFFArchive::getResource(): Archive does not contain '%s' %d", tag2str(tag), id); const ResourceMap &resMap = _types[tag]; if (!resMap.contains(id)) error("RIFFArchive::getResource(): Archive does not contain '%s' %d", tag2str(tag), id); const Resource &res = resMap[id]; // Adjust to skip the resource header uint32 offset = res.offset + 12; uint32 size = res.size - 4; // Skip the Pascal string _stream->seek(_startOffset + offset); byte stringSize = _stream->readByte(); // 1 for this byte offset += stringSize + 1; size -= stringSize + 1; // Align to nearest word boundary if (offset & 1) { offset++; size--; } return new Common::SeekableSubReadStreamEndian(_stream, _startOffset + offset, _startOffset + offset + size, true, DisposeAfterUse::NO); } // RIFX Archive code RIFXArchive::RIFXArchive() : Archive() { _isBigEndian = true; _rifxType = 0; _ilsBodyOffset = 0; } RIFXArchive::~RIFXArchive() { for (Common::HashMap<uint32, byte *>::iterator it = _ilsData.begin(); it != _ilsData.end(); it++) free(it->_value); } bool RIFXArchive::openStream(Common::SeekableReadStream *stream, uint32 startOffset) { if (stream != _stream) { close(); _stream = stream; } stream->seek(startOffset); uint32 moreOffset = 0; uint32 headerTag = stream->readUint32BE(); if (headerTag != MKTAG('R', 'I', 'F', 'X') && headerTag != MKTAG('X', 'F', 'I', 'R')) { // Check if it is MacBinary stream->seek(startOffset); if (Common::MacResManager::isMacBinary(*stream)) { warning("RIFXArchive::openStream(): MacBinary detected, overriding"); // We need to look at the resource fork to detect XCOD resources Common::SeekableSubReadStream *macStream = new Common::SeekableSubReadStream(stream, 0, stream->size()); MacArchive *macArchive = new MacArchive(); macArchive->openStream(macStream); g_director->getCurrentWindow()->probeMacBinary(macArchive); delete macArchive; // Then read the data fork moreOffset = Common::MacResManager::getDataForkOffset(); stream->seek(startOffset + moreOffset); headerTag = stream->readUint32BE(); } } if (headerTag == MKTAG('R', 'I', 'F', 'X')) { _isBigEndian = true; } else if (SWAP_BYTES_32(headerTag) == MKTAG('R', 'I', 'F', 'X')) { _isBigEndian = false; } else { warning("RIFXArchive::openStream(): RIFX or XFIR expected but %s found", tag2str(headerTag)); return false; } Common::SeekableSubReadStreamEndian endianStream(stream, 0, stream->size(), _isBigEndian, DisposeAfterUse::NO); endianStream.seek(startOffset + moreOffset + 4); uint32 sz = endianStream.readUint32(); // size // If it is an embedded file, dump it if requested. // Start by copying the movie data to a new buffer. byte *dumpData = nullptr; Common::SeekableMemoryWriteStream *dumpStream = nullptr; if (ConfMan.getBool("dump_scripts") && startOffset) { dumpData = (byte *)malloc(sz); dumpStream = new Common::SeekableMemoryWriteStream(dumpData, sz); stream->seek(startOffset); stream->read(dumpData, sz); stream->seek(startOffset + 8); } _rifxType = endianStream.readUint32(); warning("RIFX: type: %s", tag2str(_rifxType)); // Now read the memory map. // At the same time, we will patch the offsets in the dump data. bool readMapSuccess = false; switch (_rifxType) { case MKTAG('M', 'V', '9', '3'): case MKTAG('M', 'C', '9', '5'): readMapSuccess = readMemoryMap(endianStream, moreOffset, dumpStream, startOffset); break; case MKTAG('A', 'P', 'P', 'L'): readMapSuccess = readMemoryMap(endianStream, moreOffset, dumpStream, startOffset); break; case MKTAG('F', 'G', 'D', 'M'): case MKTAG('F', 'G', 'D', 'C'): readMapSuccess = readAfterburnerMap(endianStream, moreOffset); break; default: break; } // Now that the dump data has been patched, actually dump it. if (dumpData) { Common::DumpFile out; char buf[256]; sprintf(buf, "./dumps/%s-%08x", encodePathForDump(g_director->getEXEName()).c_str(), startOffset); if (out.open(buf, true)) { out.write(dumpData, sz); out.flush(); out.close(); } else { warning("RIFXArchive::openStream(): Can not open dump file %s", buf); } } free(dumpData); delete dumpStream; // If we couldn't read the map, we can't do anything past this point. if (!readMapSuccess) return false; if (_rifxType == MKTAG('A', 'P', 'P', 'L')) { if (hasResource(MKTAG('F', 'i', 'l', 'e'), -1)) { // Replace this archive with the embedded archive. uint32 fileId = getResourceIDList(MKTAG('F', 'i', 'l', 'e'))[0]; int32 fileOffset = _resources[fileId]->offset; _types.clear(); _resources.clear(); return openStream(_stream, fileOffset); } else { warning("No 'File' resource present in APPL archive"); return false; } } if (ConfMan.getBool("dump_scripts")) { debug("RIFXArchive::openStream(): Dumping %d resources", _resources.size()); byte *data = nullptr; uint dataSize = 0; Common::DumpFile out; for (uint i = 0; i < _resources.size(); i++) { if ((_rifxType == MKTAG('F', 'G', 'D', 'M') || _rifxType == MKTAG('F', 'G', 'D', 'C')) && _resources[i]->index < 3) { // This is in the initial load segment and can't be read like a normal chunk. continue; } Common::SeekableReadStreamEndian *resStream = getResource(_resources[i]->tag, _resources[i]->index); uint32 len = _resources[i]->size; if (dataSize < _resources[i]->size) { free(data); data = (byte *)malloc(resStream->size()); dataSize = resStream->size(); } Common::String prepend; if (_pathName.size() != 0) prepend = _pathName; else prepend = "stream"; Common::String filename = Common::String::format("./dumps/%s-%s-%d", encodePathForDump(prepend).c_str(), tag2str(_resources[i]->tag), _resources[i]->index); resStream->read(data, len); if (!out.open(filename, true)) { warning("RIFXArchive::openStream(): Can not open dump file %s", filename.c_str()); break; } out.write(data, len); out.flush(); out.close(); delete resStream; } } // Parse the CAS*, if present if (hasResource(MKTAG('C', 'A', 'S', '*'), -1)) { Common::SeekableReadStreamEndian *casStream = getFirstResource(MKTAG('C', 'A', 'S', '*')); readCast(*casStream); delete casStream; } // A KEY* must be present if (!hasResource(MKTAG('K', 'E', 'Y', '*'), -1)) { warning("No 'KEY*' resource present"); return false; } // Parse the KEY* Common::SeekableReadStreamEndian *keyStream = getFirstResource(MKTAG('K', 'E', 'Y', '*'), true); readKeyTable(*keyStream); delete keyStream; return true; } bool RIFXArchive::readMemoryMap(Common::SeekableReadStreamEndian &stream, uint32 moreOffset, Common::SeekableMemoryWriteStream *dumpStream, uint32 movieStartOffset) { if (stream.readUint32() != MKTAG('i', 'm', 'a', 'p')) return false; stream.readUint32(); // imap length stream.readUint32(); // unknown uint32 mmapOffsetPos = stream.pos(); uint32 mmapOffset = stream.readUint32() + moreOffset; if (dumpStream) { // If we're dumping the movie, patch this offset in the dump data. dumpStream->seek(mmapOffsetPos - movieStartOffset); if (stream.isBE()) dumpStream->writeUint32BE(mmapOffset - movieStartOffset); else dumpStream->writeUint32LE(mmapOffset - movieStartOffset); } uint32 version = stream.readUint32(); // 0 for 4.0, 0x4c1 for 5.0, 0x4c7 for 6.0, 0x708 for 8.5, 0x742 for 10.0 warning("mmap: version: %x", version); stream.seek(mmapOffset); if (stream.readUint32() != MKTAG('m', 'm', 'a', 'p')) { warning("RIFXArchive::readMemoryMap(): mmap expected but not found"); return false; } stream.readUint32(); // mmap length stream.readUint16(); // unknown stream.readUint16(); // unknown stream.readUint32(); // resCount + empty entries uint32 resCount = stream.readUint32(); stream.skip(8); // all 0xFF stream.readUint32(); // id of the first free resource, -1 if none. _resources.reserve(resCount); for (uint32 i = 0; i < resCount; i++) { uint32 tag = stream.readUint32(); uint32 size = stream.readUint32(); uint32 offsetPos = stream.pos(); int32 offset = stream.readUint32() + moreOffset; if (dumpStream) { dumpStream->seek(offsetPos - movieStartOffset); if (stream.isBE()) dumpStream->writeUint32BE(offset - movieStartOffset); else dumpStream->writeUint32LE(offset - movieStartOffset); } uint16 flags = stream.readUint16(); uint16 unk1 = stream.readUint16(); uint32 nextFreeResourceId = stream.readUint32(); // for free resources, the next id, flag like for imap and mmap resources debug(3, "Found RIFX resource index %d: '%s', %d bytes @ 0x%08x (%d), flags: %x unk1: %x nextFreeResourceId: %d", i, tag2str(tag), size, offset, offset, flags, unk1, nextFreeResourceId); Resource &res = _types[tag][i]; res.index = i; res.offset = offset; res.size = size; res.tag = tag; _resources.push_back(&res); } return true; } bool RIFXArchive::readAfterburnerMap(Common::SeekableReadStreamEndian &stream, uint32 moreOffset) { uint32 start, end; // File version if (stream.readUint32() != MKTAG('F', 'v', 'e', 'r')) { warning("RIFXArchive::readAfterburnerMap(): Fver expected but not found"); return false; } uint32 fverLength = readVarInt(stream); start = stream.pos(); uint32 version = readVarInt(stream); debug(3, "Fver: version: %x", version); end = stream.pos(); if (end - start != fverLength) { warning("RIFXArchive::readAfterburnerMap(): Expected Fver of length %d but read %d bytes", fverLength, end - start); stream.seek(start + fverLength); } // Compression types if (stream.readUint32() != MKTAG('F', 'c', 'd', 'r')) { warning("RIFXArchive::readAfterburnerMap(): Fcdr expected but not found"); return false; } uint32 fcdrLength = readVarInt(stream); stream.skip(fcdrLength); // Afterburner map if (stream.readUint32() != MKTAG('A', 'B', 'M', 'P')) { warning("RIFXArchive::readAfterburnerMap(): ABMP expected but not found"); return false; } uint32 abmpLength = readVarInt(stream); uint32 abmpEnd = stream.pos() + abmpLength; uint32 abmpCompressionType = readVarInt(stream); unsigned long abmpUncompLength = readVarInt(stream); unsigned long abmpActualUncompLength = abmpUncompLength; debug(3, "ABMP: length: %d compressionType: %d uncompressedLength: %lu", abmpLength, abmpCompressionType, abmpUncompLength); Common::SeekableReadStreamEndian *abmpStream = readZlibData(stream, abmpEnd - stream.pos(), &abmpActualUncompLength, _isBigEndian); if (!abmpStream) { warning("RIFXArchive::readAfterburnerMap(): Could not uncompress ABMP"); return false; } if (abmpUncompLength != abmpActualUncompLength) { warning("ABMP: Expected uncompressed length %lu but got length %lu", abmpUncompLength, abmpActualUncompLength); } if (ConfMan.getBool("dump_scripts")) { Common::DumpFile out; char buf[256]; sprintf(buf, "./dumps/%s-%s", encodePathForDump(g_director->getEXEName()).c_str(), "ABMP"); if (out.open(buf, true)) { byte *data = (byte *)malloc(abmpStream->size()); abmpStream->read(data, abmpStream->size()); out.write(data, abmpStream->size()); out.flush(); out.close(); free(data); abmpStream->seek(0); } else { warning("RIFXArchive::readAfterburnerMap(): Can not open dump file %s", buf); } } uint32 abmpUnk1 = readVarInt(*abmpStream); uint32 abmpUnk2 = readVarInt(*abmpStream); uint32 resCount = readVarInt(*abmpStream); debug(3, "ABMP: unk1: %d unk2: %d resCount: %d", abmpUnk1, abmpUnk2, resCount); Common::HashMap<uint32, Resource *> resourceMap; for (uint32 i = 0; i < resCount; i++) { uint32 resId = readVarInt(*abmpStream); int32 offset = readVarInt(*abmpStream); if (offset >= 0) offset += moreOffset; uint32 compSize = readVarInt(*abmpStream); uint32 uncompSize = readVarInt(*abmpStream); uint32 compressionType = readVarInt(*abmpStream); uint32 tag = abmpStream->readUint32(); debug(3, "Found RIFX resource index %d: '%s', %d bytes (%d uncompressed) @ pos 0x%08x (%d), compressionType: %d", resId, tag2str(tag), compSize, uncompSize, offset, offset, compressionType); Resource &res = _types[tag][resId]; res.index = resId; res.offset = offset; res.size = compSize; res.uncompSize = uncompSize; res.compressionType = compressionType; res.tag = tag; _resources.push_back(&res); resourceMap[resId] = &res; } delete abmpStream; // Initial load segment if (!resourceMap.contains(2)) { warning("RIFXArchive::readAfterburnerMap(): Map has no entry for ILS"); return false; } if (stream.readUint32() != MKTAG('F', 'G', 'E', 'I')) { warning("RIFXArchive::readAfterburnerMap(): FGEI expected but not found"); return false; } Resource *ilsRes = resourceMap[2]; uint32 ilsUnk1 = readVarInt(stream); debug(3, "ILS: length: %d unk1: %d", ilsRes->size, ilsUnk1); _ilsBodyOffset = stream.pos(); uint32 ilsLength = ilsRes->size; unsigned long ilsActualUncompLength = ilsRes->uncompSize; Common::SeekableReadStreamEndian *ilsStream = readZlibData(stream, ilsLength, &ilsActualUncompLength, _isBigEndian); if (!ilsStream) { warning("RIFXArchive::readAfterburnerMap(): Could not uncompress FGEI"); return false; } if (ilsRes->uncompSize != ilsActualUncompLength) { warning("ILS: Expected uncompressed length %d but got length %lu", ilsRes->uncompSize, ilsActualUncompLength); } while (ilsStream->pos() < ilsStream->size()) { uint32 resId = readVarInt(*ilsStream); Resource *res = resourceMap[resId]; debug(3, "Loading ILS resource %d: '%s', %d bytes", resId, tag2str(res->tag), res->size); byte *data = (byte *)malloc(res->size); ilsStream->read(data, res->size); _ilsData[resId] = data; } delete ilsStream; return true; } void RIFXArchive::readCast(Common::SeekableReadStreamEndian &casStream) { uint castTag = MKTAG('C', 'A', 'S', 't'); uint casSize = casStream.size() / 4; debugCN(2, kDebugLoading, "CAS*: %d [", casSize); for (uint i = 0; i < casSize; i++) { uint32 castIndex = casStream.readUint32BE(); debugCN(2, kDebugLoading, "%d ", castIndex); if (castIndex == 0) { continue; } Resource &res = _types[castTag][castIndex]; res.castId = i; } debugC(2, kDebugLoading, "]"); } void RIFXArchive::readKeyTable(Common::SeekableReadStreamEndian &keyStream) { uint16 entrySize = keyStream.readUint16(); // Should always be 12 (3 uint32's) uint16 entrySize2 = keyStream.readUint16(); uint32 entryCount = keyStream.readUint32(); // There are more entries than actually used uint32 usedCount = keyStream.readUint32(); debugC(2, kDebugLoading, "KEY*: entrySize: %d entrySize2: %d entryCount: %d usedCount: %d", entrySize, entrySize2, entryCount, usedCount); ResourceMap &castResMap = _types[MKTAG('C', 'A', 'S', 't')]; for (uint16 i = 0; i < usedCount; i++) { uint32 childIndex = keyStream.readUint32(); uint32 parentIndex = keyStream.readUint32(); uint32 childTag = keyStream.readUint32(); debugC(2, kDebugLoading, "KEY*: childIndex: %d parentIndex: %d childTag: %s", childIndex, parentIndex, tag2str(childTag)); if (castResMap.contains(parentIndex)) { castResMap[parentIndex].children.push_back(_types[childTag][childIndex]); } else if (castResMap.contains(childIndex)) { // sometimes parent and child index are reversed... castResMap[childIndex].children.push_back(_types[childTag][parentIndex]); } } } Common::SeekableReadStreamEndian *RIFXArchive::getFirstResource(uint32 tag) { return getResource(tag, getResourceIDList(tag)[0], false); } Common::SeekableReadStreamEndian *RIFXArchive::getFirstResource(uint32 tag, bool fileEndianness) { return getResource(tag, getResourceIDList(tag)[0], fileEndianness); } Common::SeekableReadStreamEndian *RIFXArchive::getResource(uint32 tag, uint16 id) { return getResource(tag, id, false); } Common::SeekableReadStreamEndian *RIFXArchive::getResource(uint32 tag, uint16 id, bool fileEndianness) { if (!_types.contains(tag)) error("RIFXArchive::getResource(): Archive does not contain '%s' %d", tag2str(tag), id); const ResourceMap &resMap = _types[tag]; if (!resMap.contains(id)) error("RIFXArchive::getResource(): Archive does not contain '%s' %d", tag2str(tag), id); const Resource &res = resMap[id]; bool bigEndian = fileEndianness ? _isBigEndian : true; if (_rifxType == MKTAG('F', 'G', 'D', 'M') || _rifxType == MKTAG('F', 'G', 'D', 'C')) { if (res.offset == -1) { return new Common::MemoryReadStreamEndian(_ilsData[id], res.uncompSize, bigEndian, DisposeAfterUse::NO); } else { _stream->seek(_ilsBodyOffset + res.offset); unsigned long actualUncompLength = res.uncompSize; Common::SeekableReadStreamEndian *stream = readZlibData(*_stream, res.size, &actualUncompLength, _isBigEndian); if (!stream) { warning("RIFXArchive::getResource(): Could not uncompress '%s' %d", tag2str(tag), id); return nullptr; } if (res.uncompSize != actualUncompLength) { warning("RIFXArchive::getResource(): For '%s' %d expected uncompressed length %d but got length %lu", tag2str(tag), id, res.uncompSize, actualUncompLength); } return stream; } } uint32 offset = res.offset + 8; uint32 size = res.size; return new Common::SeekableSubReadStreamEndian(_stream, offset, offset + size, bigEndian, DisposeAfterUse::NO); } Resource RIFXArchive::getResourceDetail(uint32 tag, uint16 id) { if (!_types.contains(tag)) error("RIFXArchive::getResourceDetail(): Archive does not contain '%s' %d", tag2str(tag), id); const ResourceMap &resMap = _types[tag]; if (!resMap.contains(id)) error("RIFXArchive::getResourceDetail(): Archive does not contain '%s' %d", tag2str(tag), id); return resMap[id]; } } // End of namespace Director
vanfanel/scummvm
engines/director/archive.cpp
C++
gpl-2.0
27,260
/** * BxSlider v4.1.2 - Fully loaded, responsive content slider * http://bxslider.com * * Copyright 2014, Steven Wanderski - http://stevenwanderski.com - http://bxcreative.com * Written while drinking Belgian ales and listening to jazz * * Released under the MIT license - http://opensource.org/licenses/MIT */ !function(t){ var e={},s={ mode:"horizontal", slideSelector:"", infiniteLoop:!0, hideControlOnEnd:!1, speed:500, easing:null, slideMargin:0, startSlide:0, randomStart:!1, captions:!1, ticker:!1, tickerHover:!1, adaptiveHeight:!1, adaptiveHeightSpeed:500, video:!1, useCSS:!0, preloadImages:"visible", responsive:!0, slideZIndex:50, touchEnabled:!0, swipeThreshold:50, oneToOneTouch:!0, preventDefaultSwipeX:!0, preventDefaultSwipeY:!1, pager:!0, pagerType:"full", pagerShortSeparator:" / ", pagerSelector:null, buildPager:null, pagerCustom:null, controls:!0, nextText:"Next", prevText:"Prev", nextSelector:null, prevSelector:null, autoControls:!1, startText:"Start", stopText:"Stop", autoControlsCombine:!1, autoControlsSelector:null, auto:!0, pause:4e3, autoStart:!0, autoDirection:"next", autoHover:!1, autoDelay:0, minSlides:1, maxSlides:1, moveSlides:0, slideWidth:0, onSliderLoad:function(){}, onSlideBefore:function(){}, onSlideAfter:function(){}, onSlideNext:function(){}, onSlidePrev:function(){}, onSliderResize:function(){} }; t.fn.bxSlider=function(n){ if(0==this.length)return this; if(this.length>1)return this.each(function(){ t(this).bxSlider(n) }),this; var o={},r=this; e.el=this; var a=t(window).width(),l=t(window).height(),d=function(){ o.settings=t.extend({},s,n),o.settings.slideWidth=parseInt(o.settings.slideWidth),o.children=r.children(o.settings.slideSelector),o.children.length<o.settings.minSlides&&(o.settings.minSlides=o.children.length),o.children.length<o.settings.maxSlides&&(o.settings.maxSlides=o.children.length),o.settings.randomStart&&(o.settings.startSlide=Math.floor(Math.random()*o.children.length)),o.active={ index:o.settings.startSlide },o.carousel=o.settings.minSlides>1||o.settings.maxSlides>1,o.carousel&&(o.settings.preloadImages="all"),o.minThreshold=o.settings.minSlides*o.settings.slideWidth+(o.settings.minSlides-1)*o.settings.slideMargin,o.maxThreshold=o.settings.maxSlides*o.settings.slideWidth+(o.settings.maxSlides-1)*o.settings.slideMargin,o.working=!1,o.controls={},o.interval=null,o.animProp="vertical"==o.settings.mode?"top":"left",o.usingCSS=o.settings.useCSS&&"fade"!=o.settings.mode&&function(){ var t=document.createElement("div"),e=["WebkitPerspective","MozPerspective","OPerspective","msPerspective"]; for(var i in e)if(void 0!==t.style[e[i]])return o.cssPrefix=e[i].replace("Perspective","").toLowerCase(),o.animProp="-"+o.cssPrefix+"-transform",!0;return!1 }(),"vertical"==o.settings.mode&&(o.settings.maxSlides=o.settings.minSlides),r.data("origStyle",r.attr("style")),r.children(o.settings.slideSelector).each(function(){ t(this).data("origStyle",t(this).attr("style")) }),c() },c=function(){ r.wrap('<div class="bx-wrapper"><div class="bx-viewport"></div></div>'),o.viewport=r.parent(),o.loader=t('<div class="bx-loading" />'),o.viewport.prepend(o.loader),r.css({ width:"horizontal"==o.settings.mode?100*o.children.length+215+"%":"auto", position:"relative" }),o.usingCSS&&o.settings.easing?r.css("-"+o.cssPrefix+"-transition-timing-function",o.settings.easing):o.settings.easing||(o.settings.easing="swing"),f(),o.viewport.css({ width:"100%", overflow:"hidden", position:"relative" }),o.viewport.parent().css({ maxWidth:p() }),o.settings.pager||o.viewport.parent().css({ margin:"0 auto 0px" }),o.children.css({ "float":"horizontal"==o.settings.mode?"left":"none", listStyle:"none", position:"relative" }),o.children.css("width",u()),"horizontal"==o.settings.mode&&o.settings.slideMargin>0&&o.children.css("marginRight",o.settings.slideMargin),"vertical"==o.settings.mode&&o.settings.slideMargin>0&&o.children.css("marginBottom",o.settings.slideMargin),"fade"==o.settings.mode&&(o.children.css({ position:"absolute", zIndex:0, display:"none" }),o.children.eq(o.settings.startSlide).css({ zIndex:o.settings.slideZIndex, display:"block" })),o.controls.el=t('<div class="bx-controls" />'),o.settings.captions&&P(),o.active.last=o.settings.startSlide==x()-1,o.settings.video&&r.fitVids(); var e=o.children.eq(o.settings.startSlide); "all"==o.settings.preloadImages&&(e=o.children),o.settings.ticker?o.settings.pager=!1:(o.settings.pager&&T(),o.settings.controls&&C(),o.settings.auto&&o.settings.autoControls&&E(),(o.settings.controls||o.settings.autoControls||o.settings.pager)&&o.viewport.after(o.controls.el)),g(e,h) },g=function(e,i){ var s=e.find("img, iframe").length; if(0==s)return i(),void 0; var n=0; e.find("img, iframe").each(function(){ t(this).one("load",function(){ ++n==s&&i() }).each(function(){ this.complete&&t(this).load() }) }) },h=function(){ if(o.settings.infiniteLoop&&"fade"!=o.settings.mode&&!o.settings.ticker){ var e="vertical"==o.settings.mode?o.settings.minSlides:o.settings.maxSlides,i=o.children.slice(0,e).clone().addClass("bx-clone"),s=o.children.slice(-e).clone().addClass("bx-clone"); r.append(i).prepend(s) } o.loader.remove(),S(),"vertical"==o.settings.mode&&(o.settings.adaptiveHeight=!0),o.viewport.height(v()),r.redrawSlider(),o.settings.onSliderLoad(o.active.index),o.initialized=!0,o.settings.responsive&&t(window).bind("resize",Z),o.settings.auto&&o.settings.autoStart&&H(),o.settings.ticker&&L(),o.settings.pager&&q(o.settings.startSlide),o.settings.controls&&W(),o.settings.touchEnabled&&!o.settings.ticker&&O() },v=function(){ var e=0,s=t(); if("vertical"==o.settings.mode||o.settings.adaptiveHeight)if(o.carousel){ var n=1==o.settings.moveSlides?o.active.index:o.active.index*m(); for(s=o.children.eq(n),i=1;i<=o.settings.maxSlides-1;i++)s=n+i>=o.children.length?s.add(o.children.eq(i-1)):s.add(o.children.eq(n+i)) }else s=o.children.eq(o.active.index);else s=o.children; return"vertical"==o.settings.mode?(s.each(function(){ e+=t(this).outerHeight() }),o.settings.slideMargin>0&&(e+=o.settings.slideMargin*(o.settings.minSlides-1))):e=Math.max.apply(Math,s.map(function(){ return t(this).outerHeight(!1) }).get()),e },p=function(){ var t="100%"; return o.settings.slideWidth>0&&(t="horizontal"==o.settings.mode?o.settings.maxSlides*o.settings.slideWidth+(o.settings.maxSlides-1)*o.settings.slideMargin:o.settings.slideWidth),t },u=function(){ var t=o.settings.slideWidth,e=o.viewport.width(); return 0==o.settings.slideWidth||o.settings.slideWidth>e&&!o.carousel||"vertical"==o.settings.mode?t=e:o.settings.maxSlides>1&&"horizontal"==o.settings.mode&&(e>o.maxThreshold||e<o.minThreshold&&(t=(e-o.settings.slideMargin*(o.settings.minSlides-1))/o.settings.minSlides)),t },f=function(){ var t=1; if("horizontal"==o.settings.mode&&o.settings.slideWidth>0)if(o.viewport.width()<o.minThreshold)t=o.settings.minSlides; else if(o.viewport.width()>o.maxThreshold)t=o.settings.maxSlides; else{ var e=o.children.first().width(); t=Math.floor(o.viewport.width()/e) }else"vertical"==o.settings.mode&&(t=o.settings.minSlides); return t },x=function(){ var t=0; if(o.settings.moveSlides>0)if(o.settings.infiniteLoop)t=o.children.length/m();else for(var e=0,i=0;e<o.children.length;)++t,e=i+f(),i+=o.settings.moveSlides<=f()?o.settings.moveSlides:f();else t=Math.ceil(o.children.length/f()); return t },m=function(){ return o.settings.moveSlides>0&&o.settings.moveSlides<=f()?o.settings.moveSlides:f() },S=function(){ if(o.children.length>o.settings.maxSlides&&o.active.last&&!o.settings.infiniteLoop){ if("horizontal"==o.settings.mode){ var t=o.children.last(),e=t.position(); b(-(e.left-(o.viewport.width()-t.width())),"reset",0) }else if("vertical"==o.settings.mode){ var i=o.children.length-o.settings.minSlides,e=o.children.eq(i).position(); b(-e.top,"reset",0) } }else{ var e=o.children.eq(o.active.index*m()).position(); o.active.index==x()-1&&(o.active.last=!0),void 0!=e&&("horizontal"==o.settings.mode?b(-e.left,"reset",0):"vertical"==o.settings.mode&&b(-e.top,"reset",0)) } },b=function(t,e,i,s){ if(o.usingCSS){ var n="vertical"==o.settings.mode?"translate3d(0, "+t+"px, 0)":"translate3d("+t+"px, 0, 0)"; r.css("-"+o.cssPrefix+"-transition-duration",i/1e3+"s"),"slide"==e?(r.css(o.animProp,n),r.bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd",function(){ r.unbind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd"),D() })):"reset"==e?r.css(o.animProp,n):"ticker"==e&&(r.css("-"+o.cssPrefix+"-transition-timing-function","linear"),r.css(o.animProp,n),r.bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd",function(){ r.unbind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd"),b(s.resetValue,"reset",0),N() })) }else{ var a={}; a[o.animProp]=t,"slide"==e?r.animate(a,i,o.settings.easing,function(){ D() }):"reset"==e?r.css(o.animProp,t):"ticker"==e&&r.animate(a,speed,"linear",function(){ b(s.resetValue,"reset",0),N() }) } },w=function(){ for(var e="",i=x(),s=0;i>s;s++){ var n=""; o.settings.buildPager&&t.isFunction(o.settings.buildPager)?(n=o.settings.buildPager(s),o.pagerEl.addClass("bx-custom-pager")):(n=s+1,o.pagerEl.addClass("bx-default-pager")),e+='<div class="bx-pager-item"><a href="" data-slide-index="'+s+'" class="bx-pager-link" style="overflow: hidden">'+n+"</a></div>" } o.pagerEl.html(e) },T=function(){ o.settings.pagerCustom?o.pagerEl=t(o.settings.pagerCustom):(o.pagerEl=t('<div class="bx-pager" />'),o.settings.pagerSelector?t(o.settings.pagerSelector).html(o.pagerEl):o.controls.el.addClass("bx-has-pager").append(o.pagerEl),w()),o.pagerEl.on("click","a",I) },C=function(){ o.controls.next=t('<a class="bx-next" href="">'+o.settings.nextText+"</a>"),o.controls.prev=t('<a class="bx-prev" href="">'+o.settings.prevText+"</a>"),o.controls.next.bind("click",y),o.controls.prev.bind("click",z),o.settings.nextSelector&&t(o.settings.nextSelector).append(o.controls.next),o.settings.prevSelector&&t(o.settings.prevSelector).append(o.controls.prev),o.settings.nextSelector||o.settings.prevSelector||(o.controls.directionEl=t('<div class="bx-controls-direction" />'),o.controls.directionEl.append(o.controls.prev).append(o.controls.next),o.controls.el.addClass("bx-has-controls-direction").append(o.controls.directionEl)) },E=function(){ o.controls.start=t('<div class="bx-controls-auto-item"><a class="bx-start" href="">'+o.settings.startText+"</a></div>"),o.controls.stop=t('<div class="bx-controls-auto-item"><a class="bx-stop" href="">'+o.settings.stopText+"</a></div>"),o.controls.autoEl=t('<div class="bx-controls-auto" />'),o.controls.autoEl.on("click",".bx-start",k),o.controls.autoEl.on("click",".bx-stop",M),o.settings.autoControlsCombine?o.controls.autoEl.append(o.controls.start):o.controls.autoEl.append(o.controls.start).append(o.controls.stop),o.settings.autoControlsSelector?t(o.settings.autoControlsSelector).html(o.controls.autoEl):o.controls.el.addClass("bx-has-controls-auto").append(o.controls.autoEl),A(o.settings.autoStart?"stop":"start") },P=function(){ o.children.each(function(){ var e=t(this).find("img:first").attr("title"); void 0!=e&&(""+e).length&&t(this).append('<div class="bx-caption"><span>'+e+"</span></div>") }) },y=function(t){ o.settings.auto&&r.stopAuto(),r.goToNextSlide(),t.preventDefault() },z=function(t){ o.settings.auto&&r.stopAuto(),r.goToPrevSlide(),t.preventDefault() },k=function(t){ r.startAuto(),t.preventDefault() },M=function(t){ r.stopAuto(),t.preventDefault() },I=function(e){ o.settings.auto&&r.stopAuto(); var i=t(e.currentTarget),s=parseInt(i.attr("data-slide-index")); s!=o.active.index&&r.goToSlide(s),e.preventDefault() },q=function(e){ var i=o.children.length; return"short"==o.settings.pagerType?(o.settings.maxSlides>1&&(i=Math.ceil(o.children.length/o.settings.maxSlides)),o.pagerEl.html(e+1+o.settings.pagerShortSeparator+i),void 0):(o.pagerEl.find("a").removeClass("active"),o.pagerEl.each(function(i,s){ t(s).find("a").eq(e).addClass("active") }),void 0) },D=function(){ if(o.settings.infiniteLoop){ var t=""; 0==o.active.index?t=o.children.eq(0).position():o.active.index==x()-1&&o.carousel?t=o.children.eq((x()-1)*m()).position():o.active.index==o.children.length-1&&(t=o.children.eq(o.children.length-1).position()),t&&("horizontal"==o.settings.mode?b(-t.left,"reset",0):"vertical"==o.settings.mode&&b(-t.top,"reset",0)) } o.working=!1,o.settings.onSlideAfter(o.children.eq(o.active.index),o.oldIndex,o.active.index) },A=function(t){ o.settings.autoControlsCombine?o.controls.autoEl.html(o.controls[t]):(o.controls.autoEl.find("a").removeClass("active"),o.controls.autoEl.find("a:not(.bx-"+t+")").addClass("active")) },W=function(){ 1==x()?(o.controls.prev.addClass("disabled"),o.controls.next.addClass("disabled")):!o.settings.infiniteLoop&&o.settings.hideControlOnEnd&&(0==o.active.index?(o.controls.prev.addClass("disabled"),o.controls.next.removeClass("disabled")):o.active.index==x()-1?(o.controls.next.addClass("disabled"),o.controls.prev.removeClass("disabled")):(o.controls.prev.removeClass("disabled"),o.controls.next.removeClass("disabled"))) },H=function(){ o.settings.autoDelay>0?setTimeout(r.startAuto,o.settings.autoDelay):r.startAuto(),o.settings.autoHover&&r.hover(function(){ o.interval&&(r.stopAuto(!0),o.autoPaused=!0) },function(){ o.autoPaused&&(r.startAuto(!0),o.autoPaused=null) }) },L=function(){ var e=0; if("next"==o.settings.autoDirection)r.append(o.children.clone().addClass("bx-clone")); else{ r.prepend(o.children.clone().addClass("bx-clone")); var i=o.children.first().position(); e="horizontal"==o.settings.mode?-i.left:-i.top } b(e,"reset",0),o.settings.pager=!1,o.settings.controls=!1,o.settings.autoControls=!1,o.settings.tickerHover&&!o.usingCSS&&o.viewport.hover(function(){ r.stop() },function(){ var e=0; o.children.each(function(){ e+="horizontal"==o.settings.mode?t(this).outerWidth(!0):t(this).outerHeight(!0) }); var i=o.settings.speed/e,s="horizontal"==o.settings.mode?"left":"top",n=i*(e-Math.abs(parseInt(r.css(s)))); N(n) }),N() },N=function(t){ speed=t?t:o.settings.speed; var e={ left:0, top:0 },i={ left:0, top:0 }; "next"==o.settings.autoDirection?e=r.find(".bx-clone").first().position():i=o.children.first().position(); var s="horizontal"==o.settings.mode?-e.left:-e.top,n="horizontal"==o.settings.mode?-i.left:-i.top,a={ resetValue:n }; b(s,"ticker",speed,a) },O=function(){ o.touch={ start:{ x:0, y:0 }, end:{ x:0, y:0 } },o.viewport.bind("touchstart",X) },X=function(t){ if(o.working)t.preventDefault(); else{ o.touch.originalPos=r.position(); var e=t.originalEvent; o.touch.start.x=e.changedTouches[0].pageX,o.touch.start.y=e.changedTouches[0].pageY,o.viewport.bind("touchmove",Y),o.viewport.bind("touchend",V) } },Y=function(t){ var e=t.originalEvent,i=Math.abs(e.changedTouches[0].pageX-o.touch.start.x),s=Math.abs(e.changedTouches[0].pageY-o.touch.start.y); if(3*i>s&&o.settings.preventDefaultSwipeX?t.preventDefault():3*s>i&&o.settings.preventDefaultSwipeY&&t.preventDefault(),"fade"!=o.settings.mode&&o.settings.oneToOneTouch){ var n=0; if("horizontal"==o.settings.mode){ var r=e.changedTouches[0].pageX-o.touch.start.x; n=o.touch.originalPos.left+r }else{ var r=e.changedTouches[0].pageY-o.touch.start.y; n=o.touch.originalPos.top+r } b(n,"reset",0) } },V=function(t){ o.viewport.unbind("touchmove",Y); var e=t.originalEvent,i=0; if(o.touch.end.x=e.changedTouches[0].pageX,o.touch.end.y=e.changedTouches[0].pageY,"fade"==o.settings.mode){ var s=Math.abs(o.touch.start.x-o.touch.end.x); s>=o.settings.swipeThreshold&&(o.touch.start.x>o.touch.end.x?r.goToNextSlide():r.goToPrevSlide(),r.stopAuto()) }else{ var s=0; "horizontal"==o.settings.mode?(s=o.touch.end.x-o.touch.start.x,i=o.touch.originalPos.left):(s=o.touch.end.y-o.touch.start.y,i=o.touch.originalPos.top),!o.settings.infiniteLoop&&(0==o.active.index&&s>0||o.active.last&&0>s)?b(i,"reset",200):Math.abs(s)>=o.settings.swipeThreshold?(0>s?r.goToNextSlide():r.goToPrevSlide(),r.stopAuto()):b(i,"reset",200) } o.viewport.unbind("touchend",V) },Z=function(){ var e=t(window).width(),i=t(window).height(); (a!=e||l!=i)&&(a=e,l=i,r.redrawSlider(),o.settings.onSliderResize.call(r,o.active.index)) }; return r.goToSlide=function(e,i){ if(!o.working&&o.active.index!=e)if(o.working=!0,o.oldIndex=o.active.index,o.active.index=0>e?x()-1:e>=x()?0:e,o.settings.onSlideBefore(o.children.eq(o.active.index),o.oldIndex,o.active.index),"next"==i?o.settings.onSlideNext(o.children.eq(o.active.index),o.oldIndex,o.active.index):"prev"==i&&o.settings.onSlidePrev(o.children.eq(o.active.index),o.oldIndex,o.active.index),o.active.last=o.active.index>=x()-1,o.settings.pager&&q(o.active.index),o.settings.controls&&W(),"fade"==o.settings.mode)o.settings.adaptiveHeight&&o.viewport.height()!=v()&&o.viewport.animate({ height:v() },o.settings.adaptiveHeightSpeed),o.children.filter(":visible").fadeOut(o.settings.speed).css({ zIndex:0 }),o.children.eq(o.active.index).css("zIndex",o.settings.slideZIndex+1).fadeIn(o.settings.speed,function(){ t(this).css("zIndex",o.settings.slideZIndex),D() }); else{ o.settings.adaptiveHeight&&o.viewport.height()!=v()&&o.viewport.animate({ height:v() },o.settings.adaptiveHeightSpeed); var s=0,n={ left:0, top:0 }; if(!o.settings.infiniteLoop&&o.carousel&&o.active.last)if("horizontal"==o.settings.mode){ var a=o.children.eq(o.children.length-1); n=a.position(),s=o.viewport.width()-a.outerWidth() }else{ var l=o.children.length-o.settings.minSlides; n=o.children.eq(l).position() }else if(o.carousel&&o.active.last&&"prev"==i){ var d=1==o.settings.moveSlides?o.settings.maxSlides-m():(x()-1)*m()-(o.children.length-o.settings.maxSlides),a=r.children(".bx-clone").eq(d); n=a.position() }else if("next"==i&&0==o.active.index)n=r.find("> .bx-clone").eq(o.settings.maxSlides).position(),o.active.last=!1; else if(e>=0){ var c=e*m(); n=o.children.eq(c).position() } if("undefined"!=typeof n){ var g="horizontal"==o.settings.mode?-(n.left-s):-n.top; b(g,"slide",o.settings.speed) } } },r.goToNextSlide=function(){ if(o.settings.infiniteLoop||!o.active.last){ var t=parseInt(o.active.index)+1; r.goToSlide(t,"next") } },r.goToPrevSlide=function(){ if(o.settings.infiniteLoop||0!=o.active.index){ var t=parseInt(o.active.index)-1; r.goToSlide(t,"prev") } },r.startAuto=function(t){ o.interval||(o.interval=setInterval(function(){ "next"==o.settings.autoDirection?r.goToNextSlide():r.goToPrevSlide() },o.settings.pause),o.settings.autoControls&&1!=t&&A("stop")) },r.stopAuto=function(t){ o.interval&&(clearInterval(o.interval),o.interval=null,o.settings.autoControls&&1!=t&&A("start")) },r.getCurrentSlide=function(){ return o.active.index },r.getCurrentSlideElement=function(){ return o.children.eq(o.active.index) },r.getSlideCount=function(){ return o.children.length },r.redrawSlider=function(){ o.children.add(r.find(".bx-clone")).outerWidth(u()),o.viewport.css("height",v()),o.settings.ticker||S(),o.active.last&&(o.active.index=x()-1),o.active.index>=x()&&(o.active.last=!0),o.settings.pager&&!o.settings.pagerCustom&&(w(),q(o.active.index)) },r.destroySlider=function(){ o.initialized&&(o.initialized=!1,t(".bx-clone",this).remove(),o.children.each(function(){ void 0!=t(this).data("origStyle")?t(this).attr("style",t(this).data("origStyle")):t(this).removeAttr("style") }),void 0!=t(this).data("origStyle")?this.attr("style",t(this).data("origStyle")):t(this).removeAttr("style"),t(this).unwrap().unwrap(),o.controls.el&&o.controls.el.remove(),o.controls.next&&o.controls.next.remove(),o.controls.prev&&o.controls.prev.remove(),o.pagerEl&&o.settings.controls&&o.pagerEl.remove(),t(".bx-caption",this).remove(),o.controls.autoEl&&o.controls.autoEl.remove(),clearInterval(o.interval),o.settings.responsive&&t(window).unbind("resize",Z)) },r.reloadSlider=function(t){ void 0!=t&&(n=t),r.destroySlider(),d() },d(),this } }(jQuery);
mhndev/shopping
public/js/jquery.bxslider.min.js
JavaScript
gpl-2.0
23,177
'use strict'; if (mejs.i18n.ca !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; } if (mejs.i18n.cs !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; } if (mejs.i18n.de !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; } if (mejs.i18n.es !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; } if (mejs.i18n.fr !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; } if (mejs.i18n.hr !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; } if (mejs.i18n.hu !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; } if (mejs.i18n.it !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; } if (mejs.i18n.ja !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; } if (mejs.i18n.ko !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; } if (mejs.i18n.nl !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; } if (mejs.i18n.pl !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; } if (mejs.i18n.pt !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; } if (mejs.i18n['pt-BR'] !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; } if (mejs.i18n.ro !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; } if (mejs.i18n.ru !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; } if (mejs.i18n.sk !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; } if (mejs.i18n.sv !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; } if (mejs.i18n.uk !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; } if (mejs.i18n.zh !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; } if (mejs.i18n['zh-CN'] !== undefined) { //mejs.i18n.en["mejs.frame-rate"] = "Media frame rate (select according to your video source)"; //mejs.i18n.en["mejs.step-fwd"] = "Step forward"; //mejs.i18n.en["mejs.step-back"] = "Step back"; }
exponentcms/exponent-cms
external/mediaelement/build/frameNavigator/frameNavigator-i18n.js
JavaScript
gpl-2.0
5,105
<?php /* WARNING: This is a core Generate file. DO NOT edit this file under any circumstances. Please do all modifications in the form of a child theme. */ /** * Generate Spacing integration * * This file is a core Generate file and should not be edited. * * @package GeneratePress * @author Thomas Usborne * @license http://www.opensource.org/licenses/gpl-license.php GPL v2.0 (or later) * @link http://www.generatepress.com */ if ( !function_exists('generate_spacing_get_defaults') ) : function generate_spacing_get_defaults() { $generate_spacing_defaults = array( 'header_top' => '40', 'header_right' => '40', 'header_bottom' => '40', 'header_left' => '40', 'menu_item' => '20', 'menu_item_height' => '60', 'sub_menu_item_height' => '10', 'content_top' => '40', 'content_right' => '40', 'content_bottom' => '40', 'content_left' => '40', 'separator' => '20', 'left_sidebar_width' => '25', 'right_sidebar_width' => '25', 'widget_top' => '40', 'widget_right' => '40', 'widget_bottom' => '40', 'widget_left' => '40', 'footer_widget_container_top' => '40', 'footer_widget_container_right' => '0', 'footer_widget_container_bottom' => '40', 'footer_widget_container_left' => '0', 'footer_top' => '20', 'footer_right' => '0', 'footer_bottom' => '20', 'footer_left' => '0', ); return apply_filters( 'generate_spacing_option_defaults', $generate_spacing_defaults ); } endif; if ( !function_exists('generate_spacing_css') ) : function generate_spacing_css() { $spacing_settings = wp_parse_args( get_option( 'generate_spacing_settings', array() ), generate_spacing_get_defaults() ); $space = ' '; // Start the magic $spacing_css = array ( '.inside-header' => array( 'padding-top' => ( isset( $spacing_settings['header_top'] ) ) ? $spacing_settings['header_top'] . 'px' : null, 'padding-right' => ( isset( $spacing_settings['header_right'] ) ) ? $spacing_settings['header_right'] . 'px' : null, 'padding-bottom' => ( isset( $spacing_settings['header_bottom'] ) ) ? $spacing_settings['header_bottom'] . 'px' : null, 'padding-left' => ( isset( $spacing_settings['header_left'] ) ) ? $spacing_settings['header_left'] . 'px' : null, ), '.separate-containers .inside-article, .separate-containers .comments-area, .separate-containers .page-header, .separate-containers .paging-navigation, .one-container .site-content' => array( 'padding-top' => ( isset( $spacing_settings['content_top'] ) ) ? $spacing_settings['content_top'] . 'px' : null, 'padding-right' => ( isset( $spacing_settings['content_right'] ) ) ? $spacing_settings['content_right'] . 'px' : null, 'padding-bottom' => ( isset( $spacing_settings['content_bottom'] ) ) ? $spacing_settings['content_bottom'] . 'px' : null, 'padding-left' => ( isset( $spacing_settings['content_left'] ) ) ? $spacing_settings['content_left'] . 'px' : null, ), '.ignore-x-spacing' => array( 'margin-right' => ( isset( $spacing_settings['content_right'] ) ) ? '-' . $spacing_settings['content_right'] . 'px' : null, 'margin-bottom' => ( isset( $spacing_settings['content_bottom'] ) ) ? $spacing_settings['content_bottom'] . 'px' : null, 'margin-left' => ( isset( $spacing_settings['content_left'] ) ) ? '-' . $spacing_settings['content_left'] . 'px' : null, ), '.ignore-xy-spacing' => array( 'margin-top' => ( isset( $spacing_settings['content_top'] ) ) ? '-' . $spacing_settings['content_top'] . 'px' : null, 'margin-right' => ( isset( $spacing_settings['content_right'] ) ) ? '-' . $spacing_settings['content_right'] . 'px' : null, 'margin-bottom' => ( isset( $spacing_settings['content_bottom'] ) ) ? $spacing_settings['content_bottom'] . 'px' : null, 'margin-left' => ( isset( $spacing_settings['content_left'] ) ) ? '-' . $spacing_settings['content_left'] . 'px' : null, ), '.main-navigation .main-nav ul li a, .menu-toggle, .menu-toggle .search-item a, .menu-toggle .search-item-disabled a' => array( 'padding-left' => ( isset( $spacing_settings['menu_item'] ) ) ? $spacing_settings['menu_item'] . 'px' : null, 'padding-right' => ( isset( $spacing_settings['menu_item'] ) ) ? $spacing_settings['menu_item'] . 'px' : null, 'line-height' => ( isset( $spacing_settings['menu_item_height'] ) ) ? $spacing_settings['menu_item_height'] . 'px' : null, ), '.nav-float-right .main-navigation .main-nav ul li a' => array( 'line-height' => ( isset( $spacing_settings['menu_item_height'] ) ) ? $spacing_settings['menu_item_height'] . 'px' : null, ), '.main-navigation .main-nav ul ul li a' => array( 'padding-left' => ( isset( $spacing_settings['menu_item'] ) ) ? $spacing_settings['menu_item'] . 'px' : null, 'padding-right' => ( isset( $spacing_settings['menu_item'] ) ) ? $spacing_settings['menu_item'] . 'px' : null, 'padding-top' => ( isset( $spacing_settings['sub_menu_item_height'] ) ) ? $spacing_settings['sub_menu_item_height'] . 'px' : null, 'padding-bottom' => ( isset( $spacing_settings['sub_menu_item_height'] ) ) ? $spacing_settings['sub_menu_item_height'] . 'px' : null, ), '.main-navigation ul ul' => array( 'top' => ( isset( $spacing_settings['menu_item_height'] ) ) ? $spacing_settings['menu_item_height'] . 'px' : null ), '.navigation-search' => array( 'height' => ( isset( $spacing_settings['menu_item_height'] ) ) ? $spacing_settings['menu_item_height'] . 'px' : null, 'line-height' => '0px' ), '.navigation-search input' => array( 'height' => ( isset( $spacing_settings['menu_item_height'] ) ) ? $spacing_settings['menu_item_height'] . 'px' : null, 'line-height' => '0px' ), '.separate-containers .widget-area .widget' => array( 'padding-top' => ( isset( $spacing_settings['widget_top'] ) ) ? $spacing_settings['widget_top'] . 'px' : null, 'padding-right' => ( isset( $spacing_settings['widget_right'] ) ) ? $spacing_settings['widget_right'] . 'px' : null, 'padding-bottom' => ( isset( $spacing_settings['widget_bottom'] ) ) ? $spacing_settings['widget_bottom'] . 'px' : null, 'padding-left' => ( isset( $spacing_settings['widget_left'] ) ) ? $spacing_settings['widget_left'] . 'px' : null, ), '.footer-widgets' => array( 'padding-top' => ( isset( $spacing_settings['footer_widget_container_top'] ) ) ? $spacing_settings['footer_widget_container_top'] . 'px' : null, 'padding-right' => ( isset( $spacing_settings['footer_widget_container_right'] ) ) ? $spacing_settings['footer_widget_container_right'] . 'px' : null, 'padding-bottom' => ( isset( $spacing_settings['footer_widget_container_bottom'] ) ) ? $spacing_settings['footer_widget_container_bottom'] . 'px' : null, 'padding-left' => ( isset( $spacing_settings['footer_widget_container_left'] ) ) ? $spacing_settings['footer_widget_container_left'] . 'px' : null, ), '.site-info' => array( 'padding-top' => ( isset( $spacing_settings['footer_top'] ) ) ? $spacing_settings['footer_top'] . 'px' : null, 'padding-right' => ( isset( $spacing_settings['footer_right'] ) ) ? $spacing_settings['footer_right'] . 'px' : null, 'padding-bottom' => ( isset( $spacing_settings['footer_bottom'] ) ) ? $spacing_settings['footer_bottom'] . 'px' : null, 'padding-left' => ( isset( $spacing_settings['footer_left'] ) ) ? $spacing_settings['footer_left'] . 'px' : null, ), '.right-sidebar.separate-containers .site-main' => array( 'margin-top' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] . 'px' : null, 'margin-right' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] . 'px' : null, 'margin-bottom' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] . 'px' : null, 'margin-left' => '0px', 'padding' => '0px' ), '.left-sidebar.separate-containers .site-main' => array( 'margin-top' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] . 'px' : null, 'margin-right' => '0px', 'margin-bottom' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] . 'px' : null, 'margin-left' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] . 'px' : null, 'padding' => '0px' ), '.both-sidebars.separate-containers .site-main' => array( 'margin' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] . 'px' : null, 'padding' => '0px' ), '.both-right.separate-containers .site-main' => array( 'margin-top' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] . 'px' : null, 'margin-right' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] . 'px' : null, 'margin-bottom' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] . 'px' : null, 'margin-left' => '0px', 'padding' => '0px' ), '.separate-containers .site-main' => array( 'margin-top' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] . 'px' : null, 'margin-bottom' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] . 'px' : null, 'padding' => '0px' ), '.separate-containers .page-header-image, .separate-containers .page-header-content, .separate-containers .page-header-image-single, .separate-containers .page-header-content-single' => array( 'margin-top' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] . 'px' : null, ), '.both-left.separate-containers .site-main' => array( 'margin-top' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] . 'px' : null, 'margin-right' => '0px', 'margin-bottom' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] . 'px' : null, 'margin-left' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] . 'px' : null, 'padding' => '0px' ), '.separate-containers .inside-right-sidebar, .inside-left-sidebar' => array( 'margin-top' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] . 'px' : null, 'margin-bottom' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] . 'px' : null, 'padding-top' => '0px', 'padding-bottom' => '0px' ), '.separate-containers .widget, .separate-containers .hentry, .separate-containers .page-header, .widget-area .main-navigation' => array( 'margin-bottom' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] . 'px' : null, ), '.both-left.separate-containers .inside-left-sidebar' => array( 'margin-right' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] / 2 . 'px' : null, 'padding-right' => '0px' ), '.both-left.separate-containers .inside-right-sidebar' => array( 'margin-left' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] / 2 . 'px' : null, 'padding-left' => '0px' ), '.both-right.separate-containers .inside-left-sidebar' => array( 'margin-right' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] / 2 . 'px' : null, 'padding-right' => '0px' ), '.both-right.separate-containers .inside-right-sidebar' => array( 'margin-left' => ( isset( $spacing_settings['separator'] ) ) ? $spacing_settings['separator'] / 2 . 'px' : null, 'padding-left' => '0px' ) ); // Output the above CSS $output = ''; foreach($spacing_css as $k => $properties) { if(!count($properties)) continue; $temporary_output = $k . ' {'; $elements_added = 0; foreach($properties as $p => $v) { if(empty($v)) continue; $elements_added++; $temporary_output .= $p . ': ' . $v . '; '; } $temporary_output .= "}"; if($elements_added > 0) $output .= $temporary_output; } $output = str_replace(array("\r", "\n"), '', $output); return $output; } /** * Enqueue scripts and styles */ add_action( 'wp_enqueue_scripts', 'generate_spacing_scripts', 50 ); function generate_spacing_scripts() { wp_add_inline_style( 'generate-style', generate_spacing_css() ); } endif;
geraldpasion/gsm
wp-content/themes/generatepress/inc/add-ons/spacing.php
PHP
gpl-2.0
12,447
/* Dungeon : Gate of the Setting Sun 90 Heroic Instance General Script */ #include "gate_setting_sun.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "Vehicle.h" enum spells { SPELL_MANTID_MUNITION_EXPLOSION = 107153, SPELL_EXPLOSE_GATE = 115456, SPELL_BOMB_CAST_VISUAL = 106729, SPELL_BOMB_AURA = 106875, }; class mob_serpent_spine_defender : public CreatureScript { public: mob_serpent_spine_defender() : CreatureScript("mob_serpent_spine_defender") { } struct mob_serpent_spine_defenderAI : public ScriptedAI { mob_serpent_spine_defenderAI(Creature* creature) : ScriptedAI(creature) {} uint32 attackTimer; void Reset() { attackTimer = urand(1000, 5000); } void DamageDealt(Unit* /*target*/, uint32& damage, DamageEffectType /*damageType*/) { damage = 0; } void UpdateAI(uint32 diff) { if (!me->IsInCombat()) { if (attackTimer <= diff) { if (Unit* target = me->SelectNearestTarget(5.0f)) if (!target->IsFriendlyTo(me)) AttackStart(target); } else attackTimer -= diff; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const { return new mob_serpent_spine_defenderAI(creature); } }; class npc_krikthik_bombarder : public CreatureScript { public: npc_krikthik_bombarder() : CreatureScript("npc_krikthik_bombarder") { } struct npc_krikthik_bombarderAI : public ScriptedAI { npc_krikthik_bombarderAI(Creature* creature) : ScriptedAI(creature) { pInstance = creature->GetInstanceScript(); } InstanceScript* pInstance; uint32 bombTimer; void Reset() { me->GetMotionMaster()->MoveRandom(5.0f); bombTimer = urand(1000, 7500); } // Called when spell hits a target void SpellHitTarget(Unit* target, SpellInfo const* /*spell*/) { if (target->GetEntry() == NPC_BOMB_STALKER) me->AddAura(SPELL_BOMB_AURA, target); } void UpdateAI(uint32 diff) { if (bombTimer <= diff) { if (Unit* stalker = pInstance->instance->GetCreature(pInstance->GetData64(DATA_RANDOM_BOMB_STALKER))) if (!stalker->HasAura(SPELL_BOMB_AURA)) me->CastSpell(stalker, SPELL_BOMB_CAST_VISUAL, true); bombTimer = urand(1000, 5000); } else bombTimer -= diff; } }; CreatureAI* GetAI(Creature* creature) const { return new npc_krikthik_bombarderAI (creature); } }; //8359 class AreaTrigger_at_first_door : public AreaTriggerScript { public: AreaTrigger_at_first_door() : AreaTriggerScript("at_first_door") {} bool OnTrigger(Player* player, AreaTriggerEntry const* /*trigger*/) { if (player->GetInstanceScript()) player->GetInstanceScript()->SetData(DATA_OPEN_FIRST_DOOR, DONE); return false; } }; class go_setting_sun_brasier : public GameObjectScript { public: go_setting_sun_brasier() : GameObjectScript("go_setting_sun_brasier") { } bool OnGossipHello(Player* player, GameObject* /*go*/) { if (player->GetInstanceScript()) player->GetInstanceScript()->SetData(DATA_BRASIER_CLICKED, DONE); return false; } }; class go_setting_sun_temp_portal : public GameObjectScript { public: go_setting_sun_temp_portal() : GameObjectScript("go_setting_sun_temp_portal") { } bool OnGossipHello(Player* player, GameObject* go) { switch (go->GetEntry()) { case 400001: player->NearTeleportTo(1078.96f, 2305.48f, 381.55f, 0.01f); break; case 400002: if (go->GetPositionZ() < 400.0f) player->NearTeleportTo(go->GetPositionX(), go->GetPositionY(), 431.0f, go->GetOrientation()); else player->NearTeleportTo(go->GetPositionX(), go->GetPositionY(), 388.5f, go->GetOrientation()); break; } return false; } }; class vehicle_artillery_to_wall : public VehicleScript { public: vehicle_artillery_to_wall() : VehicleScript("vehicle_artillery_to_wall") {} void OnAddPassenger(Vehicle* veh, Unit* /*passenger*/, int8 /*seatId*/) { if (veh->GetBase()) if (veh->GetBase()->ToCreature()) if (veh->GetBase()->ToCreature()->AI()) veh->GetBase()->ToCreature()->AI()->DoAction(0); } struct vehicle_artillery_to_wallAI : public ScriptedAI { vehicle_artillery_to_wallAI(Creature* creature) : ScriptedAI(creature) {} uint32 launchEventTimer; void Reset() { launchEventTimer = 0; } void DoAction(int32 action) { launchEventTimer = 2500; } void UpdateAI(uint32 diff) { if (!launchEventTimer) return; if (launchEventTimer <= diff) { if (me->GetVehicleKit()) { if (Unit* passenger = me->GetVehicleKit()->GetPassenger(0)) { passenger->ExitVehicle(); passenger->GetMotionMaster()->MoveJump(1100.90f, 2304.58f, 381.23f, 30.0f, 50.0f); } } launchEventTimer = 0; } else launchEventTimer -= diff; } }; CreatureAI* GetAI(Creature* creature) const { return new vehicle_artillery_to_wallAI(creature); } }; void AddSC_gate_setting_sun() { new mob_serpent_spine_defender(); new npc_krikthik_bombarder(); new AreaTrigger_at_first_door(); new go_setting_sun_brasier(); new go_setting_sun_temp_portal(); new vehicle_artillery_to_wall(); }
NightCotRe0110/SkyFire.548
src/server/scripts/Pandaria/Neuer Ordner/Dungeons/GateoftheSettingSun/gate_setting_sun.cpp
C++
gpl-2.0
6,470
<?php /* * Registration Page */ require_once('lib-core.php'); require_once('layout-headermd.php'); echo "<h2 style='color:green'>Register</h2>"; echo "<form action='handle-register.php' method='POST'>" . "<br>Username: <input type='text' name='username' class='form-control' placeholder='Username' />" . "<br>Password: <input type='password' name='password' class='form-control' placeholder='Password' />" . "<br>Email: <input type='email' name='email' class='form-control' placeholder='Email' />" . "<br><input type=\"submit\" name=\"polrsubmit\" class=\"btn btn-default btn-warning\" value=\"Register\"/>"; require_once('layout-footermd.php');
gnowxilef/polr
register.php
PHP
gpl-2.0
682
<?php /** * Copyright © 2015 Magento. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Sales\Model\Order\Payment; use Magento\Sales\Api\Data\InvoiceInterface; use Magento\Sales\Api\Data\OrderPaymentInterface; use Magento\Sales\Model\Order\Invoice; use Magento\Sales\Model\Order\Payment; use Magento\Sales\Model\Order\Payment\Operations\AuthorizeOperation; use Magento\Sales\Model\Order\Payment\Operations\CaptureOperation; use Magento\Sales\Model\Order\Payment\Operations\OrderOperation as OrderOperation; use Magento\Sales\Model\Order\Payment\Operations\RegisterCaptureNotificationOperation; /** * Class Processor using for process payment */ class Processor { /** * @var AuthorizeOperation */ protected $authorizeOperation; /** * @var CaptureOperation */ protected $captureOperation; /** * @var OrderOperation */ protected $orderOperation; /** * @var RegisterCaptureNotificationOperation */ protected $registerCaptureNotification; /** * Set operations * * @param AuthorizeOperation $authorizeOperation * @param CaptureOperation $captureOperation * @param OrderOperation $orderOperation * @param RegisterCaptureNotificationOperation $registerCaptureNotification */ public function __construct( AuthorizeOperation $authorizeOperation, CaptureOperation $captureOperation, OrderOperation $orderOperation, RegisterCaptureNotificationOperation $registerCaptureNotification ) { $this->authorizeOperation = $authorizeOperation; $this->captureOperation = $captureOperation; $this->orderOperation = $orderOperation; $this->registerCaptureNotification = $registerCaptureNotification; } /** * Process authorize operation * * @param OrderPaymentInterface $payment * @param bool $isOnline * @param float $amount * @return OrderPaymentInterface|Payment */ public function authorize(OrderPaymentInterface $payment, $isOnline, $amount) { return $this->authorizeOperation->authorize($payment, $isOnline, $amount); } /** * Process capture operation * * @param OrderPaymentInterface $payment * @param InvoiceInterface $invoice * @return OrderPaymentInterface|Payment * @throws \Magento\Framework\Exception\LocalizedException */ public function capture(OrderPaymentInterface $payment, $invoice) { return $this->captureOperation->capture($payment, $invoice); } /** * Process order operation * * @param OrderPaymentInterface $payment * @param float $amount * @return OrderPaymentInterface|Payment */ public function order(OrderPaymentInterface $payment, $amount) { return $this->orderOperation->order($payment, $amount); } /** * Registers capture notification. * * @param OrderPaymentInterface $payment * @param string|float $amount * @param bool|int $skipFraudDetection * @return OrderPaymentInterface */ public function registerCaptureNotification( OrderPaymentInterface $payment, $amount, $skipFraudDetection = false ) { return $this->registerCaptureNotification->registerCaptureNotification($payment, $amount, $skipFraudDetection); } }
FPLD/project0
vendor/magento/module-sales/Model/Order/Payment/Processor.php
PHP
gpl-2.0
3,409
// { dg-do compile { target c++11 } } // Copyright (C) 2013-2021 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // NB: This file is for testing type_traits with NO OTHER INCLUDES. #include <type_traits> namespace std { typedef short test_type; template struct add_pointer<test_type>; }
Gurgel100/gcc
libstdc++-v3/testsuite/20_util/add_pointer/requirements/explicit_instantiation.cc
C++
gpl-2.0
983
/*************************************************************************** * (C) Copyright 2013 Faiumoni e.V. * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package games.stendhal.client.gui.chattext; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.AbstractButton; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent; import org.apache.log4j.Logger; /** * A drop down menu for selecting special characters that players may want to * use in chat. */ public class CharacterMap extends JButton { /** * Create a new CharacterMap. * * @param textField text field where selected character should be inserted */ public CharacterMap(final JTextComponent textField) { super("☺"); setFocusable(false); setToolTipText("Insert a special character"); final JPopupMenu menu = new JPopupMenu(); addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Place the menu right justified to the button menu.show(CharacterMap.this, getWidth() - menu.getPreferredSize().width, getHeight()); } }); ActionListener selectionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { Object source = ev.getSource(); if (source instanceof AbstractButton) { String str = ((AbstractButton) source).getText(); int pos = textField.getCaretPosition(); try { textField.getDocument().insertString(pos, str, null); } catch (BadLocationException ex) { Logger.getLogger(CharacterMap.class).error("Bug", ex); } } } }; fillMenu(menu, selectionListener); } /** * Fill the popup menu with characters. * * @param menu popup menu * @param listener action listener that should be attached to the menu items */ private void fillMenu(JComponent menu, ActionListener listener) { String[][] characters = { { "☺", "☹", "😃", "😲", "😇", "😈", "😊", "😌", "😍", "😎", "😏", "😐", "😴" }, { "🐭", "🐮", "🐱", "🐵", "🐯", "🐰", "🐴", "🐶", "🐷", "🐹", "🐺", "🐻", "🐼" }, { "♥", "♡", "💔", "💡", "☠" }, { "£", "$", "€", "₤", "₱", "¥" }, { "♩", "♪", "♫", "♬", "♭", "♮", "♯", "𝄞", "𝄢" } }; menu.setLayout(new GridLayout(0, characters[0].length)); Insets insets = new Insets(1, 1, 1, 1); setMargin(insets); for (String[] row : characters) { for (String chr : row) { JMenuItem item = new JMenuItem(chr); item.setMargin(insets); item.addActionListener(listener); item.setBorder(null); item.setHorizontalTextPosition(CENTER); menu.add(item); } } } }
AntumDeluge/arianne-stendhal
src/games/stendhal/client/gui/chattext/CharacterMap.java
Java
gpl-2.0
3,590
<!DOCTYPE html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title><?php wp_title( '|', true, 'right' ); ?></title> <link rel="profile" href="http://gmpg.org/xfn/11"> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>"> <link rel="stylesheet" href="<?php echo get_stylesheet_uri(); ?>" type="text/css" media="all" /> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <div id="page" class="wrapper hfeed site"> <header id="masthead" class="site-header" role="banner"> <div class="container_16 clearfix"> <div class="grid_16"> <?php get_template_part( 'custom', 'header' ); ?> </div> </div> </header><!-- #masthead --> <div class="container_16 clearfix"> <nav id="site-navigation" class="grid_16 main-navigation" role="navigation"> <?php get_template_part( 'primary', 'menu' ); ?> </nav><!-- #site-navigation --> </div>
xav335/frenchenglishservices
wp-content/themes/contango/header.php
PHP
gpl-2.0
1,055
/* * Stellarium * Copyright (C) 2009 Fabien Chereau * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA. */ #ifndef CLIPROCESSOR_HPP #define CLIPROCESSOR_HPP #include <QStringList> class QSettings; class CLIProcessor { public: //! Check if a QStringList has a CLI-style option in it (before the first --). //! @param argList a list of strings, think argv //! @param shortOpt a short-form option string, e.g, "-h" //! @param longOpt a long-form option string, e.g. "--help" //! @return true if the option exists in args before any element which is "--" static bool argsGetOption(const QStringList& argList, QString shortOpt, QString longOpt); //! Retrieve the argument to an option from a QStringList. //! Given a list of strings, this function will extract the argument of //! type T to an option, where the option in an element which matches //! either the short or long forms, and the argument to that option //! is the following element in the list, e.g. ("--option", "arg"). //! It is also possible to extract argument to options which are //! part of the option element, separated by the "=" character, e.g. //! ( "--option=arg" ). //! Type conversion is done using the QTextStream class, and as such //! possible types which this template function may use are restricted //! to those where there is a value operator<<() defined in the //! QTextStream class for that type. //! The argument list is only processed as far as the first value "--". //! If an argument "--" is to be retrieved, it must be apecified using //! the "--option=--" form. //! @param argList a list of strings, think argv. //! @param shortOpt the short form of the option, e.g. "-n". //! @param longOpt the long form of the option, e.g. "--number". //! @param defaultValue the default value to return if the option was //! not found in args. //! @exception runtime_error("no_optarg") the expected argument to the //! option was not found. //! @exception runtime_error("optarg_type") the expected argument to //! the option could not be converted. //! @return The value of the argument to the specified option which //! occurs before the first element with the value "--". If the option //! is not found, defaultValue is returned. static QVariant argsGetOptionWithArg(const QStringList& argList, QString shortOpt, QString longOpt, QVariant defaultValue); //! Check if a QStringList has a yes/no CLI-style option in it, and //! find out the argument to that parameter. //! e.g. option --use-foo can have parameter "yes" or "no" //! It is also possible for the argument to take values, "1", "0"; //! "true", "false"; //! @param argList a list of strings, think argv //! @param shortOpt a short-form option string, e.g, "-h" //! @param longOpt a long-form option string, e.g. "--help" //! @param defaultValue the default value to return if the option was //! not found in args. //! @exception runtime_error("no_optarg") the expected argument to the //! option was not found. The longOpt value is appended in parenthesis. //! @exception runtime_error("optarg_type") the expected argument to //! the option could not be converted. The longOpt value is appended //! in parenthesis. //! @return 1 if the argument to the specified opion is "yes", "y", //! "true", "on" or 1; 0 if the argument to the specified opion is "no", //! "n", "false", "off" or 0; the value of the defaultValue parameter if //! the option was not found in the argument list before an element which //! has the value "--". static int argsGetYesNoOption(const QStringList& argList, QString shortOpt, QString longOpt, int defaultValue); //! Processing of command line options which is to be done before config file is read. //! This includes the chance to set the configuration file name. It is to be done //! in the sub-class of the StelApp, as the sub-class may want to manage the //! argument list, as is the case with the StelMainWindow version. static void parseCLIArgsPreConfig(const QStringList& argList); //! Processing of command line options which is to be done after the config file is //! read. This gives us the chance to over-ride settings which are in the configuration //! file. static void parseCLIArgsPostConfig(const QStringList& argList, QSettings* conf); }; #endif // CLIPROCESSOR_HPP
skorjevec/stel-n9
stellarium/src/CLIProcessor.hpp
C++
gpl-2.0
4,990
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /** * Code Igniter * * An open source application development framework for PHP 4.3.2 or newer * * @package CodeIgniter * @author Rick Ellis * @copyright Copyright (c) 2006, pMachine, Inc. * @license http://www.codeignitor.com/user_guide/license.html * @link http://www.codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Code Igniter Smiley Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author Rick Ellis * @link http://www.codeigniter.com/user_guide/helpers/smiley_helper.html */ // ------------------------------------------------------------------------ /** * JS Insert Smiley * * Generates the javascrip function needed to insert smileys into a form field * * @access public * @param string form name * @param string field name * @return string */ function js_insert_smiley($form_name = '', $form_field = '') { return <<<EOF <script type="text/javascript"> function insert_smiley(smiley) { document.{$form_name}.{$form_field}.value += " " + smiley; } </script> EOF; } // ------------------------------------------------------------------------ /** * Get Clickable Smileys * * Returns an array of image tag links that can be clicked to be inserted * into a form field. * * @access public * @param string the URL to the folder containing the smiley images * @return array */ function get_clickable_smileys($image_url = '', $smileys = NULL) { if ( ! is_array($smileys)) { if (FALSE === ($smileys = _get_smiley_array())) { return $str; } } // Add a trailing slash to the file path if needed $image_url = preg_replace("/(.+?)\/*$/", "\\1/", $image_url); $used = array(); foreach ($smileys as $key => $val) { // Keep duplicates from being used, which can happen if the // mapping array contains multiple identical replacements. For example: // :-) and :) might be replaced with the same image so both smileys // will be in the array. if (isset($used[$smileys[$key][0]])) { continue; } $link[] = "<a href=\"javascript:void(0);\" onClick=\"insert_smiley('".$key."')\"><img src=\"".$image_url.$smileys[$key][0]."\" width=\"".$smileys[$key][1]."\" height=\"".$smileys[$key][2]."\" alt=\"".$smileys[$key][3]."\" style=\"border:0;\" /></a>"; $used[$smileys[$key][0]] = TRUE; } return $link; } // ------------------------------------------------------------------------ /** * Parse Smileys * * Takes a string as input and swaps any contained smileys for the actual image * * @access public * @param string the text to be parsed * @param string the URL to the folder containing the smiley images * @return string */ function parse_smileys($str = '', $image_url = '', $smileys = NULL) { if ($image_url == '') { return $str; } if ( ! is_array($smileys)) { if (FALSE === ($smileys = _get_smiley_array())) { return $str; } } // Add a trailing slash to the file path if needed $image_url = preg_replace("/(.+?)\/*$/", "\\1/", $image_url); foreach ($smileys as $key => $val) { $str = str_replace($key, "<img src=\"".$image_url.$smileys[$key][0]."\" width=\"".$smileys[$key][1]."\" height=\"".$smileys[$key][2]."\" alt=\"".$smileys[$key][3]."\" style=\"border:0;\" />", $str); } return $str; } // ------------------------------------------------------------------------ /** * Get Smiley Array * * Fetches the config/smiley.php file * * @access private * @return mixed */ function _get_smiley_array() { if ( ! file_exists(APPPATH.'config/smileys'.EXT)) { return FALSE; } include(APPPATH.'config/smileys'.EXT); if ( ! isset($smileys) OR ! is_array($smileys)) { return FALSE; } return $smileys; } ?>
Calico90/codeigniter-version-scanner
CodeIgniter_1.5.2/CodeIgniter_1.5.2/system/helpers/smiley_helper.php
PHP
gpl-2.0
3,884
# asciixmas # December 1989 Larry Bartz Indianapolis, IN # # $Id: xmas.py 36559 2004-07-18 05:56:09Z tim_one $ # # I'm dreaming of an ascii character-based monochrome Christmas, # Just like the one's I used to know! # Via a full duplex communications channel, # At 9600 bits per second, # Even though it's kinda slow. # # I'm dreaming of an ascii character-based monochrome Christmas, # With ev'ry C program I write! # May your screen be merry and bright! # And may all your Christmases be amber or green, # (for reduced eyestrain and improved visibility)! # # # Notes on the Python version: # I used a couple of `try...except curses.error' to get around some functions # returning ERR. The errors come from using wrapping functions to fill # windows to the last character cell. The C version doesn't have this problem, # it simply ignores any return values. # import curses import sys FROMWHO = "Thomas Gellekum <tg@FreeBSD.org>" def set_color(win, color): if curses.has_colors(): n = color + 1 curses.init_pair(n, color, my_bg) win.attroff(curses.A_COLOR) win.attron(curses.color_pair(n)) def unset_color(win): if curses.has_colors(): win.attrset(curses.color_pair(0)) def look_out(msecs): curses.napms(msecs) if stdscr.getch() != -1: curses.beep() sys.exit(0) def boxit(): for y in range(0, 20): stdscr.addch(y, 7, ord('|')) for x in range(8, 80): stdscr.addch(19, x, ord('_')) for x in range(0, 80): stdscr.addch(22, x, ord('_')) return def seas(): stdscr.addch(4, 1, ord('S')) stdscr.addch(6, 1, ord('E')) stdscr.addch(8, 1, ord('A')) stdscr.addch(10, 1, ord('S')) stdscr.addch(12, 1, ord('O')) stdscr.addch(14, 1, ord('N')) stdscr.addch(16, 1, ord("'")) stdscr.addch(18, 1, ord('S')) return def greet(): stdscr.addch(3, 5, ord('G')) stdscr.addch(5, 5, ord('R')) stdscr.addch(7, 5, ord('E')) stdscr.addch(9, 5, ord('E')) stdscr.addch(11, 5, ord('T')) stdscr.addch(13, 5, ord('I')) stdscr.addch(15, 5, ord('N')) stdscr.addch(17, 5, ord('G')) stdscr.addch(19, 5, ord('S')) return def fromwho(): stdscr.addstr(21, 13, FROMWHO) return def tree(): set_color(treescrn, curses.COLOR_GREEN) treescrn.addch(1, 11, ord('/')) treescrn.addch(2, 11, ord('/')) treescrn.addch(3, 10, ord('/')) treescrn.addch(4, 9, ord('/')) treescrn.addch(5, 9, ord('/')) treescrn.addch(6, 8, ord('/')) treescrn.addch(7, 7, ord('/')) treescrn.addch(8, 6, ord('/')) treescrn.addch(9, 6, ord('/')) treescrn.addch(10, 5, ord('/')) treescrn.addch(11, 3, ord('/')) treescrn.addch(12, 2, ord('/')) treescrn.addch(1, 13, ord('\\')) treescrn.addch(2, 13, ord('\\')) treescrn.addch(3, 14, ord('\\')) treescrn.addch(4, 15, ord('\\')) treescrn.addch(5, 15, ord('\\')) treescrn.addch(6, 16, ord('\\')) treescrn.addch(7, 17, ord('\\')) treescrn.addch(8, 18, ord('\\')) treescrn.addch(9, 18, ord('\\')) treescrn.addch(10, 19, ord('\\')) treescrn.addch(11, 21, ord('\\')) treescrn.addch(12, 22, ord('\\')) treescrn.addch(4, 10, ord('_')) treescrn.addch(4, 14, ord('_')) treescrn.addch(8, 7, ord('_')) treescrn.addch(8, 17, ord('_')) treescrn.addstr(13, 0, "//////////// \\\\\\\\\\\\\\\\\\\\\\\\") treescrn.addstr(14, 11, "| |") treescrn.addstr(15, 11, "|_|") unset_color(treescrn) treescrn.refresh() w_del_msg.refresh() return def balls(): treescrn.overlay(treescrn2) set_color(treescrn2, curses.COLOR_BLUE) treescrn2.addch(3, 9, ord('@')) treescrn2.addch(3, 15, ord('@')) treescrn2.addch(4, 8, ord('@')) treescrn2.addch(4, 16, ord('@')) treescrn2.addch(5, 7, ord('@')) treescrn2.addch(5, 17, ord('@')) treescrn2.addch(7, 6, ord('@')) treescrn2.addch(7, 18, ord('@')) treescrn2.addch(8, 5, ord('@')) treescrn2.addch(8, 19, ord('@')) treescrn2.addch(10, 4, ord('@')) treescrn2.addch(10, 20, ord('@')) treescrn2.addch(11, 2, ord('@')) treescrn2.addch(11, 22, ord('@')) treescrn2.addch(12, 1, ord('@')) treescrn2.addch(12, 23, ord('@')) unset_color(treescrn2) treescrn2.refresh() w_del_msg.refresh() return def star(): treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) set_color(treescrn2, curses.COLOR_YELLOW) treescrn2.addch(0, 12, ord('*')) treescrn2.standend() unset_color(treescrn2) treescrn2.refresh() w_del_msg.refresh() return def strng1(): treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) set_color(treescrn2, curses.COLOR_WHITE) treescrn2.addch(3, 13, ord('\'')) treescrn2.addch(3, 12, ord(':')) treescrn2.addch(3, 11, ord('.')) treescrn2.attroff(curses.A_BOLD | curses.A_BLINK) unset_color(treescrn2) treescrn2.refresh() w_del_msg.refresh() return def strng2(): treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) set_color(treescrn2, curses.COLOR_WHITE) treescrn2.addch(5, 14, ord('\'')) treescrn2.addch(5, 13, ord(':')) treescrn2.addch(5, 12, ord('.')) treescrn2.addch(5, 11, ord(',')) treescrn2.addch(6, 10, ord('\'')) treescrn2.addch(6, 9, ord(':')) treescrn2.attroff(curses.A_BOLD | curses.A_BLINK) unset_color(treescrn2) treescrn2.refresh() w_del_msg.refresh() return def strng3(): treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) set_color(treescrn2, curses.COLOR_WHITE) treescrn2.addch(7, 16, ord('\'')) treescrn2.addch(7, 15, ord(':')) treescrn2.addch(7, 14, ord('.')) treescrn2.addch(7, 13, ord(',')) treescrn2.addch(8, 12, ord('\'')) treescrn2.addch(8, 11, ord(':')) treescrn2.addch(8, 10, ord('.')) treescrn2.addch(8, 9, ord(',')) treescrn2.attroff(curses.A_BOLD | curses.A_BLINK) unset_color(treescrn2) treescrn2.refresh() w_del_msg.refresh() return def strng4(): treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) set_color(treescrn2, curses.COLOR_WHITE) treescrn2.addch(9, 17, ord('\'')) treescrn2.addch(9, 16, ord(':')) treescrn2.addch(9, 15, ord('.')) treescrn2.addch(9, 14, ord(',')) treescrn2.addch(10, 13, ord('\'')) treescrn2.addch(10, 12, ord(':')) treescrn2.addch(10, 11, ord('.')) treescrn2.addch(10, 10, ord(',')) treescrn2.addch(11, 9, ord('\'')) treescrn2.addch(11, 8, ord(':')) treescrn2.addch(11, 7, ord('.')) treescrn2.addch(11, 6, ord(',')) treescrn2.addch(12, 5, ord('\'')) treescrn2.attroff(curses.A_BOLD | curses.A_BLINK) unset_color(treescrn2) treescrn2.refresh() w_del_msg.refresh() return def strng5(): treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) set_color(treescrn2, curses.COLOR_WHITE) treescrn2.addch(11, 19, ord('\'')) treescrn2.addch(11, 18, ord(':')) treescrn2.addch(11, 17, ord('.')) treescrn2.addch(11, 16, ord(',')) treescrn2.addch(12, 15, ord('\'')) treescrn2.addch(12, 14, ord(':')) treescrn2.addch(12, 13, ord('.')) treescrn2.addch(12, 12, ord(',')) treescrn2.attroff(curses.A_BOLD | curses.A_BLINK) unset_color(treescrn2) # save a fully lit tree treescrn2.overlay(treescrn) treescrn2.refresh() w_del_msg.refresh() return def blinkit(): treescrn8.touchwin() for cycle in range(0, 5): if cycle == 0: treescrn3.overlay(treescrn8) treescrn8.refresh() w_del_msg.refresh() break elif cycle == 1: treescrn4.overlay(treescrn8) treescrn8.refresh() w_del_msg.refresh() break elif cycle == 2: treescrn5.overlay(treescrn8) treescrn8.refresh() w_del_msg.refresh() break elif cycle == 3: treescrn6.overlay(treescrn8) treescrn8.refresh() w_del_msg.refresh() break elif cycle == 4: treescrn7.overlay(treescrn8) treescrn8.refresh() w_del_msg.refresh() break treescrn8.touchwin() # ALL ON treescrn.overlay(treescrn8) treescrn8.refresh() w_del_msg.refresh() return def deer_step(win, y, x): win.mvwin(y, x) win.refresh() w_del_msg.refresh() look_out(5) def reindeer(): y_pos = 0 for x_pos in range(70, 62, -1): if x_pos < 66: y_pos = 1 for looper in range(0, 4): dotdeer0.addch(y_pos, x_pos, ord('.')) dotdeer0.refresh() w_del_msg.refresh() dotdeer0.erase() dotdeer0.refresh() w_del_msg.refresh() look_out(50) y_pos = 2 for x_pos in range(x_pos - 1, 50, -1): for looper in range(0, 4): if x_pos < 56: y_pos = 3 try: stardeer0.addch(y_pos, x_pos, ord('*')) except curses.error: pass stardeer0.refresh() w_del_msg.refresh() stardeer0.erase() stardeer0.refresh() w_del_msg.refresh() else: dotdeer0.addch(y_pos, x_pos, ord('*')) dotdeer0.refresh() w_del_msg.refresh() dotdeer0.erase() dotdeer0.refresh() w_del_msg.refresh() x_pos = 58 for y_pos in range(2, 5): lildeer0.touchwin() lildeer0.refresh() w_del_msg.refresh() for looper in range(0, 4): deer_step(lildeer3, y_pos, x_pos) deer_step(lildeer2, y_pos, x_pos) deer_step(lildeer1, y_pos, x_pos) deer_step(lildeer2, y_pos, x_pos) deer_step(lildeer3, y_pos, x_pos) lildeer0.touchwin() lildeer0.refresh() w_del_msg.refresh() x_pos -= 2 x_pos = 35 for y_pos in range(5, 10): middeer0.touchwin() middeer0.refresh() w_del_msg.refresh() for looper in range(0, 2): deer_step(middeer3, y_pos, x_pos) deer_step(middeer2, y_pos, x_pos) deer_step(middeer1, y_pos, x_pos) deer_step(middeer2, y_pos, x_pos) deer_step(middeer3, y_pos, x_pos) middeer0.touchwin() middeer0.refresh() w_del_msg.refresh() x_pos -= 3 look_out(300) y_pos = 1 for x_pos in range(8, 16): deer_step(bigdeer4, y_pos, x_pos) deer_step(bigdeer3, y_pos, x_pos) deer_step(bigdeer2, y_pos, x_pos) deer_step(bigdeer1, y_pos, x_pos) deer_step(bigdeer2, y_pos, x_pos) deer_step(bigdeer3, y_pos, x_pos) deer_step(bigdeer4, y_pos, x_pos) deer_step(bigdeer0, y_pos, x_pos) x_pos -= 1 for looper in range(0, 6): deer_step(lookdeer4, y_pos, x_pos) deer_step(lookdeer3, y_pos, x_pos) deer_step(lookdeer2, y_pos, x_pos) deer_step(lookdeer1, y_pos, x_pos) deer_step(lookdeer2, y_pos, x_pos) deer_step(lookdeer3, y_pos, x_pos) deer_step(lookdeer4, y_pos, x_pos) deer_step(lookdeer0, y_pos, x_pos) for y_pos in range(y_pos, 10): for looper in range(0, 2): deer_step(bigdeer4, y_pos, x_pos) deer_step(bigdeer3, y_pos, x_pos) deer_step(bigdeer2, y_pos, x_pos) deer_step(bigdeer1, y_pos, x_pos) deer_step(bigdeer2, y_pos, x_pos) deer_step(bigdeer3, y_pos, x_pos) deer_step(bigdeer4, y_pos, x_pos) deer_step(bigdeer0, y_pos, x_pos) y_pos -= 1 deer_step(lookdeer3, y_pos, x_pos) return def main(win): global stdscr stdscr = win global my_bg, y_pos, x_pos global treescrn, treescrn2, treescrn3, treescrn4 global treescrn5, treescrn6, treescrn7, treescrn8 global dotdeer0, stardeer0 global lildeer0, lildeer1, lildeer2, lildeer3 global middeer0, middeer1, middeer2, middeer3 global bigdeer0, bigdeer1, bigdeer2, bigdeer3, bigdeer4 global lookdeer0, lookdeer1, lookdeer2, lookdeer3, lookdeer4 global w_holiday, w_del_msg my_bg = curses.COLOR_BLACK # curses.curs_set(0) treescrn = curses.newwin(16, 27, 3, 53) treescrn2 = curses.newwin(16, 27, 3, 53) treescrn3 = curses.newwin(16, 27, 3, 53) treescrn4 = curses.newwin(16, 27, 3, 53) treescrn5 = curses.newwin(16, 27, 3, 53) treescrn6 = curses.newwin(16, 27, 3, 53) treescrn7 = curses.newwin(16, 27, 3, 53) treescrn8 = curses.newwin(16, 27, 3, 53) dotdeer0 = curses.newwin(3, 71, 0, 8) stardeer0 = curses.newwin(4, 56, 0, 8) lildeer0 = curses.newwin(7, 53, 0, 8) lildeer1 = curses.newwin(2, 4, 0, 0) lildeer2 = curses.newwin(2, 4, 0, 0) lildeer3 = curses.newwin(2, 4, 0, 0) middeer0 = curses.newwin(15, 42, 0, 8) middeer1 = curses.newwin(3, 7, 0, 0) middeer2 = curses.newwin(3, 7, 0, 0) middeer3 = curses.newwin(3, 7, 0, 0) bigdeer0 = curses.newwin(10, 23, 0, 0) bigdeer1 = curses.newwin(10, 23, 0, 0) bigdeer2 = curses.newwin(10, 23, 0, 0) bigdeer3 = curses.newwin(10, 23, 0, 0) bigdeer4 = curses.newwin(10, 23, 0, 0) lookdeer0 = curses.newwin(10, 25, 0, 0) lookdeer1 = curses.newwin(10, 25, 0, 0) lookdeer2 = curses.newwin(10, 25, 0, 0) lookdeer3 = curses.newwin(10, 25, 0, 0) lookdeer4 = curses.newwin(10, 25, 0, 0) w_holiday = curses.newwin(1, 27, 3, 27) w_del_msg = curses.newwin(1, 20, 23, 60) try: w_del_msg.addstr(0, 0, "Hit any key to quit") except curses.error: pass try: w_holiday.addstr(0, 0, "H A P P Y H O L I D A Y S") except curses.error: pass # set up the windows for our various reindeer lildeer1.addch(0, 0, ord('V')) lildeer1.addch(1, 0, ord('@')) lildeer1.addch(1, 1, ord('<')) lildeer1.addch(1, 2, ord('>')) try: lildeer1.addch(1, 3, ord('~')) except curses.error: pass lildeer2.addch(0, 0, ord('V')) lildeer2.addch(1, 0, ord('@')) lildeer2.addch(1, 1, ord('|')) lildeer2.addch(1, 2, ord('|')) try: lildeer2.addch(1, 3, ord('~')) except curses.error: pass lildeer3.addch(0, 0, ord('V')) lildeer3.addch(1, 0, ord('@')) lildeer3.addch(1, 1, ord('>')) lildeer3.addch(1, 2, ord('<')) try: lildeer2.addch(1, 3, ord('~')) # XXX except curses.error: pass middeer1.addch(0, 2, ord('y')) middeer1.addch(0, 3, ord('y')) middeer1.addch(1, 2, ord('0')) middeer1.addch(1, 3, ord('(')) middeer1.addch(1, 4, ord('=')) middeer1.addch(1, 5, ord(')')) middeer1.addch(1, 6, ord('~')) middeer1.addch(2, 3, ord('\\')) middeer1.addch(2, 5, ord('/')) middeer2.addch(0, 2, ord('y')) middeer2.addch(0, 3, ord('y')) middeer2.addch(1, 2, ord('0')) middeer2.addch(1, 3, ord('(')) middeer2.addch(1, 4, ord('=')) middeer2.addch(1, 5, ord(')')) middeer2.addch(1, 6, ord('~')) middeer2.addch(2, 3, ord('|')) middeer2.addch(2, 5, ord('|')) middeer3.addch(0, 2, ord('y')) middeer3.addch(0, 3, ord('y')) middeer3.addch(1, 2, ord('0')) middeer3.addch(1, 3, ord('(')) middeer3.addch(1, 4, ord('=')) middeer3.addch(1, 5, ord(')')) middeer3.addch(1, 6, ord('~')) middeer3.addch(2, 3, ord('/')) middeer3.addch(2, 5, ord('\\')) bigdeer1.addch(0, 17, ord('\\')) bigdeer1.addch(0, 18, ord('/')) bigdeer1.addch(0, 19, ord('\\')) bigdeer1.addch(0, 20, ord('/')) bigdeer1.addch(1, 18, ord('\\')) bigdeer1.addch(1, 20, ord('/')) bigdeer1.addch(2, 19, ord('|')) bigdeer1.addch(2, 20, ord('_')) bigdeer1.addch(3, 18, ord('/')) bigdeer1.addch(3, 19, ord('^')) bigdeer1.addch(3, 20, ord('0')) bigdeer1.addch(3, 21, ord('\\')) bigdeer1.addch(4, 17, ord('/')) bigdeer1.addch(4, 18, ord('/')) bigdeer1.addch(4, 19, ord('\\')) bigdeer1.addch(4, 22, ord('\\')) bigdeer1.addstr(5, 7, "^~~~~~~~~// ~~U") bigdeer1.addstr(6, 7, "( \\_____( /") # )) bigdeer1.addstr(7, 8, "( ) /") bigdeer1.addstr(8, 9, "\\\\ /") bigdeer1.addstr(9, 11, "\\>/>") bigdeer2.addch(0, 17, ord('\\')) bigdeer2.addch(0, 18, ord('/')) bigdeer2.addch(0, 19, ord('\\')) bigdeer2.addch(0, 20, ord('/')) bigdeer2.addch(1, 18, ord('\\')) bigdeer2.addch(1, 20, ord('/')) bigdeer2.addch(2, 19, ord('|')) bigdeer2.addch(2, 20, ord('_')) bigdeer2.addch(3, 18, ord('/')) bigdeer2.addch(3, 19, ord('^')) bigdeer2.addch(3, 20, ord('0')) bigdeer2.addch(3, 21, ord('\\')) bigdeer2.addch(4, 17, ord('/')) bigdeer2.addch(4, 18, ord('/')) bigdeer2.addch(4, 19, ord('\\')) bigdeer2.addch(4, 22, ord('\\')) bigdeer2.addstr(5, 7, "^~~~~~~~~// ~~U") bigdeer2.addstr(6, 7, "(( )____( /") # )) bigdeer2.addstr(7, 7, "( / |") bigdeer2.addstr(8, 8, "\\/ |") bigdeer2.addstr(9, 9, "|> |>") bigdeer3.addch(0, 17, ord('\\')) bigdeer3.addch(0, 18, ord('/')) bigdeer3.addch(0, 19, ord('\\')) bigdeer3.addch(0, 20, ord('/')) bigdeer3.addch(1, 18, ord('\\')) bigdeer3.addch(1, 20, ord('/')) bigdeer3.addch(2, 19, ord('|')) bigdeer3.addch(2, 20, ord('_')) bigdeer3.addch(3, 18, ord('/')) bigdeer3.addch(3, 19, ord('^')) bigdeer3.addch(3, 20, ord('0')) bigdeer3.addch(3, 21, ord('\\')) bigdeer3.addch(4, 17, ord('/')) bigdeer3.addch(4, 18, ord('/')) bigdeer3.addch(4, 19, ord('\\')) bigdeer3.addch(4, 22, ord('\\')) bigdeer3.addstr(5, 7, "^~~~~~~~~// ~~U") bigdeer3.addstr(6, 6, "( ()_____( /") # )) bigdeer3.addstr(7, 6, "/ / /") bigdeer3.addstr(8, 5, "|/ \\") bigdeer3.addstr(9, 5, "/> \\>") bigdeer4.addch(0, 17, ord('\\')) bigdeer4.addch(0, 18, ord('/')) bigdeer4.addch(0, 19, ord('\\')) bigdeer4.addch(0, 20, ord('/')) bigdeer4.addch(1, 18, ord('\\')) bigdeer4.addch(1, 20, ord('/')) bigdeer4.addch(2, 19, ord('|')) bigdeer4.addch(2, 20, ord('_')) bigdeer4.addch(3, 18, ord('/')) bigdeer4.addch(3, 19, ord('^')) bigdeer4.addch(3, 20, ord('0')) bigdeer4.addch(3, 21, ord('\\')) bigdeer4.addch(4, 17, ord('/')) bigdeer4.addch(4, 18, ord('/')) bigdeer4.addch(4, 19, ord('\\')) bigdeer4.addch(4, 22, ord('\\')) bigdeer4.addstr(5, 7, "^~~~~~~~~// ~~U") bigdeer4.addstr(6, 6, "( )______( /") # ) bigdeer4.addstr(7, 5, "(/ \\") # ) bigdeer4.addstr(8, 0, "v___= ----^") lookdeer1.addstr(0, 16, "\\/ \\/") lookdeer1.addstr(1, 17, "\\Y/ \\Y/") lookdeer1.addstr(2, 19, "\\=/") lookdeer1.addstr(3, 17, "^\\o o/^") lookdeer1.addstr(4, 17, "//( )") lookdeer1.addstr(5, 7, "^~~~~~~~~// \\O/") lookdeer1.addstr(6, 7, "( \\_____( /") # )) lookdeer1.addstr(7, 8, "( ) /") lookdeer1.addstr(8, 9, "\\\\ /") lookdeer1.addstr(9, 11, "\\>/>") lookdeer2.addstr(0, 16, "\\/ \\/") lookdeer2.addstr(1, 17, "\\Y/ \\Y/") lookdeer2.addstr(2, 19, "\\=/") lookdeer2.addstr(3, 17, "^\\o o/^") lookdeer2.addstr(4, 17, "//( )") lookdeer2.addstr(5, 7, "^~~~~~~~~// \\O/") lookdeer2.addstr(6, 7, "(( )____( /") # )) lookdeer2.addstr(7, 7, "( / |") lookdeer2.addstr(8, 8, "\\/ |") lookdeer2.addstr(9, 9, "|> |>") lookdeer3.addstr(0, 16, "\\/ \\/") lookdeer3.addstr(1, 17, "\\Y/ \\Y/") lookdeer3.addstr(2, 19, "\\=/") lookdeer3.addstr(3, 17, "^\\o o/^") lookdeer3.addstr(4, 17, "//( )") lookdeer3.addstr(5, 7, "^~~~~~~~~// \\O/") lookdeer3.addstr(6, 6, "( ()_____( /") # )) lookdeer3.addstr(7, 6, "/ / /") lookdeer3.addstr(8, 5, "|/ \\") lookdeer3.addstr(9, 5, "/> \\>") lookdeer4.addstr(0, 16, "\\/ \\/") lookdeer4.addstr(1, 17, "\\Y/ \\Y/") lookdeer4.addstr(2, 19, "\\=/") lookdeer4.addstr(3, 17, "^\\o o/^") lookdeer4.addstr(4, 17, "//( )") lookdeer4.addstr(5, 7, "^~~~~~~~~// \\O/") lookdeer4.addstr(6, 6, "( )______( /") # ) lookdeer4.addstr(7, 5, "(/ \\") # ) lookdeer4.addstr(8, 0, "v___= ----^") ############################################### curses.cbreak() stdscr.nodelay(1) while 1: stdscr.clear() treescrn.erase() w_del_msg.touchwin() treescrn.touchwin() treescrn2.erase() treescrn2.touchwin() treescrn8.erase() treescrn8.touchwin() stdscr.refresh() look_out(150) boxit() stdscr.refresh() look_out(150) seas() stdscr.refresh() greet() stdscr.refresh() look_out(150) fromwho() stdscr.refresh() look_out(150) tree() look_out(150) balls() look_out(150) star() look_out(150) strng1() strng2() strng3() strng4() strng5() # set up the windows for our blinking trees # # treescrn3 treescrn.overlay(treescrn3) # balls treescrn3.addch(4, 18, ord(' ')) treescrn3.addch(7, 6, ord(' ')) treescrn3.addch(8, 19, ord(' ')) treescrn3.addch(11, 22, ord(' ')) # star treescrn3.addch(0, 12, ord('*')) # strng1 treescrn3.addch(3, 11, ord(' ')) # strng2 treescrn3.addch(5, 13, ord(' ')) treescrn3.addch(6, 10, ord(' ')) # strng3 treescrn3.addch(7, 16, ord(' ')) treescrn3.addch(7, 14, ord(' ')) # strng4 treescrn3.addch(10, 13, ord(' ')) treescrn3.addch(10, 10, ord(' ')) treescrn3.addch(11, 8, ord(' ')) # strng5 treescrn3.addch(11, 18, ord(' ')) treescrn3.addch(12, 13, ord(' ')) # treescrn4 treescrn.overlay(treescrn4) # balls treescrn4.addch(3, 9, ord(' ')) treescrn4.addch(4, 16, ord(' ')) treescrn4.addch(7, 6, ord(' ')) treescrn4.addch(8, 19, ord(' ')) treescrn4.addch(11, 2, ord(' ')) treescrn4.addch(12, 23, ord(' ')) # star treescrn4.standout() treescrn4.addch(0, 12, ord('*')) treescrn4.standend() # strng1 treescrn4.addch(3, 13, ord(' ')) # strng2 # strng3 treescrn4.addch(7, 15, ord(' ')) treescrn4.addch(8, 11, ord(' ')) # strng4 treescrn4.addch(9, 16, ord(' ')) treescrn4.addch(10, 12, ord(' ')) treescrn4.addch(11, 8, ord(' ')) # strng5 treescrn4.addch(11, 18, ord(' ')) treescrn4.addch(12, 14, ord(' ')) # treescrn5 treescrn.overlay(treescrn5) # balls treescrn5.addch(3, 15, ord(' ')) treescrn5.addch(10, 20, ord(' ')) treescrn5.addch(12, 1, ord(' ')) # star treescrn5.addch(0, 12, ord(' ')) # strng1 treescrn5.addch(3, 11, ord(' ')) # strng2 treescrn5.addch(5, 12, ord(' ')) # strng3 treescrn5.addch(7, 14, ord(' ')) treescrn5.addch(8, 10, ord(' ')) # strng4 treescrn5.addch(9, 15, ord(' ')) treescrn5.addch(10, 11, ord(' ')) treescrn5.addch(11, 7, ord(' ')) # strng5 treescrn5.addch(11, 17, ord(' ')) treescrn5.addch(12, 13, ord(' ')) # treescrn6 treescrn.overlay(treescrn6) # balls treescrn6.addch(6, 7, ord(' ')) treescrn6.addch(7, 18, ord(' ')) treescrn6.addch(10, 4, ord(' ')) treescrn6.addch(11, 23, ord(' ')) # star treescrn6.standout() treescrn6.addch(0, 12, ord('*')) treescrn6.standend() # strng1 # strng2 treescrn6.addch(5, 11, ord(' ')) # strng3 treescrn6.addch(7, 13, ord(' ')) treescrn6.addch(8, 9, ord(' ')) # strng4 treescrn6.addch(9, 14, ord(' ')) treescrn6.addch(10, 10, ord(' ')) treescrn6.addch(11, 6, ord(' ')) # strng5 treescrn6.addch(11, 16, ord(' ')) treescrn6.addch(12, 12, ord(' ')) # treescrn7 treescrn.overlay(treescrn7) # balls treescrn7.addch(3, 15, ord(' ')) treescrn7.addch(6, 7, ord(' ')) treescrn7.addch(7, 18, ord(' ')) treescrn7.addch(10, 4, ord(' ')) treescrn7.addch(11, 22, ord(' ')) # star treescrn7.addch(0, 12, ord('*')) # strng1 treescrn7.addch(3, 12, ord(' ')) # strng2 treescrn7.addch(5, 13, ord(' ')) treescrn7.addch(6, 9, ord(' ')) # strng3 treescrn7.addch(7, 15, ord(' ')) treescrn7.addch(8, 11, ord(' ')) # strng4 treescrn7.addch(9, 16, ord(' ')) treescrn7.addch(10, 12, ord(' ')) treescrn7.addch(11, 8, ord(' ')) # strng5 treescrn7.addch(11, 18, ord(' ')) treescrn7.addch(12, 14, ord(' ')) look_out(150) reindeer() w_holiday.touchwin() w_holiday.refresh() w_del_msg.refresh() look_out(500) for i in range(0, 20): blinkit() curses.wrapper(main)
xbmc/atv2
xbmc/lib/libPython/Python/Demo/curses/xmas.py
Python
gpl-2.0
25,498
/* * E-UAE - The portable Amiga Emulator * * BeOS joystick driver * * (c) Richard Drummond 2005 */ extern "C" { #include "sysconfig.h" #include "sysdeps.h" #include "options.h" #include "memory_uae.h" #include "custom.h" #include "inputdevice.h" } #include <device/Joystick.h> #include <support/String.h> //#define DEBUG #ifdef DEBUG #define DEBUG_LOG write_log #else #define DEBUG_LOG(...) { } #endif extern "C" { static int init_joysticks (void); static void close_joysticks (void); static int acquire_joy (unsigned int nr, int flags); static void unacquire_joy (unsigned int nr); static void read_joysticks (void); static unsigned int get_joystick_count (void); static const char *get_joystick_name (unsigned int nr); static unsigned int get_joystick_widget_num (unsigned int nr); static int get_joystick_widget_type (unsigned int nr, unsigned int num, char *name); static int get_joystick_widget_first (unsigned int nr, int type); }; /* * The BJoystick class can't make up its mind whether it represents a joystick * port or the device attached to a port. * * We choose to believe both and thus that there's at most one joystick attached * to each port. Since USB ain't supported, I don't have any hardware which * disproves that belief... */ class UAEJoystick :public BJoystick { public: UAEJoystick (unsigned int nr, const char *port_name); private: unsigned int nr; /* Device number that UAE assigns to a joystick */ BString port_name; /* Name used to open the joystick port */ BString name; /* Full name used to describe this joystick to the user */ public: const char *getName () { return name.String(); } int acquire (); void unacquire (); void read (); }; UAEJoystick :: UAEJoystick (unsigned int nr, const char *port_name) { /* Create joystick name using both port and joystick name */ BString stick_name; this->Open(port_name); this->GetControllerName (&stick_name); this->Close (); this->name = port_name; this->name += ":"; this->name += stick_name; this->port_name = port_name; this->nr = nr; } int UAEJoystick :: acquire () { return this->Open (this->port_name.String()); } void UAEJoystick :: unacquire () { this->Close (); } void UAEJoystick :: read () { DEBUG_LOG ("read: polling joy:%d\n", this->nr); if (this->Update () != B_ERROR) { /* Read axis values */ { unsigned int nr_axes = this->CountAxes (); int16 values[nr_axes]; unsigned int axis; this->GetAxisValues (values); for (axis = 0; axis < nr_axes; axis++) setjoystickstate (this->nr, axis, values[axis], 32767); } /* Read button values */ { unsigned int nr_buttons = this->CountButtons (); int32 values; unsigned int button; values = this->ButtonValues (); for (button = 0; button < nr_buttons; button++) { setjoybuttonstate (this->nr, button, values & 1); values >>= 1; } } } } /* * Inputdevice API */ #define MAX_JOYSTICKS MAX_INPUT_DEVICES static unsigned int nr_joysticks; static UAEJoystick *joysticks [MAX_JOYSTICKS]; static int init_joysticks (void) { BJoystick joy; unsigned int nr_ports; unsigned int i; nr_joysticks = 0; nr_ports = joy.CountDevices (); if (nr_ports > MAX_JOYSTICKS) nr_ports = MAX_JOYSTICKS; /* * Enumerate joysticks */ for (i = 0; i < nr_ports; i++) { char port_name[B_OS_NAME_LENGTH]; joy.GetDeviceName (i, port_name); if (joy.Open (port_name)) { BString stick_name; joy.Close (); joysticks[nr_joysticks] = new UAEJoystick (nr_joysticks, port_name); write_log ("BJoystick: device %d = %s\n", nr_joysticks, joysticks[nr_joysticks]->getName ()); nr_joysticks++; } else DEBUG_LOG ("Failed to open port='%s'\n", port_name); } write_log ("BJoystick: Found %d joystick(s)\n", nr_joysticks); return 1; } static void close_joysticks (void) { unsigned int i; for (i = 0; i < nr_joysticks; i++) delete joysticks[i]; nr_joysticks = 0; } static int acquire_joy (unsigned int nr, int flags) { int result = 0; DEBUG_LOG ("acquire_joy (%d)...\n", nr); if (nr < nr_joysticks) result = joysticks[nr]->acquire (); DEBUG_LOG ("%s\n", result ? "okay" : "failed"); return result; } static void unacquire_joy (unsigned int nr) { DEBUG_LOG ("unacquire_joy (%d)\n", nr); if (nr < nr_joysticks) joysticks[nr]->unacquire (); } static void read_joysticks (void) { unsigned int i; for (i = 0; i < get_joystick_count (); i++) { /* In compatibility mode, don't read joystick unless it's selected in the prefs */ if (currprefs.input_selected_setting == 0) { if (jsem_isjoy (0, &currprefs) != (int)i && jsem_isjoy (1, &currprefs) != (int)i) continue; } joysticks[i]->read (); } } static unsigned int get_joystick_num (void) { return nr_joysticks; } static const char *get_joystick_friendlyname (unsigned int nr) { return joysticks[nr]->getName (); } static const char *get_joystick_uniquename (unsigned int nr) { return joysticks[nr]->getName (); } static unsigned int get_joystick_widget_num (unsigned int nr) { return joysticks[nr]->CountAxes () + joysticks[nr]->CountButtons (); } static int get_joystick_widget_type (unsigned int nr, unsigned int widget_num, char *name, uae_u32 *what) { unsigned int nr_axes = joysticks[nr]->CountAxes (); unsigned int nr_buttons = joysticks[nr]->CountButtons (); if (widget_num >= nr_axes && widget_num < nr_axes + nr_buttons) { if (name) sprintf (name, "Button %d", widget_num + 1 - nr_axes); return IDEV_WIDGET_BUTTON; } else if (widget_num < nr_axes) { if (name) sprintf (name, "Axis %d", widget_num + 1); return IDEV_WIDGET_AXIS; } return IDEV_WIDGET_NONE; } static int get_joystick_widget_first (unsigned int nr, int type) { switch (type) { case IDEV_WIDGET_BUTTON: return joysticks[nr]->CountAxes (); case IDEV_WIDGET_AXIS: return 0; } return -1; } static int get_joystick_flags (int num) { return 0; } struct inputdevice_functions inputdevicefunc_joystick = { init_joysticks, close_joysticks, acquire_joy, unacquire_joy, read_joysticks, get_joystick_num, get_joystick_friendlyname, get_joystick_uniquename, get_joystick_widget_num, get_joystick_widget_type, get_joystick_widget_first, get_joystick_flags }; /* * Set default inputdevice config for joysticks */ int input_get_default_joystick (struct uae_input_device *uid, int num, int port, int cd32) { unsigned int i, port; for (i = 0; i < nr_joysticks; i++) { port = i & 1; uid[i].eventid[ID_AXIS_OFFSET + 0][0] = port ? INPUTEVENT_JOY2_HORIZ : INPUTEVENT_JOY1_HORIZ; uid[i].eventid[ID_AXIS_OFFSET + 1][0] = port ? INPUTEVENT_JOY2_VERT : INPUTEVENT_JOY1_VERT; uid[i].eventid[ID_BUTTON_OFFSET + 0][0] = port ? INPUTEVENT_JOY2_FIRE_BUTTON : INPUTEVENT_JOY1_FIRE_BUTTON; uid[i].eventid[ID_BUTTON_OFFSET + 1][0] = port ? INPUTEVENT_JOY2_2ND_BUTTON : INPUTEVENT_JOY1_2ND_BUTTON; uid[i].eventid[ID_BUTTON_OFFSET + 2][0] = port ? INPUTEVENT_JOY2_3RD_BUTTON : INPUTEVENT_JOY1_3RD_BUTTON; } uid[0].enabled = 1; if (i == 0) return 1; return 0; }
ErisBlastar/PUAE
src/jd-beos/joystick.cpp
C++
gpl-2.0
7,504
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_Newsletter * @copyright Copyright (c) 2006-2014 X.commerce, Inc. (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * FOREIGN KEY update * * @category Mage * @package Mage_Newsletter * @author Magento Core Team <core@magentocommerce.com> */ $installer = $this; /* @var $installer Mage_Tax_Model_Mysql4_Setup */ $installer->startSetup(); $table = $installer->getTable('newsletter_queue_link'); $installer->getConnection()->addKey($table, 'IDX_NEWSLETTER_QUEUE_LINK_SEND_AT', array('queue_id', 'letter_sent_at')); $installer->endSetup();
T0MM0R/magento
web/app/code/core/Mage/Newsletter/sql/newsletter_setup/mysql4-upgrade-0.8.0-0.8.1.php
PHP
gpl-2.0
1,394
<?php // Avoid direct access to this piece of code if ( ! function_exists( 'add_action' ) ) { header( 'Location: /' ); exit; } global $wp_subscribe_reloaded; $wp_subscribe_reloaded->update_subscription_status( $post_ID, $email, '-C' ); $message = html_entity_decode( stripslashes( get_option( 'subscribe_reloaded_subscription_confirmed' ) ), ENT_COMPAT, 'UTF-8' ); if ( function_exists( 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage' ) ) { $message = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage( $message ); } return "<p>$message</p>";
ych622/tax1on1
wp-content/plugins/subscribe-to-comments-reloaded/templates/confirm.php
PHP
gpl-2.0
575
<?php /** * This file is part of the League.csv library * * @license http://opensource.org/licenses/MIT * @link https://github.com/thephpleague/csv/ * @version 8.2.0 * @package League.csv * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace League\Csv\Modifier; use LogicException; use OutOfBoundsException; use SplFileObject; /** * A Trait to ease PHP Stream Filters manipulation * with a SplFileObject * * @package League.csv * @since 6.0.0 * */ trait StreamFilter { /** * collection of stream filters * * @var array */ protected $stream_filters = []; /** * Stream filtering mode to apply on all filters * * @var int */ protected $stream_filter_mode = STREAM_FILTER_ALL; /** *the real path * * @var string the real path to the file * */ protected $stream_uri; /** * PHP Stream Filter Regex * * @var string */ protected $stream_regex = ',^ php://filter/ (?P<mode>:?read=|write=)? # The resource open mode (?P<filters>.*?) # The resource registered filters /resource=(?P<resource>.*) # The resource path $,ix'; /** * Internal path setter * * The path must be an SplFileInfo object * an object that implements the `__toString` method * a path to a file * * @param StreamIterator|SplFileObject|string $path The file path */ protected function initStreamFilter($path) { $this->stream_filters = []; if (!is_string($path)) { $this->stream_uri = null; return; } if (!preg_match($this->stream_regex, $path, $matches)) { $this->stream_uri = $path; return; } $this->stream_uri = $matches['resource']; $this->stream_filters = array_map('urldecode', explode('|', $matches['filters'])); $this->stream_filter_mode = $this->fetchStreamModeAsInt($matches['mode']); } /** * Get the stream mode * * @param string $mode * * @return int */ protected function fetchStreamModeAsInt($mode) { $mode = strtolower($mode); $mode = rtrim($mode, '='); if ('write' == $mode) { return STREAM_FILTER_WRITE; } if ('read' == $mode) { return STREAM_FILTER_READ; } return STREAM_FILTER_ALL; } /** * Check if the trait methods can be used * * @throws LogicException If the API can not be use */ protected function assertStreamable() { if (!is_string($this->stream_uri)) { throw new LogicException('The stream filter API can not be used'); } } /** * Tells whether the stream filter capabilities can be used * * @return bool */ public function isActiveStreamFilter() { return is_string($this->stream_uri); } /** * stream filter mode Setter * * Set the new Stream Filter mode and remove all * previously attached stream filters * * @param int $mode * * @throws OutOfBoundsException If the mode is invalid * * @return $this */ public function setStreamFilterMode($mode) { $this->assertStreamable(); if (!in_array($mode, [STREAM_FILTER_ALL, STREAM_FILTER_READ, STREAM_FILTER_WRITE])) { throw new OutOfBoundsException('the $mode should be a valid `STREAM_FILTER_*` constant'); } $this->stream_filter_mode = $mode; $this->stream_filters = []; return $this; } /** * stream filter mode getter * * @return int */ public function getStreamFilterMode() { $this->assertStreamable(); return $this->stream_filter_mode; } /** * append a stream filter * * @param string $filter_name a string or an object that implements the '__toString' method * * @return $this */ public function appendStreamFilter($filter_name) { $this->assertStreamable(); $this->stream_filters[] = $this->sanitizeStreamFilter($filter_name); return $this; } /** * prepend a stream filter * * @param string $filter_name a string or an object that implements the '__toString' method * * @return $this */ public function prependStreamFilter($filter_name) { $this->assertStreamable(); array_unshift($this->stream_filters, $this->sanitizeStreamFilter($filter_name)); return $this; } /** * Sanitize the stream filter name * * @param string $filter_name the stream filter name * * @return string */ protected function sanitizeStreamFilter($filter_name) { return urldecode($this->validateString($filter_name)); } /** * @inheritdoc */ abstract public function validateString($str); /** * Detect if the stream filter is already present * * @param string $filter_name * * @return bool */ public function hasStreamFilter($filter_name) { $this->assertStreamable(); return false !== array_search(urldecode($filter_name), $this->stream_filters, true); } /** * Remove a filter from the collection * * @param string $filter_name * * @return $this */ public function removeStreamFilter($filter_name) { $this->assertStreamable(); $res = array_search(urldecode($filter_name), $this->stream_filters, true); if (false !== $res) { unset($this->stream_filters[$res]); } return $this; } /** * Remove all registered stream filter * * @return $this */ public function clearStreamFilter() { $this->assertStreamable(); $this->stream_filters = []; return $this; } /** * Return the filter path * * @return string */ protected function getStreamFilterPath() { $this->assertStreamable(); if (!$this->stream_filters) { return $this->stream_uri; } return 'php://filter/' .$this->getStreamFilterPrefix() .implode('|', array_map('urlencode', $this->stream_filters)) .'/resource='.$this->stream_uri; } /** * Return PHP stream filter prefix * * @return string */ protected function getStreamFilterPrefix() { if (STREAM_FILTER_READ == $this->stream_filter_mode) { return 'read='; } if (STREAM_FILTER_WRITE == $this->stream_filter_mode) { return 'write='; } return ''; } }
laura-johnson/sistema-drupal
vendor/league/csv/src/Modifier/StreamFilter.php
PHP
gpl-2.0
6,884
/* * Copyright (C) 2011-2013 Team XBMC * http://kodi.tv * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include <unistd.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <string> #include "AMLUtils.h" #include "utils/CPUInfo.h" #include "utils/log.h" #include "utils/SysfsUtils.h" #include "utils/StringUtils.h" #include "guilib/gui3d.h" #include "utils/RegExp.h" #include "filesystem/SpecialProtocol.h" #include "rendering/RenderSystem.h" #include "linux/fb.h" #include <sys/ioctl.h> bool aml_present() { static int has_aml = -1; if (has_aml == -1) { if (SysfsUtils::Has("/sys/class/audiodsp/digital_raw")) has_aml = 1; else has_aml = 0; if (has_aml) CLog::Log(LOGNOTICE, "AML device detected"); } return has_aml == 1; } bool aml_wired_present() { static int has_wired = -1; if (has_wired == -1) { std::string test; if (SysfsUtils::GetString("/sys/class/net/eth0/operstate", test) != -1) has_wired = 1; else has_wired = 0; } return has_wired == 1; } bool aml_permissions() { if (!aml_present()) return false; static int permissions_ok = -1; if (permissions_ok == -1) { permissions_ok = 1; if (!SysfsUtils::HasRW("/dev/amvideo")) { CLog::Log(LOGERROR, "AML: no rw on /dev/amvideo"); permissions_ok = 0; } if (!SysfsUtils::HasRW("/dev/amstream_mpts")) { CLog::Log(LOGERROR, "AML: no rw on /dev/amstream*"); permissions_ok = 0; } if (!SysfsUtils::HasRW("/sys/class/video/axis")) { CLog::Log(LOGERROR, "AML: no rw on /sys/class/video/axis"); permissions_ok = 0; } if (!SysfsUtils::HasRW("/sys/class/video/screen_mode")) { CLog::Log(LOGERROR, "AML: no rw on /sys/class/video/screen_mode"); permissions_ok = 0; } if (!SysfsUtils::HasRW("/sys/class/video/disable_video")) { CLog::Log(LOGERROR, "AML: no rw on /sys/class/video/disable_video"); permissions_ok = 0; } if (!SysfsUtils::HasRW("/sys/class/tsync/pts_pcrscr")) { CLog::Log(LOGERROR, "AML: no rw on /sys/class/tsync/pts_pcrscr"); permissions_ok = 0; } if (!SysfsUtils::HasRW("/dev/video10")) { CLog::Log(LOGERROR, "AML: no rw on /dev/video10"); permissions_ok = 0; } if (!SysfsUtils::HasRW("/sys/module/amlvideodri/parameters/freerun_mode")) { CLog::Log(LOGERROR, "AML: no rw on /sys/module/amlvideodri/parameters/freerun_mode"); permissions_ok = 0; } if (!SysfsUtils::HasRW("/sys/class/audiodsp/digital_raw")) { CLog::Log(LOGERROR, "AML: no rw on /sys/class/audiodsp/digital_raw"); } if (!SysfsUtils::HasRW("/sys/class/amhdmitx/amhdmitx0/config")) { CLog::Log(LOGERROR, "AML: no rw on /sys/class/amhdmitx/amhdmitx0/config"); } if (!SysfsUtils::HasRW("/sys/class/vfm/map")) { CLog::Log(LOGERROR, "AML: no rw on /sys/class/vfm/map"); } if (!SysfsUtils::HasRW("/sys/class/tsync/enable")) { CLog::Log(LOGERROR, "AML: no rw on /sys/class/tsync/enable"); } if (!SysfsUtils::HasRW("/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq")) { CLog::Log(LOGERROR, "AML: no rw on /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq"); } if (!SysfsUtils::HasRW("/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq")) { CLog::Log(LOGERROR, "AML: no rw on /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq"); } if (!SysfsUtils::HasRW("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor")) { CLog::Log(LOGERROR, "AML: no rw on /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor"); } if (aml_has_frac_rate_policy() && !SysfsUtils::HasRW("/sys/class/amhdmitx/amhdmitx0/frac_rate_policy")) { CLog::Log(LOGERROR, "AML: no rw on /sys/class/amhdmitx/amhdmitx0/frac_rate_policy"); } } return permissions_ok == 1; } bool aml_support_hevc() { static int has_hevc = -1; if (has_hevc == -1) { std::string valstr; if(SysfsUtils::GetString("/sys/class/amstream/vcodec_profile", valstr) != 0) has_hevc = 0; else has_hevc = (valstr.find("hevc:") != std::string::npos) ? 1: 0; } return (has_hevc == 1); } bool aml_support_hevc_4k2k() { static int has_hevc_4k2k = -1; if (has_hevc_4k2k == -1) { CRegExp regexp; regexp.RegComp("hevc:.*4k"); std::string valstr; if (SysfsUtils::GetString("/sys/class/amstream/vcodec_profile", valstr) != 0) has_hevc_4k2k = 0; else has_hevc_4k2k = (regexp.RegFind(valstr) >= 0) ? 1 : 0; } return (has_hevc_4k2k == 1); } bool aml_support_hevc_10bit() { static int has_hevc_10bit = -1; if (has_hevc_10bit == -1) { CRegExp regexp; regexp.RegComp("hevc:.*10bit"); std::string valstr; if (SysfsUtils::GetString("/sys/class/amstream/vcodec_profile", valstr) != 0) has_hevc_10bit = 0; else has_hevc_10bit = (regexp.RegFind(valstr) >= 0) ? 1 : 0; } return (has_hevc_10bit == 1); } AML_SUPPORT_H264_4K2K aml_support_h264_4k2k() { static AML_SUPPORT_H264_4K2K has_h264_4k2k = AML_SUPPORT_H264_4K2K_UNINIT; if (has_h264_4k2k == AML_SUPPORT_H264_4K2K_UNINIT) { std::string valstr; if (SysfsUtils::GetString("/sys/class/amstream/vcodec_profile", valstr) != 0) has_h264_4k2k = AML_NO_H264_4K2K; else if (valstr.find("h264:4k") != std::string::npos) has_h264_4k2k = AML_HAS_H264_4K2K_SAME_PROFILE; else if (valstr.find("h264_4k2k:") != std::string::npos) has_h264_4k2k = AML_HAS_H264_4K2K; else has_h264_4k2k = AML_NO_H264_4K2K; } return has_h264_4k2k; } bool aml_support_vp9() { static int has_vp9 = -1; if (has_vp9 == -1) { CRegExp regexp; regexp.RegComp("vp9:.*compressed"); std::string valstr; if (SysfsUtils::GetString("/sys/class/amstream/vcodec_profile", valstr) != 0) has_vp9 = 0; else has_vp9 = (regexp.RegFind(valstr) >= 0) ? 1 : 0; } return (has_vp9 == 1); } bool aml_has_frac_rate_policy() { static int has_frac_rate_policy = -1; if (has_frac_rate_policy == -1) has_frac_rate_policy = SysfsUtils::Has("/sys/class/amhdmitx/amhdmitx0/frac_rate_policy"); return (has_frac_rate_policy == 1); } void aml_set_audio_passthrough(bool passthrough) { SysfsUtils::SetInt("/sys/class/audiodsp/digital_raw", passthrough ? 2:0); } void aml_probe_hdmi_audio() { // Audio {format, channel, freq, cce} // {1, 7, 7f, 7} // {7, 5, 1e, 0} // {2, 5, 7, 0} // {11, 7, 7e, 1} // {10, 7, 6, 0} // {12, 7, 7e, 0} int fd = open("/sys/class/amhdmitx/amhdmitx0/edid", O_RDONLY); if (fd >= 0) { char valstr[1024] = {0}; read(fd, valstr, sizeof(valstr) - 1); valstr[strlen(valstr)] = '\0'; close(fd); std::vector<std::string> probe_str = StringUtils::Split(valstr, "\n"); for (std::vector<std::string>::const_iterator i = probe_str.begin(); i != probe_str.end(); ++i) { if (i->find("Audio") == std::string::npos) { for (std::vector<std::string>::const_iterator j = i + 1; j != probe_str.end(); ++j) { if (j->find("{1,") != std::string::npos) printf(" PCM found {1,\n"); else if (j->find("{2,") != std::string::npos) printf(" AC3 found {2,\n"); else if (j->find("{3,") != std::string::npos) printf(" MPEG1 found {3,\n"); else if (j->find("{4,") != std::string::npos) printf(" MP3 found {4,\n"); else if (j->find("{5,") != std::string::npos) printf(" MPEG2 found {5,\n"); else if (j->find("{6,") != std::string::npos) printf(" AAC found {6,\n"); else if (j->find("{7,") != std::string::npos) printf(" DTS found {7,\n"); else if (j->find("{8,") != std::string::npos) printf(" ATRAC found {8,\n"); else if (j->find("{9,") != std::string::npos) printf(" One_Bit_Audio found {9,\n"); else if (j->find("{10,") != std::string::npos) printf(" Dolby found {10,\n"); else if (j->find("{11,") != std::string::npos) printf(" DTS_HD found {11,\n"); else if (j->find("{12,") != std::string::npos) printf(" MAT found {12,\n"); else if (j->find("{13,") != std::string::npos) printf(" ATRAC found {13,\n"); else if (j->find("{14,") != std::string::npos) printf(" WMA found {14,\n"); else break; } break; } } } } int aml_axis_value(AML_DISPLAY_AXIS_PARAM param) { std::string axis; int value[8]; SysfsUtils::GetString("/sys/class/display/axis", axis); sscanf(axis.c_str(), "%d %d %d %d %d %d %d %d", &value[0], &value[1], &value[2], &value[3], &value[4], &value[5], &value[6], &value[7]); return value[param]; } bool aml_IsHdmiConnected() { int hpd_state; SysfsUtils::GetInt("/sys/class/amhdmitx/amhdmitx0/hpd_state", hpd_state); if (hpd_state == 2) { return 1; } return 0; } bool aml_mode_to_resolution(const char *mode, RESOLUTION_INFO *res) { if (!res) return false; res->iWidth = 0; res->iHeight= 0; if(!mode) return false; std::string fromMode = mode; StringUtils::Trim(fromMode); // strips, for example, 720p* to 720p // the * indicate the 'native' mode of the display if (StringUtils::EndsWith(fromMode, "*")) fromMode.erase(fromMode.size() - 1); if (StringUtils::EqualsNoCase(fromMode, "panel")) { res->iWidth = aml_axis_value(AML_DISPLAY_AXIS_PARAM_WIDTH); res->iHeight= aml_axis_value(AML_DISPLAY_AXIS_PARAM_HEIGHT); res->iScreenWidth = aml_axis_value(AML_DISPLAY_AXIS_PARAM_WIDTH); res->iScreenHeight= aml_axis_value(AML_DISPLAY_AXIS_PARAM_HEIGHT); res->fRefreshRate = 60; res->dwFlags = D3DPRESENTFLAG_PROGRESSIVE; } else if (StringUtils::EqualsNoCase(fromMode, "4k2ksmpte") || StringUtils::EqualsNoCase(fromMode, "smpte24hz")) { res->iWidth = 1920; res->iHeight= 1080; res->iScreenWidth = 4096; res->iScreenHeight= 2160; res->fRefreshRate = 24; res->dwFlags = D3DPRESENTFLAG_PROGRESSIVE; } else { int width = 0, height = 0, rrate = 60; char smode = 'p'; if (sscanf(fromMode.c_str(), "%dx%dp%dhz", &width, &height, &rrate) == 3) { smode = 'p'; } else if (sscanf(fromMode.c_str(), "%d%[ip]%dhz", &height, &smode, &rrate) >= 2) { switch (height) { case 480: case 576: width = 720; break; case 720: width = 1280; break; case 1080: width = 1920; break; case 2160: width = 3840; break; } } else if (sscanf(fromMode.c_str(), "%dcvbs", &height) == 1) { width = 720; smode = 'i'; rrate = (height == 576) ? 50 : 60; } else if (sscanf(fromMode.c_str(), "4k2k%d", &rrate) == 1) { width = 3840; height = 2160; smode = 'p'; } else { return false; } res->iWidth = (width < 3840) ? width : 1920; res->iHeight= (height < 2160) ? height : 1080; res->iScreenWidth = width; res->iScreenHeight = height; res->dwFlags = (smode == 'p') ? D3DPRESENTFLAG_PROGRESSIVE : D3DPRESENTFLAG_INTERLACED; switch (rrate) { case 23: case 29: case 59: res->fRefreshRate = (float)((rrate + 1)/1.001); break; default: res->fRefreshRate = (float)rrate; break; } } res->iScreen = 0; res->bFullScreen = true; res->iSubtitles = (int)(0.965 * res->iHeight); res->fPixelRatio = 1.0f; res->strId = fromMode; res->strMode = StringUtils::Format("%dx%d @ %.2f%s - Full Screen", res->iScreenWidth, res->iScreenHeight, res->fRefreshRate, res->dwFlags & D3DPRESENTFLAG_INTERLACED ? "i" : ""); return res->iWidth > 0 && res->iHeight> 0; } bool aml_get_native_resolution(RESOLUTION_INFO *res) { std::string mode; SysfsUtils::GetString("/sys/class/display/mode", mode); bool result = aml_mode_to_resolution(mode.c_str(), res); if (aml_has_frac_rate_policy()) { int fractional_rate; SysfsUtils::GetInt("/sys/class/amhdmitx/amhdmitx0/frac_rate_policy", fractional_rate); if (fractional_rate == 1) res->fRefreshRate /= 1.001; } return result; } bool aml_set_native_resolution(const RESOLUTION_INFO &res, std::string framebuffer_name, const int stereo_mode) { bool result = false; result = aml_set_display_resolution(res, framebuffer_name); aml_handle_scale(res); aml_handle_display_stereo_mode(stereo_mode); return result; } bool aml_probe_resolutions(std::vector<RESOLUTION_INFO> &resolutions) { std::string valstr, vesastr, dcapfile; dcapfile = CSpecialProtocol::TranslatePath("special://home/userdata/disp_cap"); if (SysfsUtils::GetString(dcapfile, valstr) < 0) { if (SysfsUtils::GetString("/sys/class/amhdmitx/amhdmitx0/disp_cap", valstr) < 0) return false; if (SysfsUtils::GetString("/sys/class/amhdmitx/amhdmitx0/vesa_cap", vesastr) == 0) valstr += "\n" + vesastr; } std::vector<std::string> probe_str = StringUtils::Split(valstr, "\n"); resolutions.clear(); RESOLUTION_INFO res; for (std::vector<std::string>::const_iterator i = probe_str.begin(); i != probe_str.end(); ++i) { if (((StringUtils::StartsWith(i->c_str(), "4k2k")) && (aml_support_h264_4k2k() > AML_NO_H264_4K2K)) || !(StringUtils::StartsWith(i->c_str(), "4k2k"))) { if (aml_mode_to_resolution(i->c_str(), &res)) resolutions.push_back(res); if (aml_has_frac_rate_policy()) { // Add fractional frame rates: 23.976, 29.97 and 59.94 Hz switch ((int)res.fRefreshRate) { case 24: case 30: case 60: res.fRefreshRate /= 1.001; res.strMode = StringUtils::Format("%dx%d @ %.2f%s - Full Screen", res.iScreenWidth, res.iScreenHeight, res.fRefreshRate, res.dwFlags & D3DPRESENTFLAG_INTERLACED ? "i" : ""); resolutions.push_back(res); break; } } } } return resolutions.size() > 0; } bool aml_get_preferred_resolution(RESOLUTION_INFO *res) { // check display/mode, it gets defaulted at boot if (!aml_get_native_resolution(res)) { // punt to 720p if we get nothing aml_mode_to_resolution("720p", res); } return true; } bool aml_set_display_resolution(const RESOLUTION_INFO &res, std::string framebuffer_name) { std::string mode = res.strId.c_str(); std::string cur_mode; SysfsUtils::GetString("/sys/class/display/mode", cur_mode); if (aml_has_frac_rate_policy()) { if (cur_mode == mode) SysfsUtils::SetString("/sys/class/display/mode", "null"); int fractional_rate = (res.fRefreshRate == floor(res.fRefreshRate)) ? 0 : 1; SysfsUtils::SetInt("/sys/class/amhdmitx/amhdmitx0/frac_rate_policy", fractional_rate); } else if (cur_mode == mode) { // Don't set the same mode as current return true; } SysfsUtils::SetString("/sys/class/display/mode", mode.c_str()); aml_set_framebuffer_resolution(res, framebuffer_name); return true; } void aml_setup_video_scaling(const char *mode) { SysfsUtils::SetInt("/sys/class/graphics/fb0/blank", 1); SysfsUtils::SetInt("/sys/class/graphics/fb0/free_scale", 0); SysfsUtils::SetInt("/sys/class/graphics/fb1/free_scale", 0); SysfsUtils::SetInt("/sys/class/ppmgr/ppscaler", 0); if (strstr(mode, "1080")) { SysfsUtils::SetString("/sys/class/graphics/fb0/request2XScale", "8"); SysfsUtils::SetString("/sys/class/graphics/fb1/scale_axis", "1280 720 1920 1080"); SysfsUtils::SetString("/sys/class/graphics/fb1/scale", "0x10001"); } else { SysfsUtils::SetString("/sys/class/graphics/fb0/request2XScale", "16 1280 720"); } SysfsUtils::SetInt("/sys/class/graphics/fb0/blank", 0); } void aml_handle_scale(const RESOLUTION_INFO &res) { if (res.iScreenWidth > res.iWidth && res.iScreenHeight > res.iHeight) aml_enable_freeScale(res); else aml_disable_freeScale(); } void aml_handle_display_stereo_mode(const int stereo_mode) { static std::string lastHdmiTxConfig = "3doff"; std::string command = "3doff"; switch (stereo_mode) { case RENDER_STEREO_MODE_SPLIT_VERTICAL: command = "3dlr"; break; case RENDER_STEREO_MODE_SPLIT_HORIZONTAL: command = "3dtb"; break; default: // nothing - command is already initialised to "3doff" break; } CLog::Log(LOGDEBUG, "AMLUtils::aml_handle_display_stereo_mode old mode %s new mode %s", lastHdmiTxConfig.c_str(), command.c_str()); // there is no way to read back current mode from sysfs // so we track state internal. Because even // when setting the same mode again - kernel driver // will initiate a new hdmi handshake which is not // what we want of course. // for 3d mode we are called 2 times and need to allow both calls // to succeed. Because the first call doesn't switch mode (i guessi its // timing issue between switching the refreshrate and switching to 3d mode // which needs to occure in the correct order, else switching refresh rate // might reset 3dmode). // So we set the 3d mode - if the last command is different from the current // command - or in case they are the same - we ensure that its not the 3doff // command that gets repeated here. if (lastHdmiTxConfig != command || command != "3doff") { CLog::Log(LOGDEBUG, "AMLUtils::aml_handle_display_stereo_mode setting new mode"); lastHdmiTxConfig = command; SysfsUtils::SetString("/sys/class/amhdmitx/amhdmitx0/config", command); } else { CLog::Log(LOGDEBUG, "AMLUtils::aml_handle_display_stereo_mode - no change needed"); } } void aml_enable_freeScale(const RESOLUTION_INFO &res) { char fsaxis_str[256] = {0}; sprintf(fsaxis_str, "0 0 %d %d", res.iWidth-1, res.iHeight-1); char waxis_str[256] = {0}; sprintf(waxis_str, "0 0 %d %d", res.iScreenWidth-1, res.iScreenHeight-1); SysfsUtils::SetInt("/sys/class/graphics/fb0/free_scale", 0); SysfsUtils::SetString("/sys/class/graphics/fb0/free_scale_axis", fsaxis_str); SysfsUtils::SetString("/sys/class/graphics/fb0/window_axis", waxis_str); SysfsUtils::SetInt("/sys/class/graphics/fb0/scale_width", res.iWidth); SysfsUtils::SetInt("/sys/class/graphics/fb0/scale_height", res.iHeight); SysfsUtils::SetInt("/sys/class/graphics/fb0/free_scale", 0x10001); } void aml_disable_freeScale() { // turn off frame buffer freescale SysfsUtils::SetInt("/sys/class/graphics/fb0/free_scale", 0); SysfsUtils::SetInt("/sys/class/graphics/fb1/free_scale", 0); } void aml_set_framebuffer_resolution(const RESOLUTION_INFO &res, std::string framebuffer_name) { aml_set_framebuffer_resolution(res.iWidth, res.iHeight, framebuffer_name); } void aml_set_framebuffer_resolution(int width, int height, std::string framebuffer_name) { int fd0; std::string framebuffer = "/dev/" + framebuffer_name; if ((fd0 = open(framebuffer.c_str(), O_RDWR)) >= 0) { struct fb_var_screeninfo vinfo; if (ioctl(fd0, FBIOGET_VSCREENINFO, &vinfo) == 0) { vinfo.xres = width; vinfo.yres = height; vinfo.xres_virtual = 1920; vinfo.yres_virtual = 2160; vinfo.bits_per_pixel = 32; vinfo.activate = FB_ACTIVATE_ALL; ioctl(fd0, FBIOPUT_VSCREENINFO, &vinfo); } close(fd0); } }
fritsch/xbmc
xbmc/utils/AMLUtils.cpp
C++
gpl-2.0
20,206
<?php /** * Outputs responses * * @uses $vars['responses'] Responses HTML * @uses $vars['show_add_form'] Boolean to control if a comment add form is allowed to show (default: true) */ if (!elgg_extract('show_responses', $vars, true)) { return; } $entity = elgg_extract('entity', $vars); $responses = elgg_extract('responses', $vars); if ($responses === null && ($entity instanceof \ElggEntity)) { $responses = elgg_view_comments($entity, (bool) elgg_extract('show_add_form', $vars, true)); } if (!$responses) { return; } echo elgg_format_element('div', [ 'class' => 'elgg-listing-full-responses', ], $responses);
mrclay/Elgg-leaf
views/default/object/elements/full/responses.php
PHP
gpl-2.0
632
/* mkvmerge -- utility for splicing together matroska files from component media subtypes Distributed under the GPL v2 see the file COPYING for details or visit http://www.gnu.org/copyleft/gpl.html ALAC output module Written by Moritz Bunkus <moritz@bunkus.org>. */ #include "common/common_pch.h" #include "common/alac.h" #include "common/codec.h" #include "common/hacks.h" #include "merge/connection_checks.h" #include "output/p_alac.h" using namespace libmatroska; alac_packetizer_c::alac_packetizer_c(generic_reader_c *p_reader, track_info_c &p_ti, memory_cptr const &magic_cookie, unsigned int sample_rate, unsigned int channels) : generic_packetizer_c{p_reader, p_ti} , m_magic_cookie{magic_cookie} , m_sample_rate{sample_rate} , m_channels{channels} { set_codec_id(MKV_A_ALAC); set_track_type(track_audio); set_audio_sampling_freq(static_cast<double>(m_sample_rate)); set_audio_channels(m_channels); set_codec_private(magic_cookie); } alac_packetizer_c::~alac_packetizer_c() { } int alac_packetizer_c::process(packet_cptr packet) { add_packet(packet); return FILE_STATUS_MOREDATA; } connection_result_e alac_packetizer_c::can_connect_to(generic_packetizer_c *src, std::string &error_message) { alac_packetizer_c *alac_src = dynamic_cast<alac_packetizer_c *>(src); if (!alac_src) return CAN_CONNECT_NO_FORMAT; connect_check_a_samplerate(m_sample_rate, alac_src->m_sample_rate); connect_check_a_channels( m_channels, alac_src->m_channels); connect_check_codec_private(alac_src); return CAN_CONNECT_YES; }
egoitzro/mkvtoolnix
src/output/p_alac.cpp
C++
gpl-2.0
1,769
<?php /** * * @package Recent Topics Extension * Turkish translation by golelcintolga * * @copyright (c) 2015 PayBas * @license GNU General Public License, version 2 (GPL-2.0) * * Based on the original NV Recent Topics by Joas Schilling (nickvergessen) * */ if (!defined('IN_PHPBB')) { exit; } if (empty($lang) || !is_array($lang)) { $lang = array(); } $lang = array_merge($lang, array( 'RECENT_TOPICS' => 'Son Konular', ));
PayBas/RecentTopics
language/tr/recenttopics.php
PHP
gpl-2.0
440
<?php /** * JEvents Locations Component for Joomla 1.5.x * * @version $Id: jevboolean.php 1331 2010-10-19 12:35:49Z geraintedwards $ * @package JEvents * @copyright Copyright (C) 2008-2015 GWE Systems Ltd * @license GNU/GPLv2, see http://www.gnu.org/licenses/gpl-2.0.html * @link http://www.jevents.net */ // Check to ensure this file is included in Joomla! defined('JPATH_BASE') or die; jimport('joomla.html.html'); jimport('joomla.form.formfield'); jimport('joomla.form.helper'); JFormHelper::loadFieldClass('radio'); /** * JEVMenu Field class for the JEvents Component * * @package JEvents.fields * @subpackage com_banners * @since 1.6 */ class JFormFieldJEVBoolean extends JFormFieldRadio { /** * The form field type.s * * @var string * @since 1.6 */ protected $type = 'JEVBoolean'; protected function getInput() { JLoader::register('JEVHelper', JPATH_SITE . "/components/com_jevents/libraries/helper.php"); JEVHelper::ConditionalFields($this->element, $this->form->getName()); $params = JComponentHelper::getParams("com_jevents"); $value = (int) $this->value; if ($value==-1){ if (version_compare(JVERSION, '3.0.0', "<")){ $default25 = (string)$this->element["default25"]; if ($default25!=""){ $this->value = $this->default = intval($default25); } } else if (version_compare(JVERSION, '3.0.0', ">=")){ $default30 = (string)$this->element["default30"]; if ($default30!=""){ $this->value = $this->default = intval($default30); } } } if (!$params->get("bootstrapchosen", 1)) { $x = 1; } return parent::getInput(); } /** * Method to get the field options. * * @return array The field option objects. * @since 1.6 */ public function getOptions() { // Must load admin language files $lang = JFactory::getLanguage(); $lang->load("com_jevents", JPATH_ADMINISTRATOR); $options = array(); $options[] = JHTML::_('select.option', 0, JText::_("Jev_No")); $options[] = JHTML::_('select.option', 1, JText::_("jev_Yes")); return $options; } /** * Method to attach a JForm object to the field. * * @param SimpleXMLElement $element The SimpleXMLElement object representing the <field /> tag for the form field object. * @param mixed $value The form field value to validate. * @param string $group The field name group control value. This acts as as an array container for the field. * For example if the field has name="foo" and the group value is set to "bar" then the * full field name would end up being "bar[foo]". * * @return boolean True on success. * * @since 11.1 */ /* public function setup(SimpleXMLElement $element, $value, $group = null) { return parent::setup($element, $value, $group); } */ }
githubupttik/upttik
administrator/components/com_jevents/fields/jevboolean.php
PHP
gpl-2.0
2,914
<p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:', AGM_LANG ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $title; ?>" /> </p> <p> <label for="<?php echo $this->get_field_id( 'width' ); ?>"><?php _e( 'Map size:', AGM_LANG ); ?></label> <input size="3" id="<?php echo $this->get_field_id( 'width' ); ?>" name="<?php echo $this->get_field_name( 'width' ); ?>" type="text" value="<?php echo $width; ?>" /> &nbsp;x&nbsp; <input size="3" id="<?php echo $this->get_field_id( 'height' ); ?>" name="<?php echo $this->get_field_name( 'height' ); ?>" type="text" value="<?php echo $height; ?>" /> </p> <p class="agm_widget_query_options"> <label><?php _e( 'Use map(s) from:', AGM_LANG ); ?></label> <br /> <input id="<?php echo $this->get_field_id( 'query_current' ); ?>" name="<?php echo $this->get_field_name( 'query' ); ?>" type="radio" <?php echo (( 'current' == $query) ? 'checked="checked"' : '' ); ?> value="current" /> <label for="<?php echo $this->get_field_id( 'query_current' ); ?>"><?php _e( 'Current posts', AGM_LANG ); ?></label> <br /> <input id="<?php echo $this->get_field_id( 'query_all_posts' ); ?>" name="<?php echo $this->get_field_name( 'query' ); ?>" type="radio" <?php echo (( 'all_posts' == $query) ? 'checked="checked"' : '' ); ?> value="all_posts" /> <label for="<?php echo $this->get_field_id( 'query_all_posts' ); ?>"><?php _e( 'All posts', AGM_LANG ); ?></label> <br /> <input id="<?php echo $this->get_field_id( 'query_all' ); ?>" name="<?php echo $this->get_field_name( 'query' ); ?>" type="radio" <?php echo (( 'all' == $query) ? 'checked="checked"' : '' ); ?> value="all" /> <label for="<?php echo $this->get_field_id( 'query_all' ); ?>"><?php _e( 'All', AGM_LANG ); ?></label> <br /> <input id="<?php echo $this->get_field_id( 'query_random' ); ?>" name="<?php echo $this->get_field_name( 'query' ); ?>" type="radio" <?php echo (( 'random' == $query) ? 'checked="checked"' : '' ); ?> value="random" /> <label for="<?php echo $this->get_field_id( 'query_random' ); ?>"><?php _e( 'Random map', AGM_LANG ); ?></label> <br /> <input class="map_id_switch" id="<?php echo $this->get_field_id( 'query_id' ); ?>" name="<?php echo $this->get_field_name( 'query' ); ?>" type="radio" <?php echo (( 'id' == $query) ? 'checked="checked"' : '' ); ?> value="id" /> <label for="<?php echo $this->get_field_id( 'query_id' ); ?>"><?php _e( 'Use this map:', AGM_LANG ); ?></label> <select class="map_id_target" id="<?php echo $this->get_field_id( 'map_id' ); ?>" name="<?php echo $this->get_field_name( 'map_id' ); ?>"> <option value=""><?php _e( 'Select one', AGM_LANG ); ?></option> <?php foreach ($maps as $map) { ?> <option value="<?php echo $map['id'];?>" <?php echo (($map_id == $map['id']) ? 'selected="selected"' : '' );?>><?php echo esc_html($map['title']); ?></option> <?php } ?> </select> <br /> <small><a class="agm_create_new_map" href="#"><?php _e( 'Create new map' );?></a></small> <br /> <input class="custom_switch" id="<?php echo $this->get_field_id( 'query_custom_switch' ); ?>" name="<?php echo $this->get_field_name( 'query' ); ?>" type="radio" <?php echo (( 'custom' == $query) ? 'checked="checked"' : '' ); ?> value="custom" /> <label for="<?php echo $this->get_field_id( 'query_custom_switch' ); ?>"><?php _e( 'Custom query', AGM_LANG ); ?></label> <input class="widefat custom_target" id="<?php echo $this->get_field_id( 'query_custom' ); ?>" name="<?php echo $this->get_field_name( 'query_custom' ); ?>" type="text" value="<?php echo $query_custom; ?>" /> <?php if (AGM_USE_POST_INDEXER) { // Integrate post indexer ?> <input class="post_indexer_target" type="checkbox" id="<?php echo $this->get_field_id( 'network' ); ?>" name="<?php echo $this->get_field_name( 'network' ); ?>" <?php echo (( 'network' == $network) ? 'checked="checked"' : '' ); ?> value="network" /> <label for="<?php echo $this->get_field_id( 'network' ); ?>"><?php _e( 'This is a network query <small>(requires <a href="http://premium.wpmudev.org/project/post-indexer">Post Indexer</a> plugin) - only "tag=..." supported</small>', AGM_LANG ); ?></label> <br /> <?php } ?> <small><em><a target="_blank" href="http://premium.wpmudev.org/project/wordpress-google-maps-plugin/"><?php _e( 'Learn more about custom queries', AGM_LANG ); ?></a></em></small> </p> <p> <label><?php _e( 'Show:', AGM_LANG ); ?></label> <br /> <input class="show_as_one" id="<?php echo $this->get_field_id( 'show_as_one' ); ?>" name="<?php echo $this->get_field_name( 'show_as_one' ); ?>" <?php echo (($show_as_one) ? 'checked="checked"' : '' ); ?> type="checkbox" value="1" /> <label for="<?php echo $this->get_field_id( 'show_as_one' ); ?>"><?php _e( 'Show as one map', AGM_LANG ); ?></label> <select class="wdg_zoom" name="<?php echo $this->get_field_name( 'zoom' ); ?>"> <?php foreach ($zoom_items as $zidx => $zlbl) { ?> <option value="<?php echo $zidx?>" <?php echo (($zidx == $zoom) ? 'selected="selected"' : '' );?>><?php echo $zlbl;?></option> <?php } ?> </select> <br /> <input id="<?php echo $this->get_field_id( 'show_map' ); ?>" name="<?php echo $this->get_field_name( 'show_map' ); ?>" <?php echo (($show_map) ? 'checked="checked"' : '' ); ?> type="checkbox" value="1" /> <label for="<?php echo $this->get_field_id( 'show_map' ); ?>"><?php _e( 'Show map', AGM_LANG ); ?></label> <br /> <input id="<?php echo $this->get_field_id( 'show_markers' ); ?>" name="<?php echo $this->get_field_name( 'show_markers' ); ?>" <?php echo (($show_markers) ? 'checked="checked"' : '' ); ?> type="checkbox" value="1" /> <label for="<?php echo $this->get_field_id( 'show_markers' ); ?>"><?php _e( 'Show marker list', AGM_LANG ); ?></label> <br /> <input id="<?php echo $this->get_field_id( 'show_images' ); ?>" name="<?php echo $this->get_field_name( 'show_images' ); ?>" <?php echo (($show_images) ? 'checked="checked"' : '' ); ?> type="checkbox" value="1" /> <label for="<?php echo $this->get_field_id( 'show_images' ); ?>"><?php _e( 'Show images strip', AGM_LANG ); ?></label> <br /> <input id="<?php echo $this->get_field_id( 'show_posts' ); ?>" name="<?php echo $this->get_field_name( 'show_posts' ); ?>" <?php echo (($show_posts) ? 'checked="checked"' : '' ); ?> type="checkbox" value="1" /> <label for="<?php echo $this->get_field_id( 'show_posts' ); ?>"><?php _e( 'Show posts in markers', AGM_LANG ); ?></label> </p> <script type="text/javascript"> var _agmBound = false; (function($){ $(function() { function disable ($el) { $el.attr( 'disabled', true); $el.val( '' ); } function toggleTargets (e) { var $parent = $(this).parent( 'p.agm_widget_query_options' ); var $idSwitch = $parent.find( 'input.map_id_switch' ); var $idTarget = $parent.find( 'select.map_id_target' ); var $customSwitch = $parent.find( 'input.custom_switch' ); var $customTarget = $parent.find( 'input.custom_target' ); var $piTarget = $parent.find( 'input.post_indexer_target' ); if ($idSwitch.is( ':checked' )) $idTarget.attr( 'disabled', false); else disable($idTarget); if ($customSwitch.is( ':checked' )) { $customTarget.attr( 'disabled', false); $piTarget.attr( 'disabled', false); } else { disable($customTarget); $piTarget.attr( 'disabled', true); } } function toggleZoom (e) { var $me = $(this); var $parent = $me.parent( 'p' ); if ($me.is(":checked")) { $parent.find(".wdg_zoom").show().attr( 'disabled', false); } else { $parent.find(".wdg_zoom").hide().attr( 'disabled', true).val( '' ); } } function init () { $( 'body' ).on( 'click', 'p.agm_widget_query_options input:radio', toggleTargets); $( 'p.agm_widget_query_options select.map_id_target' ).each(function() { if (!$(this).val()) $(this).attr( 'disabled', true); }); $( 'p.agm_widget_query_options input.custom_target' ).each(function() { if (!$(this).val()) $(this).attr( 'disabled', true); }); $( 'body' ).on( 'change', 'input.show_as_one', toggleZoom); $( 'input.show_as_one' ).each(function () { var $me = $(this); if ($me.is(":checked")) $me.parent("p").find(".wdg_zoom").show().attr( 'disabled', false); else $me.parent("p").find(".wdg_zoom").hide().attr( 'disabled', true).val( '' ); }); _agmBound = true; } if (!_agmBound) init(); }); })(jQuery); </script>
graph-io/soundhouse-dev
wp-content/plugins/wpmu_dev_maps_plugin/views/widget_settings.php
PHP
gpl-2.0
8,536
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_Eav * @copyright Copyright (c) 2006-2014 X.commerce, Inc. (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * EAV Entity Attribute Boolean Data Model * * @category Mage * @package Mage_Eav * @author Magento Core Team <core@magentocommerce.com> */ class Mage_Eav_Model_Attribute_Data_Boolean extends Mage_Eav_Model_Attribute_Data_Select { /** * Return a text for option value * * @param int $value * @return string */ protected function _getOptionText($value) { switch ($value) { case '0': $text = Mage::helper('eav')->__('No'); break; case '1': $text = Mage::helper('eav')->__('Yes'); break; default: $text = ''; break; } return $text; } }
T0MM0R/magento
web/app/code/core/Mage/Eav/Model/Attribute/Data/Boolean.php
PHP
gpl-2.0
1,695
<?php /** * Elgg sidebar contents * * @uses $vars['show_owner_block'] (bool) Display owner block * @uses $vars['owner_block_menu_params'] (array) Params to pass to owner block menu * @uses $vars['show_page_menu'] (bool) Display page menu (default: true) * @uses $vars['page_menu_params'] (array) Params to pass to page menu * @uses $vars['sidebar'] Optional content that is displayed at the bottom of sidebar */ echo elgg_view('page/elements/owner_block', $vars); echo elgg_view('page/elements/page_menu', $vars); // optional 'sidebar' parameter echo elgg_extract('sidebar', $vars, '');
mrclay/Elgg-leaf
views/default/page/elements/sidebar.php
PHP
gpl-2.0
597
# =========================================================================== # eXe # Copyright 2004-2006, University of Auckland # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # =========================================================================== """ ReflectionBlock can render and process ReflectionIdevices as XHTML """ import logging from exe.webui.block import Block from exe.webui import common from exe.webui.element import TextAreaElement log = logging.getLogger(__name__) # =========================================================================== class ReflectionBlock(Block): """ ReflectionBlock can render and process ReflectionIdevices as XHTML """ def __init__(self, parent, idevice): """ Initialize a new Block object """ Block.__init__(self, parent, idevice) self.activityInstruc = idevice.activityInstruc self.answerInstruc = idevice.answerInstruc # to compensate for the strange unpickling timing when objects are # loaded from an elp, ensure that proper idevices are set: if idevice.activityTextArea.idevice is None: idevice.activityTextArea.idevice = idevice if idevice.answerTextArea.idevice is None: idevice.answerTextArea.idevice = idevice self.activityElement = TextAreaElement(idevice.activityTextArea) self.answerElement = TextAreaElement(idevice.answerTextArea) self.previewing = False # In view or preview render if not hasattr(self.idevice,'undo'): self.idevice.undo = True def process(self, request): """ Process the request arguments from the web server """ Block.process(self, request) is_cancel = common.requestHasCancel(request) if not is_cancel: self.activityElement.process(request) self.answerElement.process(request) if "title"+self.id in request.args: self.idevice.title = request.args["title"+self.id][0] def renderEdit(self, style): """ Returns an XHTML string with the form element for editing this block """ html = "<div class=\"iDevice\"><br/>\n" html += common.textInput("title"+self.id, self.idevice.title) html += self.activityElement.renderEdit() html += self.answerElement.renderEdit() html += "<br/>" + self.renderEditButtons() html += "</div>\n" return html def renderPreview(self, style): """ Remembers if we're previewing or not, then implicitly calls self.renderViewContent (via Block.renderPreview) """ self.previewing = True return Block.renderPreview(self, style) def renderView(self, style): """ Remembers if we're previewing or not, then implicitly calls self.renderViewContent (via Block.renderPreview) """ self.previewing = False return Block.renderView(self, style) def renderViewContent(self): """ Returns an XHTML string for this block """ if self.previewing: html = self.activityElement.renderPreview() feedback = self.answerElement.renderPreview() else: html = self.activityElement.renderView() feedback = self.answerElement.renderView() #added lernmodule.net html += '<div class="Reflection" id="Reflection%s">' % (self.id) html += '<textarea id="ReflectionText%s" class="ReflectionText" name="ReflectionText%s"' % (self.id, self.id) html += ' rows=5 style="width:99%"></textarea></div>' html += common.feedbackBlock(self.id,feedback) return html from exe.engine.reflectionidevice import ReflectionIdevice from exe.webui.blockfactory import g_blockFactory g_blockFactory.registerBlockType(ReflectionBlock, ReflectionIdevice) # ===========================================================================
tquilian/exeNext
exe/webui/reflectionblock.py
Python
gpl-2.0
4,875
<?php /** * @package modx */ /** * Represents a user setting which overrides system and context settings. * * * @param int $user The ID of the User * @property string $key The key of the Setting * @property string $value The value of the Setting * @property string $xtype The xtype that is used to render the Setting input in the manager * @property string $namespace The Namespace of the setting * @property string $area The area of the Setting * @property timestamp $editedon The last edited on time of this Setting * @package modx */ class modUserSetting extends xPDOObject {}
wshearn/openshift-quickstart-modx
php/core/model/modx/modusersetting.class.php
PHP
gpl-2.0
593
<?php /* Copyright 2005 Flávio Ribeiro This file is part of OCOMON. OCOMON is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. OCOMON 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 Foobar; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */session_start(); include ("../../includes/include_geral.inc.php"); include ("../../includes/include_geral_II.inc.php"); $hoje = date("Y-m-d H:i:s"); $destaque=false; $cor=TD_COLOR; $cor1=TD_COLOR; $percLimit = 20; //Tolerância em percentual $imgSlaR = 'sla1.png'; $imgSlaS = 'checked.png'; $dtS = new dateOpers; //objeto para Solução $dtR = new dateOpers; //objeto para Resposta ?> <script type="text/javascript"> function popup(pagina) { //Exibe uma janela popUP x = window.open(pagina,'popup','dependent=yes,width=400,height=200,scrollbars=yes,statusbar=no,resizable=yes'); x.moveTo(window.parent.screenX+100, window.parent.screenY+100); return false } function popup_alerta(pagina) { //Exibe uma janela popUP x = window.open(pagina,'_blank','dependent=yes,width=700,height=470,scrollbars=yes,statusbar=no,resizable=yes'); x.moveTo(window.parent.screenX+50, window.parent.screenY+50); return false } </script> <?php print "<HTML>"; print "<BODY bgcolor='".BODY_COLOR."'>"; $auth = new auth; $auth->testa_user($_SESSION['s_usuario'],$_SESSION['s_nivel'],$_SESSION['s_nivel_desc'],2); $query = ""; $query = "SELECT o.numero, o.data_abertura, o.data_atendimento, o.data_fechamento, o.sistema AS cod_area, o.contato, ". "o.telefone, o.descricao, o.status as status, u.login as operador, st.status AS stat, s.sistema, p.problema AS problema, ". "sl.slas_desc AS sla, sl.slas_tempo AS tempo, l. * , pr. * , res.slas_tempo AS resposta ". "FROM localizacao AS l ". "LEFT JOIN prioridades AS pr ON pr.prior_cod = l.loc_prior ". "LEFT JOIN sla_solucao AS res ON res.slas_cod = pr.prior_sla, problemas AS p ". "LEFT JOIN sla_solucao AS sl ON p.prob_sla = sl.slas_cod, ocorrencias AS o, sistemas AS s, status AS st, ". "usuarios as u ". "WHERE s.sis_id = o.sistema AND p.prob_id = o.problema AND o.local = l.loc_id AND o.status = st.stat_id ". "and o.operador=u.user_id "; if (isset($_GET['numero']) ) $query.=" and o.numero in (".$_GET['numero'].") "; $query.=" ORDER BY numero"; //dump($query); $resultado = mysql_query($query) or die($query); $linhas = mysql_numrows($resultado); if ($linhas==0) { $aviso = "Nenhuma ocorrência localizada!"; print "<script>mensagem('".$aviso."'); redirect('consultar.php');</script>"; exit; } print "<br><B>Listando ".$linhas." ocorrências.<BR>"; print "<TABLE border='0' cellpadding='5' cellspacing='0' align='center' width='100%'>"; $valign = " valign=top "; print "<TR class='header'>"; print "<TD class='line'>Número</TD>"; print "<td class='line'>Problema</TD>"; print "<td class='line'>Contato<BR>Operador</TD>"; print "<td class='line'>Local</TD>"; print "<td class='line'>Data"; if (isset($_POST['tipo_data'])) print " de ".$_POST['tipo_data'].""; print "</TD>"; print "<td class='line'>Status</TD>"; print "<td class='line'>RESP.</TD>"; print "<td class='line'>SOLUC.</TD>"; print "</TR>"; $j=2; while ($row = mysql_fetch_array($resultado)) { if ($j % 2) { $trClass = "lin_par"; } else { $trClass = "lin_impar"; } if ($row['status']==4 and $destaque) { $color = "#F1FD4A";} if (($row['status'] == 1)) { $calcula = true;} else $calcula = false; $j++; $texto = trim( $row['descricao']); $limite = 250; if (strlen($texto)>$limite){ $texto = substr($texto,0,($limite-3))."..."; }; if ($calcula) { $areaChamado = ""; $areaChamado=testaArea($areaChamado,$row['cod_area'],$H_horarios); $dtR->setData1($row['data_abertura']); if ($row['data_atendimento'] =="") { $dtR->setData2($hoje) ; } else { $dtR->setData2($row['data_atendimento']) ; } $dtR->tempo_valido($dtR->data1,$dtR->data2,$H_horarios[$areaChamado][0],$H_horarios[$areaChamado][1],$H_horarios[$areaChamado][2],$H_horarios[$areaChamado][3],"H"); $diffR = $dtR->tValido; $diff2R = $dtR->diff["hValido"]; $segundosR = $dtR->diff["sValido"]; //segundos válidos $diff = date_difference($row['data_abertura'],$hoje); $sep = explode ("dias",$diff); if ($sep[0]>20) { //Se o chamado estiver aberto a mais de 20 dias o tempo é mostrado em dias para não ficar muito pesado. $diff = $sep[0]." dias"; $segundosS = ($sep[0]*86400); } else { $dtS->setData1($row['data_abertura']); if ($row['data_fechamento'] =="") { $dtS->setData2($hoje) ; } else { $dtS->setData2($row['data_fechamento']) ; } $dtS->tempo_valido($dtS->data1,$dtS->data2,$H_horarios[$areaChamado][0],$H_horarios[$areaChamado][1],$H_horarios[$areaChamado][2],$H_horarios[$areaChamado][3],"H"); $diffS = $dtS->tValido; $diff2S = $dtS->diff["hValido"]; $segundosS = $dtS->diff["sValido"]; //segundos válidos } if ($row['data_atendimento'] ==""){//Controle das bolinhas de SLA de Resposta if ($segundosR<=($row['resposta']*60)){ $imgSlaR = 'sla1.png'; } else if ($segundosR <=(($row['resposta']*60) + (($row['resposta']*60) *$percLimit/100)) ){ $imgSlaR = 'sla2.png'; } else { $imgSlaR = 'sla3.png'; } } else $imgSlaR = 'checked.png'; $sla_tempo = $row['tempo']; if (($sla_tempo !="") && ($row['data_fechamento']=="")) { //Controle das bolinhas de SLA de solução if ($segundosS <= ($row['tempo']*60)){ $imgSlaS = 'sla1.png'; } else if ($segundosS <=(($row['tempo']*60) + (($row['tempo']*60) *$percLimit/100)) ){ $imgSlaS = 'sla2.png'; } else $imgSlaS = 'sla3.png'; } else $imgSlaS = 'checked.png'; } else { $imgSlaR = 'checked.png'; $imgSlaS = 'checked.png'; } $sqlSubCall = "select * from ocodeps where dep_pai = ".$row['numero']." or dep_filho=".$row['numero'].""; $execSubCall = mysql_query($sqlSubCall) or die ('ERRO NA TENTATIVA DE RECUPERAR AS INFORMAÇÕES DOS SUBCHAMADOS!<br>'.$sqlSubCall); $regSub = mysql_num_rows($execSubCall); if ($regSub > 0) { #É CHAMADO PAI? $sqlSubCall = "select * from ocodeps where dep_pai = ".$row['numero'].""; $execSubCall = mysql_query($sqlSubCall) or die ('ERRO NA TENTATIVA DE RECUPERAR AS INFORMAÇÕES DOS SUBCHAMADOS!<br>'.$sqlSubCall); $regSub = mysql_num_rows($execSubCall); $comDeps = false; while ($rowSubPai = mysql_fetch_array($execSubCall)){ $sqlStatus = "select o.*, s.* from ocorrencias o, `status` s where o.numero=".$rowSubPai['dep_filho']." and o.`status`=s.stat_id and s.stat_painel not in (3) "; $execStatus = mysql_query($sqlStatus) or die ('ERRO NA TENTATIVA DE RECUPERAR AS INFORMAÇÕES DE STATUS DOS CHAMADOS FILHOS<br>'.$sqlStatus); $regStatus = mysql_num_rows($execStatus); if ($regStatus > 0) { $comDeps = true; } } if ($comDeps) { $imgSub = "<img src='".ICONS_PATH."view_tree_red.png' width='16' height='16' title='Chamado com vínculos pendentes'>"; } else $imgSub = "<img src='".ICONS_PATH."view_tree_green.png' width='16' height='16' title='Chamado com vínculos mas sem pendências'>"; } else $imgSub = ""; print "<tr class=".$trClass." id='linhax".$j."' onMouseOver=\"destaca('linhax".$j."','".$_SESSION['s_colorDestaca']."');\" onMouseOut=\"libera('linhax".$j."','".$_SESSION['s_colorLinPar']."','".$_SESSION['s_colorLinImpar']."');\" onMouseDown=\"marca('linhax".$j."','".$_SESSION['s_colorMarca']."');\">"; print "<TD ".$valign."><a onClick= \"javascript: popup_alerta('mostra_consulta.php?popup=true&numero=".$row['numero']."')\"><font color='blue'>".$row['numero']."</font></a>".$imgSub."</TD>"; print "<TD ".$valign.">".$row['problema']."</TD>"; print "<TD ".$valign."><b>".$row['contato']."</b><br>".$row['operador']."</TD>"; print "<TD ".$valign."><b>".$row['local']."</b><br>".$texto."</TD>"; print "<TD ".$valign.">".$row['data_abertura']."</TD>"; print "<TD ".$valign."><a onClick=\"javascript:popup('mostra_hist_status.php?popup=true&numero=".$row['numero']."')\"><font color='blue'>".$row['stat']."</font></a></TD>"; print "<TD ".$valign." align='center'><a onClick=\"javascript:popup('../../includes/help/sla_popup.php?sla=r')\"><img height='14' width='14' src='../../includes/imgs/".$imgSlaR."'></a></TD>"; print "<TD ".$valign." align='center'><a onClick=\"javascript:popup('../../includes/help/sla_popup.php?sla=s')\"><img height='14' width='14' src='../../includes/imgs/".$imgSlaS."'></a></TD>"; print "</TR>"; } //while print "</TABLE>"; print "</body>"; print "</html>"; ?>
rafaelfoster/ocomon
ocomon/geral/mostra_chamados.php
PHP
gpl-2.0
9,382
/* * $Source$ * $Revision$ * * Copyright (C) 2000 Myles Chippendale * * Part of Melati (http://melati.org), a framework for the rapid * development of clean, maintainable web applications. * * Melati is free software; Permission is granted to copy, distribute * and/or modify this software under the terms either: * * a) the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version, * * or * * b) any version of the Melati Software License, as published * at http://melati.org * * You should have received a copy of the GNU General Public License and * the Melati Software License along with this program; * if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA to obtain the * GNU General Public License and visit http://melati.org to obtain the * Melati Software License. * * Feel free to contact the Developers of Melati (http://melati.org), * if you would like to work out a different arrangement than the options * outlined here. It is our intention to allow Melati to be used by as * wide an audience as possible. * * 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. * * Contact details for copyright holder: * * Mylesc Chippendale <mylesc AT paneris.org> * http://paneris.org/ * 29 Stanley Road, Oxford, OX4 1QY, UK */ package org.melati.servlet; import java.util.Hashtable; import org.melati.Melati; /** * A way to implement policies about how to save uploaded files. */ public abstract class FormDataAdaptorFactory { /** * We need to establish the user and set up any request specific melati stuff * so that we can verify the user has permission for this task, and use * melati Table / Objects to manipulate what the FormDataAdaptor does. * * Please note that when uploading a file for a record that has not yet been * inserted (ie whilst adding), melati.getObject will return null. * * @param melati the {@link Melati} * @param field a {@link MultipartFormField} to process * @return a new {@link FormDataAdaptor} */ public FormDataAdaptor get(final Melati melati, final MultipartFormField field) { final Hashtable<String, FormDataAdaptor> holder = new Hashtable<String, FormDataAdaptor>(); if (melati.getDatabase() == null) { holder.put("hereiam",getIt(melati,field)); } else { melati.loadTableAndObject(); holder.put("hereiam",getIt(melati,field)); } return holder.get("hereiam"); } /** * Implements different policies for saving uploaded files depending * on the details of the file and the state of the application. * * @param melati the state of (this call to) the application * @param field details of the uploaded file * @return an adaptor which will save the contents of the file */ public abstract FormDataAdaptor getIt(Melati melati, MultipartFormField field); }
timp21337/melati-old
melati/src/main/java/org/melati/servlet/FormDataAdaptorFactory.java
Java
gpl-2.0
3,293
/* * Copyright 2010, Red Hat, Inc. and individual contributors as indicated by the * @author tags. See the copyright.txt file in the distribution for a full * listing of individual contributors. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF * site: http://www.fsf.org. */ package org.zanata.service; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import org.zanata.rest.dto.ReindexStatus; /** * @author Carlos Munoz <a * href="mailto:camunoz@redhat.com">camunoz@redhat.com</a> */ public interface SearchService { /** * Requests the start of a system reindex. NOTE: This is not a stable, * supported API. It might change from release to release. * * @param purgeAll * Purges all indexes. * @param indexAll * Reindexes all elements. * @param optimizeAll * Optimizes all indexes. * @return The following response status codes will be returned from this * operation:<br> * OK(200) - Response containing the Indexing process' status.<br> * INTERNAL SERVER ERROR(500) - If there is an unexpected error in * the server while performing this operation. */ @POST @Path("/reindex/start") ReindexStatus startReindex(@QueryParam("purge") boolean purgeAll, @QueryParam("index") boolean indexAll, @QueryParam("optimize") boolean optimizeAll); /** * Returns the status of a system search reindex operation. NOTE: This is * not a stable, supported API. It might change from release to release. * * @return The following response status codes will be returned from this * operation:<br> * OK(200) - Response containing the Indexing process' status if one * is in progress.<br> * NOT FOUND(404) - If there is no indexing task currently in * progress.<br> * INTERNAL SERVER ERROR(500) - If there is an unexpected error in * the server while performing this operation. */ @GET @Path("/reindex") ReindexStatus getReindexStatus(); }
mvehar/zanata-server
zanata-war/src/main/java/org/zanata/service/SearchService.java
Java
gpl-2.0
2,902
<?php /** * @version $Id: extensions.html.php 147 2013-10-06 08:58:34Z michel $ * @copyright Copyright (C) ##year##, ##author##. All rights reserved. * @license ###license## */ defined('JPATH_BASE') or die; require_once (JPATH_ADMINISTRATOR.'/components/com_##component##/helpers/##component##.php' ); jimport('joomla.html.html'); JFormHelper::loadFieldClass('list'); class JFormFieldExtensions extends JFormFieldList { /** * The field type. * * @var string */ protected $type = 'Extensions'; /** * Method to get a list of options for a list input. * * @return array An array of JHtml options. */ protected function getOptions() { $class = ($v = $this->element['class']) ? 'class="'.$v.'"' : 'class="inputbox"'; $extensions = ##Component##Helper::getExtensions(); $options = array(); foreach ($extensions as $extension) { $listview = is_object($extension->listview) ? $extension->listview->__toString() : $extension->listview; $name = is_object($extension->name) ? $extension->name->__toString() : $extension->name; $option = new stdClass(); $option->text = JText::_(ucfirst($listview)); $option->value = 'com_##component##.'.$name ; $options[] = $option; } $options = array_merge( parent::getOptions(), $options ); return $options; } } ?>
ranrolls/ras-full-portal
administrator/components/com_jacc/templates/mvcbase/admin/models/fields/extensions.php
PHP
gpl-2.0
1,339
// 2000-08-02 bkoz // Copyright (C) 2000-2021 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include <iostream> // Interactive test, to be exercised as follows: // assign stderr to stdout in shell command line, // pipe stdout to cat process and/or redirect stdout to file. // a.out >& output // "hello fine world\n" should be written to stdout, and output, in // proper order. This is a version of the scott snyder test taken // from: http://gcc.gnu.org/ml/libstdc++/1999-q4/msg00108.html void test04() { using namespace std; cout << "hello "; cout.flush(); cerr << "fine "; cerr.flush(); cout << "world" << endl; cout.flush(); } int main() { test04(); return 0; }
Gurgel100/gcc
libstdc++-v3/testsuite/27_io/objects/char/2.cc
C++
gpl-2.0
1,381
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing author: Axel Kohlmeyer (Temple U) This style is a simplified re-implementation of the CG/CMM pair style ------------------------------------------------------------------------- */ #include "pair_lj_sdk_coul_msm.h" #include <cmath> #include <cstring> #include "atom.h" #include "force.h" #include "kspace.h" #include "neigh_list.h" #include "error.h" #include "lj_sdk_common.h" using namespace LAMMPS_NS; using namespace LJSDKParms; /* ---------------------------------------------------------------------- */ PairLJSDKCoulMSM::PairLJSDKCoulMSM(LAMMPS *lmp) : PairLJSDKCoulLong(lmp) { ewaldflag = pppmflag = 0; msmflag = 1; respa_enable = 0; ftable = NULL; } /* ---------------------------------------------------------------------- */ void PairLJSDKCoulMSM::compute(int eflag, int vflag) { if (force->kspace->scalar_pressure_flag) error->all(FLERR,"Must use 'kspace_modify pressure/scalar no' with Pair style"); ev_init(eflag,vflag); if (evflag) { if (eflag) { if (force->newton_pair) eval_msm<1,1,1>(); else eval_msm<1,1,0>(); } else { if (force->newton_pair) eval_msm<1,0,1>(); else eval_msm<1,0,0>(); } } else { if (force->newton_pair) eval_msm<0,0,1>(); else eval_msm<0,0,0>(); } if (vflag_fdotr) virial_fdotr_compute(); } /* ---------------------------------------------------------------------- */ template <int EVFLAG, int EFLAG, int NEWTON_PAIR> void PairLJSDKCoulMSM::eval_msm() { int i,ii,j,jj,jtype,itable; double qtmp,xtmp,ytmp,ztmp,delx,dely,delz,evdwl,ecoul,fpair; double fraction,table; double r,rsq,r2inv,forcecoul,forcelj,factor_coul,factor_lj; double egamma,fgamma,prefactor; const double * const * const x = atom->x; double * const * const f = atom->f; const double * const q = atom->q; const int * const type = atom->type; const int nlocal = atom->nlocal; const double * const special_coul = force->special_coul; const double * const special_lj = force->special_lj; const double qqrd2e = force->qqrd2e; double fxtmp,fytmp,fztmp; const int inum = list->inum; const int * const ilist = list->ilist; const int * const numneigh = list->numneigh; const int * const * const firstneigh = list->firstneigh; // loop over neighbors of my atoms for (ii = 0; ii < inum; ii++) { i = ilist[ii]; qtmp = q[i]; xtmp = x[i][0]; ytmp = x[i][1]; ztmp = x[i][2]; fxtmp=fytmp=fztmp=0.0; const int itype = type[i]; const int * const jlist = firstneigh[i]; const int jnum = numneigh[i]; for (jj = 0; jj < jnum; jj++) { forcecoul = forcelj = evdwl = ecoul = 0.0; j = jlist[jj]; factor_lj = special_lj[sbmask(j)]; factor_coul = special_coul[sbmask(j)]; j &= NEIGHMASK; delx = xtmp - x[j][0]; dely = ytmp - x[j][1]; delz = ztmp - x[j][2]; rsq = delx*delx + dely*dely + delz*delz; jtype = type[j]; if (rsq < cutsq[itype][jtype]) { r2inv = 1.0/rsq; const int ljt = lj_type[itype][jtype]; if (rsq < cut_coulsq) { if (!ncoultablebits || rsq <= tabinnersq) { r = sqrt(rsq); prefactor = qqrd2e * qtmp*q[j]/r; fgamma = 1.0 + (rsq/cut_coulsq)*force->kspace->dgamma(r/cut_coul); forcecoul = prefactor * fgamma; if (EFLAG) { egamma = 1.0 - (r/cut_coul)*force->kspace->gamma(r/cut_coul); ecoul = prefactor*egamma; } if (factor_coul < 1.0) { forcecoul -= (1.0-factor_coul)*prefactor; if (EFLAG) ecoul -= (1.0-factor_coul)*prefactor; } } else { union_int_float_t rsq_lookup; rsq_lookup.f = rsq; itable = rsq_lookup.i & ncoulmask; itable >>= ncoulshiftbits; fraction = (rsq_lookup.f - rtable[itable]) * drtable[itable]; table = ftable[itable] + fraction*dftable[itable]; forcecoul = qtmp*q[j] * table; if (EFLAG) ecoul = qtmp*q[j] * (etable[itable] + fraction*detable[itable]); if (factor_coul < 1.0) { table = ctable[itable] + fraction*dctable[itable]; prefactor = qtmp*q[j] * table; forcecoul -= (1.0-factor_coul)*prefactor; if (EFLAG) ecoul -= (1.0-factor_coul)*prefactor; } } } else forcecoul = 0.0; if (rsq < cut_ljsq[itype][jtype]) { if (ljt == LJ12_4) { const double r4inv=r2inv*r2inv; forcelj = r4inv*(lj1[itype][jtype]*r4inv*r4inv - lj2[itype][jtype]); if (EFLAG) evdwl = r4inv*(lj3[itype][jtype]*r4inv*r4inv - lj4[itype][jtype]) - offset[itype][jtype]; } else if (ljt == LJ9_6) { const double r3inv = r2inv*sqrt(r2inv); const double r6inv = r3inv*r3inv; forcelj = r6inv*(lj1[itype][jtype]*r3inv - lj2[itype][jtype]); if (EFLAG) evdwl = r6inv*(lj3[itype][jtype]*r3inv - lj4[itype][jtype]) - offset[itype][jtype]; } else if (ljt == LJ12_6) { const double r6inv = r2inv*r2inv*r2inv; forcelj = r6inv*(lj1[itype][jtype]*r6inv - lj2[itype][jtype]); if (EFLAG) evdwl = r6inv*(lj3[itype][jtype]*r6inv - lj4[itype][jtype]) - offset[itype][jtype]; } forcelj *= factor_lj; if (EFLAG) evdwl *= factor_lj; } fpair = (forcecoul + forcelj) * r2inv; fxtmp += delx*fpair; fytmp += dely*fpair; fztmp += delz*fpair; if (NEWTON_PAIR || j < nlocal) { f[j][0] -= delx*fpair; f[j][1] -= dely*fpair; f[j][2] -= delz*fpair; } if (EVFLAG) ev_tally(i,j,nlocal,NEWTON_PAIR, evdwl,ecoul,fpair,delx,dely,delz); } } f[i][0] += fxtmp; f[i][1] += fytmp; f[i][2] += fztmp; } } /* ---------------------------------------------------------------------- */ double PairLJSDKCoulMSM::single(int i, int j, int itype, int jtype, double rsq, double factor_coul, double factor_lj, double &fforce) { double r2inv,r,fgamma,egamma,prefactor; double fraction,table,forcecoul,forcelj,phicoul,philj; int itable; forcecoul = forcelj = phicoul = philj = 0.0; r2inv = 1.0/rsq; if (rsq < cut_coulsq) { if (!ncoultablebits || rsq <= tabinnersq) { r = sqrt(rsq); prefactor = force->qqrd2e * atom->q[i]*atom->q[j]/r; egamma = 1.0 - (r/cut_coul)*force->kspace->gamma(r/cut_coul); fgamma = 1.0 + (rsq/cut_coulsq)*force->kspace->dgamma(r/cut_coul); forcecoul = prefactor * fgamma; phicoul = prefactor * egamma; if (factor_coul < 1.0) { forcecoul -= (1.0-factor_coul)*prefactor; phicoul -= (1.0-factor_coul)*prefactor; } } else { union_int_float_t rsq_lookup_single; rsq_lookup_single.f = rsq; itable = rsq_lookup_single.i & ncoulmask; itable >>= ncoulshiftbits; fraction = (rsq_lookup_single.f - rtable[itable]) * drtable[itable]; table = ftable[itable] + fraction*dftable[itable]; forcecoul = atom->q[i]*atom->q[j] * table; table = etable[itable] + fraction*detable[itable]; phicoul = atom->q[i]*atom->q[j] * table; if (factor_coul < 1.0) { table = ctable[itable] + fraction*dctable[itable]; prefactor = atom->q[i]*atom->q[j] * table; forcecoul -= (1.0-factor_coul)*prefactor; phicoul -= (1.0-factor_coul)*prefactor; } } } if (rsq < cut_ljsq[itype][jtype]) { const int ljt = lj_type[itype][jtype]; const double ljpow1 = lj_pow1[ljt]; const double ljpow2 = lj_pow2[ljt]; const double ljpref = lj_prefact[ljt]; const double ratio = sigma[itype][jtype]/sqrt(rsq); const double eps = epsilon[itype][jtype]; forcelj = factor_lj * ljpref*eps * (ljpow1*pow(ratio,ljpow1) - ljpow2*pow(ratio,ljpow2))/rsq; philj = factor_lj * (ljpref*eps * (pow(ratio,ljpow1) - pow(ratio,ljpow2)) - offset[itype][jtype]); } fforce = (forcecoul + forcelj) * r2inv; return phicoul + philj; } /* ---------------------------------------------------------------------- */ void *PairLJSDKCoulMSM::extract(const char *str, int &dim) { dim = 2; if (strcmp(str,"epsilon") == 0) return (void *) epsilon; if (strcmp(str,"sigma") == 0) return (void *) sigma; if (strcmp(str,"lj_type") == 0) return (void *) lj_type; if (strcmp(str,"lj1") == 0) return (void *) lj1; if (strcmp(str,"lj2") == 0) return (void *) lj2; if (strcmp(str,"lj3") == 0) return (void *) lj3; if (strcmp(str,"lj4") == 0) return (void *) lj4; if (strcmp(str,"rminsq") == 0) return (void *) rminsq; if (strcmp(str,"emin") == 0) return (void *) emin; dim = 0; if (strcmp(str,"cut_coul") == 0) return (void *) &cut_coul; if (strcmp(str,"cut_msm") == 0) return (void *) &cut_coul; return NULL; }
Pakketeretet2/lammps
src/USER-CGSDK/pair_lj_sdk_coul_msm.cpp
C++
gpl-2.0
9,995
<?php /** * * WhCountries.php * * Date: 06/09/14 * Time: 14:17 * @author Antonio Ramirez <amigo.cobos@gmail.com> * @link http://www.ramirezcobos.com/ * @link http://www.2amigos.us/ */ Yii::import('yiiwheels.widgets.formhelpers.WhInputWidget'); class WhPhone extends WhInputWidget { /** * @var string the formatting options */ public $format = false; public function init() { parent::init(); TbHtml::addCssClass('bfh-phone', $this->htmlOptions); $this->htmlOptions['data-format'] = $this->format; unset($this->htmlOptions['data-name'], $this->htmlOptions['data-value']); } public function run() { if (!$this->readOnly) { echo $this->hasModel() ? CHtml::activeTextField($this->model, $this->attribute, $this->htmlOptions) : CHtml::textField($this->name, $this->value, $this->htmlOptions); } else { $this->htmlOptions['data-number'] = $this->hasModel() ? $this->model->{$this->attribute} : $this->value; echo CHtml::tag('span', $this->htmlOptions, ''); } $this->registerPlugin('bfhphone'); } }
owliber/grand-time-auto
protected/extensions/yiiwheels/widgets/formhelpers/WhPhone.php
PHP
gpl-2.0
1,211
/***************************************************************************** * messages.cpp : Information about an item **************************************************************************** * Copyright (C) 2006-2011 the VideoLAN team * $Id$ * * Authors: Jean-Baptiste Kempf <jb (at) videolan.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "dialogs/messages.hpp" #include <QPlainTextEdit> #include <QTextCursor> #include <QTextBlock> #include <QFileDialog> #include <QTextStream> #include <QMessageBox> #include <QTabWidget> #include <QTreeWidget> #include <QTreeWidgetItem> #include <QMutex> #include <QLineEdit> #include <QScrollBar> #include <QMutex> #include <QMutexLocker> #include <assert.h> enum { MsgEvent_Type = QEvent::User + MsgEventTypeOffset + 1, }; class MsgEvent : public QEvent { public: MsgEvent( int, const msg_item_t *, const char * ); int priority; uintptr_t object_id; QString object_type; QString header; QString module; QString text; }; MsgEvent::MsgEvent( int type, const msg_item_t *msg, const char *text ) : QEvent( (QEvent::Type)MsgEvent_Type ), priority( type ), object_id( msg->i_object_id ), object_type( qfu(msg->psz_object_type) ), header( qfu(msg->psz_header) ), module( qfu(msg->psz_module) ), text( qfu(text) ) { } MessagesDialog::MessagesDialog( intf_thread_t *_p_intf) : QVLCFrame( _p_intf ) { setWindowTitle( qtr( "Messages" ) ); setWindowRole( "vlc-messages" ); /* Build Ui */ ui.setupUi( this ); ui.bottomButtonsBox->addButton( new QPushButton( qtr("&Close"), this ), QDialogButtonBox::RejectRole ); /* Modules tree */ ui.modulesTree->setHeaderHidden( true ); /* Buttons and general layout */ ui.saveLogButton->setToolTip( qtr( "Saves all the displayed logs to a file" ) ); int i_verbosity = var_InheritInteger( p_intf, "verbose" ); changeVerbosity( i_verbosity ); ui.verbosityBox->setValue( qMin( i_verbosity, 2 ) ); getSettings()->beginGroup( "Messages" ); ui.filterEdit->setText( getSettings()->value( "messages-filter" ).toString() ); getSettings()->endGroup(); updateButton = new QPushButton( QIcon(":/update"), "" ); updateButton->setFlat( true ); ui.mainTab->setCornerWidget( updateButton ); #ifndef NDEBUG QWidget *pldebugTab = new QWidget(); QVBoxLayout *pldebugTabLayout = new QVBoxLayout(); pldebugTab->setLayout( pldebugTabLayout ); ui.mainTab->addTab( pldebugTab, "Playlist Tree" ); pldebugTree = new QTreeWidget(); pldebugTree->headerItem()->setText( 0, "Name" ); pldebugTree->headerItem()->setText( 1, "PL id" ); pldebugTree->headerItem()->setText( 2, "Item id" ); pldebugTree->headerItem()->setText( 3, "PL flags" ); pldebugTree->headerItem()->setText( 4, "Item flags" ); pldebugTree->setColumnCount( 5 ); pldebugTabLayout->addWidget( pldebugTree ); #endif tabChanged(0); BUTTONACT( updateButton, updateOrClear() ); BUTTONACT( ui.saveLogButton, save() ); CONNECT( ui.filterEdit, editingFinished(), this, updateConfig() ); CONNECT( ui.filterEdit, textChanged(QString), this, filterMessages() ); CONNECT( ui.bottomButtonsBox, rejected(), this, hide() ); CONNECT( ui.verbosityBox, valueChanged( int ), this, changeVerbosity( int ) ); CONNECT( ui.mainTab, currentChanged( int ), this, tabChanged( int ) ); /* General action */ restoreWidgetPosition( "Messages", QSize( 600, 450 ) ); /* Hook up to LibVLC messaging */ vlc_Subscribe( &sub, MsgCallback, this ); buildTree( NULL, VLC_OBJECT( p_intf->p_libvlc ) ); } MessagesDialog::~MessagesDialog() { saveWidgetPosition( "Messages" ); vlc_Unsubscribe( &sub ); }; void MessagesDialog::changeVerbosity( int i_verbosity ) { vlc_atomic_set( &this->verbosity, i_verbosity ); } void MessagesDialog::updateConfig() { getSettings()->beginGroup( "Messages" ); getSettings()->setValue( "messages-filter", ui.filterEdit->text() ); getSettings()->endGroup(); } void MessagesDialog::filterMessages() { QMutexLocker locker( &messageLocker ); QPlainTextEdit *messages = ui.messages; QTextBlock block = messages->document()->firstBlock(); while( block.isValid() ) { block.setVisible( matchFilter( block.text().toLower() ) ); block = block.next(); } /* Consider the whole QTextDocument as dirty now */ messages->document()->markContentsDirty( 0, messages->document()->characterCount() ); /* FIXME This solves a bug (Qt?) with the viewport not resizing the vertical scroll bar when one or more QTextBlock are hidden */ QSize vsize = messages->viewport()->size(); messages->viewport()->resize( vsize + QSize( 1, 1 ) ); messages->viewport()->resize( vsize ); } bool MessagesDialog::matchFilter( const QString& text ) { const QString& filter = ui.filterEdit->text(); if( filter.isEmpty() || text.contains( filter.toLower() ) ) return true; return false; } void MessagesDialog::sinkMessage( const MsgEvent *msg ) { QMutexLocker locker( &messageLocker ); QPlainTextEdit *messages = ui.messages; /* Only scroll if the viewport is at the end. Don't bug user by auto-changing/losing viewport on insert(). */ bool b_autoscroll = ( messages->verticalScrollBar()->value() + messages->verticalScrollBar()->pageStep() >= messages->verticalScrollBar()->maximum() ); /* Copy selected text to the clipboard */ if( messages->textCursor().hasSelection() ) messages->copy(); /* Fix selected text bug */ if( !messages->textCursor().atEnd() || messages->textCursor().anchor() != messages->textCursor().position() ) messages->moveCursor( QTextCursor::End ); /* Start a new logic block so we can hide it on-demand */ messages->textCursor().insertBlock(); QString buf = QString( "<i><font color='darkblue'>%1</font>" ).arg( msg->module ); switch ( msg->priority ) { case VLC_MSG_INFO: buf += "<font color='blue'> info: </font>"; break; case VLC_MSG_ERR: buf += "<font color='red'> error: </font>"; break; case VLC_MSG_WARN: buf += "<font color='green'> warning: </font>"; break; case VLC_MSG_DBG: default: buf += "<font color='grey'> debug: </font>"; break; } /* Insert the prefix */ messages->textCursor().insertHtml( buf /* + "</i>" */ ); /* Insert the message */ messages->textCursor().insertHtml( msg->text ); /* Pass the new message thru the filter */ QTextBlock b = messages->document()->lastBlock(); b.setVisible( matchFilter( b.text() ) ); /* Tell the QTextDocument to recompute the size of the given area */ messages->document()->markContentsDirty( b.position(), b.length() ); if ( b_autoscroll ) messages->ensureCursorVisible(); } void MessagesDialog::customEvent( QEvent *event ) { MsgEvent *msge = static_cast<MsgEvent *>(event); assert( msge ); sinkMessage( msge ); } bool MessagesDialog::save() { QString saveLogFileName = QFileDialog::getSaveFileName( this, qtr( "Save log file as..." ), QVLCUserDir( VLC_DOCUMENTS_DIR ), qtr( "Texts / Logs (*.log *.txt);; All (*.*) ") ); if( !saveLogFileName.isNull() ) { QFile file( saveLogFileName ); if ( !file.open( QFile::WriteOnly | QFile::Text ) ) { QMessageBox::warning( this, qtr( "Application" ), qtr( "Cannot write to file %1:\n%2." ) .arg( saveLogFileName ) .arg( file.errorString() ) ); return false; } QTextStream out( &file ); QTextBlock block = ui.messages->document()->firstBlock(); while( block.isValid() ) { if( block.isVisible() ) out << block.text() << "\n"; block = block.next(); } return true; } return false; } void MessagesDialog::buildTree( QTreeWidgetItem *parentItem, vlc_object_t *p_obj ) { QTreeWidgetItem *item; if( parentItem ) item = new QTreeWidgetItem( parentItem ); else item = new QTreeWidgetItem( ui.modulesTree ); char *name = vlc_object_get_name( p_obj ); item->setText( 0, QString("%1%2 (0x%3)") .arg( qfu( p_obj->psz_object_type ) ) .arg( ( name != NULL ) ? QString( " \"%1\"" ).arg( qfu( name ) ) : "" ) .arg( (uintptr_t)p_obj, 0, 16 ) ); free( name ); item->setExpanded( true ); vlc_list_t *l = vlc_list_children( p_obj ); for( int i=0; i < l->i_count; i++ ) buildTree( item, l->p_values[i].p_object ); vlc_list_release( l ); } void MessagesDialog::updateOrClear() { if( ui.mainTab->currentIndex() == 1) { ui.modulesTree->clear(); buildTree( NULL, VLC_OBJECT( p_intf->p_libvlc ) ); } else if( ui.mainTab->currentIndex() == 0 ) ui.messages->clear(); #ifndef NDEBUG else updatePLTree(); #endif } void MessagesDialog::tabChanged( int i ) { updateButton->setIcon( i != 0 ? QIcon(":/update") : QIcon(":/toolbar/clear") ); updateButton->setToolTip( i != 0 ? qtr("Update the tree") : qtr("Clear the messages") ); } void MessagesDialog::MsgCallback( void *self, int type, const msg_item_t *item, const char *format, va_list ap ) { MessagesDialog *dialog = (MessagesDialog *)self; char *str; int verbosity = vlc_atomic_get( &dialog->verbosity ); if( verbosity < 0 || verbosity < (type - VLC_MSG_ERR) || unlikely(vasprintf( &str, format, ap ) == -1) ) return; int canc = vlc_savecancel(); QApplication::postEvent( dialog, new MsgEvent( type, item, str ) ); vlc_restorecancel( canc ); free( str ); } #ifndef NDEBUG static QTreeWidgetItem * PLWalk( playlist_item_t *p_node ) { QTreeWidgetItem *current = new QTreeWidgetItem(); current->setText( 0, qfu( p_node->p_input->psz_name ) ); current->setToolTip( 0, qfu( p_node->p_input->psz_uri ) ); current->setText( 1, QString("%1").arg( p_node->i_id ) ); current->setText( 2, QString("%1").arg( p_node->p_input->i_id ) ); current->setText( 3, QString("0x%1").arg( p_node->i_flags, 0, 16 ) ); current->setText( 4, QString("0x%1").arg( p_node->p_input->i_type, 0, 16 ) ); for ( int i = 0; p_node->i_children > 0 && i < p_node->i_children; i++ ) current->addChild( PLWalk( p_node->pp_children[ i ] ) ); return current; } void MessagesDialog::updatePLTree() { playlist_t *p_playlist = THEPL; pldebugTree->clear(); PL_LOCK; pldebugTree->addTopLevelItem( PLWalk( p_playlist->p_root_category ) ); PL_UNLOCK; pldebugTree->expandAll(); for ( int i=0; i< 5; i++ ) pldebugTree->resizeColumnToContents( i ); } #endif
thoaionline/vlc
modules/gui/qt4/dialogs/messages.cpp
C++
gpl-2.0
12,069
<?php class EditorExtensions { var $ext = array(); function get_list(){ $this->get_themes(); $this->get_sections(); return $this->ext; } function get_themes(){ // Themes $themes = wp_get_themes(); if(is_array($themes)){ foreach($themes as $theme => $t){ $class = array(); $tags = $t->get('Tags'); if( $t->get_template() != 'dms' && ! in_array('dms', $tags) ){ continue; } $thumb = $t->get_screenshot( ); if( is_file( sprintf( '%s/splash.png', $t->get_stylesheet_directory() ) ) ) $splash = sprintf( '%s/splash.png', $t->get_stylesheet_directory_uri() ); else $splash = $thumb; $this->ext[ $theme ] = array( 'id' => $theme, 'name' => $t->name, 'desc' => $t->description, 'thumb' => $thumb, 'splash' => $splash, 'purchase' => '', 'overview' => '', 'status' => $this->theme_status( $t->get_template() ) ); } } } function get_sections(){ $sections_handler = new PageLinesSectionsHandler; $sections = $sections_handler->get_available_sections(); foreach($sections as $key => $s){ $this->ext[ $s->id ] = array( 'id' => $s->id, 'name' => stripslashes( $s->name ), 'desc' => stripslashes( $s->description ), 'thumb' => $s->screenshot, 'purchase' => '', 'overview' => '', 'docs_url' => ( isset( $s->docs_url ) ) ? $s->docs_url : false ); } } function theme_status( $slug ) { // lets see if the stylesheet exists.... $theme = wp_get_theme( $slug ); $current = wp_get_theme(); if( $theme->Name == $current ) return 'active'; if( $theme->exists() ) return 'installed'; else return false; } }
calhouny/FR
wp-content/themes/dms/dms/editor/editor.extensions.php
PHP
gpl-2.0
1,707
<?php class all_around_functions { static $wrapper, $main_object; static public function get_filename_from_filepath($file) { $file_info=pathinfo($file); return $file_info['dirname']; } static public function get_directory_from_filepath($file) { $file_info=pathinfo($file); return $file_info['basename']; } static public function get_filename_from_url($url) { $pos=strrpos($url, "/"); if ($pos!==FALSE) return substr($url, $pos+1); return $url; } static public function get_relative_urlpath_for_cms_folder() { // return relative to webroot URL $cms_url=self::$wrapper->get_site_url()."/"; if (substr($cms_url,0,7)=="http://") $cms_url=substr($cms_url,7); if (substr($cms_url,0,8)=="https://") $cms_url=substr($cms_url,8); $pos=strpos($cms_url, "/"); $folder=substr($cms_url, $pos+1); if ($folder=='') $folder='/'; return $folder; } static public function get_full_urlpath_for_cms_folder() { // return relative URL return self::$wrapper->get_site_url()."/"; } static public function get_full_urlpath_of_domain($with_slash=1) { // return full URL with / $cms_url=self::$wrapper->get_site_url()."/"; $pos=strpos($cms_url, "/", 8); return substr($cms_url, 0, $pos+$with_slash); } static public function get_webroot_filepath() { // return full folderpath, ended with / $cms_path=all_around_ABSPATH; if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $cms_path=str_replace("\\", "/", $cms_path); $cms_path_length=strlen($cms_path); $cms_folder=self::get_relative_urlpath_for_cms_folder(); if ($cms_folder!='/') { $cms_folder_length=strlen($cms_folder); $ret = substr($cms_path, 0, $cms_path_length-$cms_folder_length); } else $ret = $cms_path; if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $ret=str_replace("/", "\\", $ret); return $ret; } static public function get_relative_to_cms_urlpath_from_full_urlpath($url) { // return relative URL without / if (substr($url,0,4)!='http') { if (substr($url,0,1)!='/') $url="/".$url; return $url; } $cms_path=all_around_ABSPATH; if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $cms_path=str_replace("/", "\\", $cms_path); $cms_url=self::$wrapper->get_site_url()."/"; $cms_url_length=strlen($cms_url); if (substr($url, 0, $cms_url_length)==$cms_url) { $piece=substr($url, $cms_url_length); return $piece; } return ''; } static public function get_relative_to_webroot_urlpath_from_full_urlpath($url) { // return relative URL with / $pos=strpos($url, '/', 8); return substr($url, $pos); } static public function get_full_urlpath_from_relative_urlpath($url) { // return full URL if (self::is_http_link($url)) return $url; if (self::link_begin_with_slash($url)) { return self::get_full_urlpath_of_domain(0).$url; } else { return self::get_full_urlpath_for_cms_folder().$url; } } static public function get_relative_to_cms_urlpath_from_full_filepath($file) { // return relative URL without / $cms_path=all_around_ABSPATH; if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $cms_path=str_replace("/", "\\", $cms_path); $cms_path_length=strlen($cms_path); if (substr($file, 0, $cms_path_length)==$cms_path) { $piece=substr($file, $cms_path_length); if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $piece=str_replace("\\", "/", $piece); return $piece; } return ''; } static public function get_relative_to_webroot_urlpath_from_full_filepath($file) { // return relative URL with / $webroot_folderpath=self::get_webroot_filepath(); //echo $webroot_folderpath; exit; $webroot_folderpath_length=strlen($webroot_folderpath); $ret = '/'.substr($file, $webroot_folderpath_length); if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $ret=str_replace("\\", "/", $ret); return $ret; } static public function get_full_urlpath_from_full_filepath($file) { // return full URL $cms_path=all_around_ABSPATH; $cms_url=self::$wrapper->get_site_url()."/"; if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $cms_path=str_replace("/", "\\", $cms_path); $cms_path_length=strlen($cms_path); if (substr($file, 0, $cms_path_length)==$cms_path) { $piece=substr($file, $cms_path_length); if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $piece=str_replace("\\", "/", $piece); return $cms_url.$piece; } return ''; } static public function get_full_urlpath_from_relative_to_cms_filepath($file) { // return full URL $cms_url=self::$wrapper->get_site_url(); if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $file=str_replace("\\", "/", $file); if (substr($file,0,1)!='/') $file="/".$file; return $cms_url.$file; } static public function get_full_urlpath_from_relative_to_webroot_filepath($file) { // return full URL $cms_url=self::$wrapper->get_site_url()."/"; $cms=self::get_relative_urlpath_for_cms_folder(); $cms_length=strlen($cms); $cms_url_length=strlen($cms_url); $piece=substr($cms_url, $cms_url_length-$cms_length); if ($piece==$cms) { $n=0; if ($cms=='/') $n=1; $root=substr($cms_url, 0, $cms_url_length-$cms_length+$n); //echo 'root='.$root;exit; if (substr($file,0,1)=='/' || substr($file,0,1)=='\\') $file=substr($file,1); if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $file=str_replace("\\", "/", $file); return $root.$file; } return ''; } static public function get_full_filepath_from_relative_filepath($file) { // return full filepath $slash="/"; if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $slash="\\"; $cms_path=all_around_ABSPATH; $cms_path_length=strlen($cms_path); if (substr($cms_path, $cms_path_length-1, 1)=='/') $cms_path=substr($cms_path, 0, $cms_path_length-1); if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') if (substr($cms_path, $cms_path_length-1, 1)=='\\') $cms_path=substr($cms_path, 0, $cms_path_length-1); if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $file=str_replace("/", "\\", $file); if (substr($file,0,1)!=$slash) $file=$slash.$file; return $cms_path.$file; } static public function get_relative_filepath_from_full_filepath($file) { // return relative filepath $cms_path=all_around_ABSPATH; $cms_path_length=strlen($cms_path); if (substr($cms_path, $cms_path_length-1, 1)=='/') $cms_path=substr($cms_path, 0, $cms_path_length-1); if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $file=str_replace("/", "\\", $file); $cms_path_length=strlen($cms_path); if (substr($file, 0, $cms_path_length)==$cms_path) { $piece=substr($file,$cms_path_length); if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $piece=str_replace("/", "\\", $piece); if (substr($piece,0,1)=='/' || substr($piece,0,1)=='\\') return substr($piece, 1); return $piece; } return ''; } static public function get_full_filepath_from_full_urlpath($url) { // return full filepath $slash="/"; if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $slash="\\"; $cms_path=all_around_ABSPATH; if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $cms_path=str_replace("/", "\\", $cms_path); $cms_url=self::$wrapper->get_site_url()."/"; $cms_url_length=strlen($cms_url); if (substr($url, 0, $cms_url_length)==$cms_url) { $piece=substr($url, $cms_url_length); if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $piece=str_replace("/", "\\", $piece); $file=$cms_path.$piece; if (is_file($file)) return $file; //echo $piece."<br />"; //exit; } return ''; } static public function get_full_filepath_from_relative_to_wordpres_urlpath ($url) { // return full filepath $slash="/"; if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $slash="\\"; $cms_path=all_around_ABSPATH; if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $cms_path=str_replace("/", "\\", $cms_path); if (substr($url,0,1)=='/') $url=substr($url, 1); $piece=$url; if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $piece=str_replace("/", "\\", $piece); //echo "PIECE: ".$piece."<br />"; exit; $file=$cms_path.$piece; if (is_file($file)) return $file; return ''; } static public function get_full_filepath_from_relative_to_webroot_urlpath ($url) {// return full filepath if (substr($url,0,1)=='/') $url=substr($url, 1); $domain=self::get_full_urlpath_of_domain(); $url=$domain.$url; return self::get_full_filepath_from_full_urlpath($url); } static public function get_filepath_from_url_smart($url) { // MAIN FUNCTION FOR GETTING FILEPATH FROM URL //echo 'looking for: '.$url.'<br />'; if (self::does_file_have_resolution($url)) { $burl=self::remove_resolution_from_file($url); $file=self::get_filepath_from_url($burl); if ($file!='' && is_file($file)) return $file; } $file=self::get_filepath_from_url($url); if ($file!='' && is_file($file)) return $file; $id=self::get_attachment_id_from_url_maybe_with_resolution ($url); if ($id!=NULL) { $file = self::$wrapper->get_attachment_file_from_id($id); if (is_file($file)) return $file; } if (self::is_http_link($url)) { if (self::does_file_have_resolution($url)) { $burl=self::remove_resolution_from_file($url); $file=self::get_full_filepath_from_full_urlpath($burl); if ($file!='' && is_file($file)) return $file; } $file=self::get_full_filepath_from_full_urlpath($url); if ($file!='' && is_file($file)) return $file; } else { if (self::does_file_have_resolution($url)) { $burl=self::remove_resolution_from_file($url); $file=self::get_full_filepath_from_relative_to_wordpres_urlpath ($burl); if ($file!='' && is_file($file)) return $file; $file=self::get_full_filepath_from_relative_to_webroot_urlpath ($burl); if ($file!='' && is_file($file)) return $file; } $file=self::get_full_filepath_from_relative_to_wordpres_urlpath ($url); if ($file!='' && is_file($file)) return $file; $file=self::get_full_filepath_from_relative_to_webroot_urlpath ($url); if ($file!='' && is_file($file)) return $file; } if (self::is_http_link($url)==FALSE) $url=self::get_full_urlpath_from_relative_urlpath($url); if (self::does_file_have_resolution($url)) { $url2=self::remove_resolution_from_file($url); $ret = self::get_remote_and_upload($url2); if ($ret) return $ret; } $ret = self::get_remote_and_upload($url); if ($ret) return $ret; return ''; } static public function get_filepath_from_url($url) { // shortcut for getting filepath from database via guid $id=self::$wrapper->get_attachment_id_from_url ($url); if ($id!=NULL) return self::$wrapper->get_attachment_file_from_id($id); return ''; } static public function get_attachment_id_from_url_maybe_with_resolution ($url) { if (self::does_file_have_resolution($url)) $url=self::remove_resolution_from_file($url); return self::$wrapper->get_attachment_id_from_url_without_resolution ($url); } static public function remove_resolution_from_file($url) { $pos1=strrpos($url, "/"); $pos11=strrpos($url, "\\"); $pos1=max($pos1, $pos11); $pos2=strrpos($url, "-"); $pos3=strrpos($url, "x"); $pos4=strrpos($url, "."); $r=$pos4-$pos2; if ($pos1===FALSE || $pos2===FALSE || $pos3===FALSE || $pos4===FALSE) return FALSE; if ($pos1<$pos2 && $pos2<$pos3 && $pos3<$pos4 && $r<11) { $x=substr($url, $pos2+1, $pos3-$pos2-1); $y=substr($url, $pos3+1, $pos4-$pos3-1); if (is_numeric($x) && is_numeric($y)) { $part1=substr($url, 0, $pos2); $part2=substr($url, $pos4); return $part1.$part2; } } return FALSE; } static public function does_file_have_resolution($url) { //echo 'does_file_have_resolution ( '.$url.' )<br />'; $pos1=strrpos($url, "/"); $pos11=strrpos($url, "\\"); $pos1=max($pos1, $pos11); $pos2=strrpos($url, "-"); $pos3=strrpos($url, "x"); $pos4=strrpos($url, "."); $r=$pos4-$pos2; if ($pos1===FALSE || $pos2===FALSE || $pos3===FALSE || $pos4===FALSE) return FALSE; if ($pos1<$pos2 && $pos2<$pos3 && $pos3<$pos4 && $r<11) { $x=substr($url, $pos2+1, $pos3-$pos2-1); $y=substr($url, $pos3+1, $pos4-$pos3-1); if (is_numeric($x) && is_numeric($y)) { //$part1=substr($url, 0, $pos2); //$part2=substr($url, $pos4); return TRUE; } } return FALSE; } static public function is_http_link ($url) { if (substr($url,0,7)=="http://") return TRUE; if (substr($url,0,8)=="https://") return TRUE; if (substr($url,0,2)=="//") return TRUE; return FALSE; } static public function link_begin_with_slash($url) { if (substr($url,0,1)=="/") return TRUE; return FALSE; } static public function save_file($file, $content) { $fp = fopen($file, 'w'); if (!$fp) return FALSE; fwrite($fp, $content); fclose($fp); $stat = stat( dirname( $file )); $perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits @chmod( $file, $perms ); return TRUE; } static public function get_remote($url) { return self::$wrapper->get_remote($url); } static public function get_remote_and_upload($url) { $content=self::get_remote($url); if ($content!==FALSE) { $filename=self::get_filename_from_url($url); $dir=''; $tdir=self::$wrapper->get_current_upload_dir(); if (is_writable($tdir)) { $dir=self::$wrapper->get_current_upload_dir(true); } else { $tdir=self::$wrapper->get_root_of_uploads_dir(); if (is_writable($tdir)) { $dir=self::$wrapper->get_root_of_uploads_dir(true); } } if ($dir=='') $dir=self::$wrapper->get_current_upload_dir(true); $md5=md5($url); $filepath=$dir.$filename; if (file_exists($filepath)) { $buf = file_get_contents($filepath); if ($buf==$content) return $filepath; } $filepath=$dir.$md5.'_'.$filename; if (file_exists($filepath)) return $filepath; $ret=self::save_file($filepath, $content); if (!$ret) return FALSE; return $filepath; } return FALSE; } static public function makethumb_image_db ($url, $w, $h, $opt=array(), $suffix = '', $dest_path = '', &$return_array2=NULL) { $return_array2=array( 'orig_url' => $url, 'orig_file' => '', 'dest_url' => $url, 'dest_file' => '' ); $opts=''; $variant=1; $opt_copy=array(); foreach ($opt as $var => $val) { if ($opts!='') $opts.=','; if ($var==0) $variant=2; if ($variant==1) $opts.=$var; if ($variant==2) { $opts.=$val; $opt_copy[$val]=1; } } if ($variant==2) $opt=$opt_copy; //echo '<pre>'; print_r($opt); echo '</pre>'; exit; $ukey=$url.'?w='.$w.'&h='.$h; if ($opts!='') $ukey.='&opt='.$opts; if ($suffix!='') $ukey.='&suffix='.$suffix; if ($dest_path!='') $ukey.='&dest_path='.$dest_path; //echo $ukey; exit; $eukey=esc_sql($ukey); $table = self::$main_object->get_thumb_table_name(); $thmb = self::$wrapper->db_get_row('SELECT * FROM ' . $table . ' WHERE ukey="'.$eukey.'"'); if ($thmb!==NULL) { if (!is_file($thmb['dest_file'])) { self::$wrapper->db_query('DELETE FROM ' . $table . ' WHERE ukey="'.$eukey.'"'); $thmb=NULL; } } if ($thmb===NULL) { $return_array=array(); self::makethumb_image($url, $w, $h, $opt, $suffix, $dest_path, $return_array); //echo '<pre>';print_r($return_array);echo '</pre>'; $data=array( 'ukey' => $ukey, 'orig_url' => $return_array['orig_url'], 'orig_file' => $return_array['orig_file'], 'dest_url' => $return_array['dest_url'], 'dest_file' => $return_array['dest_file'], 'width' => $w, 'height' => $h, 'filters' => $opts, 'version' => 1 ); $return_array2=array( 'orig_url' => $return_array['orig_url'], 'orig_file' => $return_array['orig_file'], 'dest_url' => $return_array['dest_url'], 'dest_file' => $return_array['dest_file'] ); self::$wrapper->db_insert_row( $table, $data ); return $return_array['dest_url']; } else { // check if file exists !!!!!!!!!!!!!!! $return_array2=array( 'orig_url' => $thmb['orig_url'], 'orig_file' => $thmb['orig_file'], 'dest_url' => $thmb['dest_url'], 'dest_file' => $thmb['dest_file'] ); return $thmb['dest_url']; } } static public function makethumb_image($url, $w, $h, $opt=array(), $suffix = '', $dest_path = '', &$return_array=NULL) { $return_array=array( 'orig_url' => $url, 'orig_file' => '', 'dest_url' => $url, 'dest_file' => '' ); $file=self::get_filepath_from_url_smart($url); if ($file=='') return $url; $return_array['orig_file']=$file; $return_array['dest_file']=$file; $md5=md5($url); $suffix.=$md5.'-'; if ($dest_path=='') { $dir=self::get_filename_from_filepath($file); if ($dir!='' && $dir!=NULL) { if (!is_writable($dir)) { $dir2=self::$wrapper->get_current_upload_dir(); if (is_writable($dir2)) { $dest_path=$dir2; } else { $dir2=self::$wrapper->get_root_of_uploads_dir(); if (is_writable($dir2)) { $dest_path=$dir2; } } } } } require_once(self::$main_object->path . '/includes/image_functions.php'); $predicted_file=all_around_image_class::predict_final_file_static($file, $w, $h, $opt, $suffix, $dest_path); //echo 'predicted_file = '.$predicted_file.'<br />'; if (is_file($predicted_file)) { $return_array['dest_file']=$predicted_file; $url2=self::get_full_urlpath_from_full_filepath($predicted_file); if ($url2) { $return_array['dest_url']=$url2; return $url2; } } $img = all_around_image_class::create_object($file); if ($img && !$img->is_error()) { $img->resize($w,$h, true); if (isset($opt['gray'])) $img->gray(); $file2 = $img->save($suffix, $dest_path); if ($file2) { $return_array['dest_file']=$file2; $url2=self::get_full_urlpath_from_full_filepath($file2); if ($url2) { $return_array['dest_url']=$url2; return $url2; } } } unset($img); return $url; } } ?>
visitcasabacardi/backup-nov-15
wp-content/plugins/all_around/includes/functions.php
PHP
gpl-2.0
18,197
// Copyright (C) 2004-2016 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include <string> #include <stdexcept> #include <iostream> #include <sstream> #include <set> #include <map> #include <ext/mt_allocator.h> #include <bits/functexcept.h> namespace __gnu_test { // libstdc++/22309 extern "C" void try_allocation() { typedef char value_t; typedef __gnu_cxx::__mt_alloc<value_t> allocator_t; typedef std::char_traits<value_t> traits_t; typedef std::basic_string<value_t, traits_t, allocator_t> string_t; string_t s; s += "west beach, indiana dunes"; } // libstdc++/23591 extern "C" void try_throw_exception() { try { std::__throw_bad_exception(); } catch (const std::exception& e) { } } extern "C" void try_function_random_fail() { long seed = lrand48(); if (seed < 2000) seed = 2000; { std::ostringstream s; s << "random_throw, seed: " << seed << std::endl; std::cout << s.str(); } while (--seed > 0) { try_throw_exception(); } // Randomly throw. See if other threads cleanup. std::__throw_bad_exception(); } #if __cplusplus < 201103L // "must be compiled with C++98" void erase_external(std::set<int>& s) { s.erase(s.begin()); } void erase_external(std::multiset<int>& s) { s.erase(s.begin()); } void erase_external(std::map<int, int>& s) { s.erase(s.begin()); } void erase_external(std::multimap<int, int>& s) { s.erase(s.begin()); } void erase_external_iterators(std::set<int>& s) { typedef typename std::set<int>::iterator iterator_type; iterator_type iter = s.begin(); s.erase(iter, ++iter); } void erase_external_iterators(std::multiset<int>& s) { typedef typename std::multiset<int>::iterator iterator_type; iterator_type iter = s.begin(); s.erase(iter, ++iter); } void erase_external_iterators(std::map<int, int>& s) { typedef typename std::map<int, int>::iterator iterator_type; iterator_type iter = s.begin(); s.erase(iter, ++iter); } void erase_external_iterators(std::multimap<int, int>& s) { typedef typename std::multimap<int, int>::iterator iterator_type; iterator_type iter = s.begin(); s.erase(iter, ++iter); } #endif } // end namepace __gnu_test
paranoiacblack/gcc
libstdc++-v3/testsuite/util/testsuite_shared.cc
C++
gpl-2.0
2,961
package com.sogou.qadev.service.cynthia.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import com.sogou.qadev.service.cynthia.service.DbPoolConnection; /** * @description:home filter db processor * @author:liming * @mail:liming@sogou-inc.com * @date:2014-5-6 下午5:37:53 * @version:v1.0 */ public class HomeFilterAccessSessionMySQL { public HomeFilterAccessSessionMySQL() { } /** * @description:get user home filter from db * @date:2014-5-6 下午5:38:05 * @version:v1.0 * @param userName * @return */ public String getHomeFilter(String userName) { PreparedStatement pstm = null; Connection conn = null; ResultSet rs = null; String filterIdStr = ""; try { conn = DbPoolConnection.getInstance().getReadConnection(); String sql = "select filter_id from home_filter as A JOIN filter as B on A.filter_id = B.id where A.user_name= ? and B.is_valid = 1"; pstm = conn.prepareStatement(sql); pstm.setString(1, userName); rs = pstm.executeQuery(); if(rs.next()) { filterIdStr = rs.getString("filter_id"); } }catch(Exception e) { e.printStackTrace(); }finally { DbPoolConnection.getInstance().closeAll(rs, pstm, conn); return filterIdStr; } } /** * @description:add user home filter * @date:2014-5-6 下午5:38:17 * @version:v1.0 * @param userName * @param filterId * @return */ public boolean addHomeFilter(String userName,String filterId) { PreparedStatement pstm = null; Connection conn = null; try { conn = DbPoolConnection.getInstance().getConnection(); String sql = "insert into home_filter (user_name,filter_id) values (?,?)"; pstm = conn.prepareStatement(sql); pstm.setString(1, userName); pstm.setString(2, filterId); return pstm.execute(); }catch(Exception e) { e.printStackTrace(); }finally { DbPoolConnection.getInstance().closeAll(pstm, conn); } return false; } /** * @description:update user home filter * @date:2014-5-6 下午5:38:26 * @version:v1.0 * @param userName * @param filterId * @return */ public boolean updateHomeFilter(String userName,String filterId) { PreparedStatement pstm = null; Connection conn = null; try { conn = DbPoolConnection.getInstance().getConnection(); String sql = "update home_filter set filter_id=? where user_name=?"; pstm = conn.prepareStatement(sql); pstm.setString(2, userName); pstm.setString(1, filterId); return pstm.execute(); }catch(Exception e) { e.printStackTrace(); }finally { DbPoolConnection.getInstance().closeAll(pstm, conn); } return false; } }
afrous/Cynthia
src/main/java/com/sogou/qadev/service/cynthia/dao/HomeFilterAccessSessionMySQL.java
Java
gpl-2.0
2,671
<?php ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // REPORTE: Relacion de Notas de Debito / Credito // ORGANISMO: Ninguno en particular ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// session_start(); header("Pragma: public"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); if(!array_key_exists("la_logusr",$_SESSION)) { print "<script language=JavaScript>"; print "close();"; print "opener.document.form1.submit();"; print "</script>"; } //----------------------------------------------------------------------------------------------------------------------------------- function uf_insert_seguridad($as_titulo) { ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Function: uf_insert_seguridad // Access: private // Arguments: as_titulo // Título del reporte // Description: función que guarda la seguridad de quien generó el reporte // Creado Por: Ing. Yesenia Moreno/ Ing. Luis Lang // Fecha Creación: 17/07/2007 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// global $io_fun_cxp; $ls_descripcion="Generó el Reporte ".$as_titulo; $lb_valido=$io_fun_cxp->uf_load_seguridad_reporte("CXP","sigesp_cxp_r_relacionndnc.php",$ls_descripcion); return $lb_valido; } //----------------------------------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------------------------------- function uf_print_encabezado_pagina($as_titulo,&$io_pdf) { ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Function: uf_print_encabezado_pagina // Access: private // Arguments: as_titulo // Título del Reporte // io_pdf // Instancia de objeto pdf // Description: Función que imprime los encabezados por página // Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang // Fecha Creación: 17/07/2007 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// $io_encabezado=$io_pdf->openObject(); $io_pdf->saveState(); $io_pdf->line(15,40,585,40); $io_pdf->Rectangle(15,700,570,60); $io_pdf->addJpegFromFile('../../shared/imagebank/'.$_SESSION["ls_logo"],25,705,$_SESSION["ls_width"],$_SESSION["ls_height"]); // Agregar Logo $li_tm=$io_pdf->getTextWidth(11,$as_titulo); $tm=306-($li_tm/2); $io_pdf->addText($tm,730,11,$as_titulo); // Agregar el título $io_pdf->addText(540,770,7,date("d/m/Y")); // Agregar la Fecha $io_pdf->addText(546,764,6,date("h:i a")); // Agregar la Hora // cuadro inferior $io_pdf->Rectangle(15,60,570,70); $io_pdf->line(15,73,585,73); $io_pdf->line(15,117,585,117); $io_pdf->line(130,60,130,130); $io_pdf->line(240,60,240,130); $io_pdf->line(380,60,380,130); $io_pdf->addText(40,122,7,"ELABORADO POR"); // Agregar el título $io_pdf->addText(42,63,7,"FIRMA / SELLO"); // Agregar el título $io_pdf->addText(157,122,7,"VERIFICADO POR"); // Agregar el título $io_pdf->addText(145,63,7,"FIRMA / SELLO / FECHA"); // Agregar el título $io_pdf->addText(275,122,7,"AUTORIZADO POR"); // Agregar el título $io_pdf->addText(257,63,7,"ADMINISTRACIÓN Y FINANZAS"); // Agregar el título $io_pdf->addText(440,122,7,"CONTRALORIA INTERNA"); // Agregar el título $io_pdf->addText(445,63,7,"FIRMA / SELLO / FECHA"); // Agregar el título $io_pdf->restoreState(); $io_pdf->closeObject(); $io_pdf->addObject($io_encabezado,'all'); }// end function uf_print_encabezado_pagina //----------------------------------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------------------------------- function uf_print_detalle($la_data,$ai_i,$ai_totmonndnc,&$io_pdf) { ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Function: uf_print_detalle // Access: private // Arguments: la_data // arreglo de información // ai_i // total de registros // ai_totmonndnc // total de Notas (Montos) // io_pdf // Instancia de objeto pdf // Description: Función que imprime el detalle del reporte // Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang // Fecha Creación: 17/07/2007 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// $io_pdf->ezSetDy(-2); $la_datatit[1]=array('numdc'=>'<b>Numero ND/NC</b>','nombre'=>'<b>Proveedor/Beneficiario</b>','fecope'=>'<b>Fecha Registro</b>', 'descodope'=>'<b>Tipo</b>','status'=>'<b>Estatus</b>','monto'=>'<b>Monto</b>'); $la_columnas=array('numdc'=>'', 'nombre'=>'', 'fecope'=>'', 'descodope'=>'', 'status'=>'', 'monto'=>''); $la_config=array('showHeadings'=>0, // Mostrar encabezados 'fontSize' => 9, // Tamaño de Letras 'titleFontSize' => 12, // Tamaño de Letras de los títulos 'showLines'=>1, // Mostrar Líneas 'shaded'=>2, // Sombra entre líneas 'width'=>540, // Ancho de la tabla 'maxWidth'=>540, // Ancho Máximo de la tabla 'xOrientation'=>'center', // Orientación de la tabla 'cols'=>array('numdc'=>array('justification'=>'center','width'=>80), // Justificación y ancho de la columna 'nombre'=>array('justification'=>'center','width'=>225), // Justificación y ancho de la columna 'fecope'=>array('justification'=>'center','width'=>65), // Justificación y ancho de la columna 'descodope'=>array('justification'=>'center','width'=>55), // Justificación y ancho de la columna 'status'=>array('justification'=>'center','width'=>70), // Justificación y ancho de la columna 'monto'=>array('justification'=>'center','width'=>75))); // Justificación y ancho de la columna $io_pdf->ezTable($la_datatit,$la_columnas,'',$la_config); $la_columnas=array('numdc'=>'', 'nombre'=>'', 'fecope'=>'', 'descodope'=>'', 'status'=>'', 'monto'=>''); $la_config=array('showHeadings'=>0, // Mostrar encabezados 'fontSize' => 9, // Tamaño de Letras 'titleFontSize' => 12, // Tamaño de Letras de los títulos 'showLines'=>1, // Mostrar Líneas 'shaded'=>0, // Sombra entre líneas 'width'=>540, // Ancho de la tabla 'maxWidth'=>540, // Ancho Máximo de la tabla 'xOrientation'=>'center', // Orientación de la tabla 'cols'=>array('numdc'=>array('justification'=>'left','width'=>80), // Justificación y ancho de la columna 'nombre'=>array('justification'=>'left','width'=>225), // Justificación y ancho de la columna 'fecope'=>array('justification'=>'left','width'=>65), // Justificación y ancho de la columna 'descodope'=>array('justification'=>'left','width'=>55), // Justificación y ancho de la columna 'status'=>array('justification'=>'left','width'=>70), // Justificación y ancho de la columna 'monto'=>array('justification'=>'right','width'=>75))); // Justificación y ancho de la columna $io_pdf->ezTable($la_data,$la_columnas,'',$la_config); $ai_i=$ai_i-1; $la_datatot[1]=array('titulo'=>'<b>Total de Registros: </b>'.$ai_i,'total'=>$ai_totmonndnc); $la_columnas=array('titulo'=>'<b>Factura</b>', 'total'=>'<b>Total</b>'); $la_config=array('showHeadings'=>0, // Mostrar encabezados 'fontSize' => 9, // Tamaño de Letras 'titleFontSize' => 12, // Tamaño de Letras de los títulos 'showLines'=>1, // Mostrar Líneas 'shaded'=>0, // Sombra entre líneas 'width'=>540, // Ancho de la tabla 'maxWidth'=>540, // Ancho Máximo de la tabla 'xOrientation'=>'center', // Orientación de la tabla 'outerLineThickness'=>0.5, 'innerLineThickness' =>0.5, 'cols'=>array('titulo'=>array('justification'=>'left','width'=>495), // Justificación y ancho de la columna 'total'=>array('justification'=>'right','width'=>75))); // Justificación y ancho de la columna $io_pdf->ezTable($la_datatot,$la_columnas,'',$la_config); }// end function uf_print_detalle //----------------------------------------------------------------------------------------------------------------------------------- require_once("../../shared/ezpdf/class.ezpdf.php"); require_once("sigesp_cxp_class_report.php"); $io_report=new sigesp_cxp_class_report(); require_once("../../shared/class_folder/class_funciones.php"); $io_funciones=new class_funciones(); require_once("../class_folder/class_funciones_cxp.php"); $io_fun_cxp=new class_funciones_cxp(); $ls_estmodest=$_SESSION["la_empresa"]["estmodest"]; //---------------------------------------------------- Parámetros del encabezado ----------------------------------------------- $ls_titulo="<b>RELACION DE NOTAS DE DEBITO / CREDITO</b>"; //-------------------------------------------------- Parámetros para Filtar el Reporte ----------------------------------------- $ls_tipndnc= $io_fun_cxp->uf_obtenervalor_get("tipndnc",""); $ls_numsoldes= $io_fun_cxp->uf_obtenervalor_get("numsoldes",""); $ls_numsolhas= $io_fun_cxp->uf_obtenervalor_get("numsolhas",""); $ls_ndncdes= $io_fun_cxp->uf_obtenervalor_get("ndncdes",""); $ld_ndnchas= $io_fun_cxp->uf_obtenervalor_get("ndnchas",""); $ld_fecregdes= $io_fun_cxp->uf_obtenervalor_get("fecregdes",""); $ld_fecreghas= $io_fun_cxp->uf_obtenervalor_get("fecreghas",""); $ls_emitida= $io_fun_cxp->uf_obtenervalor_get("emitida",""); $ls_contabilizada= $io_fun_cxp->uf_obtenervalor_get("contabilizada",""); $ls_anulada= $io_fun_cxp->uf_obtenervalor_get("anulada",""); $ls_tiporeporte=$io_fun_cxp->uf_obtenervalor_get("tiporeporte",0); global $ls_tiporeporte; if($ls_tiporeporte==1) { require_once("sigesp_cxp_class_reportbsf.php"); $io_report=new sigesp_cxp_class_reportbsf(); } //-------------------------------------------------------------------------------------------------------------------------------- $lb_valido=uf_insert_seguridad($ls_titulo); // Seguridad de Reporte if($lb_valido) { $lb_valido=$io_report->uf_select_relacionndnc($ls_tipndnc,$ls_numsoldes,$ls_numsolhas,$ls_ndncdes,$ld_ndnchas, $ld_fecregdes,$ld_fecreghas,$ls_emitida,$ls_contabilizada,$ls_anulada); // Cargar el DS con los datos del reporte if($lb_valido==false) // Existe algún error ó no hay registros { print("<script language=JavaScript>"); print(" alert('No hay nada que Reportar');"); print(" close();"); print("</script>"); } else // Imprimimos el reporte { error_reporting(E_ALL); set_time_limit(1800); $io_pdf=new Cezpdf('LETTER','portrait'); // Instancia de la clase PDF $io_pdf->selectFont('../../shared/ezpdf/fonts/Helvetica.afm'); // Seleccionamos el tipo de letra $io_pdf->ezSetCmMargins(3.6,4.8,3,3); // Configuración de los margenes en centímetros $io_pdf->ezStartPageNumbers(570,47,8,'','',1); // Insertar el número de página $li_totrow=$io_report->DS->getRowCount("numsol"); $li_totmonndnc=0; for($li_i=1;$li_i<=$li_totrow;$li_i++) { $ls_numdc= $io_report->DS->data["numdc"][$li_i]; $ls_numsol= $io_report->DS->data["numsol"][$li_i]; $ls_nombre= $io_report->DS->data["nombre"][$li_i]; $ls_codtipdoc= $io_report->DS->data["codtipdoc"][$li_i]; $ls_numrecdoc= $io_report->DS->data["numrecdoc"][$li_i]; $ld_fecope= $io_report->DS->data["fecope"][$li_i]; $ls_codope= trim($io_report->DS->data["codope"][$li_i]); $ls_desope= $io_report->DS->data["desope"][$li_i]; $li_monto= $io_report->DS->data["monto"][$li_i]; $ls_estapr= $io_report->DS->data["estapr"][$li_i]; $ls_estnotadc= $io_report->DS->data["estnotadc"][$li_i]; $ls_denest=""; switch ($ls_estnotadc) { case 'E': if($ls_estapr==1) $ls_denest='Emitida (Aprobada)'; else $ls_denest='Emitida'; break; case 'C': $ls_denest='Contabilizada'; break; case 'A': $ls_denest='Anulada'; break; } $ls_descodope=""; switch ($ls_codope) { case"ND": $ls_descodope="Debito"; break; case"NC": $ls_descodope="Credito"; break; } $li_totmonndnc=$li_totmonndnc+$li_monto; $li_monto=number_format($li_monto,2,",","."); $ld_fecope=$io_funciones->uf_convertirfecmostrar($ld_fecope); $la_data[$li_i]=array('numdc'=>$ls_numdc,'nombre'=>$ls_nombre,'fecope'=>$ld_fecope,'descodope'=>$ls_descodope, 'status'=>$ls_denest,'monto'=>$li_monto); } $li_totmonndnc=number_format($li_totmonndnc,2,",","."); uf_print_encabezado_pagina($ls_titulo,&$io_pdf); uf_print_detalle($la_data,$li_i,$li_totmonndnc,&$io_pdf); } if($lb_valido) // Si no ocurrio ningún error { $io_pdf->ezStopPageNumbers(1,1); // Detenemos la impresión de los números de página $io_pdf->ezStream(); // Mostramos el reporte } } ?>
omerta/huayra
cxp/reportes/sigesp_cxp_rpp_relacionndnc.php
PHP
gpl-2.0
13,945
<?php $quote = get_post_meta($post->ID, 'post_quote', true); ?> <?php $author = get_post_meta($post->ID, 'post_quote_author', true); ?> <div class="post-gallery quote"> <blockquote> <?php if($quote) { echo '<p>'.$quote.'</p>'; } else { echo 'Please enter a quote using the metaboxes'; } ?> <?php if($author) { echo '<cite>'. $author.'</cite>'; } ?> </blockquote> </div>
Sananes/ScruplesWoo
wp-content/themes/uberstore/inc/postformats/quote.php
PHP
gpl-2.0
375
<?php /* +---------------------------------------------------------------------------+ | Revive Adserver | | http://www.revive-adserver.com | | | | Copyright: See the COPYRIGHT.txt file. | | License: GPLv2 or later, see the LICENSE.txt file. | +---------------------------------------------------------------------------+ */ // Set text direction and characterset // Date & time configuration // Formats used by PEAR Spreadsheet_Excel_Writer packate /* ------------------------------------------------------- */ /* Translations */ /* ------------------------------------------------------- */ $GLOBALS['strHome'] = "خانه"; $GLOBALS['strHelp'] = "راهنما"; $GLOBALS['strStartOver'] = "شروع کردن"; $GLOBALS['strShortcuts'] = "میانبر"; $GLOBALS['strActions'] = "اقدام"; $GLOBALS['strAdminstration'] = "صورت موجودی"; $GLOBALS['strMaintenance'] = "نگهداری"; $GLOBALS['strProbability'] = "احتمال"; $GLOBALS['strInvocationcode'] = "احضار کد"; $GLOBALS['strBasicInformation'] = "اطلاعات اصلی"; $GLOBALS['strAppendTrackerCode'] = "اضا�?ه کردن کد رهگیری"; $GLOBALS['strOverview'] = "شمای کلی"; $GLOBALS['strSearch'] = "<u>جستجو</u>"; $GLOBALS['strDetails'] = "جزییات"; $GLOBALS['strCheckForUpdates'] = "چک کردن برای به روز رسانی"; $GLOBALS['strCompact'] = "�?شرده"; $GLOBALS['strUser'] = "نام کاربری"; $GLOBALS['strDuplicate'] = "همسان"; $GLOBALS['strMoveTo'] = "انتقال به"; $GLOBALS['strDelete'] = "حذ�?"; $GLOBALS['strActivate'] = "�?عالسازی"; $GLOBALS['strConvert'] = "تبدیل"; $GLOBALS['strRefresh'] = "بارگذاری مجدد"; $GLOBALS['strSaveChanges'] = "ذخیره تغییرات"; $GLOBALS['strUp'] = "بالا"; $GLOBALS['strDown'] = "پایین"; $GLOBALS['strSave'] = "ذخیره"; $GLOBALS['strCancel'] = "لغوکردن"; $GLOBALS['strPrevious'] = "قبلی"; $GLOBALS['strNext'] = "بعدی"; $GLOBALS['strYes'] = "بله"; $GLOBALS['strNo'] = "خیر"; $GLOBALS['strNone'] = "خالی"; $GLOBALS['strCustom'] = "س�?ارشی"; $GLOBALS['strDefault'] = "پیش �?رض"; $GLOBALS['strUnknown'] = "مجهول"; $GLOBALS['strUnlimited'] = "نامحدود"; $GLOBALS['strUntitled'] = "بدون عنوان"; $GLOBALS['strAverage'] = "میانگین"; $GLOBALS['strOverall'] = "کلی"; $GLOBALS['strTotal'] = "جمع کل"; $GLOBALS['strFrom'] = "توسط"; $GLOBALS['strTo'] = "به"; $GLOBALS['strLinkedTo'] = "لینک به"; $GLOBALS['strDaysLeft'] = "روزهای مانده"; $GLOBALS['strCheckAllNone'] = "انتخاب همه / هیچکدام"; $GLOBALS['strExpandAll'] = "<u>همه باز</u>"; $GLOBALS['strCollapseAll'] = "<u>همه بسته</u>"; $GLOBALS['strShowAll'] = "نمایش همه"; $GLOBALS['strNoAdminInterface'] = "سرور از کار ا�?تاده است..."; $GLOBALS['strFieldContainsErrors'] = ":این ردی�?ها دارای خطا می باشد آن را اصلاح نمایید"; $GLOBALS['strFieldFixBeforeContinue1'] = "قبل از ادامه شما نیازمند این هستید که"; $GLOBALS['strFieldFixBeforeContinue2'] = "برای اصلاح این خطاها"; $GLOBALS['strMiscellaneous'] = "گوناگون"; $GLOBALS['strCollectedAllStats'] = "همه آمار"; $GLOBALS['strCollectedToday'] = "امروز"; $GLOBALS['strCollectedYesterday'] = "دیروز"; $GLOBALS['strCollectedThisWeek'] = "این ه�?ته"; $GLOBALS['strCollectedLastWeek'] = "ه�?ته گذشته"; $GLOBALS['strCollectedThisMonth'] = "این ماه"; $GLOBALS['strCollectedLastMonth'] = "ماه گذشته"; $GLOBALS['strCollectedLast7Days'] = "ه�?ت روز پیش"; $GLOBALS['strCollectedSpecificDates'] = "تاریخ مشخص"; $GLOBALS['strValue'] = "قیمت"; $GLOBALS['strWarning'] = "اخطار"; $GLOBALS['strNotice'] = "توجه"; // Dashboard // Dashboard Errors // Priority $GLOBALS['strPriority'] = "اولویت"; $GLOBALS['strPriorityLevel'] = "درجه اولویت"; $GLOBALS['strHighAds'] = "High-Priority Advertisements"; $GLOBALS['strLowAds'] = "Low-Priority Advertisements"; $GLOBALS['strLimitations'] = "محدودیت ها"; $GLOBALS['strNoLimitations'] = "هیچ محدودتی وارد نشده"; $GLOBALS['strCapping'] = "محدود کردن"; // Properties $GLOBALS['strName'] = "نام"; $GLOBALS['strSize'] = "سایز"; $GLOBALS['strWidth'] = "عرض"; $GLOBALS['strHeight'] = "ارت�?اع"; $GLOBALS['strTarget'] = "هد�?"; $GLOBALS['strLanguage'] = "زبان"; $GLOBALS['strDescription'] = "توصی�?"; $GLOBALS['strVariables'] = "متغییر"; $GLOBALS['strID'] = "شناسه"; $GLOBALS['strComments'] = "توضیحات"; // User access $GLOBALS['strLinkUserHelpUser'] = "نام کاربری"; // Login & Permissions $GLOBALS['strUserProperties'] = "تنظیمات بنر"; $GLOBALS['strAuthentification'] = "اجازه کاربری"; $GLOBALS['strWelcomeTo'] = "خوش آمدید به "; $GLOBALS['strEnterUsername'] = "کلمه کاربری و رمز خود را برای ورود وارد کنید"; $GLOBALS['strEnterBoth'] = "لط�?ا کلمه کاربری و رمز ورود را وارد کنید"; $GLOBALS['strLogin'] = "ورود به سیستم"; $GLOBALS['strLogout'] = "خروج"; $GLOBALS['strUsername'] = "نام کاربری"; $GLOBALS['strPassword'] = "رمز "; $GLOBALS['strPasswordRepeat'] = "تکرار پسورد"; $GLOBALS['strAccessDenied'] = "دسترسی مجاز نیست"; $GLOBALS['strUsernameOrPasswordWrong'] = "نام کاربری و/یا رمز اشتباه است لط�?ا مجددا تلاش کنید ."; $GLOBALS['strPasswordWrong'] = "رمز ورود صحیح نمی باشد."; $GLOBALS['strNotAdmin'] = "ممکن است شما دسترسی کا�?ی به کل امکانات نداشته باشید."; $GLOBALS['strDuplicateClientName'] = "این نام کاربری موجود می باشد. نام کاربری دیگری را انتخاب کنید.."; $GLOBALS['strInvalidPassword'] = "این رمز ورود معتبر نمی باشد. رمز ورود دیگری را انتخاب کنید."; $GLOBALS['strNotSamePasswords'] = "رمز های ورود وارد شده شبیه به هم نمی باشند"; $GLOBALS['strRepeatPassword'] = "تکرار رمز"; // General advertising $GLOBALS['strRequests'] = "درخواست ها"; $GLOBALS['strImpressions'] = "تاثیرات"; $GLOBALS['strClicks'] = "کلیک ها"; $GLOBALS['strConversions'] = "تغییرات"; $GLOBALS['strCTR'] = "CTR"; $GLOBALS['strTotalClicks'] = "کل کلیکها"; $GLOBALS['strTotalConversions'] = "کل تغییرات"; $GLOBALS['strDateTime'] = "زمان تاریخ"; $GLOBALS['strTrackerID'] = "شناسه رهگیری"; $GLOBALS['strTrackerName'] = "نام رهگیری"; $GLOBALS['strBanners'] = "بنرها"; $GLOBALS['strCampaigns'] = "داخلی"; $GLOBALS['strCampaignID'] = "شناسه Campaign"; $GLOBALS['strCampaignName'] = "نام Campaign"; $GLOBALS['strCountry'] = "کشور"; $GLOBALS['strStatsAction'] = "اقدام"; $GLOBALS['strWindowDelay'] = "پنجره تاخیر"; $GLOBALS['strStatsVariables'] = "متغییر"; // Finance $GLOBALS['strFinanceMT'] = "مدت اجاره هر ماه"; // Time and date related $GLOBALS['strDate'] = "تاریخ"; $GLOBALS['strDay'] = "روز"; $GLOBALS['strDays'] = "روزها"; $GLOBALS['strWeek'] = "ه�?ته"; $GLOBALS['strWeeks'] = "ه�?ته ها"; $GLOBALS['strSingleMonth'] = "ماه"; $GLOBALS['strMonths'] = "ماهها"; $GLOBALS['strDayOfWeek'] = "روز و ه�?ته"; $GLOBALS['strDayFullNames'] = array(); $GLOBALS['strDayShortCuts'] = array(); $GLOBALS['strHour'] = "ساعت"; $GLOBALS['strSeconds'] = "ثانیه"; $GLOBALS['strMinutes'] = "دقیقه ها"; $GLOBALS['strHours'] = "ساعتها"; // Advertiser $GLOBALS['strClient'] = "آگهی دهنده"; $GLOBALS['strClients'] = "آگهی دهندگان"; $GLOBALS['strClientsAndCampaigns'] = "نمایش در یک نگاه"; $GLOBALS['strAddClient'] = "اضا�?ه کردن آگهی دهنده"; $GLOBALS['strClientProperties'] = "تنظیمات آگهی دهندگان"; $GLOBALS['strClientHistory'] = "تاریخچه آگهی دهندگان"; $GLOBALS['strConfirmDeleteClient'] = "آیا شما واقعا میخواهید این تبلیغ کننده را حذ�? کنید؟"; $GLOBALS['strConfirmDeleteClients'] = "آیا شما واقعا میخواهید این تبلیغ کننده را حذ�? کنید؟"; $GLOBALS['strHideInactive'] = "غیر�?عال مخ�?ی"; $GLOBALS['strInactiveAdvertisersHidden'] = "مخ�?ی بودن آگهی دهندگان غیر�?عال"; $GLOBALS['strAdvertiserCampaigns'] = "نمایش در یک نگاه"; // Advertisers properties $GLOBALS['strContact'] = "تماس"; $GLOBALS['strEMail'] = "ایمیل"; $GLOBALS['strSendAdvertisingReport'] = "گزارش هر تغییر داخلی ایمیل شود"; $GLOBALS['strNoDaysBetweenReports'] = "ارسال گزارش عملکرد داخلی بعد از گذشت چند روز ارسال شود"; $GLOBALS['strSendDeactivationWarning'] = "به صورت اتوماتیک �?عال و غیر�?عال شود"; $GLOBALS['strAllowClientModifyBanner'] = "مجاز بودن کاربر برای تغییر بنرهای شخصی خود"; $GLOBALS['strAllowClientDisableBanner'] = "مجاز بودن کاربر برای غیر�?عال کردن بنرهای شخصی خود"; $GLOBALS['strAllowClientActivateBanner'] = "مجاز بودن کاربر برای �?عال کردن بنرهای شخصی خود"; // Campaign $GLOBALS['strCampaign'] = "داخلی"; $GLOBALS['strCampaigns'] = "داخلی"; $GLOBALS['strAddCampaign'] = "اضا�?ه کردن داخلی"; $GLOBALS['strAddCampaign_Key'] = "اضا�?ه کردن داخلی جدید"; $GLOBALS['strLinkedCampaigns'] = "لینکهای داخلی"; $GLOBALS['strCampaignProperties'] = "تنظیمات داخلی"; $GLOBALS['strCampaignOverview'] = "نمایش داخلی"; $GLOBALS['strCampaignHistory'] = "تاریخچه انتقالی"; $GLOBALS['strNoCampaigns'] = "در حال حاضر هیچ campaigns تعری�? نشده است."; $GLOBALS['strConfirmDeleteCampaign'] = "آیا واقعا میخواهید این campaignرا حذ�? کنید؟"; $GLOBALS['strConfirmDeleteCampaigns'] = "آیا واقعا میخواهید این campaignرا حذ�? کنید؟"; $GLOBALS['strShowParentAdvertisers'] = "نمایش منشا آگهی دهندگان"; $GLOBALS['strHideParentAdvertisers'] = "مخ�?ی بودن منشا آگهی دهندگان"; $GLOBALS['strHideInactiveCampaigns'] = "مخ�?ی کردن داخلی های غیر�?عال"; $GLOBALS['strInactiveCampaignsHidden'] = "مخ�?ی بودن داخلی های غیر�?عال"; $GLOBALS['strPriorityInformation'] = "اطلاعات اولویت"; $GLOBALS['strHiddenCampaign'] = "داخلی"; $GLOBALS['strHiddenAd'] = "آگهی دهندگان"; $GLOBALS['strHiddenAdvertiser'] = "آگهی دهنده"; $GLOBALS['strHiddenTracker'] = "تراکر"; $GLOBALS['strHiddenWebsite'] = "ناشر"; $GLOBALS['strHiddenZone'] = "ناحیه"; $GLOBALS['strCompanionPositioning'] = "همراه با موقعیت"; $GLOBALS['strSelectUnselectAll'] = "انتخاب / انتخاب همه"; // Campaign-zone linking page // Campaign properties $GLOBALS['strDontExpire'] = "غیر�?عال شدن بعد از گذشت زمان خاص"; $GLOBALS['strActivateNow'] = "�?عال کردن سریع داخلی"; $GLOBALS['strLow'] = "پایین"; $GLOBALS['strHigh'] = "بالا"; $GLOBALS['strExpirationDate'] = "تاریخ اتمام"; $GLOBALS['strExpirationDateComment'] = "اتمام در این تاریخ"; $GLOBALS['strActivationDate'] = "تاریخ شروع"; $GLOBALS['strActivationDateComment'] = "آغاز �?عالیت در این تاریخ"; $GLOBALS['strImpressionsRemaining'] = "آثار باقیمانده"; $GLOBALS['strClicksRemaining'] = "کلیکهای باقیمانده"; $GLOBALS['strConversionsRemaining'] = "تغییرات باقیمانده"; $GLOBALS['strImpressionsBooked'] = "آثار"; $GLOBALS['strClicksBooked'] = "کلیک ها"; $GLOBALS['strConversionsBooked'] = "تغییرات"; $GLOBALS['strCampaignWeight'] = "هیچ - هماهنگ نیست با حجم داخلی"; $GLOBALS['strAnonymous'] = "مخ�?ی کردن آگهی دهندگان و ناشران در نمایش داخلی"; $GLOBALS['strTargetPerDay'] = "در هر روز ."; $GLOBALS['strCampaignStatusInactive'] = "�?عال"; $GLOBALS['strCampaignStatusDeleted'] = "حذ�?"; $GLOBALS['strCampaignType'] = "نام Campaign"; $GLOBALS['strContract'] = "تماس"; $GLOBALS['strStandardContract'] = "تماس"; // Tracker $GLOBALS['strTracker'] = "تراکر"; $GLOBALS['strTrackers'] = "تراکر"; $GLOBALS['strAddTracker'] = "اضا�?ه کردن تراکر"; $GLOBALS['strNoTrackers'] = "تا به این لطحه تراکری تعری�? نشده است "; $GLOBALS['strConfirmDeleteTrackers'] = "آیا شما واقعا میخواهید این بنر را حذ�? کنید."; $GLOBALS['strConfirmDeleteTracker'] = "آیا شما واقعا میخواهید این بنر را حذ�? کنید."; $GLOBALS['strTrackerProperties'] = "تنظیمات تراکر"; $GLOBALS['strDefaultStatus'] = "وضعیت پیش �?رض"; $GLOBALS['strStatus'] = "وضعیت"; $GLOBALS['strLinkedTrackers'] = "لینکهای تراکرها"; $GLOBALS['strConversionWindow'] = "پنجره تغییر"; $GLOBALS['strUniqueWindow'] = "پنجره انحصاری"; $GLOBALS['strClick'] = "کلیک"; $GLOBALS['strView'] = "نمایش"; $GLOBALS['strLinkCampaignsByDefault'] = "آخرین پیوندی که توسط داخلی ساخته شده به صورت پیش �?رض باشد"; // Banners (General) $GLOBALS['strBanner'] = "بنر"; $GLOBALS['strBanners'] = "بنرها"; $GLOBALS['strAddBanner'] = "اضا�?ه کردن بنر"; $GLOBALS['strAddBanner_Key'] = "اضا�?ه کردن بنر جدید"; $GLOBALS['strShowBanner'] = "نمایش بنر"; $GLOBALS['strBannerProperties'] = "تنظیمات بنر"; $GLOBALS['strBannerHistory'] = "تاریخچه بنر"; $GLOBALS['strNoBanners'] = "هیچ بنری تعری�? نشده است"; $GLOBALS['strConfirmDeleteBanner'] = "آیا شما واقعا میخواهید این بنر را حذ�? کنید."; $GLOBALS['strConfirmDeleteBanners'] = "آیا شما واقعا میخواهید این بنر را حذ�? کنید."; $GLOBALS['strShowParentCampaigns'] = "نمایش campaign های پدر"; $GLOBALS['strHideParentCampaigns'] = "مخ�?ی کردن campaign های پدر"; $GLOBALS['strHideInactiveBanners'] = "مخ�?ی سازی بنرهای غیر�?عال"; $GLOBALS['strInactiveBannersHidden'] = "مخ�?ی سازی بنرهای غیر�?عال"; $GLOBALS['strWarningMissingClosing'] = " closing tag \">\""; $GLOBALS['strWarningMissingOpening'] = " opening tag \"<\""; $GLOBALS['strSubmitAnyway'] = "ذخیره سازی"; // Banner Preferences // Banner (Properties) $GLOBALS['strChooseBanner'] = "لط�?ا نوع بنر خود را از منو زیر انتخاب کنید"; $GLOBALS['strMySQLBanner'] = "بنر لوکال SQL"; $GLOBALS['strWebBanner'] = "بنر لوکال وب سرور"; $GLOBALS['strURLBanner'] = "بنر بیرونی"; $GLOBALS['strHTMLBanner'] = "بنر اچ تی ام ال"; $GLOBALS['strTextBanner'] = "تبلیغ متنی"; $GLOBALS['strUploadOrKeep'] = "آیا میخواهید تصویر موجود را نگه دارید و یا اینکه میخواهید بنر دیگری را آپلود کنید؟"; $GLOBALS['strNewBannerFile'] = "انتخاب عکس برای آپلود بنر"; $GLOBALS['strURL'] = "آدرس لینک بنر"; $GLOBALS['strKeyword'] = "کلمات کلیدی"; $GLOBALS['strTextBelow'] = "متن عکس"; $GLOBALS['strWeight'] = "حجم"; $GLOBALS['strAlt'] = "همه تکستها"; $GLOBALS['strStatusText'] = "وضعیت متن"; $GLOBALS['strBannerWeight'] = "حجم بنر"; $GLOBALS['strGenericOutputAdServer'] = "عمومی"; $GLOBALS['strSwfTransparency'] = "Transparent background (Flash-only)"; // Banner (advanced) // Banner (swf) $GLOBALS['strCheckSWF'] = "بررسی لینک های رمزی شده مشکل درون �?ایل �?لش"; $GLOBALS['strConvertSWFLinks'] = "تبدیل لینک �?لش"; $GLOBALS['strHardcodedLinks'] = "لینک های رمزی شده مشکل"; $GLOBALS['strCompressSWF'] = "�?شرده سازی �?ایل SWF برای سریعتر دانلود شدن (�?لش پلیر 6 مورد نیاز است)"; $GLOBALS['strOverwriteSource'] = "بازنویسی سورس پارامتر"; // Display limitations $GLOBALS['strModifyBannerAcl'] = "تنظیمات نمایش"; $GLOBALS['strACL'] = "تحویل"; $GLOBALS['strACLAdd'] = "اضا�?ه کردن محدودیت های جدید"; $GLOBALS['strNoLimitations'] = "هیچ محدودتی وارد نشده"; $GLOBALS['strApplyLimitationsTo'] = "بکارگیری محدودیت ها برای"; $GLOBALS['strRemoveAllLimitations'] = "حذ�? تمام محدودیت ها"; $GLOBALS['strEqualTo'] = "مساوی است با"; $GLOBALS['strDifferentFrom'] = "مت�?اوت است از"; $GLOBALS['strGreaterThan'] = "پس از"; $GLOBALS['strAND'] = "و"; // logical operator $GLOBALS['strOR'] = "یا"; // logical operator $GLOBALS['strOnlyDisplayWhen'] = "�?قط نمایش این بنر وقتی که:"; $GLOBALS['strWeekDays'] = "روز ه�?ته"; $GLOBALS['strSource'] = "منشا"; $GLOBALS['strDeliveryLimitations'] = "محدودیتهای نمایش"; $GLOBALS['strDeliveryCappingReset'] = "ریستارت مجدد پس از گذشت زمان : "; $GLOBALS['strDeliveryCappingTotal'] = "در کل"; $GLOBALS['strDeliveryCappingSession'] = "در هر ثانیه"; $GLOBALS['strCappingBanner'] = array(); $GLOBALS['strCappingBanner']['limit'] = "حد نمایش بنر به : "; $GLOBALS['strCappingCampaign'] = array(); $GLOBALS['strCappingCampaign']['limit'] = "حد داخلی نمایش به : "; $GLOBALS['strCappingZone'] = array(); $GLOBALS['strCappingZone']['limit'] = "حد ناحیه نمایش به : "; // Website $GLOBALS['strAffiliate'] = "ناشر"; $GLOBALS['strAffiliates'] = "ناشران"; $GLOBALS['strAffiliatesAndZones'] = "انتشار دسته ها"; $GLOBALS['strAddNewAffiliate'] = "اضا�?ه کردن ناشر"; $GLOBALS['strAffiliateProperties'] = "تنظیمات ناشر"; $GLOBALS['strAffiliateHistory'] = "تاریخچه ناشر"; $GLOBALS['strNoAffiliates'] = "هیچ ناشری تعری�? نشده است"; $GLOBALS['strConfirmDeleteAffiliate'] = "آیا شما واقعا میخواهید این ناشر را حذ�? کنید؟"; $GLOBALS['strConfirmDeleteAffiliates'] = "آیا شما واقعا میخواهید این ناشر را حذ�? کنید؟"; $GLOBALS['strInactiveAffiliatesHidden'] = "مخ�?ی بودن ناشران غیر �?عال"; $GLOBALS['strShowParentAffiliates'] = "نمایش منشا ناشرین"; $GLOBALS['strHideParentAffiliates'] = "مخ�?ی کردن منشا ناشرین"; // Website (properties) $GLOBALS['strWebsite'] = "ناشر"; $GLOBALS['strAllowAffiliateModifyZones'] = "مجاز بودن کاربر برای تغییر ناحیه خود"; $GLOBALS['strAllowAffiliateLinkBanners'] = "مجاز بودن کاربر برای قراردادن لینک بنرهای خود در ناحیه ها"; $GLOBALS['strAllowAffiliateAddZone'] = "مجاز بودن کاربر برای تعری�? ناحیه جدید"; $GLOBALS['strAllowAffiliateDeleteZone'] = "مجاز بودن کاربر برای حذ�? ناحیه های موجود"; $GLOBALS['strAllowAffiliateGenerateCode'] = "مجاز بودن کاربر برای ساخت کد خروجی"; // Website (properties - payment information) $GLOBALS['strPostcode'] = "کدپستی"; $GLOBALS['strCountry'] = "کشور"; // Website (properties - other information) $GLOBALS['strWebsiteZones'] = "انتشار دسته ها"; // Zone $GLOBALS['strZone'] = "ناحیه"; $GLOBALS['strZones'] = "ناحیه ها"; $GLOBALS['strAddNewZone'] = "ساخت ناحیه جدید"; $GLOBALS['strAddNewZone_Key'] = "اضا�?ه کردن ناحیه جدید"; $GLOBALS['strZoneToWebsite'] = "همه ناشرین"; $GLOBALS['strLinkedZones'] = "ناحیه پیوند"; $GLOBALS['strZoneProperties'] = "تنظیمات ناحیه"; $GLOBALS['strZoneHistory'] = "تاریخچه ناحیه"; $GLOBALS['strNoZones'] = "هیچ ناحیه ای تعری�? نشده است"; $GLOBALS['strConfirmDeleteZone'] = "آیا شما واقعا میخواهید این ناحیه را حذ�? کنید؟"; $GLOBALS['strConfirmDeleteZones'] = "آیا شما واقعا میخواهید این ناحیه را حذ�? کنید؟"; $GLOBALS['strZoneType'] = "نوع ناحیه"; $GLOBALS['strBannerButtonRectangle'] = "بنر , دکمه و یا مستطیل"; $GLOBALS['strInterstitial'] = "DHTML درون شبکه ای یا معلق"; $GLOBALS['strPopup'] = "پاپ اپ"; $GLOBALS['strTextAdZone'] = "تبلیغ متنی"; $GLOBALS['strEmailAdZone'] = "ناحیه ایمیل و خبرنامه"; $GLOBALS['strShowMatchingBanners'] = "نمایش برنهای تطبیقی"; $GLOBALS['strHideMatchingBanners'] = "مخ�?ی کردن بنرهای تطبیقی"; $GLOBALS['strBannerLinkedAds'] = "لینک بنرها در داخلی"; $GLOBALS['strCampaignLinkedAds'] = "لینکهای ناحیه های داخلی"; $GLOBALS['strInactiveZonesHidden'] = "مخ�?ی کردن ناحیه های غیر�?عال"; // Advanced zone settings $GLOBALS['strAdvanced'] = "پیشر�?ته"; $GLOBALS['strChainSettings'] = "تنظیمات کادر"; $GLOBALS['strZoneNoDelivery'] = "اگر بنری در ناحیه وجود نداشت شما می توانید خروجی را مشاهده کنید"; $GLOBALS['strZoneStopDelivery'] = "از کار انداختن و و نمایش ندادن بنر"; $GLOBALS['strZoneOtherZone'] = "نمایش و انتخاب محدوده"; $GLOBALS['strZoneAppend'] = "همیشه اضا�?ه کن این کد را در ناحیه بنرها"; $GLOBALS['strAppendSettings'] = "تنظیمات اضا�?ه کردن و پیش بینی"; $GLOBALS['strZonePrependHTML'] = "کد HTML زیر را همیشه با متن تبلیغاتی در این ناحیه نشان داده شود"; $GLOBALS['strZoneAppendNoBanner'] = "اضا�?ه کردن حتی اگر بنری وجود نداشته باشد در خروجی"; // Zone probability $GLOBALS['strZoneProbListChain'] = "همه بنرهای لینک شده به منطقه انتخاب شده در حال حاضر �?عال نیستند. <"; $GLOBALS['strZoneProbNullPri'] = "تا به حال لینک بنری در این ناحیه �?عال نشده است ."; $GLOBALS['strZoneProbListChainLoop'] = "."; // Linked banners/campaigns/trackers $GLOBALS['strSelectZoneType'] = "لط�?ا لینک ناحیه را انتخاب کنید"; $GLOBALS['strLinkedBanners'] = "لینک بنرهای شخصی"; $GLOBALS['strCampaignDefaults'] = "لینک بنرهای منشا داخلی"; $GLOBALS['strRawQueryString'] = "کلمات کلیدی"; $GLOBALS['strIncludedBanners'] = "بنرهای لینک شده"; $GLOBALS['strMatchingBanners'] = "نمایش برنهای تطبیقی"; $GLOBALS['strNoCampaignsToLink'] = "تا این زمان هنوز تراکری که امکان لینک در داخلی داشته باشد �?عال نشده"; $GLOBALS['strNoTrackersToLink'] = "تا این زمان هنوز تراکری که امکان لینک در داخلی داشته باشد �?عال نشده"; $GLOBALS['strSelectBannerToLink'] = "بنری را که می خواهید به این ناحیه لینک کنید را انتخاب نمایید:"; $GLOBALS['strSelectCampaignToLink'] = "را که می خواهید به این ناحیه لینک کنید را انتخاب نمایید:"; $GLOBALS['strSelectAdvertiser'] = "انتخاب آگهی دهنده"; $GLOBALS['strSelectPlacement'] = "انتخاب داخلی"; $GLOBALS['strSelectAd'] = "انتخاب بنر"; $GLOBALS['strConnectionType'] = "پسوند"; $GLOBALS['strStatusDuplicate'] = "همسان"; $GLOBALS['strConnectionType'] = "پسوند"; $GLOBALS['strShortcutEditStatuses'] = "ویرایش وضعیت"; $GLOBALS['strShortcutShowStatuses'] = "نمایش وضعیت"; // Statistics $GLOBALS['strStats'] = "آمار سایت"; $GLOBALS['strGlobalHistory'] = "تاریخچه کلی"; $GLOBALS['strDailyHistory'] = "نتایج روزانه"; $GLOBALS['strDailyStats'] = "آمار روزانه"; $GLOBALS['strWeeklyHistory'] = "نتایج ه�?تگی"; $GLOBALS['strMonthlyHistory'] = "نتایج ماهیانه"; $GLOBALS['strPublisherDistribution'] = "Publisher distribution"; $GLOBALS['strCampaignDistribution'] = "Campaign distribution"; $GLOBALS['strViewBreakdown'] = "نمایش به"; $GLOBALS['strBreakdownByDay'] = "روز"; $GLOBALS['strBreakdownByWeek'] = "ه�?ته"; $GLOBALS['strBreakdownByMonth'] = "ماه"; $GLOBALS['strBreakdownByDow'] = "روز و ه�?ته"; $GLOBALS['strBreakdownByHour'] = "ساعت"; $GLOBALS['strItemsPerPage'] = "آیتم ها در هر ص�?حه"; $GLOBALS['strExportStatisticsToExcel'] = "خروجی آمار به صورت �?ایل اگسل"; // Expiration $GLOBALS['strNoExpiration'] = "تا به حال انقضا نداشته"; $GLOBALS['strEstimated'] = "تحمین انقضا"; $GLOBALS['strCampaignStop'] = "تاریخچه انتقالی"; // Reports $GLOBALS['strLimitations'] = "محدودیت ها"; // Admin_UI_Fields $GLOBALS['strAllAdvertisers'] = "همه مشتریان"; $GLOBALS['strAnonAdvertisers'] = "آگهی دهندگان بی نام"; $GLOBALS['strAllPublishers'] = "همه ناشرین"; $GLOBALS['strAnonPublishers'] = "ناشرین بی نام"; $GLOBALS['strAllAvailZones'] = "همه مجموعه های �?عال"; // Userlog $GLOBALS['strUserLog'] = "گزارش روزانه کاربر"; $GLOBALS['strUserLogDetails'] = "جزییات کاربر"; $GLOBALS['strDeleteLog'] = "حذ�? کاربر"; $GLOBALS['strAction'] = "اقدام"; // Code generation $GLOBALS['strGenerateBannercode'] = "انتخاب مستقیم"; $GLOBALS['strChooseInvocationType'] = "لط�?ا پسوند خروجی را انتخاب کنید"; $GLOBALS['strGenerate'] = "تولیدکردن"; $GLOBALS['strParameters'] = "پارامترها"; $GLOBALS['strFrameSize'] = "سایز �?ریم"; $GLOBALS['strBannercode'] = "کد خروجی بنر"; $GLOBALS['strTrackercode'] = "کد خروجی تراکر"; $GLOBALS['strBackToTheList'] = "بازگشت به لیست گزارشات"; // Errors $GLOBALS['strNoMatchesFound'] = "هیچ تطبیقی پیدا نشد"; $GLOBALS['strErrorOccurred'] = "یک خطا رخ داده است"; $GLOBALS['strErrorDBPlain'] = "یک خطا در طی دسترسی به بانک اطلاعاتی رخ داده است"; $GLOBALS['strErrorDBSerious'] = "یک مشکل جدی هنگام دسترسی و شناسایی بانک اطلاعاتی رخ داده است"; $GLOBALS['strErrorDBCorrupt'] = "جداول بانک اطلاعاتی احتمالا خراب شده اند و نیاز به تعمیر دارند. برای اطلاعات بیشتر راهنمای برنامه را مطالعه نمایید."; $GLOBALS['strErrorDBContact'] = "با مدیریت سرور تماس بگیرید و این مشکل را حل نمایید."; $GLOBALS['strDatesConflict'] = "dates conflict with:"; //Validation // Email $GLOBALS['strSirMadam'] = "آقا/خانوم"; $GLOBALS['strMailSubject'] = "گزارش آگهی دهندگان"; $GLOBALS['strMailBannerStats'] = "در زیر آمار بنر ها برای {clientname}آورده شده است:"; $GLOBALS['strMailBannerActivatedSubject'] = "Campaign {id} �?عال شده است"; $GLOBALS['strMailBannerDeactivatedSubject'] = "Campaign {id} �?عال شده است"; $GLOBALS['strClientDeactivated'] = "این در حال حاضر �?عال نمی باشد زیرا"; $GLOBALS['strBeforeActivate'] = "تاریخ �?عال سازی هنوز �?را نرسیده است"; $GLOBALS['strAfterExpire'] = "تاریخ انقضاء �?رارسیده است"; $GLOBALS['strTargetIsNull'] = "its target is set to zero"; $GLOBALS['strNoViewLoggedInInterval'] = "هیچ مشاهده تبلیغاتی در طول این گزارش ثبت نشده است"; $GLOBALS['strNoClickLoggedInInterval'] = "هیچ کلیک تبلیغاتی در طول این گزارش ثبت نشده است"; $GLOBALS['strNoConversionLoggedInInterval'] = "هیچ مشاهده تبلیغاتی در طول این گزارش ثبت نشده است"; $GLOBALS['strMailReportPeriod'] = "این گزارش شامل آماری از {startdate} تا {enddate}می باشد."; $GLOBALS['strMailReportPeriodAll'] = "این گزارش شامل�? همه آمار تا {enddate} می باشد."; $GLOBALS['strNoStatsForCampaign'] = "هیچ آماری برای این موجود نمی باشد"; // Priority $GLOBALS['strPriority'] = "اولویت"; $GLOBALS['strSourceEdit'] = "ویرایش منشا"; // Preferences $GLOBALS['strPreferences'] = "پیش تنظیمات"; // Long names $GLOBALS['strImpressionSR'] = "آثار"; // Short names $GLOBALS['strID_short'] = "شناسه"; $GLOBALS['strClicks_short'] = "کلیک ها"; // Global Settings $GLOBALS['strGlobalSettings'] = "تنظیمات عمومی"; $GLOBALS['strGeneralSettings'] = "تنظیمات عمومی"; $GLOBALS['strMainSettings'] = "تنظیمات اصلی"; // Product Updates $GLOBALS['strProductUpdates'] = "به روز رسانی محصولات"; // Agency $GLOBALS['strAgencyManagement'] = "مدیریت نمایندگی"; $GLOBALS['strAgency'] = "نمایندگی"; $GLOBALS['strAddAgency'] = "ا�?زودن نماندگی"; $GLOBALS['strAddAgency_Key'] = "اضا�?ه کردن ناحیه جدید"; $GLOBALS['strTotalAgencies'] = "کل نمایندگی ها"; $GLOBALS['strAgencyProperties'] = "تنظیمات نمایندگی"; $GLOBALS['strNoAgencies'] = "هیچ ناحیه ای تعری�? نشده است"; $GLOBALS['strConfirmDeleteAgency'] = "آیا شما واقعا میخواهید این ناحیه را حذ�? کنید؟"; $GLOBALS['strHideInactiveAgencies'] = "مخ�?ی کردن نمانیندگی های غیر�?عال"; $GLOBALS['strInactiveAgenciesHidden'] = "مخ�?ی کردن ناحیه های غیر�?عال"; // Channels $GLOBALS['strChannel'] = "خط مشی"; $GLOBALS['strChannels'] = "خط مشی ها"; $GLOBALS['strChannelManagement'] = "مدیریت خط مشی"; $GLOBALS['strAddNewChannel'] = "ا�?زودن خط مشی"; $GLOBALS['strAddNewChannel_Key'] = "ساختن خط مشی جدید"; $GLOBALS['strChannelToWebsite'] = "همه ناشرین"; $GLOBALS['strNoChannels'] = "خط مشی تا به حال وارد نشده"; $GLOBALS['strEditChannelLimitations'] = "ویرایش محدودیت خط مشی"; $GLOBALS['strChannelProperties'] = "تنظیمات خط مشی"; $GLOBALS['strChannelLimitations'] = "تنظیمات نمایش"; $GLOBALS['strConfirmDeleteChannel'] = "آیا شما واقعا میخواهید این بنر را حذ�? کنید."; $GLOBALS['strConfirmDeleteChannels'] = "آیا شما واقعا میخواهید این بنر را حذ�? کنید."; // Tracker Variables $GLOBALS['strVariableDescription'] = "توصی�?"; $GLOBALS['strVariableDataType'] = "پسوند تاریخ"; $GLOBALS['strVariablePurpose'] = "زمینه"; $GLOBALS['strGeneric'] = "عمومی"; $GLOBALS['strNumber'] = "تعداد"; $GLOBALS['strString'] = "ریشه"; $GLOBALS['strTrackerType'] = "نام تراکر"; // Password recovery $GLOBALS['strForgotPassword'] = "پسورد خود را �?راموش کردید ؟ "; $GLOBALS['strPasswordRecovery'] = "بازیابی پسورد"; $GLOBALS['strEmailRequired'] = "نیاز بودن آدرس ایمیل برای ارسال"; $GLOBALS['strPwdRecEmailNotFound'] = "همچین آدرس ایمیلی وجود ندارد"; $GLOBALS['strPwdRecWrongId'] = "آی دی اشتباه"; $GLOBALS['strPwdRecEnterEmail'] = "آدرس ایمیل خود را برای بازیابی پسورد وارد کنید"; $GLOBALS['strPwdRecEnterPassword'] = "Enter your new password address below"; $GLOBALS['strPwdRecResetLink'] = "پسورد تغییر کرد"; $GLOBALS['strPwdRecEmailPwdRecovery'] = "بازیابی پسورد"; $GLOBALS['strProceed'] = "اقدام کردن &gt;"; // Audit // Widget - Audit // Widget - Campaign //confirmation messages // Report error messages /* ------------------------------------------------------- */ /* Keyboard shortcut assignments */ /* ------------------------------------------------------- */ // Reserved keys // Do not change these unless absolutely needed // Other keys // Please make sure you underline the key you // used in the string in default.lang.php
BeastModeON/revive-adserver
lib/max/language/fa/default.lang.php
PHP
gpl-2.0
33,188
<?php /** * @package EasyBlog * @copyright Copyright (C) 2010 - 2014 Stack Ideas Sdn Bhd. All rights reserved. * @license GNU/GPL, see LICENSE.php * EasyBlog is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ defined('_JEXEC') or die('Unauthorized Access'); $view = ($type=='image') ? 'tile' : 'list'; $limit = 48; $count = count($files); ?> <div class="eb-mm-filegroup type-<?php echo $type; ?> <?php echo empty($count) ? 'is-empty' : ''; ?>" data-eb-mm-filegroup data-limit="<?php echo $limit; ?>"> <div class="eb-mm-filegroup-header" data-eb-mm-filegroup-header> <i class="fa fa-angle-up"></i> <div class="eb-mm-filegroup-title"><?php echo JText::_('COM_EASYBLOG_MM_FILEGROUP_TYPE_' . strtoupper($type)); ?></div> </div> <div class="eb-mm-filegroup-body"> <div class="eb-mm-filelist view-<?php echo $view; ?>" data-eb-mm-filelist> <?php foreach($files as $i => $file) { ?> <?php if ($count > $limit && $i==$limit) { ?> <div class="eb-mm-filegroup-show-all-button" data-eb-mm-filegroup-show-all-button> <?php echo JText::_('COM_EASYBLOG_MM_SHOW_ALL');?> <span data-eb-mm-filegroup-count><?php echo $count; ?></span> items</div> <div class="eb-mm-filegroup-more"> <?php } ?> <?php // For performance reasons (~150ms faster), this is hardcoded. An almost identical copy of can be found at 'site/mediamanager/file' used by renderFile(). ?> <div class="eb-mm-file type-<?php echo $file->type; ?><?php echo empty($file->extension) ? '' : ' ext-' . $file->extension; ?>" data-eb-mm-file data-key="<?php echo $file->key; ?>" data-type="<?php echo $file->type; ?>"> <i class="<?php echo $file->icon; ?>" <?php if (isset($file->thumbnail)) { ?> data-thumbnail="<?php echo $file->thumbnail; ?>" <?php } ?>></i> <div> <span data-eb-mm-file-title><?php echo $file->title; ?></span> </div> <?php if ($type=='folder') { ?> <b class="fa fa-angle-right"></b> <?php } ?> </div> <?php if ($count > $limit && $i==$count - 1) { ?> </div> <?php } ?> <?php } ?> </div> </div> </div>
BetterBetterBetter/B3App
components/com_easyblog/themes/wireframe/mediamanager/filegroup.php
PHP
gpl-2.0
2,783
<?PHP /** * * portal_xl_install.php [English] * * @package language for phpBB3 Portal XL * @version $Id: portal_xl_install.php,v 1.1.1.1 2009/05/15 04:03:35 portalxl group Exp $ * @copyright (c) 2008 DaMysterious * @license http://opensource.org/licenses/gpl-license.php GNU Public License * */ /** * DO NOT CHANGE */ if (!defined('IN_PHPBB')) { exit; } if (empty($lang) || !is_array($lang)) { $lang = array(); } // DEVELOPERS PLEASE NOTE // // All language files should use UTF-8 as their encoding and the files must not contain a BOM. // // Placeholders can now contain order information, e.g. instead of // 'Page %s of %s' you can (and should) write 'Page %1$s of %2$s', this allows // translators to re-order the output of data while ensuring it remains correct // // You do not need this where single placeholders are used, e.g. 'Message %d' is fine // equally where a string contains only two placeholders which are used to wrap text // in a url you again do not need to specify an order e.g., 'Click %sHERE%s' is fine $lang = array_merge($lang, array( // Portal XL Convert Procedure 'PORTAL_CONVERT' => 'Portal XL Converting', 'PORTAL_CONVERT_BASIC_FINISHED' => 'The database tables are now updated for the new text functions of the phpBB 3.<br />Not the script will convert the text themselves.<br /><br />To avoid timeout errors and malfunctions while converting the texts, the script will permanently restart itself. Please do not close the browser until the script have finished the conversion.<br /><br />But if you will get an interruption of this procedure, restart the script again to continue.<br /><br />Please be patient while the script will convert the texts and wait for the closing message, because in addition for the number of texts which must be converted, the script may take some minutes to do all the work.', 'PORTAL_CONVERT_DATABASE' => 'Convert database', 'PORTAL_CONVERT_NOT_POSSIBLE' => '<strong>Conversion not possible!</strong><br /><br />This release of Portal XL can not be converted to Portal XL 4.0 Premod as it seem not to be on recommended state.<br /><br />The release must have as minimum Portal XL <strong>Premod RC2</strong><br />Your current release carries version Portal XL <strong>%1$s</strong>.<br /><br />If your release does carrie out at least Portal XL Premod RC2, you will be able to update after.', 'PORTAL_CONVERT_PROCEDURE' => 'Currently %1$s from %2$ datasets are updated.<br /><br />Please click on the button below to continue or wait a moment till the script restarts itself.', 'PORTAL_CONVERT_TODO' => 'From on here all existing database tables in use by Portal XL 5.0 Plain will be converted to the latest workflow of Portal XL 4.0 Premod RC5.<br /><br />To start the conversion procedure, click on the button below.<br /><br />Please be patient while proceeding, because it can take some time to the number of conversions to make.', 'PORTAL_FINAL_CONVERT_STEP' => 'Conversion of all existing database tables in use by Portal XL is finished now.<br />To finish the complete procedure and using the MOD at the end there is one last step needed to do. Please click for this on the button below to do this last part.', // Portal XL Installation Procedure 'PORTAL_INSTALL' => 'Portal XL Installation', 'PORTAL_INSTALL_EXPLAIN' => '<p>Welcome to the Portal XL Installation Wizard<br />This is the installation of Portal XL. Your original insane crazy Portal for phpBB3.</p> <p>In order for this installation to work successfully the following procedures are recommended:</p> <ul> <li>Make sure you did copy/upload from archive all content of directory <strong><span style="color:#FF0000;">\root\</span></strong> to your phpBB 3.0.x root eg. <strong><span style="color:#FF0000;">\forum\</span></strong> only (you did already)!</li> </ul> <ul> <li><em><strong><span style="color:#009900;">File permissions CHMOD</span></strong></em><br /> <em>After installation you should check all CHMOD\'s on files and directories for *NIX related servers.</em><br /><br /> <strong><span style="color:#009900;">CHMOD <span style="color:#FF0000;">0644</span> into</span></strong>:<br /> config.php<br /><br /> <strong><span style="color:#009900;">CHMOD <span style="color:#FF0000;">666</span> into</span></strong>:<br /> /images/counter/ip.txt<br /><br /> <strong><span style="color:#009900;">CHMOD <span style="color:#FF0000;">755</span> into</span></strong>:<br /> /cache<br /> /store<br /> /files<br /> /images/avatars/upload<br /> </li> </ul> <p>To begin the installation choose Yes and press the button.</p>', 'PORTAL_INSTALL_NEXT' => 'The database tables are now successfull created.<br /><br />Click on the button below to run the next step for writing the default values into these tables.', 'PORTAL_INSTALL_FINISHED' => 'Portal XL Installation finished', 'PORTAL_INSTALL_INTRO' => 'Welcome to the Portal XL Installation', 'PORTAL_INSTALL_FINISHED_EXPLAIN' => ' <p>You have now successfully installed Portal XL 5.0 %1$s. From here, you have several options as to what to do with your newly installed Portal XL:</p> <p><strong style="text-transform: uppercase; font-size:13px; color: #FF0000;">Note:</strong></span><br /><br /><span style="font-size:13px; color: #FF0000;">Before proceeding you must have copied/uploaded all content from within the Portal XL main archive directory <strong>\root\</strong> to your forum root.</span></p> <h2>Go live with your Portal XL!</h2> <p>Clicking the button below will take you to your Administration Control Panel (ACP). Take some time to examine the options available to you. Remember that help is available online via the <a href="http://www.portalxl.nl/forum/">Portal XL Home</a> and the <a href="http://www.portalxl.nl/forum/viewforum.php?f=1">support forums</a> for Portal XL 4.0 Premod RC5, or <a href="http://www.portalxl.nl/forum/viewforum.php?f=44">support forums</a> for Portal XL 5.0 Plain.</p><p><strong>Please now delete, move or rename the install directory before you use your board. If this directory is still present, only the Administration Control Panel (ACP) will be accessible.</strong></p>', 'PORTAL_INSTALL_NOT_POSSIBLE' => '<strong>Installation not possible!</strong><br /><br />The script found an existing installation, so you can not use the installation script again.', 'PORTAL_OVERVIEW_BODY' => 'This is the newest <strong>Free</strong> release of phpBB3 Portal XL which is a flexible and powerful portal solution for your phpBB 3.0.x forum with lots of great and advanced features.<br /><br /> This portal strives to be highly customizeable aswell as include a useful amount of addons. At the same time, we will offer a quick and efficient alternative to other phpBB3 related portal\'s. We do not claim to become a reference portal or mod for phpBB3 and we don\'t maintain to be professionals. We are modding this just for fun in our spare time, even if we are trying to do our best to have a professional looking package with as few bugs as possible and without need of any scripting knowledge required from the admin. <p>Memorable release data of phpBB3 Portal XL <ul> <li>Portal XL 5.0 RC4-Plain (26-02-2008 first release Plain version by user request)</li> <li>Portal XL 5.0 Plain (12-04-2008)</li> <li>Portal XL 5.0 Plain 0.1 (31-05-2008)</li> <li>Portal XL 5.0 Plain 0.2 (31-10-2008)</li> <li>Portal XL 5.0 Plain 0.2 (01-06-2009) pbpBB 3.0.5</li> <li>Portal XL 5.0 Plain 0.2 (24-11-2009) pbpBB 3.0.6</li> <li>Portal XL 5.0 Plain 0.2 (02-03-2010) pbpBB 3.0.7</li> <li>Portal XL 5.0 Plain 0.2 (21-11-2010) pbpBB 3.0.8</li> <li>Portal XL 5.0 Plain 0.2 (12-07-2011) pbpBB 3.0.9</li> <li>Portal XL 5.0 Plain 0.2 (05-01-2012) pbpBB 3.0.10</li> <li>Portal XL 5.0 Plain 0.2 (08-27-2012) pbpBB 3.0.11</li> </ul></p><br />Please choose from the available tabs what you want to do.', 'PORTAL_SQL_UPDATE_DONE' => '<strong>Done database action:</strong><br />', 'PORTAL_SUB_SUPPORT' => 'General Portal Support', 'PORTAL_SUPPORT_BODY' => 'During the beta- / public test releases, limited support will be available at <a href="http://www.portalxl.nl/forum/" target="_blank">www.portalxl.nl</a>, this is also the place to report portal related bugs. Bear in mind that it will only be limited support, and that we will only support the latest beta- / test release, installed with the supported phpBB3 version. <br /><br />As we are unable to know what is changed/modded to your existing phpBB3 setup before, we are not able in any way to support custom changes. Remember, using this package can lead to lost of already changed code or added mod\'s.', // Portal XL Update Procedure 'PORTAL_UPDATE' => 'Portal XL Update', 'PORTAL_UPDATE_SUCCESS' => 'Congratulation!<br />The update of the database settings from the Portal XL is finished.<br /><br />You can now go on to install the remaining parts from the install instruction of Portal XL into your forum.<br /><br />Please delete the folder /install/ from your forum root to enable your forum again.', 'PORTAL_UPDATE_BASIC_FINISHED' => 'The database tables are now updated for the new text functions of the phpBB 3.<br />Not the script will convert the text themselves.<br /><br />To avoid timeout errors and malfunctions while converting the texts, the script will permanently restart itself. Please do not close the browser until the script have finished the conversion.<br /><br />But if you will get an interruption of this procedure, restart the script again to continue.<br /><br />Please be patient while the script will convert the texts and wait for the closing message, because in addition for the number of texts which must be converted, the script may take some minutes to do all the work.', 'PORTAL_UPDATE_DATABASE' => 'Update database for the Portal XL', 'PORTAL_UPDATE_NOT_POSSIBLE' => '<strong>Update not possible!</strong><br /><br />This release of Portal XL can not be updated as it seem to be on recommended state.<br /><br />Your current release carries version Portal XL 5.0 <strong>%1$s</strong>', 'PORTAL_UPDATE_PROCEDURE' => 'Currently %1$s from %2$ datasets are updated.<br /><br />Please click on the button below to continue or wait a moment till the script restarts itself.', 'PORTAL_UPDATE_TODO' => 'From on here all existing database tables in use by Portal XL will be updated to the latest workflow.<br /><br />To start the update procedure, click on the button below.<br /><br />Please be patient while proceeding, because it can take some time to the number of updates to make.', 'PORTAL_FINAL_UPDATE_STEP' => 'The existing tables from Portal XL are now up to date.<br />To get correct displayed texts on your forum the datasets needs to be converted now.<br /><br />Click on the button below to continue now with the converting.', // Portal XL Remove Database Entries Procedure 'PORTAL_REMOVE' => 'Portal XL Remove', 'PORTAL_REMOVE_NOT_POSSIBLE' => '<strong>Remove not possible!</strong><br /><br />Your version release of this Portal: <strong>%1$s</strong><br /><br />The Portal XL must at least have the release <strong>%1$s</strong>, to be able to remove all database tables.<br /><br />Please update the Portal manually to this release, before you can use this script again.', 'PORTAL_REMOVE_SUCCESS' => 'Congratulation!<br />Remove of the database entries from Portal XL is finished.<br /><br />You can now go on to remove remaining parts of Portal XL from your forum.<br /><br />Please delete the folder /install/ from your forum root to enable your forum again.', 'PORTAL_REMOVE_TODO' => 'Portal XL will be removed from your database, it is save to delete all Portal XL related files, as there are (related to your root), if this step is completed: <ul> <li>in folder <span style="color:#009900;">/adm/style/</span> remove all <span style="color:#FF0000;">acp_portal*.html</span>.</li> <li>in folder <span style="color:#009900;">/includes/acp/</span> remove all <span style="color:#FF0000;">acp_portal*.php</span></li> <li>in folder <span style="color:#009900;">/includes/acp/info/</span> remove all <span style="color:#FF0000;">acp_portal*.php</span></li> <li>in folder <span style="color:#009900;">/language/en/</span> remove <span style="color:#FF0000;">portal.php</span></li> <li>in folder <span style="color:#009900;">/language/en/acp/</span> remove all <span style="color:#FF0000;">portal_*.php</span></li> <li>in folder <span style="color:#009900;">/language/en/mods/</span> remove <span style="color:#FF0000;">portal_xl_average_statistics.php</span></li> <li>remove main folder <span style="color:#009900;">/portal/</span></strong></li> <li>remove all <span style="color:#009900;">/portal/</span> folders (do this for every style installed) under <span style="color:#009900;">/styles/stylename/template/</span></li> <li>in root replace <span style="color:#FF0000;">.htaccess</span> by the original one from phpBB 3.0.x, remove <span style="color:#FF0000;">portal.php</span>, <span style="color:#FF0000;">portal_pages.php</span> and <span style="color:#FF0000;">robots.txt</span>.</li> <li>additional to the above all custom bbcodes installed by use of this installer will be removed.</li> </ul> <p><strong style="text-transform: uppercase;">Note:</strong> Before proceeding re-upload a original phpBB 3.0.x distribution to overwrite files which have been changed for use of Portal XL, but bear in mind before uploading anything to be sure to have removed folder <span style="color:#009900;">/install/</span> and file <span style="color:#FF0000;">config.php</span> from the original phpBB 3.0.x package.</p> <p>Thank you for using Portal XL.</p><br /><br />', 'PORTAL_SQL_REMOVE_DONE' => '<strong>Done database action:</strong><br />', 'PORTAL_FINAL_REMOVE_STEP' => 'All existing database entries and tables in use by Portal XL where removed.<br /><br />Click on the button below to continue or wait some seconds to automatically redirect to the next step.', 'REMOVE_DATABASE' => 'Proceed to Remove', 'STAGE_REMOVE_DB' => 'Removing Database', // Portal XL CHMOD Directories 'PORTAL_CHMOD' => 'Portal XL CHMOD', 'PORTAL_CHMOD_NOT_POSSIBLE' => '<strong>CHMOD not possible!</strong><br /><br />Your version release of this Portal: <strong>%1$s</strong><br /><br />The Portal XL must at least have the release <strong>%1$s</strong>, to be able to CHMOD all directories used by Portal XL.<br /><br />Please update the Portal manually to this release, before you can use this script again.', 'PORTAL_CHMOD_SUCCESS' => 'Congratulation!<br />CHMOD to folders and files was successful.', 'PORTAL_CHMOD_TODO' => 'Portal XL\'s installation Wizard will try to CHMOD / Rename following directories or files for you if acces is granted for such a procedure by your hosting company: <ul> <li><em><strong><span style="color:#009900;">File permissions CHMOD</span></strong></em><br /> <em>After installation you should check all CHMOD\'s on files and directories for *NIX related servers.</em><br /> The wizard will try to CHMOD listed directories below for you.<br /><br /> <strong><span style="color:#009900;">CHMOD <span style="color:#FF0000;">0644</span> into</span></strong>:<br /> config.php<br /><br /> <strong><span style="color:#009900;">CHMOD <span style="color:#FF0000;">0666</span> into</span></strong>:<br /> /images/counter/ip.txt<br /><br /> <strong><span style="color:#009900;">CHMOD <span style="color:#FF0000;">0777</span> into</span></strong>:<br /> /cache<br /> /store<br /> /files<br /> /images/avatars/upload<br /> </li><br /> <li><em><strong><span style="color:#009900;">Directory rename</span></strong></em><br /> <em>After installation you should check on delete, rename or move directory <strong>/install/</strong> on your server when ready.</em><br /> The wizard will try to rename <strong>/install/</strong> into <strong>/_install/</strong> for you.<br /><br /> </li> </ul> <p><strong style="text-transform: uppercase;">Note:</strong> As usual, before proceeding have a recent backup of your files.</p><br /><br />', 'PORTAL_CHMOD_DONE' => '<strong>Done database action:</strong><br />', 'PORTAL_FINAL_CHMOD_STEP' => 'All existing directories and files in use by Portal XL where CHMOD set.<br /><br />Click on the button below to continue or wait some seconds to automatically redirect to the next step.', 'PORTAL_CHMOD_FILES' => 'Proceed to CHMOD', 'STAGE_CHMOD_FILES' => 'CHMOD in action...<br /> <ul> <li><em><strong><span style="color:#009900;">File permissions CHMOD</span></strong></em><br /> <em>After CHMOD actions you should check all CHMOD\'s on files and directories for *NIX related servers.</em><br /><br /> <strong><span style="color:#009900;">CHMOD <span style="color:#FF0000;">0644</span> into</span></strong>:<br /> config.php<br /><br /> <strong><span style="color:#009900;">CHMOD <span style="color:#FF0000;">666</span> into</span></strong>:<br /> /images/counter/ip.txt<br /><br /> <strong><span style="color:#009900;">CHMOD <span style="color:#FF0000;">755</span> into</span></strong>:<br /> /cache<br /> /store<br /> /files<br /> /images/avatars/upload<br /> </li> </ul> After clicking the button you will not be able to acces this installer anymore due to rename of folder <strong>/install/</strong> to <strong>/_install/</strong>. If you need the installer again rename folder <strong>/_install/</strong> than or access the renamed directory directly.<br /><br />Click the button below to continue.', // Portal XL BBCODE Import 'PORTAL_BBCODE' => 'Portal XL Custom bbCode', 'PORTAL_BBCODE_NOT_POSSIBLE' => '<strong>Adding custom bbCodes is not possible!</strong><br /><br />Your version release of this Portal: <strong>%1$s</strong><br /><br />The Portal XL must at least have the release <strong>%1$s</strong>, to be able to BBCODE all directories used by Portal XL.<br /><br />Please update the Portal manually to this release, before you can use this script again.', 'PORTAL_BBCODE_SUCCESS' => 'Congratulation!<br />Adding custom bbCodes to database was successful.', 'PORTAL_BBCODE_TODO' => 'Welcome to the Portal XL custom bbCode installation Wizard.<br /><br />Portal XL will install following custom bbCodes into your database: <ul> <li><span style="color:#009900;">Insert spoiler: [spoiler]your text here[/spoiler]</span></li> <li><span style="color:#009900;">Insert iframe: [iframe]http://url.here[/iframe]</span></li> <li><span style="color:#009900;">Insert youtube: [youtube]videonumber[/youtube]</span></li> <li><span style="color:#009900;">Insert GVideo: [GVideo]videonumber[/GVideo]</span></li> <li><span style="color:#009900;">Insert myvideo: [myvideo]videonumber[/myvideo]</span></li> <li><span style="color:#009900;">Insert clipfish: [clipfish]videonumber[/clipfish]</span></li> <li><span style="color:#009900;">Insert myspace: [myspace]videonumber[/myspace]</span></li> <li><span style="color:#009900;">Insert gametrailers: [gametrailers]trailernumber[/gametrailers]</span></li> <li><span style="color:#009900;">Insert center: [center]your text[/center]</span></li> <li><span style="color:#009900;">Insert strike: [strike]your text[/strike]</span></li> <li><span style="color:#009900;">Insert bgcolor: [bgcolor=red]your text[/bgcolor]</span></li> <li><span style="color:#009900;">Insert hidden link: [hiddenlink=http//url.her]your text[/hiddenlink]</span></li> <li><span style="color:#009900;">Insert offtopic: [offtopic]your text[/offtopic]</span></li> <li><span style="color:#009900;">Insert marquee: [marquee=color here]your text[/marquee]</span></li> <li><span style="color:#009900;">Insert intended text: [tab=number here]your text[/tab]</span></li> <li><span style="color:#009900;">Insert align: [align=direction]your text[/align]</span></li> <li><span style="color:#009900;">Align Image Left: [img_l]http://img_url[/img_l]</span></li> <li><span style="color:#009900;">Align Image Right: [img_r]http://img_url[/img_r]</span></li> <li><span style="color:#009900;">Insert mailto: [mail=e-mail addres]e-mail addres[/mail]</span></li> <li><span style="color:#009900;">Insert spoiler center align: [spoil]your text here[/spoil]</span></li> <li><span style="color:#009900;">Insert spoiler left align: [spoil_l]your text here[/spoil_l]</span></li> <li><span style="color:#009900;">Insert horizontal ruler: [hr][/hr]</span></li> <li><span style="color:#009900;">Insert line break: [br][/br]</span></li> <li><span style="color:#009900;">Insert WMV: [wmv]http://wmv_url[/wmv]</span></li> <li><span style="color:#009900;">Insert super script: [sup]your text[/sup]</span></li> <li><span style="color:#009900;">Insert Flash video: [flash_i]your url[/flash_i]</span></li> <li><span style="color:#009900;">Insert stream: [stream]your url[/stream]</span></li> <li><span style="color:#009900;">Insert FLV: [flv]your url[/flv]</span></li> <li><span style="color:#009900;">Insert Real Media: [rm]your url[/rm]</span></li> <li><span style="color:#009900;">Insert MOV: [mov]your url[/mov]</span></li> </ul> <p><strong style="text-transform: uppercase;">Note:</strong> As usual, before proceeding have a recent backup of your database.</p><br /><br />', 'PORTAL_SQL_BBCODE_DONE' => '<strong>Done database action:</strong><br />', 'PORTAL_FINAL_BBCODE_STEP' => 'Update bbCodes to database where set.<br /><br />Click on the button below to continue.', 'BBCODE_DATABASE' => 'Proceed to BBCODE', 'STAGE_BBCODE_DB' => 'BBCODE in action...<br /> <ul> <li><em><strong><span style="color:#009900;">File permissions BBCODE</span></strong></em><br /> <em>After BBCODE actions you should check all BBCODE\'s on files and directories for *NIX related servers.</em><br /><br /> <strong><span style="color:#009900;">BBCODE <span style="color:#FF0000;">0644</span> into</span></strong>:<br /> config.php<br /><br /> <strong><span style="color:#009900;">BBCODE <span style="color:#FF0000;">666</span> into</span></strong>:<br /> /images/counter/ip.txt<br /><br /> <strong><span style="color:#009900;">BBCODE <span style="color:#FF0000;">755</span> into</span></strong>:<br /> /cache<br /> /store<br /> /files<br /> /images/avatars/upload<br /> </li> </ul> After clicking the button you will not be able to acces this installer anymore due to rename of folder <strong>/install/</strong> to <strong>/_install/</strong>. If you need the installer again rename folder <strong>/_install/</strong> than or access the renamed directory directly.<br /><br />Click the button below to continue.', 'PORTAL_FINAL_MODULE_STEP' => 'Update of the database modules table where set.<br /><br />Click on the button below to continue.', 'PORTAL_FINAL_CONFIGFILE_STEP' => 'Update of the file config.php in your forum root where set.<br /><br />Click on the button below to continue.', 'PORTAL_SQL_MODULE_DONE' => '<strong>Done database action:</strong><br />', 'STAGE_INSERT_DATA' => 'Insert default values', 'STAGE_POPULATE_DB' => 'The database tables are available.<br /><br />Click on the button below to populate the tables with data.', 'STAGE_CHMOD' => 'CHMOD files', 'STAGE_BBCODE' => 'bbCode Import', 'STAGE_INSERT_MODULES' => 'Insert Modules', 'PORTAL_NOT_INSTALLED' => 'No Portal installation found', 'PORTAL_NOT_INSTALLED_EXPLAIN' => 'A default installation of Portal XL is required, please <a href="%s">proceed by first installing Portal XL</a>.', // Portal XL version check 'VERSION_CHECK' => 'Version check', 'VERSION_CHECK_EXPLAIN' => 'Checks to see if the version of Portal XL you are currently running is up to date.', 'VERSION_UP_TO_DATE_ACP' => 'Your installation is up to date, no updates are available for your version of Portal XL. You do not need to update your installation.', 'VERSION_NOT_UP_TO_DATE_ACP' => 'Your version of Portal XL is not up to date.<br />Below you will find a link to the release announcement for the latest version as well as instructions on how to perform the update.', 'CURRENT_VERSION' => 'Current version', 'LATEST_VERSION' => 'Latest version', 'UPDATE_INSTRUCTIONS' => ' <h2>How to update your installation with the Latest Package</h2> <p>The recommended way of updating your installation listed here is only valid for the latest package. You are also able to update your installation using the methods listed within the \docs\PORTAL_XL_INSTALL.html document. The steps for updating Portal XL are:</p> <ul style="margin-left: 20px; font-size: 1.1em;"> <li>Go to the <a href="http://www.portalxl.nl/forum/" title="http://www.portalxl.nl/forum/">Portal XL downloads page</a> and download the "Latest Package" archive.<br /></li> <li>Unpack the archive.<br /></li> <li>Upload the complete \root\ folder (retain directory structure) to your phpBB root directory (where your config.php file is).<br /></li> <li>Browse to \install\index.php to start the installation script and choose tab "Update"<br /></li> <li>Refresh cache and style(s) when done!<br /></li> </ul> ', )); ?>
DaMysterious/portalxl50_plain
contrib/languages/nl/mods/portal_xl_install.php
PHP
gpl-3.0
25,542
<?php /* ########################################################################## # # # Version 4 / / / # # -----------__---/__---__------__----__---/---/- # # | /| / /___) / ) (_ ` / ) /___) / / # # _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ # # Free Content / Management System # # / # # # # # # Copyright 2005-2010 by webspell.org # # # # visit webSPELL.org, webspell.info to get webSPELL for free # # - Script runs under the GNU GENERAL PUBLIC LICENSE # # - It's NOT allowed to remove this copyright-tag # # -- http://www.fsf.org/licensing/licenses/gpl.html # # # # Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), # # Far Development by Development Team - webspell.org # # # # visit webspell.org # # # ########################################################################## */ $language_array = Array( /* do not edit above this line */ '1_slow'=>'1 (langsam)', '2_normal'=>'2 (normal)', '3_fast'=>'3 (schnell)', 'access_denied'=>'Zugriff verweigert', 'color'=>'Farbe', 'delay'=>'Verzögerung', 'delete'=>'löschen', 'direction'=>'Ausrichtung', 'example'=>'(z.B.: #FFFFFF)', 'left_to_right'=>'von links nach rechts', 'right_to_left'=>'von rechts nach links', 'scrolltext'=>'Lauftext', 'transaction_invalid'=>'Transaktions ID ungültig', 'update'=>'aktualisieren', 'you_can_use_html'=>'Du kannst HTML-Tags benutzen' ); ?>
Dwarfex/Hosting-Service
hosting_project/ws_versions/ws2/admin/languages/de/scrolltext.php
PHP
gpl-3.0
2,359
<?php /** * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Framework\DB; class HelperTest extends \PHPUnit_Framework_TestCase { /** * @var \Magento\Framework\DB\Helper */ protected $_model; /** * @var \Magento\Framework\DB\Select */ protected $_select; protected function setUp() { $this->_model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( 'Magento\Framework\DB\Helper', ['modulePrefix' => 'core'] ); $collection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( 'Magento\Store\Model\ResourceModel\Store\Collection' ); $this->_select = $collection->getSelect(); } public function testPrepareColumnsList() { $columns = $this->_model->prepareColumnsList($this->_select); $this->assertContains('STORE_ID', array_keys($columns)); } public function testAddGroupConcatColumn() { $select = (string)$this->_model->addGroupConcatColumn($this->_select, 'test_alias', 'store_id'); $this->assertContains('GROUP_CONCAT', $select); $this->assertContains('test_alias', $select); } public function testGetDateDiff() { $diff = $this->_model->getDateDiff('2011-01-01', '2011-01-01'); $this->assertInstanceOf('Zend_Db_Expr', $diff); $this->assertContains('TO_DAYS', (string)$diff); } public function testAddLikeEscape() { $value = $this->_model->addLikeEscape('test'); $this->assertInstanceOf('Zend_Db_Expr', $value); $this->assertContains('test', (string)$value); } }
rajmahesh/magento2-master
vendor/magento/magento2-base/dev/tests/integration/testsuite/Magento/Framework/DB/HelperTest.php
PHP
gpl-3.0
1,729
package org.area515.resinprinter.display; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsDevice; import java.awt.HeadlessException; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.area515.resinprinter.printer.Printer.DisplayState; import org.area515.util.Log4jUtil; public class PrinterDisplayFrame extends JFrame implements GraphicsOutputInterface { private static final long serialVersionUID = 5024551291098098753L; private static final Logger logger = LogManager.getLogger(); private String IMAGE_REALIZE_TIMER = "Image Realize:"; private DisplayState displayState = DisplayState.Blank; private int gridSquareSize; private int calibrationX; private int calibrationY; private BufferedImage displayImage; private int sliceNumber; private boolean isSimulatedDisplay; private String displayId; private class DoubleBufferedJPanel extends JPanel { private static final long serialVersionUID = 5629943117146058839L; @Override protected void paintComponent(Graphics g) { //we need to add this method back in because some UV light engines require it. super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; Rectangle screenSize = getGraphicsConfiguration().getBounds(); switch (displayState) { case Blank : g2.setBackground(Color.black); g2.clearRect(0, 0, screenSize.width, screenSize.height); logger.debug("Blank realized:{}", () -> Log4jUtil.completeGlobalTimer(IMAGE_REALIZE_TIMER)); return; case Grid : GraphicsOutputInterface.showGrid(g2, screenSize, gridSquareSize); logger.debug("Grid realized:{}", () -> Log4jUtil.completeGlobalTimer(IMAGE_REALIZE_TIMER)); return; case Calibration : GraphicsOutputInterface.showCalibration(g2, screenSize, calibrationX, calibrationY); logger.debug("Calibration realized:{}", () -> Log4jUtil.completeGlobalTimer(IMAGE_REALIZE_TIMER)); return; case CurrentSlice : logger.trace("Writing paintComponent1aboutToDisplay:{}", () -> Log4jUtil.logImage(displayImage, "paintComponent1aboutToDisplay.png")); g2.drawImage(displayImage, null, screenSize.width / 2 - displayImage.getWidth() / 2, screenSize.height / 2 - displayImage.getHeight() / 2); if (isSimulatedDisplay) { g2.setColor(Color.RED); g2.setFont(getFont()); g2.drawString("Slice:" + sliceNumber, getInsets().left, getInsets().top + g2.getFontMetrics().getHeight()); } logger.debug("Image realized:{}", () -> Log4jUtil.completeGlobalTimer(IMAGE_REALIZE_TIMER)); return; } } } public PrinterDisplayFrame(String displayId) throws HeadlessException { super(); this.displayId = displayId; this.isSimulatedDisplay = true; getRootPane().setBackground(Color.black); getContentPane().setBackground(Color.black); add(new DoubleBufferedJPanel()); IMAGE_REALIZE_TIMER += hashCode(); } public PrinterDisplayFrame(GraphicsDevice device) { super(device.getDefaultConfiguration()); this.isSimulatedDisplay = false; getRootPane().setBackground(Color.black); getContentPane().setBackground(Color.black); add(new DoubleBufferedJPanel()); IMAGE_REALIZE_TIMER += hashCode(); } public DisplayState getDisplayState() { return displayState; } public void setDisplayState(DisplayState displayState) { this.displayState = displayState; } public void resetSliceCount() { sliceNumber = 0; } public void showBlankImage() { logger.debug("Blank assigned:{}", () -> Log4jUtil.startGlobalTimer(IMAGE_REALIZE_TIMER)); setDisplayState(DisplayState.Blank); repaint(); } public void showCalibrationImage(int xPixels, int yPixels) { logger.debug("Calibration assigned:{}", () -> Log4jUtil.startGlobalTimer(IMAGE_REALIZE_TIMER)); setDisplayState(DisplayState.Calibration); calibrationX = xPixels; calibrationY = yPixels; repaint(); } public void showGridImage(int pixels) { logger.debug("Grid assigned:{}", () -> Log4jUtil.startGlobalTimer(IMAGE_REALIZE_TIMER)); setDisplayState(DisplayState.Grid); gridSquareSize = pixels; repaint(); } public void showImage(BufferedImage image, boolean performFullUpdate) { logger.debug("Image assigned:{}", () -> Log4jUtil.startGlobalTimer(IMAGE_REALIZE_TIMER)); if (performFullUpdate) { sliceNumber++; } setDisplayState(DisplayState.CurrentSlice); displayImage = image; repaint(); } @Override public Rectangle getBoundary() { return getGraphicsConfiguration().getBounds(); } @Override public boolean isDisplayBusy() { return false; } @Override public String getIDstring() { return displayId; } @Override public String buildIDString() { throw new IllegalStateException("You should never call buildIDString from this class"); } @Override public GraphicsOutputInterface initializeDisplay(String displayId) { throw new IllegalStateException("You should never call initializeDisplay from this class"); } }
Xtrememicrotech/XtremeD-Dev
host/src/main/java/org/area515/resinprinter/display/PrinterDisplayFrame.java
Java
gpl-3.0
5,168
#region Copyright & License Information /* * Copyright 2007-2015 The OpenRA Developers (see AUTHORS) * This file is part of OpenRA, which is free software. It is made * available to you under the terms of the GNU General Public License * as published by the Free Software Foundation. For more information, * see COPYING. */ #endregion using OpenRA.Graphics; using OpenRA.Traits; namespace OpenRA.Mods.Common.Traits { [Desc("Renders an overlay when the actor is taking heavy damage.")] public class WithSmokeInfo : ITraitInfo, Requires<RenderSpritesInfo> { [Desc("Needs to define \"idle\", \"loop\" and \"end\" sub-sequences.")] public readonly string Sequence = "smoke_m"; public object Create(ActorInitializer init) { return new WithSmoke(init.Self, this); } } public class WithSmoke : INotifyDamage { bool isSmoking; Animation anim; public WithSmoke(Actor self, WithSmokeInfo info) { var rs = self.Trait<RenderSprites>(); anim = new Animation(self.World, info.Sequence); rs.Add("smoke", new AnimationWithOffset(anim, null, () => !isSmoking)); } public void Damaged(Actor self, AttackInfo e) { if (isSmoking) return; if (e.Damage < 0) return; /* getting healed */ if (e.DamageState < DamageState.Heavy) return; isSmoking = true; anim.PlayThen("idle", () => anim.PlayThen("loop", () => anim.PlayBackwardsThen("end", () => isSmoking = false))); } } }
Sithil-F/OpenRA
OpenRA.Mods.Common/Traits/Render/WithSmoke.cs
C#
gpl-3.0
1,432
// -*- Mode: Go; indent-tabs-mode: t -*- /* * Copyright (C) 2017 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package userd import ( "bytes" "fmt" "net/url" "os" "os/exec" "regexp" "syscall" "time" "github.com/godbus/dbus" "github.com/snapcore/snapd/i18n" "github.com/snapcore/snapd/logger" "github.com/snapcore/snapd/osutil" "github.com/snapcore/snapd/osutil/sys" "github.com/snapcore/snapd/release" "github.com/snapcore/snapd/strutil" "github.com/snapcore/snapd/usersession/userd/ui" ) const launcherIntrospectionXML = ` <interface name="org.freedesktop.DBus.Peer"> <method name='Ping'> </method> <method name='GetMachineId'> <arg type='s' name='machine_uuid' direction='out'/> </method> </interface> <interface name='io.snapcraft.Launcher'> <method name='OpenURL'> <arg type='s' name='url' direction='in'/> </method> <method name="OpenFile"> <arg type="s" name="parent_window" direction="in"/> <arg type="h" name="fd" direction="in"/> </method> </interface>` // allowedURLSchemes are those that can be passed to xdg-open so that it may // launch the handler for the url scheme on behalf of the snap (and therefore // outside of the calling snap's confinement). Historically we've been // conservative about adding url schemes but the thinking was refined in // https://github.com/snapcore/snapd/pull/7731#pullrequestreview-362900171 // // The current criteria for adding url schemes is: // * understanding and documenting the scheme in this file // * the scheme itself does not cause xdg-open to open files (eg, file:// or // matching '^[[:alpha:]+\.\-]+:' (from xdg-open source)) // * verifying that the recipient of the url (ie, what xdg-open calls) won't // process file paths/etc that can be leveraged to break out of the sandbox // (but understanding how the url can drive the recipient application is // important) // // This code uses golang's net/url.Parse() which will help ensure the url is // ok before passing to xdg-open. xdg-open itself properly quotes the url so // shell metacharacters are blocked. var ( allowedURLSchemes = []string{ // apt: the scheme allows specifying a package for xdg-open to pass to an // apt-handling application, like gnome-software, apturl, etc which are all // protected by policykit // - scheme: apt:<name of package> // - https://github.com/snapcore/snapd/pull/7731 "apt", // help: the scheme allows for specifying a help URL. This code ensures that // the url is parseable // - scheme: help://topic // - https://github.com/snapcore/snapd/pull/6493 "help", // http/https: the scheme allows specifying a web URL. This code ensures that // the url is parseable // - scheme: http(s)://example.com "http", "https", // mailto: the scheme allows for specifying an email address // - scheme: mailto:foo@example.com "mailto", // msteams: the scheme is a thin wrapper around https. // - scheme: msteams:... // - https://github.com/snapcore/snapd/pull/8761 "msteams", // TODO: document slack URL scheme. "slack", // snap: the scheme allows specifying a package for xdg-open to pass to a // snap-handling installer application, like snap-store, etc which are // protected by policykit/snap login // - https://github.com/snapcore/snapd/pull/5181 "snap", // zoommtg: the scheme is a modified web url scheme // - scheme: https://medium.com/zoom-developer-blog/zoom-url-schemes-748b95fd9205 // (eg, zoommtg://zoom.us/...) // - https://github.com/snapcore/snapd/pull/8304 "zoommtg", // zoomphonecall: another zoom URL scheme, for dialing phone numbers // - https://github.com/snapcore/snapd/pull/8910 "zoomphonecall", // zoomus: alternative name for zoommtg // - https://github.com/snapcore/snapd/pull/8910 "zoomus", } ) // Launcher implements the 'io.snapcraft.Launcher' DBus interface. type Launcher struct { conn *dbus.Conn } // Interface returns the name of the interface this object implements func (s *Launcher) Interface() string { return "io.snapcraft.Launcher" } // ObjectPath returns the path that the object is exported as func (s *Launcher) ObjectPath() dbus.ObjectPath { return "/io/snapcraft/Launcher" } // IntrospectionData gives the XML formatted introspection description // of the DBus service. func (s *Launcher) IntrospectionData() string { return launcherIntrospectionXML } func makeAccessDeniedError(err error) *dbus.Error { return &dbus.Error{ Name: "org.freedesktop.DBus.Error.AccessDenied", Body: []interface{}{err.Error()}, } } func checkOnClassic() *dbus.Error { if !release.OnClassic { return makeAccessDeniedError(fmt.Errorf("not supported on Ubuntu Core")) } return nil } // see https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#file-naming var validDesktopFileName = regexp.MustCompile(`^[A-Za-z-_][A-Za-z0-9-_]*(\.[A-Za-z-_][A-Za-z0-9-_]*)*\.desktop$`) func schemeHasHandler(scheme string) (bool, error) { cmd := exec.Command("xdg-mime", "query", "default", "x-scheme-handler/"+scheme) // TODO: consider using Output() in case xdg-mime starts logging to // stderr out, err := cmd.CombinedOutput() if err != nil { return false, osutil.OutputErr(out, err) } out = bytes.TrimSpace(out) // if the output is a valid desktop file we have a handler for the given // scheme return validDesktopFileName.Match(out), nil } // OpenURL implements the 'OpenURL' method of the 'io.snapcraft.Launcher' // DBus interface. Before the provided url is passed to xdg-open the scheme is // validated against a list of allowed schemes. All other schemes are denied. func (s *Launcher) OpenURL(addr string, sender dbus.Sender) *dbus.Error { logger.Debugf("open url: %q", addr) if err := checkOnClassic(); err != nil { return err } u, err := url.Parse(addr) if err != nil { return &dbus.ErrMsgInvalidArg } if u.Scheme == "" { return makeAccessDeniedError(fmt.Errorf("cannot open URL without a scheme")) } isAllowed := strutil.ListContains(allowedURLSchemes, u.Scheme) if !isAllowed { // scheme is not listed in our allowed schemes list, perform // fallback and check whether the local system has a handler for // it isAllowed, err = schemeHasHandler(u.Scheme) if err != nil { logger.Noticef("cannot obtain scheme handler for %q: %v", u.Scheme, err) } } if !isAllowed { return makeAccessDeniedError(fmt.Errorf("Supplied URL scheme %q is not allowed", u.Scheme)) } if err := exec.Command("xdg-open", addr).Run(); err != nil { return dbus.MakeFailedError(fmt.Errorf("cannot open supplied URL")) } return nil } // fdToFilename determines the path associated with an open file descriptor. // // The file descriptor cannot be opened using O_PATH and must refer to // a regular file or to a directory. The symlink at /proc/self/fd/<fd> // is read to determine the filename. The descriptor is also fstat'ed // and the resulting device number and inode number are compared to // stat on the path determined earlier. The numbers must match. func fdToFilename(fd int) (string, error) { flags, err := sys.FcntlGetFl(fd) if err != nil { return "", err } // File descriptors opened with O_PATH do not imply access to // the file in question. if flags&sys.O_PATH != 0 { return "", fmt.Errorf("cannot use file descriptors opened using O_PATH") } // Determine the file name associated with the passed file descriptor. filename, err := os.Readlink(fmt.Sprintf("/proc/self/fd/%d", fd)) if err != nil { return "", err } var fileStat, fdStat syscall.Stat_t if err := syscall.Stat(filename, &fileStat); err != nil { return "", err } if err := syscall.Fstat(fd, &fdStat); err != nil { return "", err } // Sanity check to ensure we've got the right file if fdStat.Dev != fileStat.Dev || fdStat.Ino != fileStat.Ino { return "", fmt.Errorf("cannot determine file name") } fileType := fileStat.Mode & syscall.S_IFMT if fileType != syscall.S_IFREG && fileType != syscall.S_IFDIR { return "", fmt.Errorf("cannot open anything other than regular files or directories") } return filename, nil } func (s *Launcher) OpenFile(parentWindow string, clientFd dbus.UnixFD, sender dbus.Sender) *dbus.Error { // godbus transfers ownership of this file descriptor to us fd := int(clientFd) defer syscall.Close(fd) if err := checkOnClassic(); err != nil { return err } filename, err := fdToFilename(fd) if err != nil { return dbus.MakeFailedError(err) } snap, err := snapFromSender(s.conn, sender) if err != nil { return dbus.MakeFailedError(err) } dialog, err := ui.New() if err != nil { return dbus.MakeFailedError(err) } answeredYes := dialog.YesNo( i18n.G("Allow opening file?"), fmt.Sprintf(i18n.G("Allow snap %q to open file %q?"), snap, filename), &ui.DialogOptions{ Timeout: 5 * 60 * time.Second, Footer: i18n.G("This dialog will close automatically after 5 minutes of inactivity."), }, ) if !answeredYes { return dbus.MakeFailedError(fmt.Errorf("permission denied")) } if err = exec.Command("xdg-open", filename).Run(); err != nil { return dbus.MakeFailedError(fmt.Errorf("cannot open supplied URL")) } return nil }
sergiocazzolato/snapd
usersession/userd/launcher.go
GO
gpl-3.0
9,786
intelli.database = []; $(function() { if ($('#query_out').text()) { setTimeout( (function(){ $('#query_out').height(window.screen.height - $('#query_out').offset().top - 300) }), 1000); } $('a', '.js-selecting').on('click', function(e) { e.preventDefault(); var $ctl = $('#tbl option'); switch ($(this).data('action')) { case 'select': $ctl.prop('selected', true); break; case 'drop': $ctl.prop('selected', false); break; case 'invert': $ctl.each(function(i, obj) { $(obj).prop('selected', !$(obj).prop('selected')); }); } }); $('#save_file').on('change', function() { var obj = $('#js-save-options'); (1 == $(this).val()) ? obj.show() : obj.hide(); }); $('#form-dump').on('submit', function(e) { if (!$('#sql_structure').prop('checked') && !$('#sql_data').prop('checked')) { e.preventDefault(); intelli.admin.alert({title: _t('error'), type: 'error', msg: _t('export_not_checked')}); } }); $('#js-cmd-import').on('click', function() { if ($('#sql_file').val().length > 0) { $('#run_update').val('1'); $('#update').submit(); return true; } else { intelli.admin.alert( { title: _t('error'), type: 'error', msg: _t('choose_import_file') }); } return false; }); $('#addTableButton').on('click', function(e) { e.preventDefault(); addData('table'); }); $('#table').dblclick(function() { addData('table'); }).click(function() { var table = $(this).val(); if (table) { if (!intelli.database[table]) { $.ajax( { url: intelli.config.admin_url + '/database.json', data: {table: table}, success: function(data){ var fields = $('#field')[0]; intelli.database[table] = data; fields.options.length = 0; for (var i = 0; i < data.length; i++) { fields.options[fields.options.length] = new Option(data[i], data[i]); } fields.options[0].selected = true; // Show dropdown and the button $('#field').parent().fadeIn(); } }); } else { var items = intelli.database[table]; var fields = $('#field')[0]; fields.options.length = 0; for (var i = 0; i < items.length; i++) { fields.options[fields.options.length] = new Option(items[i], items[i]); } fields.options[0].selected = true; // Show dropdown and the button $('#field').parent().fadeIn(); } } }); $('#addFieldButton').click(function(e) { e.preventDefault(); addData('field'); }); $('#field').dblclick(function() { addData('field'); }); $('a', '#query_history').on('click', function(e) { e.preventDefault(); $('#query').val($(this).closest('li').find('span').text()).focus(); $(window).scrollTop(0); }); $('#clearButton').on('click', function() { Ext.Msg.confirm(_t('confirm'), _t('clear_confirm'), function(btn, text) { if (btn == 'yes') { $('#query').prop('value', 'SELECT * FROM '); $('#field').parent().fadeOut(); } }); return true; }); function addData(item) { var value = $('#' + item).val(); if (value) { addText('`' + value + '`'); } else { intelli.admin.alert( { title: _t('error'), type: 'error', msg: 'Please choose any ' + item + '.' }); } } // add text to query function addText(text) { text = ' ' + text + ' '; var query = $('#query'); if (document.selection) { query.focus(); sel = document.selection.createRange(); sel.text = text; } else if (query.selectionStart || query.selectionStart == '0') { var startPos = query.selectionStart; var endPos = query.selectionEnd; var flag = false; if(query.value.length == startPos) flag = true; query.value = query.value.substring(0, startPos) + text + query.value.substring(endPos, query.value.length); if(flag) query.selectionStart = query.value.length; } else { query.val(query.val() + text); } focusCampo('query'); } // sql template click $('a', '#sqlButtons').on('click', function(e) { e.preventDefault(); addText($(this).text()); }); // reset tables $('#js-reset-all, #js-reset').on('click', function(e) { if ($(this).attr('id') == 'js-reset-all') { $('input[name="options[]"]').each(function() { $(this).prop('checked', true); }); } else { if (!$('input:checkbox[name="options[]"]:checked').length) { intelli.notifBox({msg: _t('reset_choose_table'), type: 'error'}); return false; } } var $self = $(this); Ext.Msg.confirm(_t('confirm'), _t('clear_reset'), function(btn, text) { if ('yes' == btn) { $self.closest('form').submit(); } }); }); if ($('#query').length > 0) { focusCampo('query'); } }); function focusCampo(id) { var inputField = document.getElementById(id); if (inputField != null && inputField.value.length != 0){ if (inputField.createTextRange){ var FieldRange = inputField.createTextRange(); FieldRange.moveStart('character',inputField.value.length); FieldRange.collapse(); FieldRange.select(); }else if (inputField.selectionStart || inputField.selectionStart == '0') { var elemLen = inputField.value.length; inputField.selectionStart = elemLen; inputField.selectionEnd = elemLen; inputField.focus(); } }else{ inputField.focus(); } }
wildanSawaludin/subrion
js/admin/database.js
JavaScript
gpl-3.0
5,357
<?php /** --------------------------------------------------------------------- * app/models/ca_object_lots_x_collections.php : table access class for table ca_object_lots_x_collections * ---------------------------------------------------------------------- * CollectiveAccess * Open-source collections management software * ---------------------------------------------------------------------- * * Software by Whirl-i-Gig (http://www.whirl-i-gig.com) * Copyright 2008-2010 Whirl-i-Gig * * For more information visit http://www.CollectiveAccess.org * * This program is free software; you may redistribute it and/or modify it under * the terms of the provided license as published by Whirl-i-Gig * * CollectiveAccess is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * This source code is free and modifiable under the terms of * GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See * the "license.txt" file for details, or visit the CollectiveAccess web site at * http://www.CollectiveAccess.org * * @package CollectiveAccess * @subpackage models * @license http://www.gnu.org/copyleft/gpl.html GNU Public License version 3 * * ---------------------------------------------------------------------- */ /** * */ require_once(__CA_LIB_DIR__.'/core/BaseRelationshipModel.php'); BaseModel::$s_ca_models_definitions['ca_object_lots_x_collections'] = array( 'NAME_SINGULAR' => _t('object lot ⇔ collection relationship'), 'NAME_PLURAL' => _t('object lot ⇔ collection relationships'), 'FIELDS' => array( 'relation_id' => array( 'FIELD_TYPE' => FT_NUMBER, 'DISPLAY_TYPE' => DT_HIDDEN, 'IDENTITY' => true, 'DISPLAY_WIDTH' => 10, 'DISPLAY_HEIGHT' => 1, 'IS_NULL' => false, 'DEFAULT' => '', 'LABEL' => 'Relation id', 'DESCRIPTION' => 'Identifier for Relation' ), 'lot_id' => array( 'FIELD_TYPE' => FT_NUMBER, 'DISPLAY_TYPE' => DT_FIELD, 'DISPLAY_WIDTH' => 10, 'DISPLAY_HEIGHT' => 1, 'IS_NULL' => false, 'DEFAULT' => '', 'LABEL' => 'Lot id', 'DESCRIPTION' => 'Identifier for Lot' ), 'collection_id' => array( 'FIELD_TYPE' => FT_NUMBER, 'DISPLAY_TYPE' => DT_FIELD, 'DISPLAY_WIDTH' => 10, 'DISPLAY_HEIGHT' => 1, 'IS_NULL' => false, 'DEFAULT' => '', 'LABEL' => 'Collection id', 'DESCRIPTION' => 'Identifier for Collection' ), 'type_id' => array( 'FIELD_TYPE' => FT_NUMBER, 'DISPLAY_TYPE' => DT_FIELD, 'DISPLAY_WIDTH' => 10, 'DISPLAY_HEIGHT' => 1, 'IS_NULL' => false, 'DEFAULT' => '', 'LABEL' => 'Type id', 'DESCRIPTION' => 'Identifier for Type', 'BOUNDS_VALUE' => array(0,65535) ), 'source_info' => array( 'FIELD_TYPE' => FT_TEXT, 'DISPLAY_TYPE' => DT_FIELD, 'DISPLAY_WIDTH' => 88, 'DISPLAY_HEIGHT' => 15, 'IS_NULL' => false, 'DEFAULT' => '', 'LABEL' => 'Source information', 'DESCRIPTION' => 'Source information' ), 'effective_date' => array( 'FIELD_TYPE' => FT_HISTORIC_DATERANGE, 'DISPLAY_TYPE' => DT_FIELD, 'DISPLAY_WIDTH' => 40, 'DISPLAY_HEIGHT' => 1, 'IS_NULL' => true, 'DEFAULT' => '', 'START' => 'sdatetime', 'END' => 'edatetime', 'LABEL' => _t('Effective dates'), 'DESCRIPTION' => _t('Period of time for which this relationship was in effect. This is an option qualification for the relationship. If left blank, this relationship is implied to have existed for as long as the related items have existed.') ), 'rank' => array( 'FIELD_TYPE' => FT_NUMBER, 'DISPLAY_TYPE' => DT_OMIT, 'DISPLAY_WIDTH' => 10, 'DISPLAY_HEIGHT' => 1, 'IS_NULL' => false, 'DEFAULT' => '', 'LABEL' => _t('Sort order'), 'DESCRIPTION' => _t('The relative priority of the relationship when displayed in a list with other relationships. Lower numbers indicate higher priority.') ) ) ); class ca_object_lots_x_collections extends BaseRelationshipModel { # --------------------------------- # --- Object attribute properties # --------------------------------- # Describe structure of content object's properties - eg. database fields and their # associated types, what modes are supported, et al. # # ------------------------------------------------------ # --- Basic object parameters # ------------------------------------------------------ # what table does this class represent? protected $TABLE = 'ca_object_lots_x_collections'; # what is the primary key of the table? protected $PRIMARY_KEY = 'relation_id'; # ------------------------------------------------------ # --- Properties used by standard editing scripts # # These class properties allow generic scripts to properly display # records from the table represented by this class # # ------------------------------------------------------ # Array of fields to display in a listing of records from this table protected $LIST_FIELDS = array('source_info'); # When the list of "list fields" above contains more than one field, # the LIST_DELIMITER text is displayed between fields as a delimiter. # This is typically a comma or space, but can be any string you like protected $LIST_DELIMITER = ' '; # What you'd call a single record from this table (eg. a "person") protected $NAME_SINGULAR; # What you'd call more than one record from this table (eg. "people") protected $NAME_PLURAL; # List of fields to sort listing of records by; you can use # SQL 'ASC' and 'DESC' here if you like. protected $ORDER_BY = array('source_info'); # Maximum number of record to display per page in a listing protected $MAX_RECORDS_PER_PAGE = 20; # How do you want to page through records in a listing: by number pages ordered # according to your setting above? Or alphabetically by the letters of the first # LIST_FIELD? protected $PAGE_SCHEME = 'alpha'; # alpha [alphabetical] or num [numbered pages; default] # If you want to order records arbitrarily, add a numeric field to the table and place # its name here. The generic list scripts can then use it to order table records. protected $RANK = 'rank'; # ------------------------------------------------------ # Hierarchical table properties # ------------------------------------------------------ protected $HIERARCHY_TYPE = null; protected $HIERARCHY_LEFT_INDEX_FLD = null; protected $HIERARCHY_RIGHT_INDEX_FLD = null; protected $HIERARCHY_PARENT_ID_FLD = null; protected $HIERARCHY_DEFINITION_TABLE = null; protected $HIERARCHY_ID_FLD = null; protected $HIERARCHY_POLY_TABLE = null; # ------------------------------------------------------ # Change logging # ------------------------------------------------------ protected $UNIT_ID_FIELD = null; protected $LOG_CHANGES_TO_SELF = true; protected $LOG_CHANGES_USING_AS_SUBJECT = array( "FOREIGN_KEYS" => array( 'lot_id', 'collection_id' ), "RELATED_TABLES" => array( ) ); # ------------------------------------------------------ # --- Relationship info # ------------------------------------------------------ protected $RELATIONSHIP_LEFT_TABLENAME = 'ca_object_lots'; protected $RELATIONSHIP_RIGHT_TABLENAME = 'ca_collections'; protected $RELATIONSHIP_LEFT_FIELDNAME = 'lot_id'; protected $RELATIONSHIP_RIGHT_FIELDNAME = 'collection_id'; protected $RELATIONSHIP_TYPE_FIELDNAME = 'type_id'; # ------------------------------------------------------ # $FIELDS contains information about each field in the table. The order in which the fields # are listed here is the order in which they will be returned using getFields() protected $FIELDS; # ------------------------------------------------------ # --- Constructor # # This is a function called when a new instance of this object is created. This # standard constructor supports three calling modes: # # 1. If called without parameters, simply creates a new, empty objects object # 2. If called with a single, valid primary key value, creates a new objects object and loads # the record identified by the primary key value # # ------------------------------------------------------ public function __construct($pn_id=null) { parent::__construct($pn_id); # call superclass constructor } # ------------------------------------------------------ } ?>
perryrothjohnson/artifact-database
pawtucket/app/models/ca_object_lots_x_collections.php
PHP
gpl-3.0
8,365
<?php defined('SYSPATH') or die('No direct script access.'); class Kohana extends Kohana_Core { /** * @var boolean True if Kohana is running from the command line */ public static $is_cli = FALSE; /** * original requested data * @var array */ public static $_POST_ORIG; public static $_GET_ORIG; public static $_COOKIE_ORIG; /** * overrides default init * @param array $settings * @return void */ public static function init(array $settings = NULL) { //before cleaning getting a copy of the original in case we need it. self::$_GET_ORIG = $_GET; self::$_COOKIE_ORIG = $_COOKIE; //we remove slashes if needed self::$_POST_ORIG = Kohana::stripslashes($_POST); parent::init($settings); } /** * Provides auto-loading support of classes that follow Kohana's old class * naming conventions. * * This is included for compatibility purposes with older modules. * * @param string $class Class name * @param string $directory Directory to load from * @return boolean */ public static function auto_load_lowercase($class, $directory = 'classes') { // Transform the class name into a path $file = str_replace('_', DIRECTORY_SEPARATOR, $class); //try find file in lower $path = Kohana::find_file($directory, strtolower($file)); //shit not found, try normal... if (!$path) $path = Kohana::find_file($directory, $file); //oh yeah baby fund you! if ($path) { // Load the class file require $path; // Class has been found return TRUE; } // Class is not in the filesystem @todo throw exception? return FALSE; } /** * Override * Recursively sanitizes an input variable: * * - Strips slashes if magic quotes are enabled * - Normalizes all newlines to LF * * @param mixed $value any variable * @return mixed sanitized variable */ public static function sanitize($value) { if (is_array($value) OR is_object($value)) { foreach ($value as $key => $val) { // Recursively clean each value $value[$key] = Kohana::sanitize($val); } } elseif (is_string($value)) { // Remove slashes added by magic quotes $value = stripslashes($value); if (strpos($value, "\r") !== FALSE) { // Standardize newlines $value = str_replace(array("\r\n", "\r"), "\n", $value); } //Added strip tags $value = strip_tags($value); } return $value; } /** * Override * Recursively stripslashes an input variable: * * - Strips slashes if magic quotes are enabled * * @param mixed $value any variable * @return mixed stripslashes variable */ public static function stripslashes($value) { if (is_array($value) OR is_object($value)) { foreach ($value as $key => $val) { // Recursively clean each value $value[$key] = Kohana::stripslashes($val); } } elseif (is_string($value)) { // Remove slashes added by magic quotes $value = stripslashes($value); } return $value; } /** * Provides simple file-based caching for strings and arrays: * * // Set the "foo" cache * Kohana::cache('foo', 'hello, world'); * * // Get the "foo" cache * $foo = Kohana::cache('foo'); * * All caches are stored as PHP code, generated with [var_export][ref-var]. * Caching objects may not work as expected. Storing references or an * object or array that has recursion will cause an E_FATAL. * * The cache directory and default cache lifetime is set by [Kohana::init] * * [ref-var]: http://php.net/var_export * * @throws Kohana_Exception * @param string $name name of the cache * @param mixed $data data to cache * @param integer $lifetime number of seconds the cache is valid for * @return mixed for getting * @return boolean for setting */ public static function cache($name, $data = NULL, $lifetime = NULL) { //in case the OC_core is not yet loaded we need to use the normal cache...sucks but happens onload if (class_exists('Kohana_Cache')) return Core::cache($name, $data, $lifetime); else return parent::cache($name, $data, $lifetime); } }
open-classifieds/openclassifieds2
oc/classes/kohana.php
PHP
gpl-3.0
4,945
<?php include('header.php'); if (!empty($_GET['iddevice']) && !empty($_GET['val']) && !empty($_GET['opt'])){ $request = new Api(); $request -> add_request('mcSetVolume', array($_GET['iddevice'], $_GET['val'], $_GET['opt'])); $result = $request -> send_request(); } ?>
giorda-a/Domoleaf
www/form/form_mc_volume.php
PHP
gpl-3.0
277
<?php namespace Company\Model; use Doctrine\ORM\Mapping as ORM; //use Doctrine\Common\Collections\ArrayCollection; //use Zend\Permissions\Acl\Role\RoleInterface; //use Zend\Permissions\Acl\Resource\ResourceInterface; /** * CompanyFeaturedPackage model. * * @ORM\Entity */ class CompanyFeaturedPackage extends CompanyPackage //implements RoleInterface, ResourceInterface { /** * Constructor. */ public function __construct() { parent::__construct(); // todo } /** * The featured package content article. * * @ORM\Column(type="text") */ protected $article; /** * Get the featured package's article text * * @return string */ public function getArticle() { return $this->article; } /** * Set the featured package's article text * * @param string $image */ public function setArticle($article) { $this->article = $article; } /** * The package's language. * * @ORM\Column(type="string") */ protected $language; /** * Get the package's language. * * @return string language of the package */ public function getLanguage() { return $this->language; } /** * Set the package's language. * * @param string $language language of the package */ public function setLanguage($language) { $this->language = $language; } // For zend2 forms public function getArrayCopy() { $array = parent::getArrayCopy(); $array['language'] = $this->getLanguage(); $array['article'] = $this->getArticle(); return $array; } public function exchangeArray($data) { parent::exchangeArray($data); $this->setLanguage((isset($data['language'])) ? $data['language'] : $this->getLanguage()); $this->setArticle((isset($data['article'])) ? $data['article'] : $this->getArticle()); } }
armandduijn/gewisweb
module/Company/src/Company/Model/CompanyFeaturedPackage.php
PHP
gpl-3.0
2,015
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// AlipayDaoweiOrderQueryModel Data Structure. /// </summary> [Serializable] public class AlipayDaoweiOrderQueryModel : AopObject { /// <summary> /// 到位业务订单号。用户在到位下单时,由到位系统生成的32位全局唯一数字 id。 通过应用中的应用网关post发送给商户(应用网关配置参考链接:https%3A%2F%2Fdoc.open.alipay.com%2Fdocs%2Fdoc.htm%3Fspm%3Da219a.7629140.0.0.TcIuKL%26treeId%3D193%26articleId%3D105310%26docType%3D1)。 /// </summary> [XmlElement("order_no")] public string OrderNo { get; set; } } }
ColgateKas/cms
source/BaiRong.Core/ThirdParty/Alipay/openapi/Domain/AlipayDaoweiOrderQueryModel.cs
C#
gpl-3.0
718
"""Tests for CMFNotification installation ad uninstallation. $Id: testInstallation.py 65679 2008-05-25 23:45:26Z dbaty $ """ from zope.component import getUtility from zope.component import getMultiAdapter from AccessControl.PermissionRole import rolesForPermissionOn from plone.portlets.interfaces import IPortletManager from plone.portlets.interfaces import IPortletAssignmentMapping from Products.CMFCore.utils import getToolByName from Products.CMFNotification.config import LAYER_NAME from Products.CMFNotification.config import PORTLET_NAME from Products.CMFNotification.NotificationTool import ID as TOOL_ID from Products.CMFNotification.permissions import SUBSCRIBE_PERMISSION from Products.CMFNotification.tests.plonetestbrowser import Browser from Products.CMFNotification.tests.base import CMFNotificationTestCase class TestInstallation(CMFNotificationTestCase): """Make sure that the product is properly installed.""" def afterSetUp(self): pass def testToolIsThere(self): portal = self.portal tool = getToolByName(self.portal, TOOL_ID) self.failUnless(tool is not None) def testSkinLayerIsThere(self): stool = getToolByName(self.portal, 'portal_skins') for skin, layers in stool._getSelections().items(): layers = layers.split(',') self.failUnless(LAYER_NAME in layers) self.failUnless(LAYER_NAME in stool.objectIds()) def testPortletCanBeAdded(self): base_url = self.portal.absolute_url() for name in ('plone.leftcolumn', 'plone.rightcolumn'): manager = getUtility(IPortletManager, name=name, context=self.portal) titles = [p.title for p in manager.getAddablePortletTypes()] self.failUnless(PORTLET_NAME in titles) manager = getUtility(IPortletManager, name='plone.rightcolumn', context=self.portal) right_portlets = getMultiAdapter((self.portal, manager), IPortletAssignmentMapping, context=self.portal) right_portlets = right_portlets.keys() self.failUnless(PORTLET_NAME in right_portlets) def testPermissionHasBeenSet(self): roles = set(rolesForPermissionOn(SUBSCRIBE_PERMISSION, self.portal)) self.failUnlessEqual(roles, set(('Manager', 'Member'))) def testConfigletHasBeenAdded(self): cptool = getToolByName(self.portal, 'portal_controlpanel') configlets = [c.getId() for c in cptool.listActions()] self.failUnless('cmfnotification_configuration' in configlets) class TestUnInstallation(CMFNotificationTestCase): """Test that the product has been properly uninstalled.""" def afterSetUp(self): """Uninstall the product before running each test.""" qtool = getToolByName(self.portal, 'portal_quickinstaller') self.setRoles(['Manager']) qtool.uninstallProducts(['CMFNotification']) def testToolIsNotThere(self): tool = getToolByName(self.portal, TOOL_ID, None) self.failUnless(tool is None) def testSkinLayerIsNotThere(self): stool = getToolByName(self.portal, 'portal_skins') for skin, layers in stool._getSelections().items(): layers = layers.split(',') self.failUnless (LAYER_NAME not in layers) self.failUnless(LAYER_NAME not in stool.objectIds()) def testPortletDoNoExist(self): base_url = self.portal.absolute_url() for name in ('plone.leftcolumn', 'plone.rightcolumn'): manager = getUtility(IPortletManager, name=name, context=self.portal) titles = [p.title for p in manager.getAddablePortletTypes()] self.failUnless(PORTLET_NAME not in titles) manager = getUtility(IPortletManager, name='plone.rightcolumn', context=self.portal) right_portlets = getMultiAdapter((self.portal, manager), IPortletAssignmentMapping, context=self.portal) right_portlets = right_portlets.keys() self.failUnless(PORTLET_NAME not in right_portlets) def testConfigletDoNotExist(self): cptool = getToolByName(self.portal, 'portal_controlpanel') configlets = [c.getId() for c in cptool.listActions()] self.failUnless('cmfnotification_configuration' not in configlets) def test_suite(): from unittest import TestSuite, makeSuite suite = TestSuite() suite.addTest(makeSuite(TestInstallation)) suite.addTest(makeSuite(TestUnInstallation)) return suite
cynapse/cynin
products/CMFNotification/tests/testInstallation.py
Python
gpl-3.0
4,873
$(document).ready(function() { /* Add a [>>>] button on the top-right corner of getthecode div to show the code */ var div = $('.getthecode-header') var button_text = 'Show/Hide the code'; var button_styles = { 'cursor':'pointer', 'float': 'right', 'text-size': '75%', 'font-family': 'monospace' } div.each(function(index) { var jthis = $(this); var button = $('<span class="show-code-button">&gt;&gt;&gt;</span><div style="clear:both;"></div>'); button.css(button_styles) button.attr('title', button_text); jthis.append(button); jthis.parent().find('.highlight-python').toggle(); }); // define the behavior of the button when it's clicked $('.show-code-button').click(function() { var button = $(this); button.parent().parent().find('.highlight-python').toggle(); }); });
FabriceSalvaire/simple-morpho-math
doc/sphinx/source/_static/hidecode.js
JavaScript
gpl-3.0
851
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack.tests.unit import base from openstack.orchestration.v1 import resource FAKE_ID = '32e39358-2422-4ad0-a1b5-dd60696bf564' FAKE_NAME = 'test_stack' FAKE = { 'links': [{ 'href': 'http://res_link', 'rel': 'self' }, { 'href': 'http://stack_link', 'rel': 'stack' }], 'logical_resource_id': 'the_resource', 'name': 'the_resource', 'physical_resource_id': '9f38ab5a-37c8-4e40-9702-ce27fc5f6954', 'required_by': [], 'resource_type': 'OS::Heat::FakeResource', 'status': 'CREATE_COMPLETE', 'status_reason': 'state changed', 'updated_time': '2015-03-09T12:15:57.233772', } class TestResource(base.TestCase): def test_basic(self): sot = resource.Resource() self.assertEqual('resource', sot.resource_key) self.assertEqual('resources', sot.resources_key) self.assertEqual('/stacks/%(stack_name)s/%(stack_id)s/resources', sot.base_path) self.assertFalse(sot.allow_create) self.assertFalse(sot.allow_retrieve) self.assertFalse(sot.allow_commit) self.assertFalse(sot.allow_delete) self.assertTrue(sot.allow_list) def test_make_it(self): sot = resource.Resource(**FAKE) self.assertEqual(FAKE['links'], sot.links) self.assertEqual(FAKE['logical_resource_id'], sot.logical_resource_id) self.assertEqual(FAKE['name'], sot.name) self.assertEqual(FAKE['physical_resource_id'], sot.physical_resource_id) self.assertEqual(FAKE['required_by'], sot.required_by) self.assertEqual(FAKE['resource_type'], sot.resource_type) self.assertEqual(FAKE['status'], sot.status) self.assertEqual(FAKE['status_reason'], sot.status_reason) self.assertEqual(FAKE['updated_time'], sot.updated_at)
ctrlaltdel/neutrinator
vendor/openstack/tests/unit/orchestration/v1/test_resource.py
Python
gpl-3.0
2,405
/** * License Agreement for OpenSearchServer * * Copyright (C) 2013-2015 Emmanuel Keller / Jaeksoft * * http://www.open-search-server.com * * This file is part of OpenSearchServer. * * OpenSearchServer 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. * * OpenSearchServer 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 OpenSearchServer. * If not, see <http://www.gnu.org/licenses/>. **/ package com.jaeksoft.searchlib.script.commands; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.apache.commons.collections.CollectionUtils; import com.jaeksoft.searchlib.Client; import com.jaeksoft.searchlib.SearchLibException; import com.jaeksoft.searchlib.analysis.LanguageEnum; import com.jaeksoft.searchlib.index.IndexDocument; import com.jaeksoft.searchlib.script.CommandAbstract; import com.jaeksoft.searchlib.script.CommandEnum; import com.jaeksoft.searchlib.script.ScriptCommandContext; import com.jaeksoft.searchlib.script.ScriptException; public class IndexDocumentCommands { public static class New extends CommandAbstract { public New() { super(CommandEnum.INDEX_DOCUMENT_NEW); } @Override public void run(ScriptCommandContext context, String id, String... parameters) throws ScriptException { IndexDocument indexDocument = new IndexDocument( LanguageEnum.findByNameOrCode(getParameterString(1))); context.addIndexDocument(indexDocument); } } public static class AddValue extends CommandAbstract { public AddValue() { super(CommandEnum.INDEX_DOCUMENT_ADD_VALUE); } @Override public void run(ScriptCommandContext context, String id, String... parameters) throws ScriptException { checkParameters(2, parameters); IndexDocument indexDocument = context.getIndexDocument(); if (indexDocument == null) throwError("No index document has been created. Call INDEX_DOCUMENT_NEW."); String field = getParameterString(0); String value = getParameterString(1); value = context.replaceVariables(value); Float boost = getParameterFloat(2); indexDocument.add(field, value, boost == null ? 1.0F : boost); } } public static class AddNow extends CommandAbstract { public AddNow() { super(CommandEnum.INDEX_DOCUMENT_ADD_NOW); } @Override public void run(ScriptCommandContext context, String id, String... parameters) throws ScriptException { checkParameters(2, parameters); IndexDocument indexDocument = context.getIndexDocument(); if (indexDocument == null) throwError("No index document has been created. Call INDEX_DOCUMENT_NEW."); String field = getParameterString(0); String format = getParameterString(1); format = context.replaceVariables(format); SimpleDateFormat df = new SimpleDateFormat(format); String value = df.format(new Date()); Float boost = getParameterFloat(2); indexDocument.add(field, value, boost == null ? 1.0F : boost); } } public static class Update extends CommandAbstract { public Update() { super(CommandEnum.INDEX_DOCUMENT_UPDATE); } @Override public void run(ScriptCommandContext context, String id, String... parameters) throws ScriptException { List<IndexDocument> indexDocuments = context.getIndexDocuments(); if (CollectionUtils.isEmpty(indexDocuments)) return; Client client = (Client) context.getConfig(); try { context.clearIndexDocuments(client .updateDocuments(indexDocuments)); } catch (IOException e) { throw new ScriptException(e); } catch (SearchLibException e) { throw new ScriptException(e); } } } }
nvoron23/opensearchserver
src/main/java/com/jaeksoft/searchlib/script/commands/IndexDocumentCommands.java
Java
gpl-3.0
4,085
/* * * Copyright (c) Toon Knapen & Kresimir Fresl 2003 * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * KF acknowledges the support of the Faculty of Civil Engineering, * University of Zagreb, Croatia. * */ #ifndef BOOST_NUMERIC_BINDINGS_LAPACK_POSV_HPP #define BOOST_NUMERIC_BINDINGS_LAPACK_POSV_HPP #include <boost/numeric/bindings/traits/type_traits.hpp> #include <boost/numeric/bindings/traits/traits.hpp> #include <boost/numeric/bindings/lapack/lapack.h> #ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK # include <boost/numeric/bindings/traits/detail/symm_herm_traits.hpp> # include <boost/static_assert.hpp> # include <boost/type_traits/is_same.hpp> #endif #include <cassert> namespace boost { namespace numeric { namespace bindings { namespace lapack { ///////////////////////////////////////////////////////////////////// // // system of linear equations A * X = B // with A symmetric or Hermitian positive definite matrix // ///////////////////////////////////////////////////////////////////// /* * posv() computes the solution to a system of linear equations * A * X = B, where A is an N-by-N symmetric or Hermitian positive * definite matrix and X and B are N-by-NRHS matrices. * * The Cholesky decomposition is used to factor A as * A = U^T * U or A = U^H * U, if UPLO = 'U', * A = L * L^T or A = L * L^H, if UPLO = 'L', * where U is an upper triangular matrix and L is a lower triangular * matrix. The factored form of A is then used to solve the system of * equations A * X = B. * * If UPLO = 'U', the leading N-by-N upper triangular part of A * contains the upper triangular part of the matrix A, and the * strictly lower triangular part of A is not referenced. * If UPLO = 'L', the leading N-by-N lower triangular part of A * contains the lower triangular part of the matrix A, and the * strictly upper triangular part of A is not referenced. */ namespace detail { inline void posv (char const uplo, int const n, int const nrhs, float* a, int const lda, float* b, int const ldb, int* info) { LAPACK_SPOSV (&uplo, &n, &nrhs, a, &lda, b, &ldb, info); } inline void posv (char const uplo, int const n, int const nrhs, double* a, int const lda, double* b, int const ldb, int* info) { LAPACK_DPOSV (&uplo, &n, &nrhs, a, &lda, b, &ldb, info); } inline void posv (char const uplo, int const n, int const nrhs, traits::complex_f* a, int const lda, traits::complex_f* b, int const ldb, int* info) { LAPACK_CPOSV (&uplo, &n, &nrhs, traits::complex_ptr (a), &lda, traits::complex_ptr (b), &ldb, info); } inline void posv (char const uplo, int const n, int const nrhs, traits::complex_d* a, int const lda, traits::complex_d* b, int const ldb, int* info) { LAPACK_ZPOSV (&uplo, &n, &nrhs, traits::complex_ptr (a), &lda, traits::complex_ptr (b), &ldb, info); } template <typename SymmMatrA, typename MatrB> inline int posv (char const uplo, SymmMatrA& a, MatrB& b) { int const n = traits::matrix_size1 (a); assert (n == traits::matrix_size2 (a)); assert (n == traits::matrix_size1 (b)); int info; posv (uplo, n, traits::matrix_size2 (b), traits::matrix_storage (a), traits::leading_dimension (a), traits::matrix_storage (b), traits::leading_dimension (b), &info); return info; } } template <typename SymmMatrA, typename MatrB> inline int posv (char const uplo, SymmMatrA& a, MatrB& b) { assert (uplo == 'U' || uplo == 'L'); #ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK BOOST_STATIC_ASSERT((boost::is_same< typename traits::matrix_traits<SymmMatrA>::matrix_structure, traits::general_t >::value)); BOOST_STATIC_ASSERT((boost::is_same< typename traits::matrix_traits<MatrB>::matrix_structure, traits::general_t >::value)); #endif return detail::posv (uplo, a, b); } template <typename SymmMatrA, typename MatrB> inline int posv (SymmMatrA& a, MatrB& b) { #ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK typedef traits::matrix_traits<SymmMatrA> matraits; typedef typename matraits::value_type val_t; BOOST_STATIC_ASSERT( (traits::detail::symm_herm_compatible< val_t, typename matraits::matrix_structure >::value ) ) ; BOOST_STATIC_ASSERT((boost::is_same< typename traits::matrix_traits<MatrB>::matrix_structure, traits::general_t >::value)); #endif char uplo = traits::matrix_uplo_tag (a); return detail::posv (uplo, a, b); } /* * potrf() computes the Cholesky factorization of a symmetric * or Hermitian positive definite matrix A. The factorization has * the form * A = U^T * U or A = U^H * U, if UPLO = 'U', * A = L * L^T or A = L * L^H, if UPLO = 'L', * where U is an upper triangular matrix and L is lower triangular. */ namespace detail { inline void potrf (char const uplo, int const n, float* a, int const lda, int* info) { LAPACK_SPOTRF (&uplo, &n, a, &lda, info); } inline void potrf (char const uplo, int const n, double* a, int const lda, int* info) { LAPACK_DPOTRF (&uplo, &n, a, &lda, info); } inline void potrf (char const uplo, int const n, traits::complex_f* a, int const lda, int* info) { LAPACK_CPOTRF (&uplo, &n, traits::complex_ptr (a), &lda, info); } inline void potrf (char const uplo, int const n, traits::complex_d* a, int const lda, int* info) { LAPACK_ZPOTRF (&uplo, &n, traits::complex_ptr (a), &lda, info); } template <typename SymmMatrA> inline int potrf (char const uplo, SymmMatrA& a) { int const n = traits::matrix_size1 (a); assert (n == traits::matrix_size2 (a)); int info; potrf (uplo, n, traits::matrix_storage (a), traits::leading_dimension (a), &info); return info; } } template <typename SymmMatrA> inline int potrf (char const uplo, SymmMatrA& a) { assert (uplo == 'U' || uplo == 'L'); #ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK BOOST_STATIC_ASSERT((boost::is_same< typename traits::matrix_traits<SymmMatrA>::matrix_structure, traits::general_t >::value)); #endif return detail::potrf (uplo, a); } template <typename SymmMatrA> inline int potrf (SymmMatrA& a) { #ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK typedef traits::matrix_traits<SymmMatrA> matraits; typedef typename matraits::value_type val_t; BOOST_STATIC_ASSERT((boost::is_same< typename matraits::matrix_structure, typename traits::detail::symm_herm_t<val_t>::type >::value)); #endif char uplo = traits::matrix_uplo_tag (a); return detail::potrf (uplo, a); } /* * potrs() solves a system of linear equations A*X = B with * a symmetric or Hermitian positive definite matrix A using * the Cholesky factorization computed by potrf(). */ namespace detail { inline void potrs (char const uplo, int const n, int const nrhs, float const* a, int const lda, float* b, int const ldb, int* info) { LAPACK_SPOTRS (&uplo, &n, &nrhs, a, &lda, b, &ldb, info); } inline void potrs (char const uplo, int const n, int const nrhs, double const* a, int const lda, double* b, int const ldb, int* info) { LAPACK_DPOTRS (&uplo, &n, &nrhs, a, &lda, b, &ldb, info); } inline void potrs (char const uplo, int const n, int const nrhs, traits::complex_f const* a, int const lda, traits::complex_f* b, int const ldb, int* info) { LAPACK_CPOTRS (&uplo, &n, &nrhs, traits::complex_ptr (a), &lda, traits::complex_ptr (b), &ldb, info); } inline void potrs (char const uplo, int const n, int const nrhs, traits::complex_d const* a, int const lda, traits::complex_d* b, int const ldb, int* info) { LAPACK_ZPOTRS (&uplo, &n, &nrhs, traits::complex_ptr (a), &lda, traits::complex_ptr (b), &ldb, info); } template <typename SymmMatrA, typename MatrB> inline int potrs (char const uplo, SymmMatrA const& a, MatrB& b) { int const n = traits::matrix_size1 (a); assert (n == traits::matrix_size2 (a)); assert (n == traits::matrix_size1 (b)); int info; potrs (uplo, n, traits::matrix_size2 (b), #ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING traits::matrix_storage (a), #else traits::matrix_storage_const (a), #endif traits::leading_dimension (a), traits::matrix_storage (b), traits::leading_dimension (b), &info); return info; } } template <typename SymmMatrA, typename MatrB> inline int potrs (char const uplo, SymmMatrA const& a, MatrB& b) { assert (uplo == 'U' || uplo == 'L'); #ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK BOOST_STATIC_ASSERT((boost::is_same< typename traits::matrix_traits<SymmMatrA>::matrix_structure, traits::general_t >::value)); BOOST_STATIC_ASSERT((boost::is_same< typename traits::matrix_traits<MatrB>::matrix_structure, traits::general_t >::value)); #endif return detail::potrs (uplo, a, b); } template <typename SymmMatrA, typename MatrB> inline int potrs (SymmMatrA const& a, MatrB& b) { #ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK typedef traits::matrix_traits<SymmMatrA> matraits; typedef traits::matrix_traits<MatrB> mbtraits; typedef typename matraits::value_type val_t; BOOST_STATIC_ASSERT((boost::is_same< typename matraits::matrix_structure, typename traits::detail::symm_herm_t<val_t>::type >::value)); BOOST_STATIC_ASSERT((boost::is_same< typename mbtraits::matrix_structure, traits::general_t >::value)); #endif char uplo = traits::matrix_uplo_tag (a); return detail::potrs (uplo, a, b); } // TO DO: potri() } }}} #endif
BhallaLab/moose
moose-core/external/boost-numeric-bindings/boost/numeric/bindings/lapack/posv.hpp
C++
gpl-3.0
11,117
/* * Copyright (c) 2017, Miguel Gamboa * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package util; import java.util.Comparator; import java.util.function.Function; /** * @author Miguel Gamboa * created on 26-04-2017 */ public class Comparators { public static <T, R extends Comparable<R>> ComparatorBy<T> comparing(Function<T, R> prop) { return (o1, o2) -> prop.apply(o1).compareTo(prop.apply(o2)); } public interface ComparatorBy<T> extends Comparator<T> { public default ComparatorBy<T> invert() { return (o1, o2) -> compare(o2, o1); } public default <R extends Comparable<R>> ComparatorBy<T> thenBy(Function<T, R> prop) { Comparator<T> then = Comparators.comparing(prop); // Comparador criado 1 x return (o1, o2) -> { int res = compare(o1, o2); if(res != 0) return res; return then.compare(o1, o2); // Captura da variável then }; } } } /* public class Comparators { public static <T, R extends Comparable<R>> ComparatorBy<T> comparing(Function<T, R> prop) { Comparator<T> cmp = (o1, o2) -> prop.apply(o1).compareTo(prop.apply(o2)); return new ComparatorBy<T>(cmp); } public static class ComparatorBy<T> implements Comparator<T> { final Comparator<T> cmp; public ComparatorBy(Comparator<T> cmp) { this.cmp = cmp; } @Override public int compare(T o1, T o2) { return cmp.compare(o1, o2); } public ComparatorBy<T> invert() { return new ComparatorBy<>((o1, o2) -> cmp.compare(o2, o1)); } public <R extends Comparable<R>> ComparatorBy<T> thenBy(Function<T, R> prop) { Comparator<T> then = Comparators.comparing(prop); // Comparador criado 1 x return new ComparatorBy<>((o1, o2) -> { int res = compare(o1, o2); if(res != 0) return res; return then.compare(o1, o2); // Captura da variável then }); } } } */
isel-leic-mpd/mpd-2017-i41d
aula33-weather-async/src/main/java/util/Comparators.java
Java
gpl-3.0
2,718
<?php namespace Elementor\Core\Common\Modules\Connect\Apps; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } abstract class Base_User_App extends Base_App { /** * @since 2.3.0 * @access protected */ protected function update_settings() { update_user_option( get_current_user_id(), $this->get_option_name(), $this->data ); } /** * @since 2.3.0 * @access protected */ protected function init_data() { $this->data = get_user_option( $this->get_option_name() ); if ( ! $this->data ) { $this->data = []; } } }
pojome/elementor
core/common/modules/connect/apps/base-user-app.php
PHP
gpl-3.0
560
using System; using System.ComponentModel.Composition; using System.IO; using System.IO.Abstractions; using System.Linq; namespace GitCommands.Git { /// <summary> /// Provides the ability to resolve the location of .git folder. /// </summary> public interface IGitDirectoryResolver { /// <summary> /// Resolves the .git folder for the given repository. /// </summary> /// <param name="repositoryPath">The repository working folder.</param> /// <returns>The resolved location of .git folder.</returns> string Resolve(string repositoryPath); } /// <summary> /// Resolves the location of .git folder. /// </summary> [Export(typeof(IGitDirectoryResolver))] public sealed class GitDirectoryResolver : IGitDirectoryResolver { private readonly IFileSystem _fileSystem; public GitDirectoryResolver(IFileSystem fileSystem) { _fileSystem = fileSystem; } public GitDirectoryResolver() : this(new FileSystem()) { } /// <summary> /// Resolves the .git folder for the given repository. /// </summary> /// <param name="repositoryPath">The repository working folder.</param> /// <returns> /// The resolved location of .git folder. /// <list type="table"> /// <item> /// <term>If <paramref name="repositoryPath"/> is an empty string</term> /// <description>it resolves to <see cref="string.Empty"/></description> /// </item> /// <item> /// <term>If <paramref name="repositoryPath"/> contains a .git file (i.e. the repository is a submodule)</term> /// <description>it resolves to the location of the submodule's .git folder under the superproject's .git folder with the trailing slash</description> /// </item> /// <item> /// <term>If <paramref name="repositoryPath"/> contains .git folder</term> /// <description>it resolves to the .git folder with the trailing slash</description> /// </item> /// <item> /// <term>else</term> /// <description>it returns <paramref name="repositoryPath"/> unchanged.</description> /// </item> /// </list> /// </returns> /// <exception cref="ArgumentNullException"><paramref name="repositoryPath"/> is <see langword="null"/>.</exception> public string Resolve(string repositoryPath) { if (repositoryPath is null) { throw new ArgumentNullException(nameof(repositoryPath)); } if (string.IsNullOrWhiteSpace(repositoryPath)) { return string.Empty; } var gitPath = Path.Combine(repositoryPath, ".git"); if (_fileSystem.File.Exists(gitPath)) { const string gitdir = "gitdir:"; var line = _fileSystem.File.ReadLines(gitPath).FirstOrDefault(l => l.StartsWith(gitdir)); if (line is not null) { string path = line.Substring(gitdir.Length).Trim().ToNativePath(); if (Path.IsPathRooted(path)) { return path.EnsureTrailingPathSeparator(); } return Path.GetFullPath(Path.Combine(repositoryPath, path)).EnsureTrailingPathSeparator(); } } gitPath = gitPath.EnsureTrailingPathSeparator(); return !_fileSystem.Directory.Exists(gitPath) ? repositoryPath : gitPath; } } }
pmiossec/gitextensions
GitCommands/Git/GitDirectoryResolver.cs
C#
gpl-3.0
3,720
package org.bukkit.entity.minecart; import org.bukkit.entity.Minecart; /** * Represents a powered minecart. A powered minecart moves on its own when a * player deposits {@link org.bukkit.Material#COAL fuel}. */ public interface PoweredMinecart extends Minecart { }
Scrik/Cauldron-1
eclipse/cauldron/src/main/java/org/bukkit/entity/minecart/PoweredMinecart.java
Java
gpl-3.0
269
<?php /** --------------------------------------------------------------------- * themes/default/views/mediaViewers/UniversalViewerSearchManifest.php : * ---------------------------------------------------------------------- * CollectiveAccess * Open-source collections management software * ---------------------------------------------------------------------- * * Software by Whirl-i-Gig (http://www.whirl-i-gig.com) * Copyright 2017-2018 Whirl-i-Gig * * For more information visit http://www.CollectiveAccess.org * * This program is free software; you may redistribute it and/or modify it under * the terms of the provided license as published by Whirl-i-Gig * * CollectiveAccess is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * This source code is free and modifiable under the terms of * GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See * the "license.txt" file for details, or visit the CollectiveAccess web site at * http://www.CollectiveAccess.org * * @package CollectiveAccess * @subpackage Media * @license http://www.gnu.org/copyleft/gpl.html GNU Public License version 3 * * ---------------------------------------------------------------------- */ $va_data = $this->getVar('data'); $vs_identifier = $this->getVar('identifier'); $t_instance = $this->getVar('t_instance'); $vo_request = $this->getVar('request'); $va_locs = $this->getVar('locations'); $va_resources = []; foreach($va_locs['locations'] as $p => $va_loc_parts) { if (!is_array($va_loc_parts)) { continue; } foreach($va_loc_parts as $va_loc) { $x = (int)(($va_loc['x1p']) * $va_data['width']); $y = (int)(($va_loc['y1p']) * $va_data['height']); $w = (int)(($va_loc['x2p']) * $va_data['width']) - (int)(($va_loc['x1p']) * $va_data['width']); $h = (int)(($va_loc['y2p']) * $va_data['height']) - (int)(($va_loc['y1p']) * $va_data['height']); $va_resources[] = [ "@id" => "anno_{$vs_identifier}:{$p}", "@type" => "oa:Annotation", "motivation" => "sc:painting", "resource" => [ "@type" => "cnt:ContentAsText", "chars"=> $va_loc['word'] ], "on" => "{$vs_identifier}:{$p}#xywh={$x},{$y},{$w},{$h}" ]; } } $va_manifest = [ "@context" => "http://iiif.io/api/search/0/context.json", "@id" => "{$vs_identifier}_results", "@type" => "sc:AnnotationList", "within" => [ "@type" => "sc:Layer", "total" => sizeof($va_locs) ], "startIndex" => 0, "resources" => $va_resources ]; print caFormatJson(json_encode($va_manifest, JSON_UNESCAPED_SLASHES));
gjerdery/providence
themes/default/views/mediaViewers/UniversalViewerSearchManifest.php
PHP
gpl-3.0
2,915
/*** * itSIMPLE: Integrated Tool Software Interface for Modeling PLanning Environments * * Copyright (C) 2007,2008 Universidade de Sao Paulo * * This file is part of itSIMPLE. * * itSIMPLE 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. Other licenses might be available * upon written agreement. * * itSIMPLE 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 itSIMPLE. If not, see <http://www.gnu.org/licenses/>. * * Authors: Tiago S. Vaquero, * Victor Romero. **/ package src.gui; // SplashScreen.java //A simple application to show a title screen in the center of the screen //for the amount of time given in the constructor. This class includes //a sample main() method to test the splash screen, but it's meant for use //with other applications. // import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.ImageIcon; import javax.swing.JWindow; public class SplashScreen extends JWindow implements Runnable { /** * */ private static final long serialVersionUID = -7720533134526695367L; private int duration; private Image splash; int width; int height; public SplashScreen(int d) { duration = d; setAlwaysOnTop(true); addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e){ setVisible(false); dispose(); } }); } // A simple little method to show a title screen in the center // of the screen for the amount of time given in the constructor public void showSplash() { ImageIcon splashImage = new ImageIcon("resources/images/Splash.png"); splash = splashImage.getImage(); width = splashImage.getIconWidth(); height = splashImage.getIconHeight(); // Set the window's bounds, centering the window Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); int x = (screen.width - width) / 2; int y = (screen.height - height) / 2; setBounds(x, y, width, height); // Display it setVisible(true); // wait pauseExec(duration); // close it setVisible(false); } public void showSplashAndExit() { showSplash(); System.exit(0); } private void pauseExec(long dur){ try{ Thread.sleep(dur); } catch (InterruptedException ie){} } public void paint(Graphics g) { g.drawImage(splash,0,0,width, height, this); } public void run() { showSplash(); } }
jdahaldev/itsimple
src/gui/SplashScreen.java
Java
gpl-3.0
3,009
/* * Copyright © 2011,2012 Google, Inc. * * This is part of HarfBuzz, a text shaping library. * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and its documentation for any purpose, provided that the * above copyright notice and the following two paragraphs appear in * all copies of this software. * * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. * * Google Author(s): Behdad Esfahbod */ #include "options.hh" #ifdef HAVE_FREETYPE #include <hb-ft.h> #endif #ifdef HAVE_OT #include <hb-ot.h> #endif struct supported_font_funcs_t { char name[4]; void (*func) (hb_font_t *); } supported_font_funcs[] = { #ifdef HAVE_FREETYPE {"ft", hb_ft_font_set_funcs}, #endif #ifdef HAVE_OT {"ot", hb_ot_font_set_funcs}, #endif }; void fail (hb_bool_t suggest_help, const char *format, ...) { const char *msg; va_list vap; va_start (vap, format); msg = g_strdup_vprintf (format, vap); va_end (vap); const char *prgname = g_get_prgname (); g_printerr ("%s: %s\n", prgname, msg); if (suggest_help) g_printerr ("Try `%s --help' for more information.\n", prgname); exit (1); } hb_bool_t debug = false; static gchar * shapers_to_string (void) { GString *shapers = g_string_new (NULL); const char **shaper_list = hb_shape_list_shapers (); for (; *shaper_list; shaper_list++) { g_string_append (shapers, *shaper_list); g_string_append_c (shapers, ','); } g_string_truncate (shapers, MAX (0, (gint)shapers->len - 1)); return g_string_free (shapers, false); } static G_GNUC_NORETURN gboolean show_version (const char *name G_GNUC_UNUSED, const char *arg G_GNUC_UNUSED, gpointer data G_GNUC_UNUSED, GError **error G_GNUC_UNUSED) { g_printf ("%s (%s) %s\n", g_get_prgname (), PACKAGE_NAME, PACKAGE_VERSION); char *shapers = shapers_to_string (); g_printf ("Available shapers: %s\n", shapers); g_free (shapers); if (strcmp (HB_VERSION_STRING, hb_version_string ())) g_printf ("Linked HarfBuzz library has a different version: %s\n", hb_version_string ()); exit(0); } void option_parser_t::add_main_options (void) { GOptionEntry entries[] = { {"version", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, (gpointer) &show_version, "Show version numbers", NULL}, {"debug", 0, 0, G_OPTION_ARG_NONE, &debug, "Free all resources before exit", NULL}, {NULL} }; g_option_context_add_main_entries (context, entries, NULL); } static gboolean pre_parse (GOptionContext *context G_GNUC_UNUSED, GOptionGroup *group G_GNUC_UNUSED, gpointer data, GError **error) { option_group_t *option_group = (option_group_t *) data; option_group->pre_parse (error); return *error == NULL; } static gboolean post_parse (GOptionContext *context G_GNUC_UNUSED, GOptionGroup *group G_GNUC_UNUSED, gpointer data, GError **error) { option_group_t *option_group = static_cast<option_group_t *>(data); option_group->post_parse (error); return *error == NULL; } void option_parser_t::add_group (GOptionEntry *entries, const gchar *name, const gchar *description, const gchar *help_description, option_group_t *option_group) { GOptionGroup *group = g_option_group_new (name, description, help_description, static_cast<gpointer>(option_group), NULL); g_option_group_add_entries (group, entries); g_option_group_set_parse_hooks (group, pre_parse, post_parse); g_option_context_add_group (context, group); } void option_parser_t::parse (int *argc, char ***argv) { setlocale (LC_ALL, ""); GError *parse_error = NULL; if (!g_option_context_parse (context, argc, argv, &parse_error)) { if (parse_error != NULL) { fail (true, "%s", parse_error->message); //g_error_free (parse_error); } else fail (true, "Option parse error"); } } static gboolean parse_margin (const char *name G_GNUC_UNUSED, const char *arg, gpointer data, GError **error G_GNUC_UNUSED) { view_options_t *view_opts = (view_options_t *) data; view_options_t::margin_t &m = view_opts->margin; switch (sscanf (arg, "%lf%*[ ,]%lf%*[ ,]%lf%*[ ,]%lf", &m.t, &m.r, &m.b, &m.l)) { case 1: m.r = m.t; case 2: m.b = m.t; case 3: m.l = m.r; case 4: return true; default: g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "%s argument should be one to four space-separated numbers", name); return false; } } static gboolean parse_shapers (const char *name G_GNUC_UNUSED, const char *arg, gpointer data, GError **error G_GNUC_UNUSED) { shape_options_t *shape_opts = (shape_options_t *) data; g_strfreev (shape_opts->shapers); shape_opts->shapers = g_strsplit (arg, ",", 0); return true; } static G_GNUC_NORETURN gboolean list_shapers (const char *name G_GNUC_UNUSED, const char *arg G_GNUC_UNUSED, gpointer data G_GNUC_UNUSED, GError **error G_GNUC_UNUSED) { for (const char **shaper = hb_shape_list_shapers (); *shaper; shaper++) g_printf ("%s\n", *shaper); exit(0); } static gboolean parse_features (const char *name G_GNUC_UNUSED, const char *arg, gpointer data, GError **error G_GNUC_UNUSED) { shape_options_t *shape_opts = (shape_options_t *) data; char *s = (char *) arg; char *p; shape_opts->num_features = 0; g_free (shape_opts->features); shape_opts->features = NULL; if (!*s) return true; /* count the features first, so we can allocate memory */ p = s; do { shape_opts->num_features++; p = strchr (p, ','); if (p) p++; } while (p); shape_opts->features = (hb_feature_t *) calloc (shape_opts->num_features, sizeof (*shape_opts->features)); /* now do the actual parsing */ p = s; shape_opts->num_features = 0; while (p && *p) { char *end = strchr (p, ','); if (hb_feature_from_string (p, end ? end - p : -1, &shape_opts->features[shape_opts->num_features])) shape_opts->num_features++; p = end ? end + 1 : NULL; } return true; } void view_options_t::add_options (option_parser_t *parser) { GOptionEntry entries[] = { {"annotate", 0, 0, G_OPTION_ARG_NONE, &this->annotate, "Annotate output rendering", NULL}, {"background", 0, 0, G_OPTION_ARG_STRING, &this->back, "Set background color (default: " DEFAULT_BACK ")", "rrggbb/rrggbbaa"}, {"foreground", 0, 0, G_OPTION_ARG_STRING, &this->fore, "Set foreground color (default: " DEFAULT_FORE ")", "rrggbb/rrggbbaa"}, {"line-space", 0, 0, G_OPTION_ARG_DOUBLE, &this->line_space, "Set space between lines (default: 0)", "units"}, {"margin", 0, 0, G_OPTION_ARG_CALLBACK, (gpointer) &parse_margin, "Margin around output (default: " G_STRINGIFY(DEFAULT_MARGIN) ")","one to four numbers"}, {NULL} }; parser->add_group (entries, "view", "View options:", "Options controlling output rendering", this); } void shape_options_t::add_options (option_parser_t *parser) { GOptionEntry entries[] = { {"list-shapers", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, (gpointer) &list_shapers, "List available shapers and quit", NULL}, {"shaper", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_CALLBACK, (gpointer) &parse_shapers, "Hidden duplicate of --shapers", NULL}, {"shapers", 0, 0, G_OPTION_ARG_CALLBACK, (gpointer) &parse_shapers, "Set comma-separated list of shapers to try","list"}, {"direction", 0, 0, G_OPTION_ARG_STRING, &this->direction, "Set text direction (default: auto)", "ltr/rtl/ttb/btt"}, {"language", 0, 0, G_OPTION_ARG_STRING, &this->language, "Set text language (default: $LANG)", "langstr"}, {"script", 0, 0, G_OPTION_ARG_STRING, &this->script, "Set text script (default: auto)", "ISO-15924 tag"}, {"bot", 0, 0, G_OPTION_ARG_NONE, &this->bot, "Treat text as beginning-of-paragraph", NULL}, {"eot", 0, 0, G_OPTION_ARG_NONE, &this->eot, "Treat text as end-of-paragraph", NULL}, {"preserve-default-ignorables",0, 0, G_OPTION_ARG_NONE, &this->preserve_default_ignorables, "Preserve Default-Ignorable characters", NULL}, {"utf8-clusters", 0, 0, G_OPTION_ARG_NONE, &this->utf8_clusters, "Use UTF8 byte indices, not char indices", NULL}, {"cluster-level", 0, 0, G_OPTION_ARG_INT, &this->cluster_level, "Cluster merging level (default: 0)", "0/1/2"}, {"normalize-glyphs",0, 0, G_OPTION_ARG_NONE, &this->normalize_glyphs, "Rearrange glyph clusters in nominal order", NULL}, {"num-iterations", 0, 0, G_OPTION_ARG_INT, &this->num_iterations, "Run shaper N times (default: 1)", "N"}, {NULL} }; parser->add_group (entries, "shape", "Shape options:", "Options controlling the shaping process", this); const gchar *features_help = "Comma-separated list of font features\n" "\n" " Features can be enabled or disabled, either globally or limited to\n" " specific character ranges. The format for specifying feature settings\n" " follows. All valid CSS font-feature-settings values other than 'normal'\n" " and 'inherited' are also accepted, though, not documented below.\n" "\n" " The range indices refer to the positions between Unicode characters,\n" " unless the --utf8-clusters is provided, in which case range indices\n" " refer to UTF-8 byte indices. The position before the first character\n" " is always 0.\n" "\n" " The format is Python-esque. Here is how it all works:\n" "\n" " Syntax: Value: Start: End:\n" "\n" " Setting value:\n" " \"kern\" 1 0 ∞ # Turn feature on\n" " \"+kern\" 1 0 ∞ # Turn feature on\n" " \"-kern\" 0 0 ∞ # Turn feature off\n" " \"kern=0\" 0 0 ∞ # Turn feature off\n" " \"kern=1\" 1 0 ∞ # Turn feature on\n" " \"aalt=2\" 2 0 ∞ # Choose 2nd alternate\n" "\n" " Setting index:\n" " \"kern[]\" 1 0 ∞ # Turn feature on\n" " \"kern[:]\" 1 0 ∞ # Turn feature on\n" " \"kern[5:]\" 1 5 ∞ # Turn feature on, partial\n" " \"kern[:5]\" 1 0 5 # Turn feature on, partial\n" " \"kern[3:5]\" 1 3 5 # Turn feature on, range\n" " \"kern[3]\" 1 3 3+1 # Turn feature on, single char\n" "\n" " Mixing it all:\n" "\n" " \"aalt[3:5]=2\" 2 3 5 # Turn 2nd alternate on for range"; GOptionEntry entries2[] = { {"features", 0, 0, G_OPTION_ARG_CALLBACK, (gpointer) &parse_features, features_help, "list"}, {NULL} }; parser->add_group (entries2, "features", "Features options:", "Options controlling font features used", this); } static gboolean parse_font_size (const char *name G_GNUC_UNUSED, const char *arg, gpointer data, GError **error G_GNUC_UNUSED) { font_options_t *font_opts = (font_options_t *) data; if (0 == strcmp (arg, "upem")) { font_opts->font_size_y = font_opts->font_size_x = FONT_SIZE_UPEM; return true; } switch (sscanf (arg, "%lf%*[ ,]%lf", &font_opts->font_size_x, &font_opts->font_size_y)) { case 1: font_opts->font_size_y = font_opts->font_size_x; case 2: return true; default: g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "%s argument should be one to four space-separated numbers", name); return false; } } void font_options_t::add_options (option_parser_t *parser) { char *text = NULL; { ASSERT_STATIC (ARRAY_LENGTH_CONST (supported_font_funcs) > 0); GString *s = g_string_new (NULL); g_string_printf (s, "Set font functions implementation to use (default: %s)\n\n Supported font function implementations are: %s", supported_font_funcs[0].name, supported_font_funcs[0].name); for (unsigned int i = 1; i < ARRAY_LENGTH (supported_font_funcs); i++) { g_string_append_c (s, '/'); g_string_append (s, supported_font_funcs[i].name); } text = g_string_free (s, FALSE); parser->free_later (text); } char *font_size_text; if (default_font_size == FONT_SIZE_UPEM) font_size_text = (char *) "Font size (default: upem)"; else { font_size_text = g_strdup_printf ("Font size (default: %d)", default_font_size); parser->free_later (font_size_text); } GOptionEntry entries[] = { {"font-file", 0, 0, G_OPTION_ARG_STRING, &this->font_file, "Set font file-name", "filename"}, {"face-index", 0, 0, G_OPTION_ARG_INT, &this->face_index, "Set face index (default: 0)", "index"}, {"font-size", 0, default_font_size ? 0 : G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_CALLBACK, (gpointer) &parse_font_size, font_size_text, "1/2 numbers or 'upem'"}, {"font-funcs", 0, 0, G_OPTION_ARG_STRING, &this->font_funcs, text, "impl"}, {NULL} }; parser->add_group (entries, "font", "Font options:", "Options controlling the font", this); } void text_options_t::add_options (option_parser_t *parser) { GOptionEntry entries[] = { {"text", 0, 0, G_OPTION_ARG_STRING, &this->text, "Set input text", "string"}, {"text-file", 0, 0, G_OPTION_ARG_STRING, &this->text_file, "Set input text file-name\n\n If no text is provided, standard input is used for input.\n", "filename"}, {"text-before", 0, 0, G_OPTION_ARG_STRING, &this->text_before, "Set text context before each line", "string"}, {"text-after", 0, 0, G_OPTION_ARG_STRING, &this->text_after, "Set text context after each line", "string"}, {NULL} }; parser->add_group (entries, "text", "Text options:", "Options controlling the input text", this); } void output_options_t::add_options (option_parser_t *parser) { const char *text; if (NULL == supported_formats) text = "Set output serialization format"; else { char *items = g_strjoinv ("/", const_cast<char **> (supported_formats)); text = g_strdup_printf ("Set output format\n\n Supported output formats are: %s", items); g_free (items); parser->free_later ((char *) text); } GOptionEntry entries[] = { {"output-file", 0, 0, G_OPTION_ARG_STRING, &this->output_file, "Set output file-name (default: stdout)","filename"}, {"output-format", 0, 0, G_OPTION_ARG_STRING, &this->output_format, text, "format"}, {NULL} }; parser->add_group (entries, "output", "Output destination & format options:", "Options controlling the destination and form of the output", this); } hb_font_t * font_options_t::get_font (void) const { if (font) return font; hb_blob_t *blob = NULL; /* Create the blob */ { char *font_data; unsigned int len = 0; hb_destroy_func_t destroy; void *user_data; hb_memory_mode_t mm; /* This is a hell of a lot of code for just reading a file! */ if (!font_file) fail (true, "No font file set"); if (0 == strcmp (font_file, "-")) { /* read it */ GString *gs = g_string_new (NULL); char buf[BUFSIZ]; #if defined(_WIN32) || defined(__CYGWIN__) setmode (fileno (stdin), O_BINARY); #endif while (!feof (stdin)) { size_t ret = fread (buf, 1, sizeof (buf), stdin); if (ferror (stdin)) fail (false, "Failed reading font from standard input: %s", strerror (errno)); g_string_append_len (gs, buf, ret); } len = gs->len; font_data = g_string_free (gs, false); user_data = font_data; destroy = (hb_destroy_func_t) g_free; mm = HB_MEMORY_MODE_WRITABLE; } else { GError *error = NULL; GMappedFile *mf = g_mapped_file_new (font_file, false, &error); if (mf) { font_data = g_mapped_file_get_contents (mf); len = g_mapped_file_get_length (mf); if (len) { destroy = (hb_destroy_func_t) g_mapped_file_unref; user_data = (void *) mf; mm = HB_MEMORY_MODE_READONLY_MAY_MAKE_WRITABLE; } else g_mapped_file_unref (mf); } else { fail (false, "%s", error->message); //g_error_free (error); } if (!len) { /* GMappedFile is buggy, it doesn't fail if file isn't regular. * Try reading. * https://bugzilla.gnome.org/show_bug.cgi?id=659212 */ GError *error = NULL; gsize l; if (g_file_get_contents (font_file, &font_data, &l, &error)) { len = l; destroy = (hb_destroy_func_t) g_free; user_data = (void *) font_data; mm = HB_MEMORY_MODE_WRITABLE; } else { fail (false, "%s", error->message); //g_error_free (error); } } } if (debug) mm = HB_MEMORY_MODE_DUPLICATE; blob = hb_blob_create (font_data, len, mm, user_data, destroy); } /* Create the face */ hb_face_t *face = hb_face_create (blob, face_index); hb_blob_destroy (blob); font = hb_font_create (face); if (font_size_x == FONT_SIZE_UPEM) font_size_x = hb_face_get_upem (face); if (font_size_y == FONT_SIZE_UPEM) font_size_y = hb_face_get_upem (face); int scale_x = (int) scalbnf (font_size_x, subpixel_bits); int scale_y = (int) scalbnf (font_size_y, subpixel_bits); hb_font_set_scale (font, scale_x, scale_y); hb_face_destroy (face); void (*set_font_funcs) (hb_font_t *) = NULL; if (!font_funcs) { set_font_funcs = supported_font_funcs[0].func; } else { for (unsigned int i = 0; i < ARRAY_LENGTH (supported_font_funcs); i++) if (0 == g_ascii_strcasecmp (font_funcs, supported_font_funcs[i].name)) { set_font_funcs = supported_font_funcs[i].func; break; } if (!set_font_funcs) { GString *s = g_string_new (NULL); for (unsigned int i = 0; i < ARRAY_LENGTH (supported_font_funcs); i++) { if (i) g_string_append_c (s, '/'); g_string_append (s, supported_font_funcs[i].name); } char *p = g_string_free (s, FALSE); fail (false, "Unknown font function implementation `%s'; supported values are: %s; default is %s", font_funcs, p, supported_font_funcs[0].name); //free (p); } } set_font_funcs (font); return font; } const char * text_options_t::get_line (unsigned int *len) { if (text) { if (!line) line = text; if (line_len == (unsigned int) -1) line_len = strlen (line); if (!line_len) { *len = 0; return NULL; } const char *ret = line; const char *p = (const char *) memchr (line, '\n', line_len); unsigned int ret_len; if (!p) { ret_len = line_len; line += ret_len; line_len = 0; } else { ret_len = p - ret; line += ret_len + 1; line_len -= ret_len + 1; } *len = ret_len; return ret; } if (!fp) { if (!text_file) fail (true, "At least one of text or text-file must be set"); if (0 != strcmp (text_file, "-")) fp = fopen (text_file, "r"); else fp = stdin; if (!fp) fail (false, "Failed opening text file `%s': %s", text_file, strerror (errno)); gs = g_string_new (NULL); } g_string_set_size (gs, 0); char buf[BUFSIZ]; while (fgets (buf, sizeof (buf), fp)) { unsigned int bytes = strlen (buf); if (bytes && buf[bytes - 1] == '\n') { bytes--; g_string_append_len (gs, buf, bytes); break; } g_string_append_len (gs, buf, bytes); } if (ferror (fp)) fail (false, "Failed reading text: %s", strerror (errno)); *len = gs->len; return !*len && feof (fp) ? NULL : gs->str; } FILE * output_options_t::get_file_handle (void) { if (fp) return fp; if (output_file) fp = fopen (output_file, "wb"); else { #if defined(_WIN32) || defined(__CYGWIN__) setmode (fileno (stdout), O_BINARY); #endif fp = stdout; } if (!fp) fail (false, "Cannot open output file `%s': %s", g_filename_display_name (output_file), strerror (errno)); return fp; } static gboolean parse_verbose (const char *name G_GNUC_UNUSED, const char *arg G_GNUC_UNUSED, gpointer data G_GNUC_UNUSED, GError **error G_GNUC_UNUSED) { format_options_t *format_opts = (format_options_t *) data; format_opts->show_text = format_opts->show_unicode = format_opts->show_line_num = true; return true; } void format_options_t::add_options (option_parser_t *parser) { GOptionEntry entries[] = { {"show-text", 0, 0, G_OPTION_ARG_NONE, &this->show_text, "Prefix each line of output with its corresponding input text", NULL}, {"show-unicode", 0, 0, G_OPTION_ARG_NONE, &this->show_unicode, "Prefix each line of output with its corresponding input codepoint(s)", NULL}, {"show-line-num", 0, 0, G_OPTION_ARG_NONE, &this->show_line_num, "Prefix each line of output with its corresponding input line number", NULL}, {"verbose", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, (gpointer) &parse_verbose, "Prefix each line of output with all of the above", NULL}, {"no-glyph-names", 0, G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &this->show_glyph_names, "Output glyph indices instead of names", NULL}, {"no-positions", 0, G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &this->show_positions, "Do not output glyph positions", NULL}, {"no-clusters", 0, G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &this->show_clusters, "Do not output cluster indices", NULL}, {"show-extents", 0, 0, G_OPTION_ARG_NONE, &this->show_extents, "Output glyph extents", NULL}, {NULL} }; parser->add_group (entries, "output-syntax", "Output syntax:\n" " text: [<glyph name or index>=<glyph cluster index within input>@<horizontal displacement>,<vertical displacement>+<horizontal advance>,<vertical advance>|...]\n" " json: [{\"g\": <glyph name or index>, \"ax\": <horizontal advance>, \"ay\": <vertical advance>, \"dx\": <horizontal displacement>, \"dy\": <vertical displacement>, \"cl\": <glyph cluster index within input>}, ...]\n" "\nOutput syntax options:", "Options controlling the syntax of the output", this); } void format_options_t::serialize_unicode (hb_buffer_t *buffer, GString *gs) { unsigned int num_glyphs = hb_buffer_get_length (buffer); hb_glyph_info_t *info = hb_buffer_get_glyph_infos (buffer, NULL); g_string_append_c (gs, '<'); for (unsigned int i = 0; i < num_glyphs; i++) { if (i) g_string_append_c (gs, ','); g_string_append_printf (gs, "U+%04X", info->codepoint); info++; } g_string_append_c (gs, '>'); } void format_options_t::serialize_glyphs (hb_buffer_t *buffer, hb_font_t *font, hb_buffer_serialize_format_t output_format, hb_buffer_serialize_flags_t flags, GString *gs) { g_string_append_c (gs, '['); unsigned int num_glyphs = hb_buffer_get_length (buffer); unsigned int start = 0; while (start < num_glyphs) { char buf[1024]; unsigned int consumed; start += hb_buffer_serialize_glyphs (buffer, start, num_glyphs, buf, sizeof (buf), &consumed, font, output_format, flags); if (!consumed) break; g_string_append (gs, buf); } g_string_append_c (gs, ']'); } void format_options_t::serialize_line_no (unsigned int line_no, GString *gs) { if (show_line_num) g_string_append_printf (gs, "%d: ", line_no); } void format_options_t::serialize_buffer_of_text (hb_buffer_t *buffer, unsigned int line_no, const char *text, unsigned int text_len, hb_font_t *font, GString *gs) { if (show_text) { serialize_line_no (line_no, gs); g_string_append_c (gs, '('); g_string_append_len (gs, text, text_len); g_string_append_c (gs, ')'); g_string_append_c (gs, '\n'); } if (show_unicode) { serialize_line_no (line_no, gs); serialize_unicode (buffer, gs); g_string_append_c (gs, '\n'); } } void format_options_t::serialize_message (unsigned int line_no, const char *msg, GString *gs) { serialize_line_no (line_no, gs); g_string_append_printf (gs, "%s", msg); g_string_append_c (gs, '\n'); } void format_options_t::serialize_buffer_of_glyphs (hb_buffer_t *buffer, unsigned int line_no, const char *text, unsigned int text_len, hb_font_t *font, hb_buffer_serialize_format_t output_format, hb_buffer_serialize_flags_t format_flags, GString *gs) { serialize_line_no (line_no, gs); serialize_glyphs (buffer, font, output_format, format_flags, gs); g_string_append_c (gs, '\n'); }
lophyel/mupdf-for-mac
thirdparty/harfbuzz/util/options.cc
C++
gpl-3.0
25,673
<?php /** * app/Models/Alert.php * * Model for access to alerts table data * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * @link https://www.librenms.org * @copyright 2016 Neil Lathwood * @author Neil Lathwood <neil@lathwood.co.uk> */ namespace App\Models; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use LibreNMS\Enum\AlertState; class Alert extends Model { public $timestamps = false; // ---- Query scopes ---- /** * Only select active alerts * @param Builder $query * @return Builder */ public function scopeActive($query) { return $query->where('state', '=', AlertState::ACTIVE); } /** * Only select active alerts * @param Builder $query * @return Builder */ public function scopeAcknowledged($query) { return $query->where('state', '=', AlertState::ACKNOWLEDGED); } // ---- Define Relationships ---- public function device(): BelongsTo { return $this->belongsTo(\App\Models\Device::class, 'device_id'); } public function rule(): BelongsTo { return $this->belongsTo(\App\Models\AlertRule::class, 'rule_id', 'id'); } public function users(): BelongsToMany { return $this->belongsToMany(\App\Models\User::class, 'devices_perms', 'device_id', 'user_id'); } }
rasssta/librenms
app/Models/Alert.php
PHP
gpl-3.0
2,103
function init() { em.setProperty("state", "0"); em.setProperty("leader", "true"); } function setup(eim, leaderid) { em.setProperty("state", "1"); em.setProperty("leader", "true"); var eim = em.newInstance("2095_tokyo" + leaderid); var map = eim.createInstanceMap(802000311); map.killAllMonsters(false); eim.startEventTimer(1200000); // 20 min return eim; } function playerEntry(eim, player) { var map = eim.getMapInstance(0); player.changeMap(map, map.getPortal(0)); } function playerRevive(eim, player) { return false; } function scheduledTimeout(eim) { if (eim.disposeIfPlayerBelow(100, 802000312)) { em.setProperty("state", "0"); em.setProperty("leader", "true"); } } function changedMap(eim, player, mapid) { if (mapid != 802000311 && mapid != 802000313 && mapid == 802000312) { eim.unregisterPlayer(player); if (eim.disposeIfPlayerBelow(0, 0)) { em.setProperty("state", "0"); em.setProperty("leader", "true"); } } } function playerDisconnected(eim, player) { return 0; } function monsterValue(eim, mobId) { return 1; } function playerExit(eim, player) { eim.unregisterPlayer(player); if (eim.disposeIfPlayerBelow(0, 0)) { em.setProperty("state", "0"); em.setProperty("leader", "true"); } } function end(eim) { eim.disposeIfPlayerBelow(100, 0); em.setProperty("state", "0"); em.setProperty("leader", "true"); } function clearPQ(eim) { end(eim); } function allMonstersDead(eim) {} function leftParty (eim, player) {} function disbandParty (eim) {} function playerDead(eim, player) {} function cancelSchedule() {}
Maxcloud/Mushy
scripts/event/removed/2095_tokyo.js
JavaScript
gpl-3.0
1,620
package net.minecraft.item; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.item.EntityExpBottle; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.SoundEvents; import net.minecraft.stats.StatList; import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.util.SoundCategory; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class ItemExpBottle extends Item { public ItemExpBottle() { this.setCreativeTab(CreativeTabs.MISC); } @SideOnly(Side.CLIENT) public boolean hasEffect(ItemStack stack) { return true; } public ActionResult<ItemStack> onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) { if (!playerIn.capabilities.isCreativeMode) { --itemStackIn.stackSize; } worldIn.playSound((EntityPlayer)null, playerIn.posX, playerIn.posY, playerIn.posZ, SoundEvents.ENTITY_EXPERIENCE_BOTTLE_THROW, SoundCategory.NEUTRAL, 0.5F, 0.4F / (itemRand.nextFloat() * 0.4F + 0.8F)); if (!worldIn.isRemote) { EntityExpBottle entityexpbottle = new EntityExpBottle(worldIn, playerIn); entityexpbottle.setHeadingFromThrower(playerIn, playerIn.rotationPitch, playerIn.rotationYaw, -20.0F, 0.7F, 1.0F); worldIn.spawnEntityInWorld(entityexpbottle); } playerIn.addStat(StatList.getObjectUseStats(this)); return new ActionResult(EnumActionResult.SUCCESS, itemStackIn); } }
danielyc/test-1.9.4
build/tmp/recompileMc/sources/net/minecraft/item/ItemExpBottle.java
Java
gpl-3.0
1,697
/*============================================================================= Copyright (c) 2001-2009 Joel de Guzman Copyright (c) 2001-2009 Hartmut Kaiser http://spirit.sourceforge.net/ Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef BOOST_SPIRIT_INCLUDE_KARMA_REPOSITORY #define BOOST_SPIRIT_INCLUDE_KARMA_REPOSITORY #if defined(_MSC_VER) #pragma once #endif #include <boost/spirit/repository/home/karma.hpp> #endif
aJanker/TypeChef-Sampling-Linux
linux26333/systems/redhat/usr/include/boost/spirit/repository/include/karma.hpp
C++
gpl-3.0
631
using System; using System.Collections.Generic; using System.Linq; using Antlr4.Runtime; using Antlr4.Runtime.Misc; using Rubberduck.CodeAnalysis.Inspections.Abstract; using Rubberduck.CodeAnalysis.Inspections.Extensions; using Rubberduck.CodeAnalysis.Inspections.Results; using Rubberduck.Parsing; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; using Rubberduck.Parsing.VBA.DeclarationCaching; using Rubberduck.Parsing.VBA.Parsing; using Rubberduck.Resources.Inspections; using Rubberduck.VBEditor; using Rubberduck.CodeAnalysis.Inspections.Concrete.UnreachableCaseEvaluation; namespace Rubberduck.CodeAnalysis.Inspections.Concrete { /// <summary> /// Flags 'Case' blocks that will never execute. /// </summary> /// <why> /// Unreachable code is certainly unintended, and is probably either redundant, or a bug. /// </why> /// <remarks> /// Not all unreachable 'Case' blocks may be flagged, depending on expression complexity. /// </remarks> /// <example hasresult="true"> /// <module name="MyModule" type="Standard Module"> /// <![CDATA[ /// Private Sub Example(ByVal value As Long) /// Select Case value /// Case 0 To 99 /// ' ... /// Case 50 ' unreachable: case is covered by a preceding condition. /// ' ... /// Case Is < 100 /// ' ... /// Case < 0 ' unreachable: case is covered by a preceding condition. /// ' ... /// End Select /// End Sub /// ]]> /// </module> /// </example> /// <example hasresult="true"> /// <module name="MyModule" type="Standard Module"> /// <![CDATA[ /// /// 'If the cumulative result of multiple 'Case' statements /// 'cover the entire range of possible values for a data type, /// 'then all remaining 'Case' statements are unreachable /// /// Private Sub ExampleAllValuesCoveredIntegral(ByVal value As Long, ByVal result As Long) /// Select Case result /// Case Is < 100 /// ' ... /// Case Is > -100 /// ' ... /// 'all possible values are covered by preceding 'Case' statements /// Case value * value ' unreachable /// ' ... /// Case value + value ' unreachable /// ' ... /// Case Else ' unreachable /// ' ... /// End Select /// End Sub /// ]]> /// </module> /// </example> /// <example hasresult="false"> /// <module name="MyModule" type="Standard Module"> /// <![CDATA[ /// Public Enum ProductID /// Widget = 1 /// Gadget = 2 /// Gizmo = 3 /// End Enum /// /// Public Sub ExampleEnumCaseElse(ByVal product As ProductID) /// /// 'Enums are evaluated as the 'Long' data type. So, in this example, /// 'even though all the ProductID enum values have a 'Case' statement, /// 'the 'Case Else' will still execute for any value of the 'product' /// 'parameter that is not a ProductID. /// /// Select Case product /// Case Widget /// ' ... /// Case Gadget /// ' ... /// Case Gizmo /// ' ... /// Case Else 'is reachable /// ' Raise an error for unrecognized/unhandled ProductID /// End Select /// End Sub /// ]]> /// </module> /// </example> /// <example hasresult="true"> /// <module name="MyModule" type="Standard Module"> /// <![CDATA[ /// /// 'The inspection flags Range Clauses that are not of the required form: /// '[x] To [y] where [x] less than or equal to [y] /// /// Private Sub ExampleInvalidRangeExpression(ByVal value As String) /// Select Case value /// Case "Beginning" To "End" /// ' ... /// Case "Start" To "Finish" ' unreachable: incorrect form. /// ' ... /// Case Else /// ' ... /// End Select /// End Sub /// ]]> /// </module> /// </example> internal sealed class UnreachableCaseInspection : InspectionBase, IParseTreeInspection { private readonly IUnreachableCaseInspector _inspector; private readonly IParseTreeValueVisitor _parseTreeValueVisitor; private readonly IInspectionListener<VBAParser.SelectCaseStmtContext> _listener; public enum CaseInspectionResultType { Unreachable, InherentlyUnreachable, MismatchType, Overflow, CaseElse } public UnreachableCaseInspection( IDeclarationFinderProvider declarationFinderProvider, IUnreachableCaseInspector inspector, IParseTreeValueVisitor parseTreeValueVisitor) : base(declarationFinderProvider) { _inspector = inspector; _parseTreeValueVisitor = parseTreeValueVisitor; _listener = new UnreachableCaseInspectionListener(); } public CodeKind TargetKindOfCode => CodeKind.CodePaneCode; public IInspectionListener Listener => _listener; protected override IEnumerable<IInspectionResult> DoGetInspectionResults(DeclarationFinder finder) { return finder.UserDeclarations(DeclarationType.Module) .Where(module => module != null) .SelectMany(module => DoGetInspectionResults(module.QualifiedModuleName, finder)) .ToList(); } protected override IEnumerable<IInspectionResult> DoGetInspectionResults(QualifiedModuleName module, DeclarationFinder finder) { var qualifiedSelectCaseStmts = _listener.Contexts(module) // ignore filtering here to make the search space smaller .Where(result => !result.IsIgnoringInspectionResultFor(finder, AnnotationName)); return qualifiedSelectCaseStmts .SelectMany(context => ResultsForContext(context, finder)) .ToList(); } private IEnumerable<IInspectionResult> ResultsForContext(QualifiedContext<VBAParser.SelectCaseStmtContext> qualifiedSelectCaseStmt, DeclarationFinder finder) { var module = qualifiedSelectCaseStmt.ModuleName; var selectStmt = qualifiedSelectCaseStmt.Context; var contextValues = _parseTreeValueVisitor.VisitChildren(module, selectStmt, finder); var results = _inspector.InspectForUnreachableCases(module, selectStmt, contextValues, finder); return results .Select(resultTpl => CreateInspectionResult(qualifiedSelectCaseStmt, resultTpl.context, resultTpl.resultType)) .ToList(); } private IInspectionResult CreateInspectionResult(QualifiedContext<VBAParser.SelectCaseStmtContext> selectStmt, ParserRuleContext unreachableBlock, CaseInspectionResultType resultType) { return CreateInspectionResult(selectStmt, unreachableBlock, ResultMessage(resultType)); } //This cannot be a dictionary because the strings have to change after a change in the selected language. private static string ResultMessage(CaseInspectionResultType resultType) { switch (resultType) { case CaseInspectionResultType.Unreachable: return InspectionResults.UnreachableCaseInspection_Unreachable; case CaseInspectionResultType.InherentlyUnreachable: return InspectionResults.UnreachableCaseInspection_InherentlyUnreachable; case CaseInspectionResultType.MismatchType: return InspectionResults.UnreachableCaseInspection_TypeMismatch; case CaseInspectionResultType.Overflow: return InspectionResults.UnreachableCaseInspection_Overflow; case CaseInspectionResultType.CaseElse: return InspectionResults.UnreachableCaseInspection_CaseElse; default: throw new ArgumentOutOfRangeException(nameof(resultType), resultType, null); } } private IInspectionResult CreateInspectionResult(QualifiedContext<VBAParser.SelectCaseStmtContext> selectStmt, ParserRuleContext unreachableBlock, string message) { return new QualifiedContextInspectionResult(this, message, new QualifiedContext<ParserRuleContext>(selectStmt.ModuleName, unreachableBlock)); } private class UnreachableCaseInspectionListener : InspectionListenerBase<VBAParser.SelectCaseStmtContext> { public override void EnterSelectCaseStmt([NotNull] VBAParser.SelectCaseStmtContext context) { SaveContext(context); } } } }
rubberduck-vba/Rubberduck
Rubberduck.CodeAnalysis/Inspections/Concrete/UnreachableCaseInspection.cs
C#
gpl-3.0
9,101
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ class Google_Service_CloudVideoIntelligence_GoogleCloudVideointelligenceV1p1beta1ExplicitContentAnnotation extends Google_Collection { protected $collection_key = 'frames'; protected $framesType = 'Google_Service_CloudVideoIntelligence_GoogleCloudVideointelligenceV1p1beta1ExplicitContentFrame'; protected $framesDataType = 'array'; public $version; /** * @param Google_Service_CloudVideoIntelligence_GoogleCloudVideointelligenceV1p1beta1ExplicitContentFrame */ public function setFrames($frames) { $this->frames = $frames; } /** * @return Google_Service_CloudVideoIntelligence_GoogleCloudVideointelligenceV1p1beta1ExplicitContentFrame */ public function getFrames() { return $this->frames; } public function setVersion($version) { $this->version = $version; } public function getVersion() { return $this->version; } }
ftisunpar/BlueTape
vendor/google/apiclient-services/src/Google/Service/CloudVideoIntelligence/GoogleCloudVideointelligenceV1p1beta1ExplicitContentAnnotation.php
PHP
gpl-3.0
1,482
""" Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. RockStor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ from django.db import models from storageadmin.models import Appliance class UpdateSubscription(models.Model): """name of the channel. eg: stable""" name = models.CharField(max_length=64, unique=True) """detailed description or a longer name""" description = models.CharField(max_length=128) """url of the repo""" url = models.CharField(max_length=512) appliance = models.ForeignKey(Appliance) password = models.CharField(max_length=64, null=True) """status of subscription: active, inactive, expired etc..""" status = models.CharField(max_length=64) class Meta: app_label = 'storageadmin'
nkhare/rockstor-core
src/rockstor/storageadmin/models/update_subscription.py
Python
gpl-3.0
1,351
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Unit tests for badges * * @package core * @subpackage badges * @copyright 2013 onwards Totara Learning Solutions Ltd {@link http://www.totaralms.com/} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @author Yuliya Bozhko <yuliya.bozhko@totaralms.com> */ defined('MOODLE_INTERNAL') || die(); global $CFG; require_once($CFG->libdir . '/badgeslib.php'); require_once($CFG->dirroot . '/badges/lib.php'); use core_badges\helper; class core_badges_badgeslib_testcase extends advanced_testcase { protected $badgeid; protected $course; protected $user; protected $module; protected $coursebadge; protected $assertion; /** @var $assertion2 to define json format for Open badge version 2 */ protected $assertion2; protected function setUp() { global $DB, $CFG; $this->resetAfterTest(true); $CFG->enablecompletion = true; $user = $this->getDataGenerator()->create_user(); $fordb = new stdClass(); $fordb->id = null; $fordb->name = "Test badge with 'apostrophe' and other friends (<>&@#)"; $fordb->description = "Testing badges"; $fordb->timecreated = time(); $fordb->timemodified = time(); $fordb->usercreated = $user->id; $fordb->usermodified = $user->id; $fordb->issuername = "Test issuer"; $fordb->issuerurl = "http://issuer-url.domain.co.nz"; $fordb->issuercontact = "issuer@example.com"; $fordb->expiredate = null; $fordb->expireperiod = null; $fordb->type = BADGE_TYPE_SITE; $fordb->version = 1; $fordb->language = 'en'; $fordb->courseid = null; $fordb->messagesubject = "Test message subject"; $fordb->message = "Test message body"; $fordb->attachment = 1; $fordb->notification = 0; $fordb->imageauthorname = "Image Author 1"; $fordb->imageauthoremail = "author@example.com"; $fordb->imageauthorurl = "http://author-url.example.com"; $fordb->imagecaption = "Test caption image"; $fordb->status = BADGE_STATUS_INACTIVE; $this->badgeid = $DB->insert_record('badge', $fordb, true); // Set the default Issuer (because OBv2 needs them). set_config('badges_defaultissuername', $fordb->issuername); set_config('badges_defaultissuercontact', $fordb->issuercontact); // Create a course with activity and auto completion tracking. $this->course = $this->getDataGenerator()->create_course(array('enablecompletion' => true)); $this->user = $this->getDataGenerator()->create_user(); $studentrole = $DB->get_record('role', array('shortname' => 'student')); $this->assertNotEmpty($studentrole); // Get manual enrolment plugin and enrol user. require_once($CFG->dirroot.'/enrol/manual/locallib.php'); $manplugin = enrol_get_plugin('manual'); $maninstance = $DB->get_record('enrol', array('courseid' => $this->course->id, 'enrol' => 'manual'), '*', MUST_EXIST); $manplugin->enrol_user($maninstance, $this->user->id, $studentrole->id); $this->assertEquals(1, $DB->count_records('user_enrolments')); $completionauto = array('completion' => COMPLETION_TRACKING_AUTOMATIC); $this->module = $this->getDataGenerator()->create_module('forum', array('course' => $this->course->id), $completionauto); // Build badge and criteria. $fordb->type = BADGE_TYPE_COURSE; $fordb->courseid = $this->course->id; $fordb->status = BADGE_STATUS_ACTIVE; $this->coursebadge = $DB->insert_record('badge', $fordb, true); // Insert Endorsement. $endorsement = new stdClass(); $endorsement->badgeid = $this->coursebadge; $endorsement->issuername = "Issuer 123"; $endorsement->issueremail = "issuer123@email.com"; $endorsement->issuerurl = "https://example.org/issuer-123"; $endorsement->dateissued = 1524567747; $endorsement->claimid = "https://example.org/robotics-badge.json"; $endorsement->claimcomment = "Test endorser comment"; $DB->insert_record('badge_endorsement', $endorsement, true); // Insert related badges. $badge = new badge($this->coursebadge); $clonedid = $badge->make_clone(); $badgeclone = new badge($clonedid); $badgeclone->status = BADGE_STATUS_ACTIVE; $badgeclone->save(); $relatebadge = new stdClass(); $relatebadge->badgeid = $this->coursebadge; $relatebadge->relatedbadgeid = $clonedid; $relatebadge->relatedid = $DB->insert_record('badge_related', $relatebadge, true); // Insert a aligment. $alignment = new stdClass(); $alignment->badgeid = $this->coursebadge; $alignment->targetname = 'CCSS.ELA-Literacy.RST.11-12.3'; $alignment->targeturl = 'http://www.corestandards.org/ELA-Literacy/RST/11-12/3'; $alignment->targetdescription = 'Test target description'; $alignment->targetframework = 'CCSS.RST.11-12.3'; $alignment->targetcode = 'CCSS.RST.11-12.3'; $DB->insert_record('badge_alignment', $alignment, true); $this->assertion = new stdClass(); $this->assertion->badge = '{"uid":"%s","recipient":{"identity":"%s","type":"email","hashed":true,"salt":"%s"},"badge":"%s","verify":{"type":"hosted","url":"%s"},"issuedOn":"%d","evidence":"%s"}'; $this->assertion->class = '{"name":"%s","description":"%s","image":"%s","criteria":"%s","issuer":"%s"}'; $this->assertion->issuer = '{"name":"%s","url":"%s","email":"%s"}'; // Format JSON-LD for Openbadge specification version 2.0. $this->assertion2 = new stdClass(); $this->assertion2->badge = '{"recipient":{"identity":"%s","type":"email","hashed":true,"salt":"%s"},' . '"badge":{"name":"%s","description":"%s","image":"%s",' . '"criteria":{"id":"%s","narrative":"%s"},"issuer":{"name":"%s","url":"%s","email":"%s",' . '"@context":"https:\/\/w3id.org\/openbadges\/v2","id":"%s","type":"Issuer"},' . '"@context":"https:\/\/w3id.org\/openbadges\/v2","id":"%s","type":"BadgeClass","version":"%s",' . '"@language":"en","related":[{"id":"%s","version":"%s","@language":"%s"}],"endorsement":"%s",' . '"alignments":[{"targetName":"%s","targetUrl":"%s","targetDescription":"%s","targetFramework":"%s",' . '"targetCode":"%s"}]},"verify":{"type":"hosted","url":"%s"},"issuedOn":"%s","evidence":"%s",' . '"@context":"https:\/\/w3id.org\/openbadges\/v2","type":"Assertion","id":"%s"}'; $this->assertion2->class = '{"name":"%s","description":"%s","image":"%s",' . '"criteria":{"id":"%s","narrative":"%s"},"issuer":{"name":"%s","url":"%s","email":"%s",' . '"@context":"https:\/\/w3id.org\/openbadges\/v2","id":"%s","type":"Issuer"},' . '"@context":"https:\/\/w3id.org\/openbadges\/v2","id":"%s","type":"BadgeClass","version":"%s",' . '"@language":"%s","related":[{"id":"%s","version":"%s","@language":"%s"}],"endorsement":"%s",' . '"alignments":[{"targetName":"%s","targetUrl":"%s","targetDescription":"%s","targetFramework":"%s",' . '"targetCode":"%s"}]}'; $this->assertion2->issuer = '{"name":"%s","url":"%s","email":"%s",' . '"@context":"https:\/\/w3id.org\/openbadges\/v2","id":"%s","type":"Issuer"}'; } public function test_create_badge() { $badge = new badge($this->badgeid); $this->assertInstanceOf('badge', $badge); $this->assertEquals($this->badgeid, $badge->id); } public function test_clone_badge() { $badge = new badge($this->badgeid); $newid = $badge->make_clone(); $clonedbadge = new badge($newid); $this->assertEquals($badge->description, $clonedbadge->description); $this->assertEquals($badge->issuercontact, $clonedbadge->issuercontact); $this->assertEquals($badge->issuername, $clonedbadge->issuername); $this->assertEquals($badge->issuercontact, $clonedbadge->issuercontact); $this->assertEquals($badge->issuerurl, $clonedbadge->issuerurl); $this->assertEquals($badge->expiredate, $clonedbadge->expiredate); $this->assertEquals($badge->expireperiod, $clonedbadge->expireperiod); $this->assertEquals($badge->type, $clonedbadge->type); $this->assertEquals($badge->courseid, $clonedbadge->courseid); $this->assertEquals($badge->message, $clonedbadge->message); $this->assertEquals($badge->messagesubject, $clonedbadge->messagesubject); $this->assertEquals($badge->attachment, $clonedbadge->attachment); $this->assertEquals($badge->notification, $clonedbadge->notification); $this->assertEquals($badge->version, $clonedbadge->version); $this->assertEquals($badge->language, $clonedbadge->language); $this->assertEquals($badge->imagecaption, $clonedbadge->imagecaption); $this->assertEquals($badge->imageauthorname, $clonedbadge->imageauthorname); $this->assertEquals($badge->imageauthoremail, $clonedbadge->imageauthoremail); $this->assertEquals($badge->imageauthorurl, $clonedbadge->imageauthorurl); } public function test_badge_status() { $badge = new badge($this->badgeid); $old_status = $badge->status; $badge->set_status(BADGE_STATUS_ACTIVE); $this->assertAttributeNotEquals($old_status, 'status', $badge); $this->assertAttributeEquals(BADGE_STATUS_ACTIVE, 'status', $badge); } public function test_delete_badge() { $badge = new badge($this->badgeid); $badge->delete(); // We don't actually delete badges. We archive them. $this->assertAttributeEquals(BADGE_STATUS_ARCHIVED, 'status', $badge); } /** * Really delete the badge. */ public function test_delete_badge_for_real() { global $DB; $badge = new badge($this->badgeid); $newid1 = $badge->make_clone(); $newid2 = $badge->make_clone(); $newid3 = $badge->make_clone(); // Insert related badges to badge 1. $badge->add_related_badges([$newid1, $newid2, $newid3]); // Another badge. $badge2 = new badge($newid2); // Make badge 1 related for badge 2. $badge2->add_related_badges([$this->badgeid]); // Confirm that the records about this badge about its relations have been removed as well. $relatedsql = 'badgeid = :badgeid OR relatedbadgeid = :relatedbadgeid'; $relatedparams = array( 'badgeid' => $this->badgeid, 'relatedbadgeid' => $this->badgeid ); // Badge 1 has 4 related records. 3 where it's the badgeid, 1 where it's the relatedbadgeid. $this->assertEquals(4, $DB->count_records_select('badge_related', $relatedsql, $relatedparams)); // Delete the badge for real. $badge->delete(false); // Confirm that the badge itself has been removed. $this->assertFalse($DB->record_exists('badge', ['id' => $this->badgeid])); // Confirm that the records about this badge about its relations have been removed as well. $this->assertFalse($DB->record_exists_select('badge_related', $relatedsql, $relatedparams)); } public function test_create_badge_criteria() { $badge = new badge($this->badgeid); $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id)); $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ALL)); $this->assertCount(1, $badge->get_criteria()); $criteria_profile = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_PROFILE, 'badgeid' => $badge->id)); $params = array('agg' => BADGE_CRITERIA_AGGREGATION_ALL, 'field_address' => 'address'); $criteria_profile->save($params); $this->assertCount(2, $badge->get_criteria()); } public function test_add_badge_criteria_description() { $criteriaoverall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $this->badgeid)); $criteriaoverall->save(array( 'agg' => BADGE_CRITERIA_AGGREGATION_ALL, 'description' => 'Overall description', 'descriptionformat' => FORMAT_HTML )); $criteriaprofile = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_PROFILE, 'badgeid' => $this->badgeid)); $params = array( 'agg' => BADGE_CRITERIA_AGGREGATION_ALL, 'field_address' => 'address', 'description' => 'Description', 'descriptionformat' => FORMAT_HTML ); $criteriaprofile->save($params); $badge = new badge($this->badgeid); $this->assertEquals('Overall description', $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->description); $this->assertEquals('Description', $badge->criteria[BADGE_CRITERIA_TYPE_PROFILE]->description); } public function test_delete_badge_criteria() { $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $this->badgeid)); $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ALL)); $badge = new badge($this->badgeid); $this->assertInstanceOf('award_criteria_overall', $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]); $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->delete(); $this->assertEmpty($badge->get_criteria()); } public function test_badge_awards() { global $DB; $this->preventResetByRollback(); // Messaging is not compatible with transactions. $badge = new badge($this->badgeid); $user1 = $this->getDataGenerator()->create_user(); $sink = $this->redirectMessages(); $DB->set_field_select('message_processors', 'enabled', 0, "name <> 'email'"); set_user_preference('message_provider_moodle_badgerecipientnotice_loggedoff', 'email', $user1); $badge->issue($user1->id, false); $this->assertDebuggingCalled(); // Expect debugging while baking a badge via phpunit. $this->assertTrue($badge->is_issued($user1->id)); $messages = $sink->get_messages(); $sink->close(); $this->assertCount(1, $messages); $message = array_pop($messages); // Check we have the expected data. $customdata = json_decode($message->customdata); $this->assertObjectHasAttribute('notificationiconurl', $customdata); $this->assertObjectHasAttribute('hash', $customdata); $user2 = $this->getDataGenerator()->create_user(); $badge->issue($user2->id, true); $this->assertTrue($badge->is_issued($user2->id)); $this->assertCount(2, $badge->get_awards()); } /** * Test the {@link badges_get_user_badges()} function in lib/badgeslib.php */ public function test_badges_get_user_badges() { global $DB; // Messaging is not compatible with transactions. $this->preventResetByRollback(); $badges = array(); $user1 = $this->getDataGenerator()->create_user(); $user2 = $this->getDataGenerator()->create_user(); // Record the current time, we need to be precise about a couple of things. $now = time(); // Create 11 badges with which to test. for ($i = 1; $i <= 11; $i++) { // Mock up a badge. $badge = new stdClass(); $badge->id = null; $badge->name = "Test badge $i"; $badge->description = "Testing badges $i"; $badge->timecreated = $now - 12; $badge->timemodified = $now - 12; $badge->usercreated = $user1->id; $badge->usermodified = $user1->id; $badge->issuername = "Test issuer"; $badge->issuerurl = "http://issuer-url.domain.co.nz"; $badge->issuercontact = "issuer@example.com"; $badge->expiredate = null; $badge->expireperiod = null; $badge->type = BADGE_TYPE_SITE; $badge->courseid = null; $badge->messagesubject = "Test message subject for badge $i"; $badge->message = "Test message body for badge $i"; $badge->attachment = 1; $badge->notification = 0; $badge->status = BADGE_STATUS_INACTIVE; $badge->version = "Version $i"; $badge->language = "en"; $badge->imagecaption = "Image caption $i"; $badge->imageauthorname = "Image author's name $i"; $badge->imageauthoremail = "author$i@example.com"; $badge->imageauthorname = "Image author's name $i"; $badgeid = $DB->insert_record('badge', $badge, true); $badges[$badgeid] = new badge($badgeid); $badges[$badgeid]->issue($user2->id, true); // Check it all actually worked. $this->assertCount(1, $badges[$badgeid]->get_awards()); // Hack the database to adjust the time each badge was issued. // The alternative to this is sleep which is a no-no in unit tests. $DB->set_field('badge_issued', 'dateissued', $now - 11 + $i, array('userid' => $user2->id, 'badgeid' => $badgeid)); } // Make sure the first user has no badges. $result = badges_get_user_badges($user1->id); $this->assertInternalType('array', $result); $this->assertCount(0, $result); // Check that the second user has the expected 11 badges. $result = badges_get_user_badges($user2->id); $this->assertCount(11, $result); // Test pagination. // Ordering is by time issued desc, so things will come out with the last awarded badge first. $result = badges_get_user_badges($user2->id, 0, 0, 4); $this->assertCount(4, $result); $lastbadgeissued = reset($result); $this->assertSame('Test badge 11', $lastbadgeissued->name); // Page 2. Expecting 4 results again. $result = badges_get_user_badges($user2->id, 0, 1, 4); $this->assertCount(4, $result); $lastbadgeissued = reset($result); $this->assertSame('Test badge 7', $lastbadgeissued->name); // Page 3. Expecting just three results here. $result = badges_get_user_badges($user2->id, 0, 2, 4); $this->assertCount(3, $result); $lastbadgeissued = reset($result); $this->assertSame('Test badge 3', $lastbadgeissued->name); // Page 4.... there is no page 4. $result = badges_get_user_badges($user2->id, 0, 3, 4); $this->assertCount(0, $result); // Test search. $result = badges_get_user_badges($user2->id, 0, 0, 0, 'badge 1'); $this->assertCount(3, $result); $lastbadgeissued = reset($result); $this->assertSame('Test badge 11', $lastbadgeissued->name); // The term Totara doesn't appear anywhere in the badges. $result = badges_get_user_badges($user2->id, 0, 0, 0, 'Totara'); $this->assertCount(0, $result); // Issue a user with a course badge and verify its returned based on if // coursebadges are enabled or disabled. $sitebadgeid = key($badges); $badges[$sitebadgeid]->issue($this->user->id, true); $badge = new stdClass(); $badge->id = null; $badge->name = "Test course badge"; $badge->description = "Testing course badge"; $badge->timecreated = $now; $badge->timemodified = $now; $badge->usercreated = $user1->id; $badge->usermodified = $user1->id; $badge->issuername = "Test issuer"; $badge->issuerurl = "http://issuer-url.domain.co.nz"; $badge->issuercontact = "issuer@example.com"; $badge->expiredate = null; $badge->expireperiod = null; $badge->type = BADGE_TYPE_COURSE; $badge->courseid = $this->course->id; $badge->messagesubject = "Test message subject for course badge"; $badge->message = "Test message body for course badge"; $badge->attachment = 1; $badge->notification = 0; $badge->status = BADGE_STATUS_ACTIVE; $badge->version = "Version $i"; $badge->language = "en"; $badge->imagecaption = "Image caption"; $badge->imageauthorname = "Image author's name"; $badge->imageauthoremail = "author@example.com"; $badge->imageauthorname = "Image author's name"; $badgeid = $DB->insert_record('badge', $badge, true); $badges[$badgeid] = new badge($badgeid); $badges[$badgeid]->issue($this->user->id, true); // With coursebadges off, we should only get the site badge. set_config('badges_allowcoursebadges', false); $result = badges_get_user_badges($this->user->id); $this->assertCount(1, $result); // With it on, we should get both. set_config('badges_allowcoursebadges', true); $result = badges_get_user_badges($this->user->id); $this->assertCount(2, $result); } public function data_for_message_from_template() { return array( array( 'This is a message with no variables', array(), // no params 'This is a message with no variables' ), array( 'This is a message with %amissing% variables', array(), // no params 'This is a message with %amissing% variables' ), array( 'This is a message with %one% variable', array('one' => 'a single'), 'This is a message with a single variable' ), array( 'This is a message with %one% %two% %three% variables', array('one' => 'more', 'two' => 'than', 'three' => 'one'), 'This is a message with more than one variables' ), array( 'This is a message with %three% %two% %one%', array('one' => 'variables', 'two' => 'ordered', 'three' => 'randomly'), 'This is a message with randomly ordered variables' ), array( 'This is a message with %repeated% %one% %repeated% of variables', array('one' => 'and', 'repeated' => 'lots'), 'This is a message with lots and lots of variables' ), ); } /** * @dataProvider data_for_message_from_template */ public function test_badge_message_from_template($message, $params, $result) { $this->assertEquals(badge_message_from_template($message, $params), $result); } /** * Test badges observer when course module completion event id fired. */ public function test_badges_observer_course_module_criteria_review() { $this->preventResetByRollback(); // Messaging is not compatible with transactions. $badge = new badge($this->coursebadge); $this->assertFalse($badge->is_issued($this->user->id)); $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id)); $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY)); $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_ACTIVITY, 'badgeid' => $badge->id)); $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY, 'module_'.$this->module->cmid => $this->module->cmid)); // Assert the badge will not be issued to the user as is. $badge = new badge($this->coursebadge); $badge->review_all_criteria(); $this->assertFalse($badge->is_issued($this->user->id)); // Set completion for forum activity. $c = new completion_info($this->course); $activities = $c->get_activities(); $this->assertEquals(1, count($activities)); $this->assertTrue(isset($activities[$this->module->cmid])); $this->assertEquals($activities[$this->module->cmid]->name, $this->module->name); $current = $c->get_data($activities[$this->module->cmid], false, $this->user->id); $current->completionstate = COMPLETION_COMPLETE; $current->timemodified = time(); $sink = $this->redirectEmails(); $c->internal_set_data($activities[$this->module->cmid], $current); $this->assertCount(1, $sink->get_messages()); $sink->close(); // Check if badge is awarded. $this->assertDebuggingCalled('Error baking badge image!'); $this->assertTrue($badge->is_issued($this->user->id)); } /** * Test badges observer when course_completed event is fired. */ public function test_badges_observer_course_criteria_review() { $this->preventResetByRollback(); // Messaging is not compatible with transactions. $badge = new badge($this->coursebadge); $this->assertFalse($badge->is_issued($this->user->id)); $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id)); $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY)); $criteria_overall1 = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_COURSE, 'badgeid' => $badge->id)); $criteria_overall1->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY, 'course_'.$this->course->id => $this->course->id)); $ccompletion = new completion_completion(array('course' => $this->course->id, 'userid' => $this->user->id)); // Assert the badge will not be issued to the user as is. $badge = new badge($this->coursebadge); $badge->review_all_criteria(); $this->assertFalse($badge->is_issued($this->user->id)); // Mark course as complete. $sink = $this->redirectEmails(); $ccompletion->mark_complete(); $this->assertCount(1, $sink->get_messages()); $sink->close(); // Check if badge is awarded. $this->assertDebuggingCalled('Error baking badge image!'); $this->assertTrue($badge->is_issued($this->user->id)); } /** * Test badges observer when user_updated event is fired. */ public function test_badges_observer_profile_criteria_review() { global $CFG, $DB; require_once($CFG->dirroot.'/user/profile/lib.php'); // Add a custom field of textarea type. $customprofileid = $DB->insert_record('user_info_field', array( 'shortname' => 'newfield', 'name' => 'Description of new field', 'categoryid' => 1, 'datatype' => 'textarea')); $this->preventResetByRollback(); // Messaging is not compatible with transactions. $badge = new badge($this->coursebadge); $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id)); $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY)); $criteria_overall1 = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_PROFILE, 'badgeid' => $badge->id)); $criteria_overall1->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ALL, 'field_address' => 'address', 'field_aim' => 'aim', 'field_' . $customprofileid => $customprofileid)); // Assert the badge will not be issued to the user as is. $badge = new badge($this->coursebadge); $badge->review_all_criteria(); $this->assertFalse($badge->is_issued($this->user->id)); // Set the required fields and make sure the badge got issued. $this->user->address = 'Test address'; $this->user->aim = '999999999'; $sink = $this->redirectEmails(); profile_save_data((object)array('id' => $this->user->id, 'profile_field_newfield' => 'X')); user_update_user($this->user, false); $this->assertCount(1, $sink->get_messages()); $sink->close(); // Check if badge is awarded. $this->assertDebuggingCalled('Error baking badge image!'); $this->assertTrue($badge->is_issued($this->user->id)); } /** * Test badges observer when cohort_member_added event is fired. */ public function test_badges_observer_cohort_criteria_review() { global $CFG; require_once("$CFG->dirroot/cohort/lib.php"); $cohort = $this->getDataGenerator()->create_cohort(); $this->preventResetByRollback(); // Messaging is not compatible with transactions. $badge = new badge($this->badgeid); $this->assertFalse($badge->is_issued($this->user->id)); // Set up the badge criteria. $criteriaoverall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id)); $criteriaoverall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY)); $criteriaoverall1 = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_COHORT, 'badgeid' => $badge->id)); $criteriaoverall1->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY, 'cohort_cohorts' => array('0' => $cohort->id))); // Make the badge active. $badge->set_status(BADGE_STATUS_ACTIVE); // Add the user to the cohort. cohort_add_member($cohort->id, $this->user->id); // Verify that the badge was awarded. $this->assertDebuggingCalled(); $this->assertTrue($badge->is_issued($this->user->id)); } /** * Test badges assertion generated when a badge is issued. */ public function test_badges_assertion() { $this->preventResetByRollback(); // Messaging is not compatible with transactions. $badge = new badge($this->coursebadge); $this->assertFalse($badge->is_issued($this->user->id)); $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id)); $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY)); $criteria_overall1 = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_PROFILE, 'badgeid' => $badge->id)); $criteria_overall1->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ALL, 'field_address' => 'address')); $this->user->address = 'Test address'; $sink = $this->redirectEmails(); user_update_user($this->user, false); $this->assertCount(1, $sink->get_messages()); $sink->close(); // Check if badge is awarded. $this->assertDebuggingCalled('Error baking badge image!'); $awards = $badge->get_awards(); $this->assertCount(1, $awards); // Get assertion. $award = reset($awards); $assertion = new core_badges_assertion($award->uniquehash, OPEN_BADGES_V1); $testassertion = $this->assertion; // Make sure JSON strings have the same structure. $this->assertStringMatchesFormat($testassertion->badge, json_encode($assertion->get_badge_assertion())); $this->assertStringMatchesFormat($testassertion->class, json_encode($assertion->get_badge_class())); $this->assertStringMatchesFormat($testassertion->issuer, json_encode($assertion->get_issuer())); // Test Openbadge specification version 2. // Get assertion version 2. $award = reset($awards); $assertion2 = new core_badges_assertion($award->uniquehash, OPEN_BADGES_V2); $testassertion2 = $this->assertion2; // Make sure JSON strings have the same structure. $this->assertStringMatchesFormat($testassertion2->badge, json_encode($assertion2->get_badge_assertion())); $this->assertStringMatchesFormat($testassertion2->class, json_encode($assertion2->get_badge_class())); $this->assertStringMatchesFormat($testassertion2->issuer, json_encode($assertion2->get_issuer())); } /** * Tests the core_badges_myprofile_navigation() function. */ public function test_core_badges_myprofile_navigation() { // Set up the test. $tree = new \core_user\output\myprofile\tree(); $this->setAdminUser(); $badge = new badge($this->badgeid); $badge->issue($this->user->id, true); $iscurrentuser = true; $course = null; // Enable badges. set_config('enablebadges', true); // Check the node tree is correct. core_badges_myprofile_navigation($tree, $this->user, $iscurrentuser, $course); $reflector = new ReflectionObject($tree); $nodes = $reflector->getProperty('nodes'); $nodes->setAccessible(true); $this->assertArrayHasKey('localbadges', $nodes->getValue($tree)); } /** * Tests the core_badges_myprofile_navigation() function with badges disabled.. */ public function test_core_badges_myprofile_navigation_badges_disabled() { // Set up the test. $tree = new \core_user\output\myprofile\tree(); $this->setAdminUser(); $badge = new badge($this->badgeid); $badge->issue($this->user->id, true); $iscurrentuser = false; $course = null; // Disable badges. set_config('enablebadges', false); // Check the node tree is correct. core_badges_myprofile_navigation($tree, $this->user, $iscurrentuser, $course); $reflector = new ReflectionObject($tree); $nodes = $reflector->getProperty('nodes'); $nodes->setAccessible(true); $this->assertArrayNotHasKey('localbadges', $nodes->getValue($tree)); } /** * Tests the core_badges_myprofile_navigation() function with a course badge. */ public function test_core_badges_myprofile_navigation_with_course_badge() { // Set up the test. $tree = new \core_user\output\myprofile\tree(); $this->setAdminUser(); $badge = new badge($this->coursebadge); $badge->issue($this->user->id, true); $iscurrentuser = false; // Check the node tree is correct. core_badges_myprofile_navigation($tree, $this->user, $iscurrentuser, $this->course); $reflector = new ReflectionObject($tree); $nodes = $reflector->getProperty('nodes'); $nodes->setAccessible(true); $this->assertArrayHasKey('localbadges', $nodes->getValue($tree)); } /** * Test insert and update endorsement with a site badge. */ public function test_badge_endorsement() { $badge = new badge($this->badgeid); // Insert Endorsement. $endorsement = new stdClass(); $endorsement->badgeid = $this->badgeid; $endorsement->issuername = "Issuer 123"; $endorsement->issueremail = "issuer123@email.com"; $endorsement->issuerurl = "https://example.org/issuer-123"; $endorsement->dateissued = 1524567747; $endorsement->claimid = "https://example.org/robotics-badge.json"; $endorsement->claimcomment = "Test endorser comment"; $badge->save_endorsement($endorsement); $endorsement1 = $badge->get_endorsement(); $this->assertEquals($endorsement->badgeid, $endorsement1->badgeid); $this->assertEquals($endorsement->issuername, $endorsement1->issuername); $this->assertEquals($endorsement->issueremail, $endorsement1->issueremail); $this->assertEquals($endorsement->issuerurl, $endorsement1->issuerurl); $this->assertEquals($endorsement->dateissued, $endorsement1->dateissued); $this->assertEquals($endorsement->claimid, $endorsement1->claimid); $this->assertEquals($endorsement->claimcomment, $endorsement1->claimcomment); // Update Endorsement. $endorsement1->issuername = "Issuer update"; $badge->save_endorsement($endorsement1); $endorsement2 = $badge->get_endorsement(); $this->assertEquals($endorsement1->id, $endorsement2->id); $this->assertEquals($endorsement1->issuername, $endorsement2->issuername); } /** * Test insert and delete related badge with a site badge. */ public function test_badge_related() { $badge = new badge($this->badgeid); $newid1 = $badge->make_clone(); $newid2 = $badge->make_clone(); $newid3 = $badge->make_clone(); // Insert an related badge. $badge->add_related_badges([$newid1, $newid2, $newid3]); $this->assertCount(3, $badge->get_related_badges()); // Only get related is active. $clonedbage1 = new badge($newid1); $clonedbage1->status = BADGE_STATUS_ACTIVE; $clonedbage1->save(); $this->assertCount(1, $badge->get_related_badges(true)); // Delete an related badge. $badge->delete_related_badge($newid2); $this->assertCount(2, $badge->get_related_badges()); } /** * Test insert, update, delete alignment with a site badge. */ public function test_alignments() { $badge = new badge($this->badgeid); // Insert a alignment. $alignment1 = new stdClass(); $alignment1->badgeid = $this->badgeid; $alignment1->targetname = 'CCSS.ELA-Literacy.RST.11-12.3'; $alignment1->targeturl = 'http://www.corestandards.org/ELA-Literacy/RST/11-12/3'; $alignment1->targetdescription = 'Test target description'; $alignment1->targetframework = 'CCSS.RST.11-12.3'; $alignment1->targetcode = 'CCSS.RST.11-12.3'; $alignment2 = clone $alignment1; $newid1 = $badge->save_alignment($alignment1); $newid2 = $badge->save_alignment($alignment2); $alignments1 = $badge->get_alignments(); $this->assertCount(2, $alignments1); $this->assertEquals($alignment1->badgeid, $alignments1[$newid1]->badgeid); $this->assertEquals($alignment1->targetname, $alignments1[$newid1]->targetname); $this->assertEquals($alignment1->targeturl, $alignments1[$newid1]->targeturl); $this->assertEquals($alignment1->targetdescription, $alignments1[$newid1]->targetdescription); $this->assertEquals($alignment1->targetframework, $alignments1[$newid1]->targetframework); $this->assertEquals($alignment1->targetcode, $alignments1[$newid1]->targetcode); // Update aligment. $alignments1[$newid1]->targetname = 'CCSS.ELA-Literacy.RST.11-12.3 update'; $badge->save_alignment($alignments1[$newid1], $alignments1[$newid1]->id); $alignments2 = $badge->get_alignments(); $this->assertEquals($alignments1[$newid1]->id, $alignments2[$newid1]->id); $this->assertEquals($alignments1[$newid1]->targetname, $alignments2[$newid1]->targetname); // Delete alignment. $badge->delete_alignment($alignments1[$newid2]->id); $this->assertCount(1, $badge->get_alignments()); } /** * Test badges_delete_site_backpack(). * */ public function test_badges_delete_site_backpack(): void { global $DB; $this->setAdminUser(); // Create one backpack. $total = $DB->count_records('badge_external_backpack'); $this->assertEquals(1, $total); $data = new \stdClass(); $data->apiversion = OPEN_BADGES_V2P1; $data->backpackapiurl = 'https://dc.imsglobal.org/obchost/ims/ob/v2p1'; $data->backpackweburl = 'https://dc.imsglobal.org'; badges_create_site_backpack($data); $backpack = $DB->get_record('badge_external_backpack', ['backpackweburl' => $data->backpackweburl]); $user1 = $this->getDataGenerator()->create_user(); $user2 = $this->getDataGenerator()->create_user(); // User1 is connected to the backpack to be removed and has 2 collections. $backpackuser1 = helper::create_fake_backpack(['userid' => $user1->id, 'externalbackpackid' => $backpack->id]); helper::create_fake_backpack_collection(['backpackid' => $backpackuser1->id]); helper::create_fake_backpack_collection(['backpackid' => $backpackuser1->id]); // User2 is connected to a different backpack and has 1 collection. $backpackuser2 = helper::create_fake_backpack(['userid' => $user2->id]); helper::create_fake_backpack_collection(['backpackid' => $backpackuser2->id]); $total = $DB->count_records('badge_external_backpack'); $this->assertEquals(2, $total); $total = $DB->count_records('badge_backpack'); $this->assertEquals(2, $total); $total = $DB->count_records('badge_external'); $this->assertEquals(3, $total); // Remove the backpack created previously. $result = badges_delete_site_backpack($backpack->id); $this->assertTrue($result); $total = $DB->count_records('badge_external_backpack'); $this->assertEquals(1, $total); $total = $DB->count_records('badge_backpack'); $this->assertEquals(1, $total); $total = $DB->count_records('badge_external'); $this->assertEquals(1, $total); // Try to remove an non-existent backpack. $result = badges_delete_site_backpack($backpack->id); $this->assertFalse($result); } }
samhemelryk/moodle
badges/tests/badgeslib_test.php
PHP
gpl-3.0
42,221
// This file is part of BOINC. // http://boinc.berkeley.edu // Copyright (C) 2008 University of California // // BOINC is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // BOINC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with BOINC. If not, see <http://www.gnu.org/licenses/>. // job dispatch using a score-based approach: // - scan the job array, assigning a score to each job and building a list // (the score reflect a variety of factors). // - sort the list // - send jobs in order of decreasing score until request is satisfied // - do the above separately for each resource type #include <algorithm> #include "boinc_db.h" #include "error_numbers.h" #include "util.h" #include "sched_check.h" #include "sched_config.h" #include "sched_hr.h" #include "sched_main.h" #include "sched_msgs.h" #include "sched_send.h" #include "sched_shmem.h" #include "sched_types.h" #include "sched_version.h" #include "sched_score.h" // given the host's estimated speed, determine its size class // static int get_size_class(APP& app, double es) { for (int i=0; i<app.n_size_classes-1; i++) { if (es < app.size_class_quantiles[i]) return i; } return app.n_size_classes - 1; } // Assign a score to this job, // representing the value of sending the job to this host. // Also do some initial screening, // and return false if can't send the job to host // bool JOB::get_score(WU_RESULT& wu_result) { score = 0; if (!app->beta && wu_result.need_reliable) { if (!bavp->reliable) { return false; } } if (app->beta) { if (g_wreq->allow_beta_work) { score += 1; } else { if (config.debug_send_job) { log_messages.printf(MSG_NORMAL, "[send_job] can't send job %d for beta app to non-beta user\n", wu_result.workunit.id ); } return false; } } if (app_not_selected(app->id)) { if (g_wreq->allow_non_preferred_apps) { score -= 1; } else { if (config.debug_send_job) { log_messages.printf(MSG_NORMAL, "[send_job] app not selected for job %d\n", wu_result.workunit.id ); } return false; } } if (wu_result.infeasible_count) { score += 1; } if (app->locality_scheduling == LOCALITY_SCHED_LITE && g_request->file_infos.size() ) { int n = nfiles_on_host(wu_result.workunit); if (config.debug_locality_lite) { log_messages.printf(MSG_NORMAL, "[loc_lite] job %s has %d files on this host\n", wu_result.workunit.name, n ); } if (n > 0) { score += 10; } } if (app->n_size_classes > 1) { double effective_speed = bavp->host_usage.projected_flops * available_frac(*bavp); int target_size = get_size_class(*app, effective_speed); if (config.debug_send_job) { log_messages.printf(MSG_NORMAL, "[send_job] size: host %d job %d speed %f\n", target_size, wu_result.workunit.size_class, effective_speed ); } if (target_size == wu_result.workunit.size_class) { score += 5; } else if (target_size < wu_result.workunit.size_class) { score -= 2; } else { score -= 1; } } if (config.debug_send_job) { log_messages.printf(MSG_NORMAL, "[send_job]: score %f for result %d\n", score, wu_result.resultid ); } return true; } bool job_compare(JOB j1, JOB j2) { return (j1.score > j2.score); } static double req_sec_save[NPROC_TYPES]; static double req_inst_save[NPROC_TYPES]; static void clear_others(int rt) { for (int i=0; i<NPROC_TYPES; i++) { if (i == rt) continue; req_sec_save[i] = g_wreq->req_secs[i]; g_wreq->req_secs[i] = 0; req_inst_save[i] = g_wreq->req_instances[i]; g_wreq->req_instances[i] = 0; } } static void restore_others(int rt) { for (int i=0; i<NPROC_TYPES; i++) { if (i == rt) continue; g_wreq->req_secs[i] += req_sec_save[i]; g_wreq->req_instances[i] += req_inst_save[i]; } } // send work for a particular processor type // void send_work_score_type(int rt) { vector<JOB> jobs; if (config.debug_send_scan) { log_messages.printf(MSG_NORMAL, "[send_scan] scanning for %s jobs\n", proc_type_name(rt) ); } clear_others(rt); int nscan = ssp->max_wu_results; int rnd_off = rand() % ssp->max_wu_results; if (config.debug_send_scan) { log_messages.printf(MSG_NORMAL, "[send_scan] scanning %d slots starting at %d\n", nscan, rnd_off ); } for (int j=0; j<nscan; j++) { int i = (j+rnd_off) % ssp->max_wu_results; WU_RESULT& wu_result = ssp->wu_results[i]; if (wu_result.state != WR_STATE_PRESENT && wu_result.state != g_pid) { continue; } WORKUNIT wu = wu_result.workunit; JOB job; job.app = ssp->lookup_app(wu.appid); if (job.app->non_cpu_intensive) { if (config.debug_send_job) { log_messages.printf(MSG_NORMAL, "[send_job] [RESULT#%u] app is non compute intensive\n", wu_result.resultid ); } continue; } job.bavp = get_app_version(wu, true, false); if (!job.bavp) { if (config.debug_send_job) { log_messages.printf(MSG_NORMAL, "[send_job] [RESULT#%u] no app version available\n", wu_result.resultid ); } continue; } job.index = i; job.result_id = wu_result.resultid; if (!job.get_score(wu_result)) { if (config.debug_send_job) { log_messages.printf(MSG_NORMAL, "[send_job] [RESULT#%u] get_score() returned false\n", wu_result.resultid ); } continue; } if (config.debug_send_job) { log_messages.printf(MSG_NORMAL, "[send_job] [RESULT#%u] score: %f\n", wu_result.resultid, job.score ); } jobs.push_back(job); } std::sort(jobs.begin(), jobs.end(), job_compare); bool sema_locked = false; for (unsigned int i=0; i<jobs.size(); i++) { // check limit on total jobs // if (!work_needed(false)) { break; } // check limit on jobs for this processor type // if (!g_wreq->need_proc_type(rt)) { break; } JOB& job = jobs[i]; // check limits on jobs for this (app, processor type) // if (config.max_jobs_in_progress.exceeded(job.app, job.bavp->host_usage.proc_type)) { if (config.debug_quota) { log_messages.printf(MSG_NORMAL, "[quota] limit for app/proctype exceeded\n" ); } continue; } if (!sema_locked) { lock_sema(); sema_locked = true; } // make sure the job is still in the cache // array is locked at this point. // WU_RESULT& wu_result = ssp->wu_results[job.index]; if (wu_result.state != WR_STATE_PRESENT && wu_result.state != g_pid) { continue; } if (wu_result.resultid != job.result_id) { continue; } WORKUNIT wu = wu_result.workunit; int retval = wu_is_infeasible_fast( wu, wu_result.res_server_state, wu_result.res_priority, wu_result.res_report_deadline, *job.app, *job.bavp ); if (retval) { continue; } wu_result.state = g_pid; // It passed fast checks. // Release sema and do slow checks // unlock_sema(); sema_locked = false; switch (slow_check(wu_result, job.app, job.bavp)) { case 1: wu_result.state = WR_STATE_PRESENT; break; case 2: wu_result.state = WR_STATE_EMPTY; break; default: // slow_check() refreshes fields of wu_result.workunit; // update our copy too // wu.hr_class = wu_result.workunit.hr_class; wu.app_version_id = wu_result.workunit.app_version_id; // mark slot as empty AFTER we've copied out of it // (since otherwise feeder might overwrite it) // wu_result.state = WR_STATE_EMPTY; // reread result from DB, make sure it's still unsent // TODO: from here to end of add_result_to_reply() // (which updates the DB record) should be a transaction // SCHED_DB_RESULT result; result.id = wu_result.resultid; if (result_still_sendable(result, wu)) { add_result_to_reply(result, wu, job.bavp, false); // add_result_to_reply() fails only in pathological cases - // e.g. we couldn't update the DB record or modify XML fields. // If this happens, don't replace the record in the array // (we can't anyway, since we marked the entry as "empty"). // The feeder will eventually pick it up again, // and hopefully the problem won't happen twice. } break; } } if (sema_locked) { unlock_sema(); } restore_others(rt); g_wreq->best_app_versions.clear(); } void send_work_score() { for (int i=NPROC_TYPES-1; i>= 0; i--) { if (g_wreq->need_proc_type(i)) { send_work_score_type(i); } } }
Ashod/Boinc
sched/sched_score.cpp
C++
gpl-3.0
10,601
<?php /** * ManiaPlanet dedicated server Xml-RPC client * * @license http://www.gnu.org/licenses/lgpl.html LGPL License 3 */ namespace Maniaplanet\DedicatedServer\Structures; class LadderStats extends AbstractStructure { /** @var float */ public $lastMatchScore; /** @var int */ public $nbrMatchWins; /** @var int */ public $nbrMatchDraws; /** @var int */ public $nbrMatchLosses; /** @var string */ public $teamName; /** @var ZoneRanking[] */ public $playerRankings; /** @var array */ public $teamRankings; /** * @return LadderStats */ static function fromArray($array) { $object = parent::fromArray($array); $object->playerRankings = ZoneRanking::fromArrayOfArray($object->playerRankings); return $object; } }
ManiaControl/ManiaControl
libs/Maniaplanet/DedicatedServer/Structures/LadderStats.php
PHP
gpl-3.0
750
<?php /** * This example retrieves an existing CNAME record and then deletes it */ require '../../vendor/autoload.php'; use Dyn\TrafficManagement; $tm = new TrafficManagement('customerName', 'username', 'password'); // login $tm->createSession(); // retrieve zone $zone = $tm->getZone('example.com'); // retrieve the record(s) we want removed $records = $zone->getRecords('CNAME', 'test.example.com'); // ensure we only got one back if (count($records) == 1) { $record = $records[0]; } else { throw new Exception('Multiple records found, aborting'); } // delete the record $zone->deleteRecord($record); // publish changes to the zone (makes the changes live) $zone->publish(); // logout $tm->deleteSession();
fwahyudi17/ofiskita
image/mailwizz/apps/common/vendors/Composer/vendor/dyninc/dyn-php/examples/dns/delete-dns-record.php
PHP
gpl-3.0
729
<?php namespace ProcessWire; /** * ProcessWire WireData * * This is the base data container class used throughout ProcessWire. * It provides get and set access to properties internally stored in a $data array. * Otherwise it is identical to the Wire class. * * #pw-summary WireData is the base data-storage class used by many ProcessWire object types and most modules. * #pw-body = * WireData is very much like its parent `Wire` class with the fundamental difference being that it is designed * for runtime data storage. It provides this primarily through the built-in `get()` and `set()` methods for * getting and setting named properties to WireData objects. The most common example of a WireData object is * `Page`, the type used for all pages in ProcessWire. * * Properties set to a WireData object can also be set or accessed directly, like `$item->property` or using * array access like `$item[$property]`. If you `foreach()` a WireData object, the default behavior is to * iterate all of the properties/values present within it. * #pw-body * * May also be accessed as array. * * ProcessWire 3.x, Copyright 2016 by Ryan Cramer * https://processwire.com * * @method WireArray and($items = null) * */ class WireData extends Wire implements \IteratorAggregate, \ArrayAccess { /** * Array where get/set properties are stored * */ protected $data = array(); /** * Set a value to this object’s data * * ~~~~~ * // Set a value for a property * $item->set('foo', 'bar'); * * // Set a property value directly * $item->foo = 'bar'; * * // Set a property using array access * $item['foo'] = 'bar'; * ~~~~~ * * #pw-group-manipulation * * @param string $key Name of property you want to set * @param mixed $value Value of property * @return $this * @see WireData::setQuietly(), WireData::get() * */ public function set($key, $value) { if($key === 'data') { if(!is_array($value)) $value = (array) $value; return $this->setArray($value); } $v = isset($this->data[$key]) ? $this->data[$key] : null; if(!$this->isEqual($key, $v, $value)) $this->trackChange($key, $v, $value); $this->data[$key] = $value; return $this; } /** * Same as set() but without change tracking * * - If `$this->trackChanges()` is false, then this is no different than set(), since changes aren't being tracked. * - If `$this->trackChanges()` is true, then the value will be set quietly (i.e. not recorded in the changes list). * * #pw-group-manipulation * * @param string $key Name of property you want to set * @param mixed $value Value of property * @return $this * @see Wire::trackChanges(), WireData::set() * */ public function setQuietly($key, $value) { $track = $this->trackChanges(); $this->setTrackChanges(false); $this->set($key, $value); if($track) $this->setTrackChanges(true); return $this; } /** * Is $value1 equal to $value2? * * This template method provided so that descending classes can optionally determine * whether a change should be tracked. * * #pw-internal * * @param string $key Name of the property/key that triggered the check (see `WireData::set()`) * @param mixed $value1 Comparison value * @param mixed $value2 A second comparison value * @return bool True if values are equal, false if not * */ protected function isEqual($key, $value1, $value2) { if($key) {} // intentional to avoid unused argument notice // $key intentionally not used here, but may be used by descending classes return $value1 === $value2; } /** * Set an array of key=value pairs * * This is the same as the `WireData::set()` method except that it can set an array * of properties at once. * * #pw-group-manipulation * * @param array $data Associative array of where the keys are property names, and values are… values. * @return $this * @see WireData::set() * */ public function setArray(array $data) { foreach($data as $key => $value) $this->set($key, $value); return $this; } /** * Provides direct reference access to set values in the $data array * * @param string $key * @param mixed $value * return $this * */ public function __set($key, $value) { $this->set($key, $value); } /** * Retrieve the value for a previously set property, or retrieve an API variable * * - If the given $key is an object, it will cast it to a string. * - If the given $key is a string with "|" pipe characters in it, it will try all till it finds a non-empty value. * - If given an API variable name, it will return that API variable unless the class has direct access API variables disabled. * * ~~~~~ * // Retrieve the value of a property * $value = $item->get("some_property"); * * // Retrieve the value of the first non-empty property: * $value = $item->get("property1|property2|property2"); * * // Retrieve a value using array access * $value = $item["some_property"]; * ~~~~~ * * #pw-group-retrieval * * @param string|object $key Name of property you want to retrieve. * @return mixed|null Returns value of requested property, or null if the property was not found. * @see WireData::set() * */ public function get($key) { if(is_object($key)) $key = "$key"; if(array_key_exists($key, $this->data)) return $this->data[$key]; if(strpos($key, '|')) { $keys = explode('|', $key); foreach($keys as $k) { /** @noinspection PhpAssignmentInConditionInspection */ if($value = $this->get($k)) return $value; } } return parent::__get($key); // back to Wire } /** * Get or set a low-level data value * * Like get() or set() but will only get/set from the WireData's protected $data array. * This is used to bypass any extra logic a class may have added to its get() or set() * methods. The benefit of this method over get() is that it excludes API vars and potentially * other things (defined by descending classes) that you may not want. * * - To get a value, simply omit the $value argument. * - To set a value, specify both the $key and $value arguments. * - If you omit a $key and $value, this method will return the entire data array. * * #pw-group-manipulation * #pw-group-retrieval * * ~~~~~ * // Set a property * $item->data('some_property', 'some value'); * * // Get the value of a previously set property * $value = $item->data('some_property'); * ~~~~~ * * @param string|array $key Property you want to get or set, or associative array of properties you want to set. * @param mixed $value Optionally specify a value if you want to set rather than get. * Or Specify boolean TRUE if setting an array via $key and you want to overwrite any existing values (rather than merge). * @return array|WireData|null Returns one of the following: * - `mixed` - Actual value if getting a previously set value. * - `null` - If you are attempting to get a value that has not been set. * - `$this` - If you are setting a value. */ public function data($key = null, $value = null) { if(is_null($key)) return $this->data; if(is_array($key)) { if($value === true) { $this->data = $key; } else { $this->data = array_merge($this->data, $key); } return $this; } else if(is_null($value)) { return isset($this->data[$key]) ? $this->data[$key] : null; } else { $this->data[$key] = $value; return $this; } } /** * Returns the full array of properties set to this object * * If descending classes also store data in other containers, they may want to * override this method to include that data as well. * * #pw-group-retrieval * * @return array Returned array is associative and indexed by property name. * */ public function getArray() { return $this->data; } /** * Get a property via dot syntax: field.subfield (static) * * Static version for internal core use. Use the non-static getDot() instead. * * #pw-internal * * @param string $key * @param Wire $from The instance you want to pull the value from * @return null|mixed Returns value if found or null if not * */ public static function _getDot($key, Wire $from) { $key = trim($key, '.'); if(strpos($key, '.')) { // dot present $keys = explode('.', $key); // convert to array $key = array_shift($keys); // get first item } else { // dot not present $keys = array(); } if($from->wire($key) !== null) return null; // don't allow API vars to be retrieved this way if($from instanceof WireData) $value = $from->get($key); else if($from instanceof WireArray) $value = $from->getProperty($key); else $value = $from->$key; if(!count($keys)) return $value; // final value if(is_object($value)) { if(count($keys) > 1) { $keys = implode('.', $keys); // convert back to string if($value instanceof WireData) $value = $value->getDot($keys); // for override potential else $value = self::_getDot($keys, $value); } else { $key = array_shift($keys); // just one key left, like 'title' if($value instanceof WireData) { $value = $value->get($key); } else if($value instanceof WireArray) { if($key == 'count') { $value = count($value); } else { $a = array(); foreach($value as $v) $a[] = $v->get($key); $value = $a; } } } } else { // there is a dot property remaining and nothing to send it to $value = null; } return $value; } /** * Get a property via dot syntax: field.subfield.subfield * * Some classes descending WireData may choose to add a call to this as part of their * get() method as a syntax convenience. * * ~~~~~ * $value = $item->get("parent.title"); * ~~~~~ * * #pw-group-retrieval * * @param string $key Name of property you want to retrieve in "a.b" or "a.b.c" format * @return null|mixed Returns value if found or null if not * */ public function getDot($key) { return self::_getDot($key, $this); } /** * Provides direct reference access to variables in the $data array * * Otherwise the same as get() * * @param string $key * @return mixed|null * */ public function __get($key) { return $this->get($key); } /** * Enables use of $var('key') * * @param string $key * @return mixed * */ public function __invoke($key) { return $this->get($key); } /** * Remove a previously set property * * ~~~~~ * $item->remove('some_property'); * ~~~~~ * * #pw-group-manipulation * * @param string $key Name of property you want to remove * @return $this * */ public function remove($key) { $value = isset($this->data[$key]) ? $this->data[$key] : null; $this->trackChange("unset:$key", $value, null); unset($this->data[$key]); return $this; } /** * Enables the object data properties to be iterable as an array * * ~~~~~ * foreach($item as $key => $value) { * // ... * } * ~~~~~ * * #pw-group-retrieval * * @return \ArrayObject * */ public function getIterator() { return new \ArrayObject($this->data); } /** * Does this object have the given property? * * ~~~~~ * if($item->has('some_property')) { * // the item has some_property * } * ~~~~~ * * #pw-group-retrieval * * @param string $key Name of property you want to check. * @return bool True if it has the property, false if not. * */ public function has($key) { return ($this->get($key) !== null); } /** * Take the current item and append the given item(s), returning a new WireArray * * This is for syntactic convenience in fluent interfaces. * ~~~~~ * if($page->and($page->parents)->has("featured=1")) { * // page or one of its parents has a featured property with value of 1 * } * ~~~~~ * * #pw-group-retrieval * * @param WireArray|WireData|string|null $items May be any of the following: * - `WireData` object (or derivative) * - `WireArray` object (or derivative) * - Name of any property from this object that returns one of the above. * - Omit argument to simply return this object in a WireArray * @return WireArray Returns a WireArray of this object *and* the one(s) given. * @throws WireException If invalid argument supplied. * */ public function ___and($items = null) { if(is_string($items)) $items = $this->get($items); if($items instanceof WireArray) { // great, that's what we want $a = clone $items; $a->prepend($this); } else if($items instanceof WireData || is_null($items)) { // single item $className = $this->className(true) . 'Array'; if(!class_exists($className)) $className = wireClassName('WireArray', true); $a = $this->wire(new $className()); $a->add($this); if($items) $a->add($items); } else { // unknown throw new WireException('Invalid argument provided to WireData::and(...)'); } return $a; } /** * Ensures that isset() and empty() work for this classes properties. * * #pw-internal * * @param string $key * @return bool * */ public function __isset($key) { return isset($this->data[$key]); } /** * Ensures that unset() works for this classes data. * * #pw-internal * * @param string $key * */ public function __unset($key) { $this->remove($key); } /** * Sets an index in the WireArray. * * For the ArrayAccess interface. * * #pw-internal * * @param int|string $key Key of item to set. * @param int|string|array|object $value Value of item. * */ public function offsetSet($key, $value) { $this->set($key, $value); } /** * Returns the value of the item at the given index, or false if not set. * * #pw-internal * * @param int|string $key Key of item to retrieve. * @return int|string|array|object Value of item requested, or false if it doesn't exist. * */ public function offsetGet($key) { $value = $this->get($key); return is_null($value) ? false : $value; } /** * Unsets the value at the given index. * * For the ArrayAccess interface. * * #pw-internal * * @param int|string $key Key of the item to unset. * @return bool True if item existed and was unset. False if item didn't exist. * */ public function offsetUnset($key) { if($this->__isset($key)) { $this->remove($key); return true; } else { return false; } } /** * Determines if the given index exists in this WireData. * * For the ArrayAccess interface. * * #pw-internal * * @param int|string $key Key of the item to check for existence. * @return bool True if the item exists, false if not. * */ public function offsetExists($key) { return $this->__isset($key); } /** * debugInfo PHP 5.6+ magic method * * @return array * */ public function __debugInfo() { $info = parent::__debugInfo(); if(count($this->data)) $info['data'] = $this->data; return $info; } }
sunlix/ProcessWire
wire/core/WireData.php
PHP
mpl-2.0
15,064
<?php /** * @package jelix * @subpackage dao * @author Gérald Croes, Laurent Jouanneau * @contributor Laurent Jouanneau * @contributor Philippe Villiers * @copyright 2001-2005 CopixTeam, 2005-2011 Laurent Jouanneau * This class was get originally from the Copix project (CopixDAODefinitionV1, Copix 2.3dev20050901, http://www.copix.org) * Few lines of code are still copyrighted 2001-2005 CopixTeam (LGPL licence). * Initial authors of this Copix class are Gerald Croes and Laurent Jouanneau, * and this class was adapted/improved for Jelix by Laurent Jouanneau * * @link http://www.jelix.org * @licence http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public Licence, see LICENCE file */ /** * Container for properties of a dao property * @package jelix * @subpackage dao */ class jDaoProperty { /** * the name of the property of the object */ public $name = ''; /** * the name of the field in table */ public $fieldName = ''; /** * give the regular expression that needs to be matched against. * @var string */ public $regExp = null; /** * says if the field is required when doing a check * @var boolean */ public $required = false; /** * says if the value of the field is required when construct SQL conditions * @var boolean */ public $requiredInConditions = false; /** * Says if it's a primary key. * @var boolean */ public $isPK = false; /** * Says if it's a foreign key * @var boolean */ public $isFK = false; public $datatype; public $unifiedType; public $table=null; public $updatePattern='%s'; public $insertPattern='%s'; public $selectPattern='%s'; public $sequenceName=''; /** * the maxlength of the key if given * @var int */ public $maxlength = null; public $minlength = null; public $ofPrimaryTable = true; public $defaultValue = null; public $autoIncrement = false; /** * comment field / eg : use to form's label * @var string */ public $comment = ''; /** * constructor. * @param array $aAttributes * @param jDaoParser $parser the parser on the dao file * @param jDbTools $tools * @throws jDaoXmlException * @internal param array $attributes list of attributes of a simpleXmlElement */ function __construct ($aAttributes, $parser, $tools){ $needed = array('name', 'fieldname', 'table', 'datatype', 'required', 'minlength', 'maxlength', 'regexp', 'sequence', 'default', 'autoincrement'); // Allowed attributes names $allowed = array('name', 'fieldname', 'table', 'datatype', 'required', 'minlength', 'maxlength', 'regexp', 'sequence', 'default', 'autoincrement', 'updatepattern', 'insertpattern', 'selectpattern','comment'); foreach($aAttributes as $attributeName => $attributeValue) { if(!in_array($attributeName, $allowed)) { throw new jDaoXmlException ($parser->selector, 'unknown.attr', array($attributeName, 'property')); } } $params = $parser->getAttr($aAttributes, $needed); if ($params['name']===null){ throw new jDaoXmlException ($parser->selector, 'missing.attr', array('name', 'property')); } $this->name = $params['name']; if(!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $this->name)){ throw new jDaoXmlException ($parser->selector, 'property.invalid.name', $this->name); } $this->fieldName = $params['fieldname'] !==null ? $params['fieldname'] : $this->name; $this->table = $params['table'] !==null ? $params['table'] : $parser->getPrimaryTable(); $tables = $parser->getTables(); if(!isset( $tables[$this->table])){ throw new jDaoXmlException ($parser->selector, 'property.unknown.table', $this->name); } $this->required = $this->requiredInConditions = $parser->getBool ($params['required']); $this->maxlength = $params['maxlength'] !== null ? intval($params['maxlength']) : null; $this->minlength = $params['minlength'] !== null ? intval($params['minlength']) : null; $this->regExp = $params['regexp']; $this->autoIncrement = $parser->getBool ($params['autoincrement']); if ($params['datatype']===null){ throw new jDaoXmlException ($parser->selector, 'missing.attr', array('datatype', 'property')); } $params['datatype'] = trim(strtolower($params['datatype'])); if ($params['datatype'] == '') { throw new jDaoXmlException ($parser->selector, 'wrong.attr', array($params['datatype'], $this->fieldName, 'property')); } $this->datatype = strtolower($params['datatype']); $ti = $tools->getTypeInfo($this->datatype); $this->unifiedType = $ti[1]; if (!$this->autoIncrement) $this->autoIncrement = $ti[6]; if ($this->unifiedType == 'integer' || $this->unifiedType == 'numeric') { if ($params['sequence'] !== null) { $this->sequenceName = $params['sequence']; $this->autoIncrement = true; } } $pkeys = array_map('strtolower', $tables[$this->table]['pk']); $this->isPK = in_array(strtolower($this->fieldName), $pkeys); if(!$this->isPK && $this->table == $parser->getPrimaryTable()){ foreach($tables as $table=>$info) { if ($table == $this->table) continue; if(isset($info['fk'])) { $fkeys = array_map('strtolower', $info['fk']); if(in_array(strtolower($this->fieldName), $fkeys)) { $this->isFK = true; break; } } } } else { $this->required = true; $this->requiredInConditions = true; } if ($this->autoIncrement) { $this->required = false; $this->requiredInConditions = true; } if ($params['default'] !== null) { $this->defaultValue = $tools->stringToPhpValue($this->unifiedType, $params['default']); } // insertpattern is allowed on primary keys noy autoincremented if ($this->isPK && !$this->autoIncrement && isset($aAttributes['insertpattern'])) { $this->insertPattern=(string)$aAttributes['insertpattern']; } if ($this->isPK) { $this->updatePattern = ''; } // we ignore *pattern attributes on PK and FK fields if (!$this->isPK && !$this->isFK) { if(isset($aAttributes['updatepattern'])) { $this->updatePattern=(string)$aAttributes['updatepattern']; } if(isset($aAttributes['insertpattern'])) { $this->insertPattern=(string)$aAttributes['insertpattern']; } if(isset($aAttributes['selectpattern'])) { $this->selectPattern=(string)$aAttributes['selectpattern']; } } // no update and insert patterns for field of external tables if ($this->table != $parser->getPrimaryTable()) { $this->updatePattern = ''; $this->insertPattern = ''; $this->required = false; $this->requiredInConditions = false; $this->ofPrimaryTable = false; } else { $this->ofPrimaryTable=true; } // field comment if(isset($aAttributes['comment'])) { $this->comment=(string)$aAttributes['comment']; } } }
rldhont/lizmap-web-client
lib/jelix/dao/jDaoProperty.class.php
PHP
mpl-2.0
7,974
package aws import ( "fmt" "log" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" ) func resourceAwsSubnet() *schema.Resource { return &schema.Resource{ Create: resourceAwsSubnetCreate, Read: resourceAwsSubnetRead, Update: resourceAwsSubnetUpdate, Delete: resourceAwsSubnetDelete, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ Create: schema.DefaultTimeout(10 * time.Minute), Delete: schema.DefaultTimeout(10 * time.Minute), }, SchemaVersion: 1, MigrateState: resourceAwsSubnetMigrateState, Schema: map[string]*schema.Schema{ "vpc_id": { Type: schema.TypeString, Required: true, ForceNew: true, }, "cidr_block": { Type: schema.TypeString, Required: true, ForceNew: true, }, "ipv6_cidr_block": { Type: schema.TypeString, Optional: true, Computed: true, }, "availability_zone": { Type: schema.TypeString, Optional: true, Computed: true, ForceNew: true, ConflictsWith: []string{"availability_zone_id"}, }, "availability_zone_id": { Type: schema.TypeString, Optional: true, Computed: true, ForceNew: true, ConflictsWith: []string{"availability_zone"}, }, "map_public_ip_on_launch": { Type: schema.TypeBool, Optional: true, Default: false, }, "assign_ipv6_address_on_creation": { Type: schema.TypeBool, Optional: true, Default: false, }, "ipv6_cidr_block_association_id": { Type: schema.TypeString, Computed: true, }, "arn": { Type: schema.TypeString, Computed: true, }, "tags": tagsSchema(), "owner_id": { Type: schema.TypeString, Computed: true, }, }, } } func resourceAwsSubnetCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ec2conn createOpts := &ec2.CreateSubnetInput{ AvailabilityZone: aws.String(d.Get("availability_zone").(string)), AvailabilityZoneId: aws.String(d.Get("availability_zone_id").(string)), CidrBlock: aws.String(d.Get("cidr_block").(string)), VpcId: aws.String(d.Get("vpc_id").(string)), } if v, ok := d.GetOk("ipv6_cidr_block"); ok { createOpts.Ipv6CidrBlock = aws.String(v.(string)) } var err error resp, err := conn.CreateSubnet(createOpts) if err != nil { return fmt.Errorf("Error creating subnet: %s", err) } // Get the ID and store it subnet := resp.Subnet d.SetId(*subnet.SubnetId) log.Printf("[INFO] Subnet ID: %s", *subnet.SubnetId) // Wait for the Subnet to become available log.Printf("[DEBUG] Waiting for subnet (%s) to become available", *subnet.SubnetId) stateConf := &resource.StateChangeConf{ Pending: []string{"pending"}, Target: []string{"available"}, Refresh: SubnetStateRefreshFunc(conn, *subnet.SubnetId), Timeout: 10 * time.Minute, } _, err = stateConf.WaitForState() if err != nil { return fmt.Errorf( "Error waiting for subnet (%s) to become ready: %s", d.Id(), err) } return resourceAwsSubnetUpdate(d, meta) } func resourceAwsSubnetRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ec2conn resp, err := conn.DescribeSubnets(&ec2.DescribeSubnetsInput{ SubnetIds: []*string{aws.String(d.Id())}, }) if err != nil { if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidSubnetID.NotFound" { // Update state to indicate the subnet no longer exists. d.SetId("") return nil } return err } if resp == nil { return nil } subnet := resp.Subnets[0] d.Set("vpc_id", subnet.VpcId) d.Set("availability_zone", subnet.AvailabilityZone) d.Set("availability_zone_id", subnet.AvailabilityZoneId) d.Set("cidr_block", subnet.CidrBlock) d.Set("map_public_ip_on_launch", subnet.MapPublicIpOnLaunch) d.Set("assign_ipv6_address_on_creation", subnet.AssignIpv6AddressOnCreation) // Make sure those values are set, if an IPv6 block exists it'll be set in the loop d.Set("ipv6_cidr_block_association_id", "") d.Set("ipv6_cidr_block", "") for _, a := range subnet.Ipv6CidrBlockAssociationSet { if *a.Ipv6CidrBlockState.State == "associated" { //we can only ever have 1 IPv6 block associated at once d.Set("ipv6_cidr_block_association_id", a.AssociationId) d.Set("ipv6_cidr_block", a.Ipv6CidrBlock) break } } d.Set("arn", subnet.SubnetArn) d.Set("tags", tagsToMap(subnet.Tags)) d.Set("owner_id", subnet.OwnerId) return nil } func resourceAwsSubnetUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ec2conn d.Partial(true) if err := setTags(conn, d); err != nil { return err } else { d.SetPartial("tags") } if d.HasChange("map_public_ip_on_launch") { modifyOpts := &ec2.ModifySubnetAttributeInput{ SubnetId: aws.String(d.Id()), MapPublicIpOnLaunch: &ec2.AttributeBooleanValue{ Value: aws.Bool(d.Get("map_public_ip_on_launch").(bool)), }, } log.Printf("[DEBUG] Subnet modify attributes: %#v", modifyOpts) _, err := conn.ModifySubnetAttribute(modifyOpts) if err != nil { return err } else { d.SetPartial("map_public_ip_on_launch") } } // We have to be careful here to not go through a change of association if this is a new resource // A New resource here would denote that the Update func is called by the Create func if d.HasChange("ipv6_cidr_block") && !d.IsNewResource() { // We need to handle that we disassociate the IPv6 CIDR block before we try and associate the new one // This could be an issue as, we could error out when we try and add the new one // We may need to roll back the state and reattach the old one if this is the case _, new := d.GetChange("ipv6_cidr_block") if v, ok := d.GetOk("ipv6_cidr_block_association_id"); ok { //Firstly we have to disassociate the old IPv6 CIDR Block disassociateOps := &ec2.DisassociateSubnetCidrBlockInput{ AssociationId: aws.String(v.(string)), } _, err := conn.DisassociateSubnetCidrBlock(disassociateOps) if err != nil { return err } // Wait for the CIDR to become disassociated log.Printf( "[DEBUG] Waiting for IPv6 CIDR (%s) to become disassociated", d.Id()) stateConf := &resource.StateChangeConf{ Pending: []string{"disassociating", "associated"}, Target: []string{"disassociated"}, Refresh: SubnetIpv6CidrStateRefreshFunc(conn, d.Id(), d.Get("ipv6_cidr_block_association_id").(string)), Timeout: 3 * time.Minute, } if _, err := stateConf.WaitForState(); err != nil { return fmt.Errorf( "Error waiting for IPv6 CIDR (%s) to become disassociated: %s", d.Id(), err) } } //Now we need to try and associate the new CIDR block associatesOpts := &ec2.AssociateSubnetCidrBlockInput{ SubnetId: aws.String(d.Id()), Ipv6CidrBlock: aws.String(new.(string)), } resp, err := conn.AssociateSubnetCidrBlock(associatesOpts) if err != nil { //The big question here is, do we want to try and reassociate the old one?? //If we have a failure here, then we may be in a situation that we have nothing associated return err } // Wait for the CIDR to become associated log.Printf( "[DEBUG] Waiting for IPv6 CIDR (%s) to become associated", d.Id()) stateConf := &resource.StateChangeConf{ Pending: []string{"associating", "disassociated"}, Target: []string{"associated"}, Refresh: SubnetIpv6CidrStateRefreshFunc(conn, d.Id(), *resp.Ipv6CidrBlockAssociation.AssociationId), Timeout: 3 * time.Minute, } if _, err := stateConf.WaitForState(); err != nil { return fmt.Errorf( "Error waiting for IPv6 CIDR (%s) to become associated: %s", d.Id(), err) } d.SetPartial("ipv6_cidr_block") } if d.HasChange("assign_ipv6_address_on_creation") { modifyOpts := &ec2.ModifySubnetAttributeInput{ SubnetId: aws.String(d.Id()), AssignIpv6AddressOnCreation: &ec2.AttributeBooleanValue{ Value: aws.Bool(d.Get("assign_ipv6_address_on_creation").(bool)), }, } log.Printf("[DEBUG] Subnet modify attributes: %#v", modifyOpts) _, err := conn.ModifySubnetAttribute(modifyOpts) if err != nil { return err } else { d.SetPartial("assign_ipv6_address_on_creation") } } d.Partial(false) return resourceAwsSubnetRead(d, meta) } func resourceAwsSubnetDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ec2conn log.Printf("[INFO] Deleting subnet: %s", d.Id()) if err := deleteLingeringLambdaENIs(conn, d, "subnet-id"); err != nil { return fmt.Errorf("Failed to delete Lambda ENIs: %s", err) } req := &ec2.DeleteSubnetInput{ SubnetId: aws.String(d.Id()), } wait := resource.StateChangeConf{ Pending: []string{"pending"}, Target: []string{"destroyed"}, Timeout: 10 * time.Minute, MinTimeout: 1 * time.Second, Refresh: func() (interface{}, string, error) { _, err := conn.DeleteSubnet(req) if err != nil { if apiErr, ok := err.(awserr.Error); ok { if apiErr.Code() == "DependencyViolation" { // There is some pending operation, so just retry // in a bit. return 42, "pending", nil } if apiErr.Code() == "InvalidSubnetID.NotFound" { return 42, "destroyed", nil } } return 42, "failure", err } return 42, "destroyed", nil }, } if _, err := wait.WaitForState(); err != nil { return fmt.Errorf("Error deleting subnet: %s", err) } return nil } // SubnetStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch a Subnet. func SubnetStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc { return func() (interface{}, string, error) { resp, err := conn.DescribeSubnets(&ec2.DescribeSubnetsInput{ SubnetIds: []*string{aws.String(id)}, }) if err != nil { if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidSubnetID.NotFound" { resp = nil } else { log.Printf("Error on SubnetStateRefresh: %s", err) return nil, "", err } } if resp == nil { // Sometimes AWS just has consistency issues and doesn't see // our instance yet. Return an empty state. return nil, "", nil } subnet := resp.Subnets[0] return subnet, *subnet.State, nil } } func SubnetIpv6CidrStateRefreshFunc(conn *ec2.EC2, id string, associationId string) resource.StateRefreshFunc { return func() (interface{}, string, error) { opts := &ec2.DescribeSubnetsInput{ SubnetIds: []*string{aws.String(id)}, } resp, err := conn.DescribeSubnets(opts) if err != nil { if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidSubnetID.NotFound" { resp = nil } else { log.Printf("Error on SubnetIpv6CidrStateRefreshFunc: %s", err) return nil, "", err } } if resp == nil { // Sometimes AWS just has consistency issues and doesn't see // our instance yet. Return an empty state. return nil, "", nil } if resp.Subnets[0].Ipv6CidrBlockAssociationSet == nil { return nil, "", nil } for _, association := range resp.Subnets[0].Ipv6CidrBlockAssociationSet { if *association.AssociationId == associationId { return association, *association.Ipv6CidrBlockState.State, nil } } return nil, "", nil } }
youhong316/terraform
vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_subnet.go
GO
mpl-2.0
11,481
package com.cozmo.danar.util; import android.content.Context; import info.nightscout.androidaps.MainApp; public class BleCommandUtil { public static final int DANAR_PACKET__TYPE_ENCRYPTION_REQUEST = 0x01; public static final int DANAR_PACKET__TYPE_ENCRYPTION_RESPONSE = 0x02; public static final int DANAR_PACKET__TYPE_COMMAND = 0xA1; public static final int DANAR_PACKET__TYPE_RESPONSE = 0xB2; public static final int DANAR_PACKET__TYPE_NOTIFY = 0xC3; public static final int DANAR_PACKET__OPCODE_ENCRYPTION__PUMP_CHECK = 0x00; public static final int DANAR_PACKET__OPCODE_ENCRYPTION__CHECK_PASSKEY = 0xD0; public static final int DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_REQUEST = 0xD1; public static final int DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_RETURN = 0xD2; public static final int DANAR_PACKET__OPCODE_ENCRYPTION__TIME_INFORMATION = 0x01; public static final int DANAR_PACKET__OPCODE_NOTIFY__DELIVERY_COMPLETE = 0x01; public static final int DANAR_PACKET__OPCODE_NOTIFY__DELIVERY_RATE_DISPLAY = 0x02; public static final int DANAR_PACKET__OPCODE_NOTIFY__ALARM = 0x03; public static final int DANAR_PACKET__OPCODE_NOTIFY__MISSED_BOLUS_ALARM = 0x04; public static final int DANAR_PACKET__OPCODE_REVIEW__INITIAL_SCREEN_INFORMATION = 0x02; public static final int DANAR_PACKET__OPCODE_REVIEW__DELIVERY_STATUS = 0x03; public static final int DANAR_PACKET__OPCODE_REVIEW__GET_PASSWORD = 0x04; public static final int DANAR_PACKET__OPCODE_REVIEW__BOLUS_AVG = 0x10; public static final int DANAR_PACKET__OPCODE_REVIEW__BOLUS = 0x11; public static final int DANAR_PACKET__OPCODE_REVIEW__DAILY = 0x12; public static final int DANAR_PACKET__OPCODE_REVIEW__PRIME = 0x13; public static final int DANAR_PACKET__OPCODE_REVIEW__REFILL = 0x14; public static final int DANAR_PACKET__OPCODE_REVIEW__BLOOD_GLUCOSE = 0x15; public static final int DANAR_PACKET__OPCODE_REVIEW__CARBOHYDRATE = 0x16; public static final int DANAR_PACKET__OPCODE_REVIEW__TEMPORARY = 0x17; public static final int DANAR_PACKET__OPCODE_REVIEW__SUSPEND = 0x18; public static final int DANAR_PACKET__OPCODE_REVIEW__ALARM = 0x19; public static final int DANAR_PACKET__OPCODE_REVIEW__BASAL = 0x1A; public static final int DANAR_PACKET__OPCODE_REVIEW__ALL_HISTORY = 0x1F; public static final int DANAR_PACKET__OPCODE_REVIEW__GET_SHIPPING_INFORMATION = 0x20; public static final int DANAR_PACKET__OPCODE_REVIEW__GET_PUMP_CHECK = 0x21; public static final int DANAR_PACKET__OPCODE_REVIEW__GET_USER_TIME_CHANGE_FLAG = 0x22; public static final int DANAR_PACKET__OPCODE_REVIEW__SET_USER_TIME_CHANGE_FLAG_CLEAR = 0x23; public static final int DANAR_PACKET__OPCODE_REVIEW__GET_MORE_INFORMATION = 0x24; public static final int DANAR_PACKET__OPCODE_REVIEW__SET_HISTORY_UPLOAD_MODE = 0x25; public static final int DANAR_PACKET__OPCODE_REVIEW__GET_TODAY_DELIVERY_TOTAL = 0x26; public static final int DANAR_PACKET__OPCODE_BOLUS__GET_STEP_BOLUS_INFORMATION = 0x40; public static final int DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_BOLUS_STATE = 0x41; public static final int DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_BOLUS = 0x42; public static final int DANAR_PACKET__OPCODE_BOLUS__GET_DUAL_BOLUS = 0x43; public static final int DANAR_PACKET__OPCODE_BOLUS__SET_STEP_BOLUS_STOP = 0x44; public static final int DANAR_PACKET__OPCODE_BOLUS__GET_CARBOHYDRATE_CALCULATION_INFORMATION = 0x45; public static final int DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_MENU_OPTION_STATE = 0x46; public static final int DANAR_PACKET__OPCODE_BOLUS__SET_EXTENDED_BOLUS = 0x47; public static final int DANAR_PACKET__OPCODE_BOLUS__SET_DUAL_BOLUS = 0x48; public static final int DANAR_PACKET__OPCODE_BOLUS__SET_EXTENDED_BOLUS_CANCEL = 0x49; public static final int DANAR_PACKET__OPCODE_BOLUS__SET_STEP_BOLUS_START = 0x4A; public static final int DANAR_PACKET__OPCODE_BOLUS__GET_CALCULATION_INFORMATION = 0x4B; public static final int DANAR_PACKET__OPCODE_BOLUS__GET_BOLUS_RATE = 0x4C; public static final int DANAR_PACKET__OPCODE_BOLUS__SET_BOLUS_RATE = 0x4D; public static final int DANAR_PACKET__OPCODE_BOLUS__GET_CIR_CF_ARRAY = 0x4E; public static final int DANAR_PACKET__OPCODE_BOLUS__SET_CIR_CF_ARRAY = 0x4F; public static final int DANAR_PACKET__OPCODE_BOLUS__GET_BOLUS_OPTION = 0x50; public static final int DANAR_PACKET__OPCODE_BOLUS__SET_BOLUS_OPTION = 0x51; public static final int DANAR_PACKET__OPCODE_BASAL__SET_TEMPORARY_BASAL = 0x60; public static final int DANAR_PACKET__OPCODE_BASAL__TEMPORARY_BASAL_STATE = 0x61; public static final int DANAR_PACKET__OPCODE_BASAL__CANCEL_TEMPORARY_BASAL = 0x62; public static final int DANAR_PACKET__OPCODE_BASAL__GET_PROFILE_NUMBER = 0x63; public static final int DANAR_PACKET__OPCODE_BASAL__SET_PROFILE_NUMBER = 0x64; public static final int DANAR_PACKET__OPCODE_BASAL__GET_PROFILE_BASAL_RATE = 0x65; public static final int DANAR_PACKET__OPCODE_BASAL__SET_PROFILE_BASAL_RATE = 0x66; public static final int DANAR_PACKET__OPCODE_BASAL__GET_BASAL_RATE = 0x67; public static final int DANAR_PACKET__OPCODE_BASAL__SET_BASAL_RATE = 0x68; public static final int DANAR_PACKET__OPCODE_BASAL__SET_SUSPEND_ON = 0x69; public static final int DANAR_PACKET__OPCODE_BASAL__SET_SUSPEND_OFF = 0x6A; public static final int DANAR_PACKET__OPCODE_OPTION__GET_PUMP_TIME = 0x70; public static final int DANAR_PACKET__OPCODE_OPTION__SET_PUMP_TIME = 0x71; public static final int DANAR_PACKET__OPCODE_OPTION__GET_USER_OPTION = 0x72; public static final int DANAR_PACKET__OPCODE_OPTION__SET_USER_OPTION = 0x73; public static final int DANAR_PACKET__OPCODE_BASAL__APS_SET_TEMPORARY_BASAL = 0xC1; public static final int DANAR_PACKET__OPCODE__APS_HISTORY_EVENTS = 0xC2; public static final int DANAR_PACKET__OPCODE__APS_SET_EVENT_HISTORY = 0xC3; public static final int DANAR_PACKET__OPCODE_ETC__SET_HISTORY_SAVE = 0xE0; public static final int DANAR_PACKET__OPCODE_ETC__KEEP_CONNECTION = 0xFF; static { System.loadLibrary("BleCommandUtil"); } private static native byte[] getEncryptedPacketJni(Object context, int opcode, byte[] bytes, String deviceName); private static native byte[] getDecryptedPacketJni(Object context, byte[] bytes); // --------------------------------------------------------- private static BleCommandUtil mInstance = null; public static BleCommandUtil getInstance() { if (mInstance == null) { mInstance = new BleCommandUtil(); } return mInstance; } // --------------------------------------------------------- public byte[] getEncryptedPacket(int opcode, byte[] bytes, String deviceName) { return getEncryptedPacketJni(MainApp.instance().getApplicationContext(), opcode, bytes, deviceName); } public byte[] getDecryptedPacket(byte[] bytes) { return getDecryptedPacketJni(MainApp.instance().getApplicationContext(), bytes); } }
AdrianLxM/AndroidAPS
app/src/main/java/com/cozmo/danar/util/BleCommandUtil.java
Java
agpl-3.0
7,137
# -*- coding: utf-8 -*- from datetime import datetime import uuid from werkzeug.exceptions import Forbidden import logging import openerp from openerp import api, tools from openerp import SUPERUSER_ID from openerp.addons.website.models.website import slug from openerp.exceptions import Warning from openerp.osv import osv, fields from openerp.tools import html2plaintext from openerp.tools.translate import _ _logger = logging.getLogger(__name__) class KarmaError(Forbidden): """ Karma-related error, used for forum and posts. """ pass class Forum(osv.Model): """TDE TODO: set karma values for actions dynamic for a given forum""" _name = 'forum.forum' _description = 'Forums' _inherit = ['mail.thread', 'website.seo.metadata'] def init(self, cr): """ Add forum uuid for user email validation. """ forum_uuids = self.pool['ir.config_parameter'].search(cr, SUPERUSER_ID, [('key', '=', 'website_forum.uuid')]) if not forum_uuids: self.pool['ir.config_parameter'].set_param(cr, SUPERUSER_ID, 'website_forum.uuid', str(uuid.uuid4()), ['base.group_system']) _columns = { 'name': fields.char('Name', required=True, translate=True), 'faq': fields.html('Guidelines'), 'description': fields.html('Description'), # karma generation 'karma_gen_question_new': fields.integer('Asking a question'), 'karma_gen_question_upvote': fields.integer('Question upvoted'), 'karma_gen_question_downvote': fields.integer('Question downvoted'), 'karma_gen_answer_upvote': fields.integer('Answer upvoted'), 'karma_gen_answer_downvote': fields.integer('Answer downvoted'), 'karma_gen_answer_accept': fields.integer('Accepting an answer'), 'karma_gen_answer_accepted': fields.integer('Answer accepted'), 'karma_gen_answer_flagged': fields.integer('Answer flagged'), # karma-based actions 'karma_ask': fields.integer('Ask a question'), 'karma_answer': fields.integer('Answer a question'), 'karma_edit_own': fields.integer('Edit its own posts'), 'karma_edit_all': fields.integer('Edit all posts'), 'karma_close_own': fields.integer('Close its own posts'), 'karma_close_all': fields.integer('Close all posts'), 'karma_unlink_own': fields.integer('Delete its own posts'), 'karma_unlink_all': fields.integer('Delete all posts'), 'karma_upvote': fields.integer('Upvote'), 'karma_downvote': fields.integer('Downvote'), 'karma_answer_accept_own': fields.integer('Accept an answer on its own questions'), 'karma_answer_accept_all': fields.integer('Accept an answer to all questions'), 'karma_editor_link_files': fields.integer('Linking files (Editor)'), 'karma_editor_clickable_link': fields.integer('Clickable links (Editor)'), 'karma_comment_own': fields.integer('Comment its own posts'), 'karma_comment_all': fields.integer('Comment all posts'), 'karma_comment_convert_own': fields.integer('Convert its own answers to comments and vice versa'), 'karma_comment_convert_all': fields.integer('Convert all answers to comments and vice versa'), 'karma_comment_unlink_own': fields.integer('Unlink its own comments'), 'karma_comment_unlink_all': fields.integer('Unlink all comments'), 'karma_retag': fields.integer('Change question tags'), 'karma_flag': fields.integer('Flag a post as offensive'), } def _get_default_faq(self, cr, uid, context=None): fname = openerp.modules.get_module_resource('website_forum', 'data', 'forum_default_faq.html') with open(fname, 'r') as f: return f.read() return False _defaults = { 'description': 'This community is for professionals and enthusiasts of our products and services.', 'faq': _get_default_faq, 'karma_gen_question_new': 0, # set to null for anti spam protection 'karma_gen_question_upvote': 5, 'karma_gen_question_downvote': -2, 'karma_gen_answer_upvote': 10, 'karma_gen_answer_downvote': -2, 'karma_gen_answer_accept': 2, 'karma_gen_answer_accepted': 15, 'karma_gen_answer_flagged': -100, 'karma_ask': 3, # set to not null for anti spam protection 'karma_answer': 3, # set to not null for anti spam protection 'karma_edit_own': 1, 'karma_edit_all': 300, 'karma_close_own': 100, 'karma_close_all': 500, 'karma_unlink_own': 500, 'karma_unlink_all': 1000, 'karma_upvote': 5, 'karma_downvote': 50, 'karma_answer_accept_own': 20, 'karma_answer_accept_all': 500, 'karma_editor_link_files': 20, 'karma_editor_clickable_link': 20, 'karma_comment_own': 3, 'karma_comment_all': 5, 'karma_comment_convert_own': 50, 'karma_comment_convert_all': 500, 'karma_comment_unlink_own': 50, 'karma_comment_unlink_all': 500, 'karma_retag': 75, 'karma_flag': 500, } def create(self, cr, uid, values, context=None): if context is None: context = {} create_context = dict(context, mail_create_nolog=True) return super(Forum, self).create(cr, uid, values, context=create_context) class Post(osv.Model): _name = 'forum.post' _description = 'Forum Post' _inherit = ['mail.thread', 'website.seo.metadata'] _order = "is_correct DESC, vote_count DESC, write_date DESC" def _get_user_vote(self, cr, uid, ids, field_name, arg, context): res = dict.fromkeys(ids, 0) vote_ids = self.pool['forum.post.vote'].search(cr, uid, [('post_id', 'in', ids), ('user_id', '=', uid)], context=context) for vote in self.pool['forum.post.vote'].browse(cr, uid, vote_ids, context=context): res[vote.post_id.id] = vote.vote return res def _get_vote_count(self, cr, uid, ids, field_name, arg, context): res = dict.fromkeys(ids, 0) for post in self.browse(cr, uid, ids, context=context): for vote in post.vote_ids: res[post.id] += int(vote.vote) return res def _get_post_from_vote(self, cr, uid, ids, context=None): result = {} for vote in self.pool['forum.post.vote'].browse(cr, uid, ids, context=context): result[vote.post_id.id] = True return result.keys() def _get_user_favourite(self, cr, uid, ids, field_name, arg, context): res = dict.fromkeys(ids, False) for post in self.browse(cr, uid, ids, context=context): if uid in [f.id for f in post.favourite_ids]: res[post.id] = True return res def _get_favorite_count(self, cr, uid, ids, field_name, arg, context): res = dict.fromkeys(ids, 0) for post in self.browse(cr, uid, ids, context=context): res[post.id] += len(post.favourite_ids) return res def _get_post_from_hierarchy(self, cr, uid, ids, context=None): post_ids = set(ids) for post in self.browse(cr, SUPERUSER_ID, ids, context=context): if post.parent_id: post_ids.add(post.parent_id.id) return list(post_ids) def _get_child_count(self, cr, uid, ids, field_name=False, arg={}, context=None): res = dict.fromkeys(ids, 0) for post in self.browse(cr, uid, ids, context=context): if post.parent_id: res[post.parent_id.id] = len(post.parent_id.child_ids) else: res[post.id] = len(post.child_ids) return res def _get_uid_answered(self, cr, uid, ids, field_name, arg, context=None): res = dict.fromkeys(ids, False) for post in self.browse(cr, uid, ids, context=context): res[post.id] = any(answer.create_uid.id == uid for answer in post.child_ids) return res def _get_has_validated_answer(self, cr, uid, ids, field_name, arg, context=None): res = dict.fromkeys(ids, False) ans_ids = self.search(cr, uid, [('parent_id', 'in', ids), ('is_correct', '=', True)], context=context) for answer in self.browse(cr, uid, ans_ids, context=context): res[answer.parent_id.id] = True return res def _is_self_reply(self, cr, uid, ids, field_name, arg, context=None): res = dict.fromkeys(ids, False) for post in self.browse(cr, uid, ids, context=context): res[post.id] = post.parent_id and post.parent_id.create_uid == post.create_uid or False return res def _get_post_karma_rights(self, cr, uid, ids, field_name, arg, context=None): user = self.pool['res.users'].browse(cr, uid, uid, context=context) res = dict.fromkeys(ids, False) for post in self.browse(cr, uid, ids, context=context): res[post.id] = { 'karma_ask': post.forum_id.karma_ask, 'karma_answer': post.forum_id.karma_answer, 'karma_accept': post.parent_id and post.parent_id.create_uid.id == uid and post.forum_id.karma_answer_accept_own or post.forum_id.karma_answer_accept_all, 'karma_edit': post.create_uid.id == uid and post.forum_id.karma_edit_own or post.forum_id.karma_edit_all, 'karma_close': post.create_uid.id == uid and post.forum_id.karma_close_own or post.forum_id.karma_close_all, 'karma_unlink': post.create_uid.id == uid and post.forum_id.karma_unlink_own or post.forum_id.karma_unlink_all, 'karma_upvote': post.forum_id.karma_upvote, 'karma_downvote': post.forum_id.karma_downvote, 'karma_comment': post.create_uid.id == uid and post.forum_id.karma_comment_own or post.forum_id.karma_comment_all, 'karma_comment_convert': post.create_uid.id == uid and post.forum_id.karma_comment_convert_own or post.forum_id.karma_comment_convert_all, } res[post.id].update({ 'can_ask': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_ask'], 'can_answer': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_answer'], 'can_accept': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_accept'], 'can_edit': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_edit'], 'can_close': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_close'], 'can_unlink': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_unlink'], 'can_upvote': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_upvote'], 'can_downvote': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_downvote'], 'can_comment': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_comment'], 'can_comment_convert': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_comment_convert'], }) return res _columns = { 'name': fields.char('Title'), 'forum_id': fields.many2one('forum.forum', 'Forum', required=True), 'content': fields.html('Content'), 'tag_ids': fields.many2many('forum.tag', 'forum_tag_rel', 'forum_id', 'forum_tag_id', 'Tags'), 'state': fields.selection([('active', 'Active'), ('close', 'Close'), ('offensive', 'Offensive')], 'Status'), 'views': fields.integer('Number of Views'), 'active': fields.boolean('Active'), 'is_correct': fields.boolean('Valid Answer', help='Correct Answer or Answer on this question accepted.'), 'website_message_ids': fields.one2many( 'mail.message', 'res_id', domain=lambda self: [ '&', ('model', '=', self._name), ('type', 'in', ['email', 'comment']) ], string='Post Messages', help="Comments on forum post", ), # history 'create_date': fields.datetime('Asked on', select=True, readonly=True), 'create_uid': fields.many2one('res.users', 'Created by', select=True, readonly=True), 'write_date': fields.datetime('Update on', select=True, readonly=True), 'write_uid': fields.many2one('res.users', 'Updated by', select=True, readonly=True), # vote fields 'vote_ids': fields.one2many('forum.post.vote', 'post_id', 'Votes'), 'user_vote': fields.function(_get_user_vote, string='My Vote', type='integer'), 'vote_count': fields.function( _get_vote_count, string="Votes", type='integer', store={ 'forum.post': (lambda self, cr, uid, ids, c={}: ids, ['vote_ids'], 10), 'forum.post.vote': (_get_post_from_vote, [], 10), }), # favorite fields 'favourite_ids': fields.many2many('res.users', string='Favourite'), 'user_favourite': fields.function(_get_user_favourite, string="My Favourite", type='boolean'), 'favourite_count': fields.function( _get_favorite_count, string='Favorite Count', type='integer', store={ 'forum.post': (lambda self, cr, uid, ids, c={}: ids, ['favourite_ids'], 10), }), # hierarchy 'parent_id': fields.many2one('forum.post', 'Question', ondelete='cascade'), 'self_reply': fields.function( _is_self_reply, 'Reply to own question', type='boolean', store={ 'forum.post': (lambda self, cr, uid, ids, c={}: ids, ['parent_id', 'create_uid'], 10), }), 'child_ids': fields.one2many('forum.post', 'parent_id', 'Answers'), 'child_count': fields.function( _get_child_count, string="Answers", type='integer', store={ 'forum.post': (_get_post_from_hierarchy, ['parent_id', 'child_ids'], 10), }), 'uid_has_answered': fields.function( _get_uid_answered, string='Has Answered', type='boolean', ), 'has_validated_answer': fields.function( _get_has_validated_answer, string='Has a Validated Answered', type='boolean', store={ 'forum.post': (_get_post_from_hierarchy, ['parent_id', 'child_ids', 'is_correct'], 10), } ), # closing 'closed_reason_id': fields.many2one('forum.post.reason', 'Reason'), 'closed_uid': fields.many2one('res.users', 'Closed by', select=1), 'closed_date': fields.datetime('Closed on', readonly=True), # karma 'karma_ask': fields.function(_get_post_karma_rights, string='Karma to ask', type='integer', multi='_get_post_karma_rights'), 'karma_answer': fields.function(_get_post_karma_rights, string='Karma to answer', type='integer', multi='_get_post_karma_rights'), 'karma_accept': fields.function(_get_post_karma_rights, string='Karma to accept this answer', type='integer', multi='_get_post_karma_rights'), 'karma_edit': fields.function(_get_post_karma_rights, string='Karma to edit', type='integer', multi='_get_post_karma_rights'), 'karma_close': fields.function(_get_post_karma_rights, string='Karma to close', type='integer', multi='_get_post_karma_rights'), 'karma_unlink': fields.function(_get_post_karma_rights, string='Karma to unlink', type='integer', multi='_get_post_karma_rights'), 'karma_upvote': fields.function(_get_post_karma_rights, string='Karma to upvote', type='integer', multi='_get_post_karma_rights'), 'karma_downvote': fields.function(_get_post_karma_rights, string='Karma to downvote', type='integer', multi='_get_post_karma_rights'), 'karma_comment': fields.function(_get_post_karma_rights, string='Karma to comment', type='integer', multi='_get_post_karma_rights'), 'karma_comment_convert': fields.function(_get_post_karma_rights, string='karma to convert as a comment', type='integer', multi='_get_post_karma_rights'), # access rights 'can_ask': fields.function(_get_post_karma_rights, string='Can Ask', type='boolean', multi='_get_post_karma_rights'), 'can_answer': fields.function(_get_post_karma_rights, string='Can Answer', type='boolean', multi='_get_post_karma_rights'), 'can_accept': fields.function(_get_post_karma_rights, string='Can Accept', type='boolean', multi='_get_post_karma_rights'), 'can_edit': fields.function(_get_post_karma_rights, string='Can Edit', type='boolean', multi='_get_post_karma_rights'), 'can_close': fields.function(_get_post_karma_rights, string='Can Close', type='boolean', multi='_get_post_karma_rights'), 'can_unlink': fields.function(_get_post_karma_rights, string='Can Unlink', type='boolean', multi='_get_post_karma_rights'), 'can_upvote': fields.function(_get_post_karma_rights, string='Can Upvote', type='boolean', multi='_get_post_karma_rights'), 'can_downvote': fields.function(_get_post_karma_rights, string='Can Downvote', type='boolean', multi='_get_post_karma_rights'), 'can_comment': fields.function(_get_post_karma_rights, string='Can Comment', type='boolean', multi='_get_post_karma_rights'), 'can_comment_convert': fields.function(_get_post_karma_rights, string='Can Convert to Comment', type='boolean', multi='_get_post_karma_rights'), } _defaults = { 'state': 'active', 'views': 0, 'active': True, 'vote_ids': list(), 'favourite_ids': list(), 'child_ids': list(), } def create(self, cr, uid, vals, context=None): if context is None: context = {} create_context = dict(context, mail_create_nolog=True) post_id = super(Post, self).create(cr, uid, vals, context=create_context) post = self.browse(cr, uid, post_id, context=context) # karma-based access if not post.parent_id and not post.can_ask: raise KarmaError('Not enough karma to create a new question') elif post.parent_id and not post.can_answer: raise KarmaError('Not enough karma to answer to a question') # messaging and chatter base_url = self.pool['ir.config_parameter'].get_param(cr, uid, 'web.base.url') if post.parent_id: body = _( '<p>A new answer for <i>%s</i> has been posted. <a href="%s/forum/%s/question/%s">Click here to access the post.</a></p>' % (post.parent_id.name, base_url, slug(post.parent_id.forum_id), slug(post.parent_id)) ) self.message_post(cr, uid, post.parent_id.id, subject=_('Re: %s') % post.parent_id.name, body=body, subtype='website_forum.mt_answer_new', context=context) else: body = _( '<p>A new question <i>%s</i> has been asked on %s. <a href="%s/forum/%s/question/%s">Click here to access the question.</a></p>' % (post.name, post.forum_id.name, base_url, slug(post.forum_id), slug(post)) ) self.message_post(cr, uid, post_id, subject=post.name, body=body, subtype='website_forum.mt_question_new', context=context) self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [uid], post.forum_id.karma_gen_question_new, context=context) return post_id def write(self, cr, uid, ids, vals, context=None): posts = self.browse(cr, uid, ids, context=context) if 'state' in vals: if vals['state'] in ['active', 'close'] and any(not post.can_close for post in posts): raise KarmaError('Not enough karma to close or reopen a post.') if 'active' in vals: if any(not post.can_unlink for post in posts): raise KarmaError('Not enough karma to delete or reactivate a post') if 'is_correct' in vals: if any(not post.can_accept for post in posts): raise KarmaError('Not enough karma to accept or refuse an answer') # update karma except for self-acceptance mult = 1 if vals['is_correct'] else -1 for post in self.browse(cr, uid, ids, context=context): if vals['is_correct'] != post.is_correct and post.create_uid.id != uid: self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [post.create_uid.id], post.forum_id.karma_gen_answer_accepted * mult, context=context) self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [uid], post.forum_id.karma_gen_answer_accept * mult, context=context) if any(key not in ['state', 'active', 'is_correct', 'closed_uid', 'closed_date', 'closed_reason_id'] for key in vals.keys()) and any(not post.can_edit for post in posts): raise KarmaError('Not enough karma to edit a post.') res = super(Post, self).write(cr, uid, ids, vals, context=context) # if post content modify, notify followers if 'content' in vals or 'name' in vals: for post in posts: if post.parent_id: body, subtype = _('Answer Edited'), 'website_forum.mt_answer_edit' obj_id = post.parent_id.id else: body, subtype = _('Question Edited'), 'website_forum.mt_question_edit' obj_id = post.id self.message_post(cr, uid, obj_id, body=body, subtype=subtype, context=context) return res def reopen(self, cr, uid, ids, context=None): if any(post.parent_id or post.state != 'close' for post in self.browse(cr, uid, ids, context=context)): return False reason_offensive = self.pool['ir.model.data'].xmlid_to_res_id(cr, uid, 'website_forum.reason_7') reason_spam = self.pool['ir.model.data'].xmlid_to_res_id(cr, uid, 'website_forum.reason_8') for post in self.browse(cr, uid, ids, context=context): if post.closed_reason_id.id in (reason_offensive, reason_spam): _logger.info('Upvoting user <%s>, reopening spam/offensive question', post.create_uid) # TODO: in master, consider making this a tunable karma parameter self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [post.create_uid.id], post.forum_id.karma_gen_question_downvote * -5, context=context) self.pool['forum.post'].write(cr, SUPERUSER_ID, ids, {'state': 'active'}, context=context) def close(self, cr, uid, ids, reason_id, context=None): if any(post.parent_id for post in self.browse(cr, uid, ids, context=context)): return False reason_offensive = self.pool['ir.model.data'].xmlid_to_res_id(cr, uid, 'website_forum.reason_7') reason_spam = self.pool['ir.model.data'].xmlid_to_res_id(cr, uid, 'website_forum.reason_8') if reason_id in (reason_offensive, reason_spam): for post in self.browse(cr, uid, ids, context=context): _logger.info('Downvoting user <%s> for posting spam/offensive contents', post.create_uid) # TODO: in master, consider making this a tunable karma parameter self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [post.create_uid.id], post.forum_id.karma_gen_question_downvote * 5, context=context) self.pool['forum.post'].write(cr, uid, ids, { 'state': 'close', 'closed_uid': uid, 'closed_date': datetime.today().strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT), 'closed_reason_id': reason_id, }, context=context) def unlink(self, cr, uid, ids, context=None): posts = self.browse(cr, uid, ids, context=context) if any(not post.can_unlink for post in posts): raise KarmaError('Not enough karma to unlink a post') # if unlinking an answer with accepted answer: remove provided karma for post in posts: if post.is_correct: self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [post.create_uid.id], post.forum_id.karma_gen_answer_accepted * -1, context=context) self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [uid], post.forum_id.karma_gen_answer_accept * -1, context=context) return super(Post, self).unlink(cr, uid, ids, context=context) def vote(self, cr, uid, ids, upvote=True, context=None): Vote = self.pool['forum.post.vote'] vote_ids = Vote.search(cr, uid, [('post_id', 'in', ids), ('user_id', '=', uid)], context=context) new_vote = '1' if upvote else '-1' voted_forum_ids = set() if vote_ids: for vote in Vote.browse(cr, uid, vote_ids, context=context): if upvote: new_vote = '0' if vote.vote == '-1' else '1' else: new_vote = '0' if vote.vote == '1' else '-1' Vote.write(cr, uid, vote_ids, {'vote': new_vote}, context=context) voted_forum_ids.add(vote.post_id.id) for post_id in set(ids) - voted_forum_ids: for post_id in ids: Vote.create(cr, uid, {'post_id': post_id, 'vote': new_vote}, context=context) return {'vote_count': self._get_vote_count(cr, uid, ids, None, None, context=context)[ids[0]], 'user_vote': new_vote} def convert_answer_to_comment(self, cr, uid, id, context=None): """ Tools to convert an answer (forum.post) to a comment (mail.message). The original post is unlinked and a new comment is posted on the question using the post create_uid as the comment's author. """ post = self.browse(cr, SUPERUSER_ID, id, context=context) if not post.parent_id: return False # karma-based action check: use the post field that computed own/all value if not post.can_comment_convert: raise KarmaError('Not enough karma to convert an answer to a comment') # post the message question = post.parent_id values = { 'author_id': post.create_uid.partner_id.id, 'body': html2plaintext(post.content), 'type': 'comment', 'subtype': 'mail.mt_comment', 'date': post.create_date, } message_id = self.pool['forum.post'].message_post( cr, uid, question.id, context=dict(context, mail_create_nosubcribe=True), **values) # unlink the original answer, using SUPERUSER_ID to avoid karma issues self.pool['forum.post'].unlink(cr, SUPERUSER_ID, [post.id], context=context) return message_id def convert_comment_to_answer(self, cr, uid, message_id, default=None, context=None): """ Tool to convert a comment (mail.message) into an answer (forum.post). The original comment is unlinked and a new answer from the comment's author is created. Nothing is done if the comment's author already answered the question. """ comment = self.pool['mail.message'].browse(cr, SUPERUSER_ID, message_id, context=context) post = self.pool['forum.post'].browse(cr, uid, comment.res_id, context=context) user = self.pool['res.users'].browse(cr, uid, uid, context=context) if not comment.author_id or not comment.author_id.user_ids: # only comment posted by users can be converted return False # karma-based action check: must check the message's author to know if own / all karma_convert = comment.author_id.id == user.partner_id.id and post.forum_id.karma_comment_convert_own or post.forum_id.karma_comment_convert_all can_convert = uid == SUPERUSER_ID or user.karma >= karma_convert if not can_convert: raise KarmaError('Not enough karma to convert a comment to an answer') # check the message's author has not already an answer question = post.parent_id if post.parent_id else post post_create_uid = comment.author_id.user_ids[0] if any(answer.create_uid.id == post_create_uid.id for answer in question.child_ids): return False # create the new post post_values = { 'forum_id': question.forum_id.id, 'content': comment.body, 'parent_id': question.id, } # done with the author user to have create_uid correctly set new_post_id = self.pool['forum.post'].create(cr, post_create_uid.id, post_values, context=context) # delete comment self.pool['mail.message'].unlink(cr, SUPERUSER_ID, [comment.id], context=context) return new_post_id def unlink_comment(self, cr, uid, id, message_id, context=None): comment = self.pool['mail.message'].browse(cr, SUPERUSER_ID, message_id, context=context) post = self.pool['forum.post'].browse(cr, uid, id, context=context) user = self.pool['res.users'].browse(cr, SUPERUSER_ID, uid, context=context) if not comment.model == 'forum.post' or not comment.res_id == id: return False # karma-based action check: must check the message's author to know if own or all karma_unlink = comment.author_id.id == user.partner_id.id and post.forum_id.karma_comment_unlink_own or post.forum_id.karma_comment_unlink_all can_unlink = uid == SUPERUSER_ID or user.karma >= karma_unlink if not can_unlink: raise KarmaError('Not enough karma to unlink a comment') return self.pool['mail.message'].unlink(cr, SUPERUSER_ID, [message_id], context=context) def set_viewed(self, cr, uid, ids, context=None): cr.execute("""UPDATE forum_post SET views = views+1 WHERE id IN %s""", (tuple(ids),)) return True def _get_access_link(self, cr, uid, mail, partner, context=None): post = self.pool['forum.post'].browse(cr, uid, mail.res_id, context=context) res_id = post.parent_id and "%s#answer-%s" % (post.parent_id.id, post.id) or post.id return "/forum/%s/question/%s" % (post.forum_id.id, res_id) @api.cr_uid_ids_context def message_post(self, cr, uid, thread_id, type='notification', subtype=None, context=None, **kwargs): if thread_id and type == 'comment': # user comments have a restriction on karma if isinstance(thread_id, (list, tuple)): post_id = thread_id[0] else: post_id = thread_id post = self.browse(cr, uid, post_id, context=context) if not post.can_comment: raise KarmaError('Not enough karma to comment') return super(Post, self).message_post(cr, uid, thread_id, type=type, subtype=subtype, context=context, **kwargs) class PostReason(osv.Model): _name = "forum.post.reason" _description = "Post Closing Reason" _order = 'name' _columns = { 'name': fields.char('Post Reason', required=True, translate=True), } class Vote(osv.Model): _name = 'forum.post.vote' _description = 'Vote' _columns = { 'post_id': fields.many2one('forum.post', 'Post', ondelete='cascade', required=True), 'user_id': fields.many2one('res.users', 'User', required=True), 'vote': fields.selection([('1', '1'), ('-1', '-1'), ('0', '0')], 'Vote', required=True), 'create_date': fields.datetime('Create Date', select=True, readonly=True), # TODO master: store these two 'forum_id': fields.related('post_id', 'forum_id', type='many2one', relation='forum.forum', string='Forum'), 'recipient_id': fields.related('post_id', 'create_uid', type='many2one', relation='res.users', string='To', help="The user receiving the vote"), } _defaults = { 'user_id': lambda self, cr, uid, ctx: uid, 'vote': lambda *args: '1', } def _get_karma_value(self, old_vote, new_vote, up_karma, down_karma): _karma_upd = { '-1': {'-1': 0, '0': -1 * down_karma, '1': -1 * down_karma + up_karma}, '0': {'-1': 1 * down_karma, '0': 0, '1': up_karma}, '1': {'-1': -1 * up_karma + down_karma, '0': -1 * up_karma, '1': 0} } return _karma_upd[old_vote][new_vote] def create(self, cr, uid, vals, context=None): vote_id = super(Vote, self).create(cr, uid, vals, context=context) vote = self.browse(cr, uid, vote_id, context=context) # own post check if vote.user_id.id == vote.post_id.create_uid.id: raise Warning('Not allowed to vote for its own post') # karma check if vote.vote == '1' and not vote.post_id.can_upvote: raise KarmaError('Not enough karma to upvote.') elif vote.vote == '-1' and not vote.post_id.can_downvote: raise KarmaError('Not enough karma to downvote.') # karma update if vote.post_id.parent_id: karma_value = self._get_karma_value('0', vote.vote, vote.forum_id.karma_gen_answer_upvote, vote.forum_id.karma_gen_answer_downvote) else: karma_value = self._get_karma_value('0', vote.vote, vote.forum_id.karma_gen_question_upvote, vote.forum_id.karma_gen_question_downvote) self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [vote.recipient_id.id], karma_value, context=context) return vote_id def write(self, cr, uid, ids, values, context=None): if 'vote' in values: for vote in self.browse(cr, uid, ids, context=context): # own post check if vote.user_id.id == vote.post_id.create_uid.id: raise Warning('Not allowed to vote for its own post') # karma check if (values['vote'] == '1' or vote.vote == '-1' and values['vote'] == '0') and not vote.post_id.can_upvote: raise KarmaError('Not enough karma to upvote.') elif (values['vote'] == '-1' or vote.vote == '1' and values['vote'] == '0') and not vote.post_id.can_downvote: raise KarmaError('Not enough karma to downvote.') # karma update if vote.post_id.parent_id: karma_value = self._get_karma_value(vote.vote, values['vote'], vote.forum_id.karma_gen_answer_upvote, vote.forum_id.karma_gen_answer_downvote) else: karma_value = self._get_karma_value(vote.vote, values['vote'], vote.forum_id.karma_gen_question_upvote, vote.forum_id.karma_gen_question_downvote) self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [vote.recipient_id.id], karma_value, context=context) res = super(Vote, self).write(cr, uid, ids, values, context=context) return res class Tags(osv.Model): _name = "forum.tag" _description = "Tag" _inherit = ['website.seo.metadata'] def _get_posts_count(self, cr, uid, ids, field_name, arg, context=None): return dict((tag_id, self.pool['forum.post'].search_count(cr, uid, [('tag_ids', 'in', tag_id)], context=context)) for tag_id in ids) def _get_tag_from_post(self, cr, uid, ids, context=None): return list(set( [tag.id for post in self.pool['forum.post'].browse(cr, SUPERUSER_ID, ids, context=context) for tag in post.tag_ids] )) _columns = { 'name': fields.char('Name', required=True), 'forum_id': fields.many2one('forum.forum', 'Forum', required=True), 'post_ids': fields.many2many('forum.post', 'forum_tag_rel', 'tag_id', 'post_id', 'Posts'), 'posts_count': fields.function( _get_posts_count, type='integer', string="Number of Posts", store={ 'forum.post': (_get_tag_from_post, ['tag_ids'], 10), } ), 'create_uid': fields.many2one('res.users', 'Created by', readonly=True), }
Jgarcia-IAS/SITE
addons/website_forum/models/forum.py
Python
agpl-3.0
36,003