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
class ApplicationJob < ActiveJob::Base include Job::SS::Core end
hotmix/shirasagi
app/jobs/application_job.rb
Ruby
mit
67
define('lodash/lang/isEqual', ['exports', 'lodash/internal/baseIsEqual', 'lodash/internal/bindCallback'], function (exports, _lodashInternalBaseIsEqual, _lodashInternalBindCallback) { 'use strict'; /** * Performs a deep comparison between two values to determine if they are * equivalent. If `customizer` is provided it's invoked to compare values. * If `customizer` returns `undefined` comparisons are handled by the method * instead. The `customizer` is bound to `thisArg` and invoked with up to * three arguments: (value, other [, index|key]). * * **Note:** This method supports comparing arrays, booleans, `Date` objects, * numbers, `Object` objects, regexes, and strings. Objects are compared by * their own, not inherited, enumerable properties. Functions and DOM nodes * are **not** supported. Provide a customizer function to extend support * for comparing other values. * * @static * @memberOf _ * @alias eq * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize value comparisons. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'user': 'fred' }; * var other = { 'user': 'fred' }; * * object == other; * // => false * * _.isEqual(object, other); * // => true * * // using a customizer callback * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * _.isEqual(array, other, function(value, other) { * if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) { * return true; * } * }); * // => true */ function isEqual(value, other, customizer, thisArg) { customizer = typeof customizer == 'function' ? (0, _lodashInternalBindCallback['default'])(customizer, thisArg, 3) : undefined; var result = customizer ? customizer(value, other) : undefined; return result === undefined ? (0, _lodashInternalBaseIsEqual['default'])(value, other, customizer) : !!result; } exports['default'] = isEqual; });
hoka-plus/p-01-web
tmp/babel-output_path-hOv4KMmE.tmp/lodash/lang/isEqual.js
JavaScript
mit
2,223
<?php $form = Loader::helper('form'); $ih = Loader::helper("concrete/interface"); $valt = Loader::helper('validation/token'); $akName = ''; $akIsSearchable = 1; $asID = 0; if (is_object($key)) { if (!isset($akHandle)) { $akHandle = $key->getAttributeKeyHandle(); } $akName = $key->getAttributeKeyName(); $akIsSearchable = $key->isAttributeKeySearchable(); $akIsSearchableIndexed = $key->isAttributeKeyContentIndexed(); $sets = $key->getAttributeSets(); if (count($sets) == 1) { $asID = $sets[0]->getAttributeSetID(); } print $form->hidden('akID', $key->getAttributeKeyID()); } ?> <div class="ccm-pane-body"> <?php if (is_object($key)) { ?> <?php $valt = Loader::helper('validation/token'); $ih = Loader::helper('concrete/interface'); $delConfirmJS = t('Are you sure you want to remove this attribute?'); ?> <script type="text/javascript"> deleteAttribute = function() { if (confirm('<?php echo $delConfirmJS?>')) { location.href = "<?php echo $this->action('delete', $key->getAttributeKeyID(), $valt->generate('delete_attribute'))?>"; } } </script> <?php print $ih->button_js(t('Delete Attribute'), "deleteAttribute()", 'right', 'error');?> <?php } ?> <fieldset> <legend><?php echo t('%s: Basic Details', $type->getAttributeTypeName())?></legend> <div class="clearfix"> <?php echo $form->label('akHandle', t('Handle'))?> <div class="input"> <?php echo $form->text('akHandle', $akHandle)?> <span class="help-inline"><?php echo t('Required')?></span> </div> </div> <div class="clearfix"> <?php echo $form->label('akName', t('Name'))?> <div class="input"> <?php echo $form->text('akName', $akName)?> <span class="help-inline"><?php echo t('Required')?></span> </div> </div> <?php if ($category->allowAttributeSets() == AttributeKeyCategory::ASET_ALLOW_SINGLE) { ?> <div class="clearfix"> <?php echo $form->label('asID', t('Set'))?> <div class="input"> <?php $sel = array('0' => t('** None')); $sets = $category->getAttributeSets(); foreach($sets as $as) { $sel[$as->getAttributeSetID()] = $as->getAttributeSetName(); } print $form->select('asID', $sel, $asID); ?> </div> </div> <?php } ?> <div class="clearfix"> <label><?php echo t('Searchable')?></label> <div class="input"> <ul class="inputs-list"> <?php $category_handle = $category->getAttributeKeyCategoryHandle(); $keyword_label = t('Content included in "Keyword Search".'); $advanced_label = t('Field available in "Advanced Search".'); switch ($category_handle) { case 'collection': $keyword_label = t('Content included in sitewide page search index.'); $advanced_label = t('Field available in Dashboard Page Search.'); break; case 'file': $keyword_label = t('Content included in file search index.'); $advanced_label = t('Field available in File Manager Search.'); break; case 'user': $keyword_label = t('Content included in user keyword search.'); $advanced_label = t('Field available in Dashboard User Search.'); break; } ?> <li><label><?php echo $form->checkbox('akIsSearchableIndexed', 1, $akIsSearchableIndexed)?> <span><?php echo $keyword_label?></span></label></li> <li><label><?php echo $form->checkbox('akIsSearchable', 1, $akIsSearchable)?> <span><?php echo $advanced_label?></span></label></li> </ul> </div> </div> </fieldset> <?php echo $form->hidden('atID', $type->getAttributeTypeID())?> <?php echo $form->hidden('akCategoryID', $category->getAttributeKeyCategoryID()); ?> <?php echo $valt->output('add_or_update_attribute')?> <?php if ($category->getPackageID() > 0) { Loader::packageElement('attribute/categories/' . $category->getAttributeKeyCategoryHandle(), $category->getPackageHandle(), array('key' => $key)); } else { Loader::element('attribute/categories/' . $category->getAttributeKeyCategoryHandle(), array('key' => $key)); } ?> <?php $type->render('type_form', $key); ?> </div> <div class="ccm-pane-footer"> <?php if (is_object($key)) { ?> <?php echo $ih->submit(t('Save'), 'ccm-attribute-key-form', 'right', 'primary')?> <?php } else { ?> <?php echo $ih->submit(t('Add'), 'ccm-attribute-key-form', 'right', 'primary')?> <?php } ?> </div>
clejer/concrete_
concrete/elements/attribute/type_form_required.php
PHP
mit
4,156
require 'spec_helper' describe "sitemap_pages" do subject(:site) { cms_site } subject(:node) { create_once :sitemap_node_page, filename: "docs", name: "sitemap" } subject(:item) { Sitemap::Page.last } subject(:index_path) { sitemap_pages_path site.id, node } subject(:new_path) { new_sitemap_page_path site.id, node } subject(:show_path) { sitemap_page_path site.id, node, item } subject(:edit_path) { edit_sitemap_page_path site.id, node, item } subject(:delete_path) { delete_sitemap_page_path site.id, node, item } subject(:move_path) { move_sitemap_page_path site.id, node, item } subject(:copy_path) { copy_sitemap_page_path site.id, node, item } context "with auth" do before { login_cms_user } it "#index" do visit index_path expect(current_path).not_to eq sns_login_path end it "#new" do visit new_path within "form#item-form" do fill_in "item[name]", with: "sample" fill_in "item[basename]", with: "sample" click_button "保存" end expect(status_code).to eq 200 expect(current_path).not_to eq new_path expect(page).to have_no_css("form#item-form") end it "#show" do visit show_path expect(status_code).to eq 200 expect(current_path).not_to eq sns_login_path end it "#edit" do visit edit_path within "form#item-form" do fill_in "item[name]", with: "modify" click_button "保存" end expect(current_path).not_to eq sns_login_path expect(page).to have_no_css("form#item-form") end it "#move" do visit move_path within "form" do fill_in "destination", with: "docs/destination" click_button "保存" end expect(status_code).to eq 200 expect(current_path).to eq move_path expect(page).to have_css("form#item-form h2", text: "docs/destination.html") within "form" do fill_in "destination", with: "docs/sample" click_button "保存" end expect(status_code).to eq 200 expect(current_path).to eq move_path expect(page).to have_css("form#item-form h2", text: "docs/sample.html") end it "#copy" do visit copy_path within "form" do click_button "保存" end expect(status_code).to eq 200 expect(current_path).to eq index_path expect(page).to have_css("a", text: "[複製] modify") expect(page).to have_css(".state", text: "非公開") end it "#delete" do visit delete_path within "form" do click_button "削除" end expect(current_path).to eq index_path end end end
mizoki/shirasagi
spec/features/sitemap/pages_spec.rb
Ruby
mit
2,673
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, unicode_literals, print_function import logging from collections import OrderedDict import numpy as np from monty.json import jsanitize from pymatgen.phonon.bandstructure import PhononBandStructureSymmLine from pymatgen.util.plotting import pretty_plot from pymatgen.electronic_structure.plotter import plot_brillouin_zone """ This module implements plotter for DOS and band structure. """ logger = logging.getLogger(__name__) class PhononDosPlotter(object): """ Class for plotting phonon DOSs. Note that the interface is extremely flexible given that there are many different ways in which people want to view DOS. The typical usage is:: # Initializes plotter with some optional args. Defaults are usually # fine, plotter = PhononDosPlotter() # Adds a DOS with a label. plotter.add_dos("Total DOS", dos) # Alternatively, you can add a dict of DOSs. This is the typical # form returned by CompletePhononDos.get_element_dos(). Args: stack: Whether to plot the DOS as a stacked area graph key_sort_func: function used to sort the dos_dict keys. sigma: A float specifying a standard deviation for Gaussian smearing the DOS for nicer looking plots. Defaults to None for no smearing. """ def __init__(self, stack=False, sigma=None): self.stack = stack self.sigma = sigma self._doses = OrderedDict() def add_dos(self, label, dos): """ Adds a dos for plotting. Args: label: label for the DOS. Must be unique. dos: PhononDos object """ densities = dos.get_smeared_densities(self.sigma) if self.sigma \ else dos.densities self._doses[label] = {'frequencies': dos.frequencies, 'densities': densities} def add_dos_dict(self, dos_dict, key_sort_func=None): """ Add a dictionary of doses, with an optional sorting function for the keys. Args: dos_dict: dict of {label: Dos} key_sort_func: function used to sort the dos_dict keys. """ if key_sort_func: keys = sorted(dos_dict.keys(), key=key_sort_func) else: keys = dos_dict.keys() for label in keys: self.add_dos(label, dos_dict[label]) def get_dos_dict(self): """ Returns the added doses as a json-serializable dict. Note that if you have specified smearing for the DOS plot, the densities returned will be the smeared densities, not the original densities. Returns: Dict of dos data. Generally of the form, {label: {'frequencies':.., 'densities': ...}} """ return jsanitize(self._doses) def get_plot(self, xlim=None, ylim=None): """ Get a matplotlib plot showing the DOS. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. """ import prettyplotlib as ppl from prettyplotlib import brewer2mpl ncolors = max(3, len(self._doses)) ncolors = min(9, ncolors) colors = brewer2mpl.get_map('Set1', 'qualitative', ncolors).mpl_colors y = None alldensities = [] allfrequencies = [] plt = pretty_plot(12, 8) # Note that this complicated processing of frequencies is to allow for # stacked plots in matplotlib. for key, dos in self._doses.items(): frequencies = dos['frequencies'] densities = dos['densities'] if y is None: y = np.zeros(frequencies.shape) if self.stack: y += densities newdens = y.copy() else: newdens = densities allfrequencies.append(frequencies) alldensities.append(newdens) keys = list(self._doses.keys()) keys.reverse() alldensities.reverse() allfrequencies.reverse() allpts = [] for i, (key, frequencies, densities) in enumerate(zip(keys, allfrequencies, alldensities)): allpts.extend(list(zip(frequencies, densities))) if self.stack: plt.fill(frequencies, densities, color=colors[i % ncolors], label=str(key)) else: ppl.plot(frequencies, densities, color=colors[i % ncolors], label=str(key), linewidth=3) if xlim: plt.xlim(xlim) if ylim: plt.ylim(ylim) else: xlim = plt.xlim() relevanty = [p[1] for p in allpts if xlim[0] < p[0] < xlim[1]] plt.ylim((min(relevanty), max(relevanty))) ylim = plt.ylim() plt.plot([0, 0], ylim, 'k--', linewidth=2) plt.xlabel('Frequencies (THz)') plt.ylabel('Density of states') plt.legend() leg = plt.gca().get_legend() ltext = leg.get_texts() # all the text.Text instance in the legend plt.setp(ltext, fontsize=30) plt.tight_layout() return plt def save_plot(self, filename, img_format="eps", xlim=None, ylim=None): """ Save matplotlib plot to a file. Args: filename: Filename to write to. img_format: Image format to use. Defaults to EPS. xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. """ plt = self.get_plot(xlim, ylim) plt.savefig(filename, format=img_format) def show(self, xlim=None, ylim=None): """ Show the plot using matplotlib. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. """ plt = self.get_plot(xlim, ylim) plt.show() class PhononBSPlotter(object): """ Class to plot or get data to facilitate the plot of band structure objects. Args: bs: A BandStructureSymmLine object. """ def __init__(self, bs): if not isinstance(bs, PhononBandStructureSymmLine): raise ValueError( "PhononBSPlotter only works with PhononBandStructureSymmLine objects. " "A PhononBandStructure object (on a uniform grid for instance and " "not along symmetry lines won't work)") self._bs = bs self._nb_bands = self._bs.nb_bands def _maketicks(self, plt): """ utility private method to add ticks to a band structure """ ticks = self.get_ticks() # Sanitize only plot the uniq values uniq_d = [] uniq_l = [] temp_ticks = list(zip(ticks['distance'], ticks['label'])) for i in range(len(temp_ticks)): if i == 0: uniq_d.append(temp_ticks[i][0]) uniq_l.append(temp_ticks[i][1]) logger.debug("Adding label {l} at {d}".format( l=temp_ticks[i][0], d=temp_ticks[i][1])) else: if temp_ticks[i][1] == temp_ticks[i - 1][1]: logger.debug("Skipping label {i}".format( i=temp_ticks[i][1])) else: logger.debug("Adding label {l} at {d}".format( l=temp_ticks[i][0], d=temp_ticks[i][1])) uniq_d.append(temp_ticks[i][0]) uniq_l.append(temp_ticks[i][1]) logger.debug("Unique labels are %s" % list(zip(uniq_d, uniq_l))) plt.gca().set_xticks(uniq_d) plt.gca().set_xticklabels(uniq_l) for i in range(len(ticks['label'])): if ticks['label'][i] is not None: # don't print the same label twice if i != 0: if ticks['label'][i] == ticks['label'][i - 1]: logger.debug("already print label... " "skipping label {i}".format( i=ticks['label'][i])) else: logger.debug("Adding a line at {d}" " for label {l}".format( d=ticks['distance'][i], l=ticks['label'][i])) plt.axvline(ticks['distance'][i], color='k') else: logger.debug("Adding a line at {d} for label {l}".format( d=ticks['distance'][i], l=ticks['label'][i])) plt.axvline(ticks['distance'][i], color='k') return plt def bs_plot_data(self): """ Get the data nicely formatted for a plot Returns: A dict of the following format: ticks: A dict with the 'distances' at which there is a qpoint (the x axis) and the labels (None if no label) frequencies: A list (one element for each branch) of frequencies for each qpoint: [branch][qpoint][mode]. The data is stored by branch to facilitate the plotting lattice: The reciprocal lattice. """ distance = [] frequency = [] ticks = self.get_ticks() for b in self._bs.branches: frequency.append([]) distance.append([self._bs.distance[j] for j in range(b['start_index'], b['end_index'] + 1)]) for i in range(self._nb_bands): frequency[-1].append( [self._bs.bands[i][j] for j in range(b['start_index'], b['end_index'] + 1)]) return {'ticks': ticks, 'distances': distance, 'frequency': frequency, 'lattice': self._bs.lattice_rec.as_dict()} def get_plot(self, ylim=None): """ Get a matplotlib object for the bandstructure plot. Args: ylim: Specify the y-axis (frequency) limits; by default None let the code choose. """ plt = pretty_plot(12, 8) from matplotlib import rc import scipy.interpolate as scint try: rc('text', usetex=True) except: # Fall back on non Tex if errored. rc('text', usetex=False) band_linewidth = 1 data = self.bs_plot_data() for d in range(len(data['distances'])): for i in range(self._nb_bands): plt.plot(data['distances'][d], [data['frequency'][d][i][j] for j in range(len(data['distances'][d]))], 'b-', linewidth=band_linewidth) self._maketicks(plt) # plot y=0 line plt.axhline(0, linewidth=1, color='k') # Main X and Y Labels plt.xlabel(r'$\mathrm{Wave\ Vector}$', fontsize=30) ylabel = r'$\mathrm{Frequency\ (THz)}$' plt.ylabel(ylabel, fontsize=30) # X range (K) # last distance point x_max = data['distances'][-1][-1] plt.xlim(0, x_max) if ylim is not None: plt.ylim(ylim) plt.tight_layout() return plt def show(self, ylim=None): """ Show the plot using matplotlib. Args: ylim: Specify the y-axis (frequency) limits; by default None let the code choose. """ plt = self.get_plot(ylim) plt.show() def save_plot(self, filename, img_format="eps", ylim=None): """ Save matplotlib plot to a file. Args: filename: Filename to write to. img_format: Image format to use. Defaults to EPS. ylim: Specifies the y-axis limits. """ plt = self.get_plot(ylim=ylim) plt.savefig(filename, format=img_format) plt.close() def get_ticks(self): """ Get all ticks and labels for a band structure plot. Returns: A dict with 'distance': a list of distance at which ticks should be set and 'label': a list of label for each of those ticks. """ tick_distance = [] tick_labels = [] previous_label = self._bs.qpoints[0].label previous_branch = self._bs.branches[0]['name'] for i, c in enumerate(self._bs.qpoints): if c.label is not None: tick_distance.append(self._bs.distance[i]) this_branch = None for b in self._bs.branches: if b['start_index'] <= i <= b['end_index']: this_branch = b['name'] break if c.label != previous_label \ and previous_branch != this_branch: label1 = c.label if label1.startswith("\\") or label1.find("_") != -1: label1 = "$" + label1 + "$" label0 = previous_label if label0.startswith("\\") or label0.find("_") != -1: label0 = "$" + label0 + "$" tick_labels.pop() tick_distance.pop() tick_labels.append(label0 + "$\\mid$" + label1) else: if c.label.startswith("\\") or c.label.find("_") != -1: tick_labels.append("$" + c.label + "$") else: tick_labels.append(c.label) previous_label = c.label previous_branch = this_branch return {'distance': tick_distance, 'label': tick_labels} def plot_compare(self, other_plotter): """ plot two band structure for comparison. One is in red the other in blue. The two band structures need to be defined on the same symmetry lines! and the distance between symmetry lines is the one of the band structure used to build the PhononBSPlotter Args: another PhononBSPlotter object defined along the same symmetry lines Returns: a matplotlib object with both band structures """ data_orig = self.bs_plot_data() data = other_plotter.bs_plot_data() if len(data_orig['distances']) != len(data['distances']): raise ValueError('The two objects are not compatible.') plt = self.get_plot() band_linewidth = 1 for i in range(other_plotter._nb_bands): for d in range(len(data_orig['distances'])): plt.plot(data_orig['distances'][d], [e[i] for e in data['frequency']][d], 'r-', linewidth=band_linewidth) return plt def plot_brillouin(self): """ plot the Brillouin zone """ # get labels and lines labels = {} for q in self._bs.qpoints: if q.label: labels[q.label] = q.frac_coords lines = [] for b in self._bs.branches: lines.append([self._bs.qpoints[b['start_index']].frac_coords, self._bs.qpoints[b['end_index']].frac_coords]) plot_brillouin_zone(self._bs.lattice_rec, lines=lines, labels=labels)
matk86/pymatgen
pymatgen/phonon/plotter.py
Python
mit
15,693
# Change the following to True to get a much more comprehensive set of tests # to run, albeit, which take considerably longer. full_tests = False def test(fmt, *args): print('{:8s}'.format(fmt) + '>' + fmt.format(*args) + '<') test("}}{{") test("{}-{}", 1, [4, 5]) test("{0}-{1}", 1, [4, 5]) test("{1}-{0}", 1, [4, 5]) test("{:x}", 1) test("{!r}", 2) test("{:x}", 0x10) test("{!r}", "foo") test("{!s}", "foo") test("{0!r:>10s} {0!s:>10s}", "foo") test("{:4b}", 10) test("{:4c}", 48) test("{:4d}", 123) test("{:4n}", 123) test("{:4o}", 123) test("{:4x}", 123) test("{:4X}", 123) test("{:4,d}", 12345678) test("{:#4b}", 10) test("{:#4o}", 123) test("{:#4x}", 123) test("{:#4X}", 123) test("{:#4d}", 0) test("{:#4b}", 0) test("{:#4o}", 0) test("{:#4x}", 0) test("{:#4X}", 0) test("{:<6s}", "ab") test("{:>6s}", "ab") test("{:^6s}", "ab") test("{:.1s}", "ab") test("{: <6d}", 123) test("{: <6d}", -123) test("{:0<6d}", 123) test("{:0<6d}", -123) test("{:@<6d}", 123) test("{:@<6d}", -123) test("{:@< 6d}", 123) test("{:@< 6d}", -123) test("{:@<+6d}", 123) test("{:@<+6d}", -123) test("{:@<-6d}", 123) test("{:@<-6d}", -123) test("{:@>6d}", -123) test("{:@<6d}", -123) test("{:@=6d}", -123) test("{:06d}", -123) test("{:>20}", "foo") test("{:^20}", "foo") test("{:<20}", "foo") # nested format specifiers print("{:{}}".format(123, '#>10')) print("{:{}{}{}}".format(123, '#', '>', '10')) print("{0:{1}{2}}".format(123, '#>', '10')) print("{text:{align}{width}}".format(text="foo", align="<", width=20)) print("{text:{align}{width}}".format(text="foo", align="^", width=10)) print("{text:{align}{width}}".format(text="foo", align=">", width=30)) print("{foo}/foo".format(foo="bar")) print("{}".format(123, foo="bar")) print("{}-{foo}".format(123, foo="bar")) def test_fmt(conv, fill, alignment, sign, prefix, width, precision, type, arg): fmt = '{' if conv: fmt += '!' fmt += conv fmt += ':' if alignment: fmt += fill fmt += alignment fmt += sign fmt += prefix fmt += width if precision: fmt += '.' fmt += precision fmt += type fmt += '}' test(fmt, arg) if fill == '0' and alignment == '=': fmt = '{:' fmt += sign fmt += prefix fmt += width if precision: fmt += '.' fmt += precision fmt += type fmt += '}' test(fmt, arg) int_nums = (-1234, -123, -12, -1, 0, 1, 12, 123, 1234, True, False) int_nums2 = (-12, -1, 0, 1, 12, True, False) if full_tests: for type in ('', 'b', 'd', 'o', 'x', 'X'): for width in ('', '1', '3', '5', '7'): for alignment in ('', '<', '>', '=', '^'): for fill in ('', ' ', '0', '@'): for sign in ('', '+', '-', ' '): for prefix in ('', '#'): for num in int_nums: test_fmt('', fill, alignment, sign, prefix, width, '', type, num) if full_tests: for width in ('', '1', '2'): for alignment in ('', '<', '>', '^'): for fill in ('', ' ', '0', '@'): test_fmt('', fill, alignment, '', '', width, '', 'c', 48) if full_tests: for conv in ('', 'r', 's'): for width in ('', '1', '4', '10'): for alignment in ('', '<', '>', '^'): for fill in ('', ' ', '0', '@'): for str in ('', 'a', 'bcd', 'This is a test with a longer string'): test_fmt(conv, fill, alignment, '', '', width, '', 's', str) # tests for errors in format string try: '{0:0}'.format('zzz') except (ValueError): print('ValueError') try: '{1:}'.format(1) except IndexError: print('IndexError') try: '}'.format('zzzz') except ValueError: print('ValueError') # end of format parsing conversion specifier try: '{!'.format('a') except ValueError: print('ValueError') # unknown conversion specifier try: 'abc{!d}'.format('1') except ValueError: print('ValueError') try: '{abc'.format('zzzz') except ValueError: print('ValueError') # expected ':' after specifier try: '{!s :}'.format(2) except ValueError: print('ValueError') try: '{}{0}'.format(1, 2) except ValueError: print('ValueError') try: '{1:}'.format(1) except IndexError: print('IndexError') try: '{ 0 :*^10}'.format(12) except KeyError: print('KeyError') try: '{0}{}'.format(1) except ValueError: print('ValueError') try: '{}{}'.format(1) except IndexError: print('IndexError') try: '{0:+s}'.format('1') except ValueError: print('ValueError') try: '{0:+c}'.format(1) except ValueError: print('ValueError') try: '{0:s}'.format(1) except ValueError: print('ValueError') try: '{:*"1"}'.format('zz') except ValueError: print('ValueError') # unknown format code for str arg try: '{:X}'.format('zz') except ValueError: print('ValueError')
adamkh/micropython
tests/basics/string_format.py
Python
mit
4,990
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js export default [ [ [ 'ҝеҹәјары', 'ҝ', 'сүбһ', 'сәһәр', 'ҝүндүз', 'ахшамүстү', 'ахшам', 'ҝеҹә' ], [ 'ҝеҹәјары', 'ҝүнорта', 'сүбһ', 'сәһәр', 'ҝүндүз', 'ахшамүстү', 'ахшам', 'ҝеҹә' ], ], [ [ 'ҝеҹәјары', 'ҝүнорта', 'сүбһ', 'сәһәр', 'ҝүндүз', 'ахшамүстү', 'ахшам', 'ҝеҹә' ], , ], [ '00:00', '12:00', ['04:00', '06:00'], ['06:00', '12:00'], ['12:00', '17:00'], ['17:00', '19:00'], ['19:00', '24:00'], ['00:00', '04:00'] ] ];
rkirov/angular
packages/common/locales/extra/az-Cyrl.ts
TypeScript
mit
936
/*! * VERSION: 0.2.1 * DATE: 2017-01-17 * UPDATES AND DOCS AT: http://greensock.com * * @license Copyright (c) 2008-2017, GreenSock. All rights reserved. * This work is subject to the terms at http://greensock.com/standard-license or for * Club GreenSock members, the software agreement that was issued with your membership. * * @author: Jack Doyle, jack@greensock.com **/ var _gsScope = (typeof(module) !== "undefined" && module.exports && typeof(global) !== "undefined") ? global : this || window; //helps ensure compatibility with AMD/RequireJS and CommonJS/Node (_gsScope._gsQueue || (_gsScope._gsQueue = [])).push( function() { "use strict"; var _numExp = /(\d|\.)+/g, _ColorFilter, _ColorMatrixFilter, _colorProps = ["redMultiplier","greenMultiplier","blueMultiplier","alphaMultiplier","redOffset","greenOffset","blueOffset","alphaOffset"], _colorLookup = {aqua:[0,255,255], lime:[0,255,0], silver:[192,192,192], black:[0,0,0], maroon:[128,0,0], teal:[0,128,128], blue:[0,0,255], navy:[0,0,128], white:[255,255,255], fuchsia:[255,0,255], olive:[128,128,0], yellow:[255,255,0], orange:[255,165,0], gray:[128,128,128], purple:[128,0,128], green:[0,128,0], red:[255,0,0], pink:[255,192,203], cyan:[0,255,255], transparent:[255,255,255,0]}, _parseColor = function(color) { if (color === "" || color == null || color === "none") { return _colorLookup.transparent; } else if (_colorLookup[color]) { return _colorLookup[color]; } else if (typeof(color) === "number") { return [color >> 16, (color >> 8) & 255, color & 255]; } else if (color.charAt(0) === "#") { if (color.length === 4) { //for shorthand like #9F0 color = "#" + color.charAt(1) + color.charAt(1) + color.charAt(2) + color.charAt(2) + color.charAt(3) + color.charAt(3); } color = parseInt(color.substr(1), 16); return [color >> 16, (color >> 8) & 255, color & 255]; } return color.match(_numExp) || _colorLookup.transparent; }, _parseColorFilter = function(t, v, pg) { if (!_ColorFilter) { _ColorFilter = (_gsScope.ColorFilter || _gsScope.createjs.ColorFilter); if (!_ColorFilter) { throw("EaselPlugin error: The EaselJS ColorFilter JavaScript file wasn't loaded."); } } var filters = t.filters || [], i = filters.length, c, s, e, a, p; while (--i > -1) { if (filters[i] instanceof _ColorFilter) { s = filters[i]; break; } } if (!s) { s = new _ColorFilter(); filters.push(s); t.filters = filters; } e = s.clone(); if (v.tint != null) { c = _parseColor(v.tint); a = (v.tintAmount != null) ? Number(v.tintAmount) : 1; e.redOffset = Number(c[0]) * a; e.greenOffset = Number(c[1]) * a; e.blueOffset = Number(c[2]) * a; e.redMultiplier = e.greenMultiplier = e.blueMultiplier = 1 - a; } else { for (p in v) { if (p !== "exposure") if (p !== "brightness") { e[p] = Number(v[p]); } } } if (v.exposure != null) { e.redOffset = e.greenOffset = e.blueOffset = 255 * (Number(v.exposure) - 1); e.redMultiplier = e.greenMultiplier = e.blueMultiplier = 1; } else if (v.brightness != null) { a = Number(v.brightness) - 1; e.redOffset = e.greenOffset = e.blueOffset = (a > 0) ? a * 255 : 0; e.redMultiplier = e.greenMultiplier = e.blueMultiplier = 1 - Math.abs(a); } i = 8; while (--i > -1) { p = _colorProps[i]; if (s[p] !== e[p]) { pg._addTween(s, p, s[p], e[p], "easel_colorFilter"); } } pg._overwriteProps.push("easel_colorFilter"); if (!t.cacheID) { throw("EaselPlugin warning: for filters to display in EaselJS, you must call the object's cache() method first. " + t); } }, _idMatrix = [1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0], _lumR = 0.212671, _lumG = 0.715160, _lumB = 0.072169, _applyMatrix = function(m, m2) { if (!(m instanceof Array) || !(m2 instanceof Array)) { return m2; } var temp = [], i = 0, z = 0, y, x; for (y = 0; y < 4; y++) { for (x = 0; x < 5; x++) { z = (x === 4) ? m[i + 4] : 0; temp[i + x] = m[i] * m2[x] + m[i+1] * m2[x + 5] + m[i+2] * m2[x + 10] + m[i+3] * m2[x + 15] + z; } i += 5; } return temp; }, _setSaturation = function(m, n) { if (isNaN(n)) { return m; } var inv = 1 - n, r = inv * _lumR, g = inv * _lumG, b = inv * _lumB; return _applyMatrix([r + n, g, b, 0, 0, r, g + n, b, 0, 0, r, g, b + n, 0, 0, 0, 0, 0, 1, 0], m); }, _colorize = function(m, color, amount) { if (isNaN(amount)) { amount = 1; } var c = _parseColor(color), r = c[0] / 255, g = c[1] / 255, b = c[2] / 255, inv = 1 - amount; return _applyMatrix([inv + amount * r * _lumR, amount * r * _lumG, amount * r * _lumB, 0, 0, amount * g * _lumR, inv + amount * g * _lumG, amount * g * _lumB, 0, 0, amount * b * _lumR, amount * b * _lumG, inv + amount * b * _lumB, 0, 0, 0, 0, 0, 1, 0], m); }, _setHue = function(m, n) { if (isNaN(n)) { return m; } n *= Math.PI / 180; var c = Math.cos(n), s = Math.sin(n); return _applyMatrix([(_lumR + (c * (1 - _lumR))) + (s * (-_lumR)), (_lumG + (c * (-_lumG))) + (s * (-_lumG)), (_lumB + (c * (-_lumB))) + (s * (1 - _lumB)), 0, 0, (_lumR + (c * (-_lumR))) + (s * 0.143), (_lumG + (c * (1 - _lumG))) + (s * 0.14), (_lumB + (c * (-_lumB))) + (s * -0.283), 0, 0, (_lumR + (c * (-_lumR))) + (s * (-(1 - _lumR))), (_lumG + (c * (-_lumG))) + (s * _lumG), (_lumB + (c * (1 - _lumB))) + (s * _lumB), 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1], m); }, _setContrast = function(m, n) { if (isNaN(n)) { return m; } n += 0.01; return _applyMatrix([n,0,0,0,128 * (1 - n), 0,n,0,0,128 * (1 - n), 0,0,n,0,128 * (1 - n), 0,0,0,1,0], m); }, _parseColorMatrixFilter = function(t, v, pg) { if (!_ColorMatrixFilter) { _ColorMatrixFilter = (_gsScope.ColorMatrixFilter || _gsScope.createjs.ColorMatrixFilter); if (!_ColorMatrixFilter) { throw("EaselPlugin error: The EaselJS ColorMatrixFilter JavaScript file wasn't loaded."); } } var filters = t.filters || [], i = filters.length, matrix, startMatrix, s; while (--i > -1) { if (filters[i] instanceof _ColorMatrixFilter) { s = filters[i]; break; } } if (!s) { s = new _ColorMatrixFilter(_idMatrix.slice()); filters.push(s); t.filters = filters; } startMatrix = s.matrix; matrix = _idMatrix.slice(); if (v.colorize != null) { matrix = _colorize(matrix, v.colorize, Number(v.colorizeAmount)); } if (v.contrast != null) { matrix = _setContrast(matrix, Number(v.contrast)); } if (v.hue != null) { matrix = _setHue(matrix, Number(v.hue)); } if (v.saturation != null) { matrix = _setSaturation(matrix, Number(v.saturation)); } i = matrix.length; while (--i > -1) { if (matrix[i] !== startMatrix[i]) { pg._addTween(startMatrix, i, startMatrix[i], matrix[i], "easel_colorMatrixFilter"); } } pg._overwriteProps.push("easel_colorMatrixFilter"); if (!t.cacheID) { throw("EaselPlugin warning: for filters to display in EaselJS, you must call the object's cache() method first. " + t); } pg._matrix = startMatrix; }; _gsScope._gsDefine.plugin({ propName: "easel", priority: -1, version: "0.2.1", API: 2, //called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run. init: function(target, value, tween, index) { this._target = target; var p, pt, tint, colorMatrix, end, labels, i; for (p in value) { end = value[p]; if (typeof(end) === "function") { end = end(index, target); } if (p === "colorFilter" || p === "tint" || p === "tintAmount" || p === "exposure" || p === "brightness") { if (!tint) { _parseColorFilter(target, value.colorFilter || value, this); tint = true; } } else if (p === "saturation" || p === "contrast" || p === "hue" || p === "colorize" || p === "colorizeAmount") { if (!colorMatrix) { _parseColorMatrixFilter(target, value.colorMatrixFilter || value, this); colorMatrix = true; } } else if (p === "frame") { this._firstPT = pt = {_next:this._firstPT, t:target, p:"gotoAndStop", s:target.currentFrame, f:true, n:"frame", pr:0, type:0, m:Math.round}; if (typeof(end) === "string" && end.charAt(1) !== "=" && (labels = target.labels)) { for (i = 0; i < labels.length; i++) { if (labels[i].label === end) { end = labels[i].position; } } } pt.c = (typeof(end) === "number") ? end - pt.s : parseFloat((end+"").split("=").join("")); if (pt._next) { pt._next._prev = pt; } } else if (target[p] != null) { this._firstPT = pt = {_next:this._firstPT, t:target, p:p, f:(typeof(target[p]) === "function"), n:p, pr:0, type:0}; pt.s = (!pt.f) ? parseFloat(target[p]) : target[ ((p.indexOf("set") || typeof(target["get" + p.substr(3)]) !== "function") ? p : "get" + p.substr(3)) ](); pt.c = (typeof(end) === "number") ? end - pt.s : (typeof(end) === "string") ? parseFloat(end.split("=").join("")) : 0; if (pt._next) { pt._next._prev = pt; } } } return true; }, //called each time the values should be updated, and the ratio gets passed as the only parameter (typically it's a value between 0 and 1, but it can exceed those when using an ease like Elastic.easeOut or Back.easeOut, etc.) set: function(v) { var pt = this._firstPT, min = 0.000001, val; while (pt) { val = pt.c * v + pt.s; if (pt.m) { val = pt.m(val, pt.t); } else if (val < min && val > -min) { val = 0; } if (pt.f) { pt.t[pt.p](val); } else { pt.t[pt.p] = val; } pt = pt._next; } if (this._target.cacheID) { this._target.updateCache(); } } }); }); if (_gsScope._gsDefine) { _gsScope._gsQueue.pop()(); } //export to AMD/RequireJS and CommonJS/Node (precursor to full modular build system coming at a later date) (function(name) { "use strict"; var getGlobal = function() { return (_gsScope.GreenSockGlobals || _gsScope)[name]; }; if (typeof(define) === "function" && define.amd) { //AMD define(["./TweenLite"], getGlobal); } else if (typeof(module) !== "undefined" && module.exports) { //node require("./TweenLite.js"); module.exports = getGlobal(); } }("EaselPlugin"));
alanontheweb/kaldi-hugo-cms-template
src/themes/theme-hugo-stackrox/scripts/greensock-js-shockingly-green 2/src/commonjs-flat/EaselPlugin.js
JavaScript
mit
10,530
<?php /** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\ConfigurableProduct\Test\Constraint; use Magento\Catalog\Test\Fixture\CatalogProductAttribute; use Magento\Catalog\Test\Page\Adminhtml\CatalogProductIndex; use Magento\Catalog\Test\Page\Adminhtml\CatalogProductNew; use Magento\ConfigurableProduct\Test\Block\Adminhtml\Product\Edit\Section\Variations\Config as SectionVariation; use Magento\ConfigurableProduct\Test\Fixture\ConfigurableProduct; use Magento\Mtf\Constraint\AbstractConstraint; /** * Assert check whether the attribute is used to create a configurable products. */ class AssertProductAttributeIsConfigurable extends AbstractConstraint { /** * Assert check whether the attribute is used to create a configurable products. * * @param CatalogProductAttribute $attribute * @param ConfigurableProduct $assertProduct * @param CatalogProductIndex $productGrid * @param CatalogProductNew $newProductPage */ public function processAssert( CatalogProductAttribute $attribute, ConfigurableProduct $assertProduct, CatalogProductIndex $productGrid, CatalogProductNew $newProductPage ) { $productGrid->open(); $productGrid->getGridPageActionBlock()->addProduct('configurable'); $productBlockForm = $newProductPage->getProductForm(); $productBlockForm->fill($assertProduct); $productBlockForm->openSection('variations'); /** @var SectionVariation $variationsSection */ $variationsSection = $productBlockForm->getSection('variations'); $variationsSection->createConfigurations(); $attributesGrid = $variationsSection->getAttributeBlock()->getAttributesGrid(); \PHPUnit_Framework_Assert::assertTrue( $attributesGrid->isRowVisible(['frontend_label' => $attribute->getFrontendLabel()]), "Product attribute is absent on the product page." ); } /** * Attribute label present on the product page in variations section. * * @return string */ public function toString() { return 'Attribute label present on the product page in variations section.'; } }
j-froehlich/magento2_wk
vendor/magento/magento2-base/dev/tests/functional/tests/app/Magento/ConfigurableProduct/Test/Constraint/AssertProductAttributeIsConfigurable.php
PHP
mit
2,271
<?php /** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Store\Test\Handler\Store; use Magento\Mtf\Fixture\FixtureInterface; use Magento\Mtf\Handler\Curl as AbstractCurl; use Magento\Mtf\Util\Protocol\CurlInterface; use Magento\Mtf\Util\Protocol\CurlTransport; use Magento\Mtf\Util\Protocol\CurlTransport\BackendDecorator; /** * Class Curl * Curl handler for creating Store view */ class Curl extends AbstractCurl implements StoreInterface { /** * Url for saving data * * @var string */ protected $saveUrl = 'admin/system_store/save'; /** * Mapping values for data * * @var array */ protected $mappingData = [ 'group_id' => [ 'Main Website Store' => 1, ], 'is_active' => [ 'Enabled' => 1, 'Disabled' => 0, ], ]; /** * POST request for creating store * * @param FixtureInterface|null $fixture [optional] * @return array * @throws \Exception */ public function persist(FixtureInterface $fixture = null) { $data = $this->prepareData($fixture); $url = $_ENV['app_backend_url'] . $this->saveUrl; $curl = new BackendDecorator(new CurlTransport(), $this->_configuration); $curl->write($url, $data); $response = $curl->read(); $curl->close(); if (!strpos($response, 'data-ui-id="messages-message-success"')) { throw new \Exception("Store View entity creating by curl handler was not successful! Response: $response"); } return ['store_id' => $this->getStoreId($fixture->getName())]; } /** * Prepare data from text to values * * @param FixtureInterface $fixture * @return array */ protected function prepareData(FixtureInterface $fixture) { $data = [ 'store' => $this->replaceMappingData($fixture->getData()), 'store_action' => 'add', 'store_type' => 'store', ]; $data['store']['group_id'] = $fixture->getDataFieldConfig('group_id')['source']->getStoreGroup()->getGroupId(); $data['store']['store_id'] = isset($data['store']['store_id']) ? $data['store']['store_id'] : ''; return $data; } /** * Get Store id by name after creating Store * * @param string $name * @return int|null * @throws \Exception */ protected function getStoreId($name) { //Set pager limit to 2000 in order to find created store view by name $url = $_ENV['app_backend_url'] . 'admin/system_store/index/sort/store_title/dir/asc/limit/2000'; $curl = new BackendDecorator(new CurlTransport(), $this->_configuration); $curl->addOption(CURLOPT_HEADER, 1); $curl->write($url, [], CurlInterface::GET); $response = $curl->read(); $expectedUrl = '/admin/system_store/editStore/store_id/'; $expectedUrl = preg_quote($expectedUrl); $expectedUrl = str_replace('/', '\/', $expectedUrl); preg_match('/' . $expectedUrl . '([0-9]*)\/(.)*>' . $name . '<\/a>/', $response, $matches); if (empty($matches)) { throw new \Exception('Cannot find store id'); } return empty($matches[1]) ? null : $matches[1]; } }
j-froehlich/magento2_wk
vendor/magento/magento2-base/dev/tests/functional/tests/app/Magento/Store/Test/Handler/Store/Curl.php
PHP
mit
3,380
/** Breaks up a long string @method breakUp @for Handlebars **/ Handlebars.registerHelper('breakUp', function(property, hint, options) { var prop = Ember.Handlebars.get(this, property, options); if (!prop) return ""; hint = Ember.Handlebars.get(this, hint, options); return Discourse.Formatter.breakUp(prop, hint); }); /** Truncates long strings @method shorten @for Handlebars **/ Handlebars.registerHelper('shorten', function(property, options) { return Ember.Handlebars.get(this, property, options).substring(0,35); }); /** Produces a link to a topic @method topicLink @for Handlebars **/ Handlebars.registerHelper('topicLink', function(property, options) { var topic = Ember.Handlebars.get(this, property, options), title = topic.get('fancy_title') || topic.get('title'); return "<a href='" + topic.get('lastUnreadUrl') + "' class='title'>" + title + "</a>"; }); /** Produces a link to a category given a category object and helper options @method categoryLinkHTML @param {Discourse.Category} category to link to @param {Object} options standard from handlebars **/ function categoryLinkHTML(category, options) { var categoryOptions = {}; if (options.hash) { if (options.hash.allowUncategorized) { categoryOptions.allowUncategorized = true; } if (options.hash.categories) { categoryOptions.categories = Em.Handlebars.get(this, options.hash.categories, options); } } return new Handlebars.SafeString(Discourse.HTML.categoryLink(category, categoryOptions)); } /** Produces a link to a category @method categoryLink @for Handlebars **/ Handlebars.registerHelper('categoryLink', function(property, options) { return categoryLinkHTML(Ember.Handlebars.get(this, property, options), options); }); Handlebars.registerHelper('categoryLinkRaw', function(property, options) { return categoryLinkHTML(property, options); }); /** Produces a bound link to a category @method boundCategoryLink @for Handlebars **/ Ember.Handlebars.registerBoundHelper('boundCategoryLink', categoryLinkHTML); /** Produces a link to a route with support for i18n on the title @method titledLinkTo @for Handlebars **/ Handlebars.registerHelper('titledLinkTo', function(name, object) { var options = [].slice.call(arguments, -1)[0]; if (options.hash.titleKey) { options.hash.title = I18n.t(options.hash.titleKey); } if (arguments.length === 3) { return Ember.Handlebars.helpers.linkTo.call(this, name, object, options); } else { return Ember.Handlebars.helpers.linkTo.call(this, name, options); } }); /** Shorten a URL for display by removing common components @method shortenUrl @for Handlebars **/ Handlebars.registerHelper('shortenUrl', function(property, options) { var url; url = Ember.Handlebars.get(this, property, options); // Remove trailing slash if it's a top level URL if (url.match(/\//g).length === 3) { url = url.replace(/\/$/, ''); } url = url.replace(/^https?:\/\//, ''); url = url.replace(/^www\./, ''); return url.substring(0,80); }); /** Display a property in lower case @method lower @for Handlebars **/ Handlebars.registerHelper('lower', function(property, options) { var o; o = Ember.Handlebars.get(this, property, options); if (o && typeof o === 'string') { return o.toLowerCase(); } else { return ""; } }); /** Show an avatar for a user, intelligently making use of available properties @method avatar @for Handlebars **/ Handlebars.registerHelper('avatar', function(user, options) { if (typeof user === 'string') { user = Ember.Handlebars.get(this, user, options); } if (user) { var username = Em.get(user, 'username'); if (!username) username = Em.get(user, options.hash.usernamePath); var avatarTemplate; var template = options.hash.template; if (template && template !== 'avatar_template') { avatarTemplate = Em.get(user, template); if (!avatarTemplate) avatarTemplate = Em.get(user, 'user.' + template); } if (!avatarTemplate) avatarTemplate = Em.get(user, 'avatar_template'); if (!avatarTemplate) avatarTemplate = Em.get(user, 'user.avatar_template'); var title; if (!options.hash.ignoreTitle) { // first try to get a title title = Em.get(user, 'title'); // if there was no title provided if (!title) { // try to retrieve a description var description = Em.get(user, 'description'); // if a description has been provided if (description && description.length > 0) { // preprend the username before the description title = username + " - " + description; } } } return new Handlebars.SafeString(Discourse.Utilities.avatarImg({ size: options.hash.imageSize, extraClasses: Em.get(user, 'extras') || options.hash.extraClasses, title: title || username, avatarTemplate: avatarTemplate })); } else { return ''; } }); /** Bound avatar helper. Will rerender whenever the "avatar_template" changes. @method boundAvatar @for Handlebars **/ Ember.Handlebars.registerBoundHelper('boundAvatar', function(user, options) { return new Handlebars.SafeString(Discourse.Utilities.avatarImg({ size: options.hash.imageSize, avatarTemplate: Em.get(user, options.hash.template || 'avatar_template') })); }, 'avatar_template', 'uploaded_avatar_template', 'gravatar_template'); /** Nicely format a date without a binding since the date doesn't need to change. @method unboundDate @for Handlebars **/ Handlebars.registerHelper('unboundDate', function(property, options) { var dt = new Date(Ember.Handlebars.get(this, property, options)); return Discourse.Formatter.longDate(dt); }); /** Live refreshing age helper @method unboundDate @for Handlebars **/ Handlebars.registerHelper('unboundAge', function(property, options) { var dt = new Date(Ember.Handlebars.get(this, property, options)); return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(dt)); }); /** Live refreshing age helper, with a tooltip showing the date and time @method unboundAgeWithTooltip @for Handlebars **/ Handlebars.registerHelper('unboundAgeWithTooltip', function(property, options) { var dt = new Date(Ember.Handlebars.get(this, property, options)); return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(dt, {title: true})); }); /** Display a date related to an edit of a post @method editDate @for Handlebars **/ Handlebars.registerHelper('editDate', function(property, options) { // autoupdating this is going to be painful var date = new Date(Ember.Handlebars.get(this, property, options)); return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(date, {format: 'medium', title: true, leaveAgo: true, wrapInSpan: false})); }); /** Displays a percentile based on a `percent_rank` field @method percentile @for Ember.Handlebars **/ Ember.Handlebars.registerHelper('percentile', function(property, options) { var percentile = Ember.Handlebars.get(this, property, options); return Math.round((1.0 - percentile) * 100); }); /** Displays a float nicely @method float @for Ember.Handlebars **/ Ember.Handlebars.registerHelper('float', function(property, options) { var x = Ember.Handlebars.get(this, property, options); if (!x) return "0"; if (Math.round(x) === x) return x; return x.toFixed(3); }); /** Display logic for numbers. @method number @for Handlebars **/ Handlebars.registerHelper('number', function(property, options) { var orig = parseInt(Ember.Handlebars.get(this, property, options), 10); if (isNaN(orig)) { orig = 0; } var title = orig; if (options.hash.numberKey) { title = I18n.t(options.hash.numberKey, { number: orig }); } // Round off the thousands to one decimal place var n = orig; if (orig > 999 && !options.hash.noTitle) { n = (orig / 1000).toFixed(1) + "K"; } var classNames = 'number'; if (options.hash['class']) { classNames += ' ' + Ember.Handlebars.get(this, options.hash['class'], options); } var result = "<span class='" + classNames + "'"; if (n !== title) { result += " title='" + Handlebars.Utils.escapeExpression(title) + "'"; } result += ">" + n + "</span>"; return new Handlebars.SafeString(result); }); /** Display logic for dates. @method date @for Handlebars **/ Handlebars.registerHelper('date', function(property, options) { var leaveAgo; if (property.hash) { if (property.hash.leaveAgo) { leaveAgo = property.hash.leaveAgo === "true"; } if (property.hash.path) { property = property.hash.path; } } var val = Ember.Handlebars.get(this, property, options); if (val) { var date = new Date(val); return new Handlebars.SafeString(Discourse.Formatter.autoUpdatingRelativeAge(date, {format: 'medium', title: true, leaveAgo: leaveAgo})); } }); /** Look for custom html content in the preload store. @method customHTML @for Handlebars **/ Handlebars.registerHelper('customHTML', function(property) { var html = PreloadStore.get("customHTML"); if (html && html[property] && html[property].length) { return new Handlebars.SafeString(html[property]); } });
tadp/learnswift
app/assets/javascripts/discourse/helpers/application_helpers.js
JavaScript
mit
9,347
<?php /** *-------------------------------------------------------------------- * * Sub-Class - UPC Supplemental Barcode 2 digits * * Working with UPC-A, UPC-E, EAN-13, EAN-8 * This includes 2 digits (normaly for publications) * Must be placed next to UPC or EAN Code * *-------------------------------------------------------------------- * Copyright (C) Jean-Sebastien Goupil * http://www.barcodephp.com */ include_once('BCGParseException.php'); include_once('BCGBarcode1D.php'); include_once('BCGLabel.php'); class BCGupcext2 extends BCGBarcode1D { protected $codeParity = array(); /** * Constructor. */ public function __construct() { parent::__construct(); $this->keys = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); $this->code = array( '2100', /* 0 */ '1110', /* 1 */ '1011', /* 2 */ '0300', /* 3 */ '0021', /* 4 */ '0120', /* 5 */ '0003', /* 6 */ '0201', /* 7 */ '0102', /* 8 */ '2001' /* 9 */ ); // Parity, 0=Odd, 1=Even. Depending on ?%4 $this->codeParity = array( array(0, 0), /* 0 */ array(0, 1), /* 1 */ array(1, 0), /* 2 */ array(1, 1) /* 3 */ ); } /** * Draws the barcode. * * @param resource $im */ public function draw($im) { // Starting Code $this->drawChar($im, '001', true); // Code for ($i = 0; $i < 2; $i++) { $this->drawChar($im, self::inverse($this->findCode($this->text[$i]), $this->codeParity[intval($this->text) % 4][$i]), false); if ($i === 0) { $this->DrawChar($im, '00', false); // Inter-char } } $this->drawText($im, 0, 0, $this->positionX, $this->thickness); } /** * Returns the maximal size of a barcode. * * @param int $w * @param int $h * @return int[] */ public function getDimension($w, $h) { $startlength = 4; $textlength = 2 * 7; $intercharlength = 2; $w += $startlength + $textlength + $intercharlength; $h += $this->thickness; return parent::getDimension($w, $h); } /** * Adds the default label. */ protected function addDefaultLabel() { parent::addDefaultLabel(); if ($this->defaultLabel !== null) { $this->defaultLabel->setPosition(BCGLabel::POSITION_TOP); } } /** * Validates the input. */ protected function validate() { $c = strlen($this->text); if ($c === 0) { throw new BCGParseException('upcext2', 'No data has been entered.'); } // Checking if all chars are allowed for ($i = 0; $i < $c; $i++) { if (array_search($this->text[$i], $this->keys) === false) { throw new BCGParseException('upcext2', 'The character \'' . $this->text[$i] . '\' is not allowed.'); } } // Must contain 2 digits if ($c !== 2) { throw new BCGParseException('upcext2', 'Must contain 2 digits.'); } parent::validate(); } /** * Inverses the string when the $inverse parameter is equal to 1. * * @param string $text * @param int $inverse * @return string */ private static function inverse($text, $inverse = 1) { if ($inverse === 1) { $text = strrev($text); } return $text; } } ?>
hoti06/GestionnaireAtelierIHM
vendor/barcode/library/Barcode/src/class/BCGupcext2.barcode.php
PHP
mit
3,807
'use strict'; const styles = require('./styles'); const permsToString = require('./perms-to-string'); const sizeToString = require('./size-to-string'); const sortFiles = require('./sort-files'); const fs = require('fs'); const path = require('path'); const he = require('he'); const etag = require('../etag'); const url = require('url'); const status = require('../status-handlers'); const supportedIcons = styles.icons; const css = styles.css; module.exports = (opts) => { // opts are parsed by opts.js, defaults already applied const cache = opts.cache; const root = path.resolve(opts.root); const baseDir = opts.baseDir; const humanReadable = opts.humanReadable; const hidePermissions = opts.hidePermissions; const handleError = opts.handleError; const showDotfiles = opts.showDotfiles; const si = opts.si; const weakEtags = opts.weakEtags; return function middleware(req, res, next) { // Figure out the path for the file from the given url const parsed = url.parse(req.url); const pathname = decodeURIComponent(parsed.pathname); const dir = path.normalize( path.join( root, path.relative( path.join('/', baseDir), pathname ) ) ); fs.stat(dir, (statErr, stat) => { if (statErr) { if (handleError) { status[500](res, next, { error: statErr }); } else { next(); } return; } // files are the listing of dir fs.readdir(dir, (readErr, _files) => { let files = _files; if (readErr) { if (handleError) { status[500](res, next, { error: readErr }); } else { next(); } return; } // Optionally exclude dotfiles from directory listing. if (!showDotfiles) { files = files.filter(filename => filename.slice(0, 1) !== '.'); } res.setHeader('content-type', 'text/html'); res.setHeader('etag', etag(stat, weakEtags)); res.setHeader('last-modified', (new Date(stat.mtime)).toUTCString()); res.setHeader('cache-control', cache); function render(dirs, renderFiles, lolwuts) { // each entry in the array is a [name, stat] tuple let html = `${[ '<!doctype html>', '<html>', ' <head>', ' <meta charset="utf-8">', ' <meta name="viewport" content="width=device-width">', ` <title>Index of ${he.encode(pathname)}</title>`, ` <style type="text/css">${css}</style>`, ' </head>', ' <body>', `<h1>Index of ${he.encode(pathname)}</h1>`, ].join('\n')}\n`; html += '<table>'; const failed = false; const writeRow = (file) => { // render a row given a [name, stat] tuple const isDir = file[1].isDirectory && file[1].isDirectory(); let href = `${parsed.pathname.replace(/\/$/, '')}/${encodeURIComponent(file[0])}`; // append trailing slash and query for dir entry if (isDir) { href += `/${he.encode((parsed.search) ? parsed.search : '')}`; } const displayName = he.encode(file[0]) + ((isDir) ? '/' : ''); const ext = file[0].split('.').pop(); const classForNonDir = supportedIcons[ext] ? ext : '_page'; const iconClass = `icon-${isDir ? '_blank' : classForNonDir}`; // TODO: use stylessheets? html += `${'<tr>' + '<td><i class="icon '}${iconClass}"></i></td>`; if (!hidePermissions) { html += `<td class="perms"><code>(${permsToString(file[1])})</code></td>`; } html += `<td class="file-size"><code>${sizeToString(file[1], humanReadable, si)}</code></td>` + `<td class="display-name"><a href="${href}">${displayName}</a></td>` + '</tr>\n'; }; dirs.sort((a, b) => a[0].toString().localeCompare(b[0].toString())).forEach(writeRow); renderFiles.sort((a, b) => a.toString().localeCompare(b.toString())).forEach(writeRow); lolwuts.sort((a, b) => a[0].toString().localeCompare(b[0].toString())).forEach(writeRow); html += '</table>\n'; html += `<br><address>Node.js ${ process.version }/ <a href="https://github.com/jfhbrook/node-ecstatic">ecstatic</a> ` + `server running @ ${ he.encode(req.headers.host || '')}</address>\n` + '</body></html>' ; if (!failed) { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(html); } } sortFiles(dir, files, (lolwuts, dirs, sortedFiles) => { // It's possible to get stat errors for all sorts of reasons here. // Unfortunately, our two choices are to either bail completely, // or just truck along as though everything's cool. In this case, // I decided to just tack them on as "??!?" items along with dirs // and files. // // Whatever. // if it makes sense to, add a .. link if (path.resolve(dir, '..').slice(0, root.length) === root) { fs.stat(path.join(dir, '..'), (err, s) => { if (err) { if (handleError) { status[500](res, next, { error: err }); } else { next(); } return; } dirs.unshift(['..', s]); render(dirs, sortedFiles, lolwuts); }); } else { render(dirs, sortedFiles, lolwuts); } }); }); }); }; };
ManakCP/NestJs
node_modules/ecstatic/lib/ecstatic/show-dir/index.js
JavaScript
mit
5,853
<?php /** * module return as json_encode * http://www.aa-team.com * ====================== * * @author Andrei Dinca, AA-Team * @version 1.0 */ function __pspTC_get_image_sizes() { global $psp, $_wp_additional_image_sizes; $cache_name = 'psp_tiny_compress_wp_sizes'; $cacheSizes = get_transient( $cache_name ); $sizes = array(); if ( !empty($cacheSizes) && is_array($cacheSizes) ) { $sizes = $cacheSizes; } else { // original image { $sizes[ '__original' ] = array( 'width' => 0, 'height' => 0, ); } $get_intermediate_image_sizes = get_intermediate_image_sizes(); // create array with sizes. // original source: http://codex.wordpress.org/Function_Reference/get_intermediate_image_sizes foreach ( $get_intermediate_image_sizes as $_size ) { //if ( in_array( $_size, array( 'thumbnail', 'medium', 'large' ) ) ) {} $w = get_option( $_size . '_size_w' ); $h = get_option( $_size . '_size_h' ); if ( $w && $h ); else { $w = $_wp_additional_image_sizes[ $_size ]['width']; $h = $_wp_additional_image_sizes[ $_size ]['height']; } $sizes[ $_size ] = array( 'width' => $w, 'height' => $h, ); } // basic cache sistem set_transient( $cache_name, $sizes, 1200 ); // cache expires in 20 minutes } // display $_sizes = array(); foreach ($sizes as $key => $size) { $_sizes["$key"] = $size['width'] && $size['height'] ? sprintf( '%s ( %d x %d )', $key, $size['width'], $size['height'] ) : sprintf( '%s', $key ); } return $_sizes; } function __pspTC_connection_status() { global $psp; $html = array(); // get the module init file require_once( $psp->cfg['paths']['plugin_dir_path'] . 'modules/tiny_compress/init.php' ); // Initialize the pspTinyCompress class $pspTinyCompress = new pspTinyCompress(); $connection_status = $pspTinyCompress->get_connection_status(); $compress_limits = $pspTinyCompress->get_compress_limits(); ob_start(); ?> <div class="psp-form-row"> <div class="psp-message psp-<?php echo $connection_status['status'] == 'valid' ? 'success' : 'error'; ?>"> <p><?php echo __('Connection status: ', 'psp') . $connection_status['msg']; ?></p> </div> </div> <div class="psp-form-row"> <div class="psp-message psp-<?php echo $compress_limits['status'] == 'valid' ? 'success' : 'error'; ?>"> <p><?php echo __('Monthly limit: ', 'psp') . $compress_limits['msg']; ?></p> </div> </div> <?php $content = ob_get_contents(); ob_end_clean(); $html[] = $content; return implode( "\n", $html ); } global $psp; echo json_encode( array( $tryed_module['db_alias'] => array( /* define the form_messages box */ 'tiny_compress' => array( 'title' => __('Tiny Compress', 'psp'), 'icon' => '{plugin_folder_uri}assets/menu_icon.png', 'size' => 'grid_4', // grid_1|grid_2|grid_3|grid_4 'header' => true, // true|false 'toggler' => false, // true|false 'buttons' => true, // true|false 'style' => 'panel', // panel|panel-widget // create the box elements array 'elements' => array( array( 'type' => 'message', 'html' => __(' <p><strong>The TinyPNG.com API</strong> uses optimization techniques specific to image formatting to remove unnecessary bytes from image files. It is a "lossless" tool, which means it optimizes the images without changing their look or visual quality.</p> <ul> <li style="color: blue;">You only pay for what you use. The first 500 compressions in each month are free. You will only be billed if you compress more than 500 images in a month. <a href="https://tinypng.com/developers" target="_blank">More details here</a> - see bottom "Pricing" section.</li> <li>The TinyPNG.com service will download the image via the URL and will then return a URL to the new version of the image, which will be downloaded and will replace the original image on your server.</li> <li>The image must be less than 2 megabytes in size. This is a limit of the TinyPNG.com service.</li> <li>The image must be accessible from a non-https URL. This is a limit of the TinyPNG.com service.</li> <li>The TinyPNG.com service needs to download the image via a URL and the image needs to be on a public server and not a local local development system. This is a limit of the TinyPNG.com service.</li> <li>The image must be local to the site, not stored on a CDN (Content Delivery Network).</li> </ul> ', 'psp'), ), '_connection_status' => array( 'type' => 'html', 'html' => __pspTC_connection_status() ), 'resp_timeout' => array( 'type' => 'text', 'std' => '60', 'size' => 'large', 'force_width'=> '150', 'title' => __('Response timeout: ', 'psp'), 'desc' => __('enter the maximum number of seconds you want to wait for response from TinyPNG.com service.', 'psp') ), 'do_upload' => array( 'type' => 'select', 'std' => 'yes', 'size' => 'large', 'force_width'=> '120', 'title' => __('TinyPNG.com on Upload: ', 'psp'), 'desc' => __('Choose whether to apply the TinyPNG compression automaticcally on upload, or not.', 'psp'), 'options' => array( 'yes' => __('YES', 'psp'), 'no' => __('NO', 'psp') ) ), 'same_domain_url' => array( 'type' => 'select', 'std' => 'no', 'size' => 'large', 'force_width'=> '120', 'title' => __('Image same domain: ', 'psp'), 'desc' => __('Specify if the image url must or must not be on the same domain as the website\'s home url.', 'psp'), 'options' => array( 'yes' => __('YES', 'psp'), 'no' => __('NO', 'psp') ) ), 'tiny_key' => array( 'type' => 'text', 'std' => '', 'size' => 'large', 'force_width'=> '250', 'title' => __('TinyPNG.com API Key: ', 'psp'), 'desc' => __('(required) get a free key from <a href="https://tinypng.com/developers" target="_blank">TinyPNG.com Developer section</a> (works for both PNG and JPEG).', 'psp') ), 'image_sizes' => array( 'type' => 'multiselect_left2right', 'std' => array('__original'), 'size' => 'large', 'rows_visible' => 8, 'force_width'=> '300', 'title' => __('Select wp image sizes', $psp->localizationName), 'desc' => __('(__original = original image file; we\'ll always shrink the original image file and optionally, we can compress the other image sizes created by wordpress). <span style="color: blue; font-weight: bold;">attention: each additional image size will affect your TinyPNG.com monthly limit.</span>', $psp->localizationName), 'info' => array( 'left' => __('All wp image sizes list', $psp->localizationName), 'right' => __('Your chosen wp image sizes from list', $psp->localizationName), ), 'options' => __pspTC_get_image_sizes() ), 'last_status' => array( 'type' => 'textarea-array', 'std' => '', 'size' => 'large', 'force_width'=> '400', 'title' => __('Request Last Status:', 'psp'), 'desc' => __('Last Status for a TinyPNG operation on an image.', 'psp') ) ) ) ) ) );
mandino/nu
wp-content/plugins/premium-seo-pack/modules/tiny_compress/options.php
PHP
mit
8,450
<?php /** * Created by PhpStorm. * User: gseidel * Date: 16.05.18 * Time: 11:59 */ namespace Enhavo\Bundle\SearchBundle\Command; use Enhavo\Bundle\SearchBundle\Engine\EngineInterface; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\DependencyInjection\ContainerAwareTrait; class IndexCommand extends Command { use ContainerAwareTrait; protected function configure() { $this ->setName('enhavo:search:initialize') ->setDescription('Runs search initialize') ; } protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('Start initialize'); $engineName = $this->container->getParameter('enhavo_search.search.engine'); /** @var EngineInterface $engine */ $engine = $this->container->get($engineName); $engine->initialize(); $output->writeln('Initialize finished'); } }
gseidel/enhavo
src/Enhavo/Bundle/SearchBundle/Command/IndexCommand.php
PHP
mit
1,056
'use strict' const assert = require('assert') const http = require('http') const https = require('https') const { kState, kOptions } = require('./symbols') const { codes: { FST_ERR_HTTP2_INVALID_VERSION } } = require('./errors') function createServer (options, httpHandler) { assert(options, 'Missing options') assert(httpHandler, 'Missing http handler') var server = null if (options.serverFactory) { server = options.serverFactory(httpHandler, options) } else if (options.https) { if (options.http2) { server = http2().createSecureServer(options.https, httpHandler) } else { server = https.createServer(options.https, httpHandler) } } else if (options.http2) { server = http2().createServer(httpHandler) server.on('session', sessionTimeout(options.http2SessionTimeout)) } else { server = http.createServer(httpHandler) } return { server, listen } // `this` is the Fastify object function listen () { const normalizeListenArgs = (args) => { if (args.length === 0) { return { port: 0, host: 'localhost' } } const cb = typeof args[args.length - 1] === 'function' ? args.pop() : undefined const options = { cb: cb } const firstArg = args[0] const argsLength = args.length const lastArg = args[argsLength - 1] /* Deal with listen (options) || (handle[, backlog]) */ if (typeof firstArg === 'object' && firstArg !== null) { options.backlog = argsLength > 1 ? lastArg : undefined Object.assign(options, firstArg) } else if (typeof firstArg === 'string' && isNaN(firstArg)) { /* Deal with listen (pipe[, backlog]) */ options.path = firstArg options.backlog = argsLength > 1 ? lastArg : undefined } else { /* Deal with listen ([port[, host[, backlog]]]) */ options.port = argsLength >= 1 && firstArg ? firstArg : 0 // This will listen to what localhost is. // It can be 127.0.0.1 or ::1, depending on the operating system. // Fixes https://github.com/fastify/fastify/issues/1022. options.host = argsLength >= 2 && args[1] ? args[1] : 'localhost' options.backlog = argsLength >= 3 ? args[2] : undefined } return options } const listenOptions = normalizeListenArgs(Array.from(arguments)) const cb = listenOptions.cb const wrap = err => { server.removeListener('error', wrap) if (!err) { const address = logServerAddress() cb(null, address) } else { this[kState].listening = false cb(err, null) } } const listenPromise = (listenOptions) => { if (this[kState].listening) { return Promise.reject(new Error('Fastify is already listening')) } return this.ready().then(() => { var errEventHandler var errEvent = new Promise((resolve, reject) => { errEventHandler = (err) => { this[kState].listening = false reject(err) } server.once('error', errEventHandler) }) var listen = new Promise((resolve, reject) => { server.listen(listenOptions, () => { server.removeListener('error', errEventHandler) resolve(logServerAddress()) }) // we set it afterwards because listen can throw this[kState].listening = true }) return Promise.race([ errEvent, // e.g invalid port range error is always emitted before the server listening listen ]) }) } const logServerAddress = () => { var address = server.address() const isUnixSocket = typeof address === 'string' if (!isUnixSocket) { if (address.address.indexOf(':') === -1) { address = address.address + ':' + address.port } else { address = '[' + address.address + ']:' + address.port } } address = (isUnixSocket ? '' : ('http' + (this[kOptions].https ? 's' : '') + '://')) + address this.log.info('Server listening at ' + address) return address } if (cb === undefined) return listenPromise(listenOptions) this.ready(err => { if (err != null) return cb(err) if (this[kState].listening) { return cb(new Error('Fastify is already listening'), null) } server.once('error', wrap) server.listen(listenOptions, wrap) this[kState].listening = true }) } } function http2 () { try { return require('http2') } catch (err) { throw new FST_ERR_HTTP2_INVALID_VERSION() } } function sessionTimeout (timeout) { return function (session) { session.setTimeout(timeout, close) } } function close () { this.close() } module.exports = { createServer }
cdnjs/cdnjs
ajax/libs/fastify/2.15.3/lib/server.js
JavaScript
mit
4,813
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.internal.security; import java.lang.reflect.Method; import java.security.PrivilegedExceptionAction; public class PrivilegedGetMethodParameterTypes implements PrivilegedExceptionAction<Class[]> { private final Method method; public PrivilegedGetMethodParameterTypes(Method method) { this.method = method; } @Override public Class[] run() { return PrivilegedAccessHelper.getMethodParameterTypes(method); } }
RallySoftware/eclipselink.runtime
foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/security/PrivilegedGetMethodParameterTypes.java
Java
epl-1.0
1,211
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.internal.expressions; import java.io.*; import java.util.*; import org.eclipse.persistence.exceptions.*; import org.eclipse.persistence.expressions.Expression; import org.eclipse.persistence.internal.helper.*; import org.eclipse.persistence.queries.*; import org.eclipse.persistence.internal.sessions.AbstractSession; /** * <p><b>Purpose</b>: Print UPDATE statement. * <p><b>Responsibilities</b>:<ul> * <li> Print UPDATE statement. * </ul> * @author Dorin Sandu * @since TOPLink/Java 1.0 */ public class SQLUpdateStatement extends SQLModifyStatement { /** * Append the string containing the SQL insert string for the given table. */ protected SQLCall buildCallWithoutReturning(AbstractSession session) { SQLCall call = new SQLCall(); call.returnNothing(); Writer writer = new CharArrayWriter(100); try { writer.write("UPDATE "); if (getHintString() != null) { writer.write(getHintString()); writer.write(" "); } writer.write(getTable().getQualifiedNameDelimited(session.getPlatform())); writer.write(" SET "); ExpressionSQLPrinter printer = null; Vector fieldsForTable = new Vector(); Enumeration valuesEnum = getModifyRow().getValues().elements(); Vector values = new Vector(); for (Enumeration fieldsEnum = getModifyRow().keys(); fieldsEnum.hasMoreElements();) { DatabaseField field = (DatabaseField)fieldsEnum.nextElement(); Object value = valuesEnum.nextElement(); if (field.getTable().equals(getTable()) || (!field.hasTableName())) { fieldsForTable.addElement(field); values.addElement(value); } } if (fieldsForTable.isEmpty()) { return null; } for (int i = 0; i < fieldsForTable.size(); i++) { DatabaseField field = (DatabaseField)fieldsForTable.elementAt(i); writer.write(field.getNameDelimited(session.getPlatform())); writer.write(" = "); if(values.elementAt(i) instanceof Expression) { // the value in the modify row is an expression - assign it. Expression exp = (Expression)values.elementAt(i); if(printer == null) { printer = new ExpressionSQLPrinter(session, getTranslationRow(), call, false, getBuilder()); printer.setWriter(writer); } printer.printExpression(exp); } else { // the value in the modify row is ignored, the parameter corresponding to the key field will be assigned. call.appendModify(writer, field); } if ((i + 1) < fieldsForTable.size()) { writer.write(", "); } } if (!(getWhereClause() == null)) { writer.write(" WHERE "); if(printer == null) { printer = new ExpressionSQLPrinter(session, getTranslationRow(), call, false, getBuilder()); printer.setWriter(writer); } printer.printExpression(getWhereClause()); } call.setSQLString(writer.toString()); return call; } catch (IOException exception) { throw ValidationException.fileError(exception); } } }
RallySoftware/eclipselink.runtime
foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/expressions/SQLUpdateStatement.java
Java
epl-1.0
4,367
OW_FriendRequest = function( itemKey, params ) { var listLoaded = false; var model = OW.Console.getData(itemKey); var list = OW.Console.getItem(itemKey); var counter = new OW_DataModel(); counter.addObserver(this); this.onDataChange = function( data ) { var newCount = data.get('new'); var counterNumber = newCount > 0 ? newCount : data.get('all'); list.setCounter(counterNumber, newCount > 0); if ( counterNumber > 0 ) { list.showItem(); } }; list.onHide = function() { counter.set('new', 0); list.getItems().removeClass('ow_console_new_message'); model.set('counter', counter.get()); }; list.onShow = function() { if ( counter.get('all') <= 0 ) { this.showNoContent(); return; } if ( counter.get('new') > 0 || !listLoaded ) { this.loadList(); listLoaded = true; } }; model.addObserver(function() { if ( !list.opened ) { counter.set(model.get('counter')); } }); this.accept = function( requestKey, userId ) { var item = list.getItem(requestKey); var c = {}; if ( item.hasClass('ow_console_new_message') ) { c["new"] = counter.get("new") - 1; } c["all"] = counter.get("all") - 1; counter.set(c); this.send('friends-accept', {id: userId}); $('#friend_request_accept_'+userId).addClass( "ow_hidden"); $('#friend_request_ignore_'+userId).addClass( "ow_hidden"); return this; }; this.ignore = function( requestKey, userId ) { var item = list.getItem(requestKey); var c = {}; this.send('friends-ignore', {id: userId}); if ( item.hasClass('ow_console_new_message') ) { c["new"] = counter.get("new") - 1; } c["all"] = counter.get("all") - 1; counter.set(c); list.removeItem(item); return this; }; this.send = function( command, data ) { var request = $.ajax({ url: params.rsp, type: "POST", data: { "command": command, "data": JSON.stringify(data) }, dataType: "json" }); request.done(function( res ) { if ( res && res.script ) { OW.addScript(res.script); } }); return this; }; } OW.FriendRequest = null;
seret/oxtebafu
ow_static/plugins/friends/js/friend_request.js
JavaScript
gpl-2.0
2,629
<?php /** * @package Joomla.Administrator * @subpackage com_installer * * @copyright (C) 2008 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\Component\Installer\Administrator\View\Manage; \defined('_JEXEC') or die; use Joomla\CMS\Form\Form; use Joomla\CMS\Helper\ContentHelper; use Joomla\CMS\MVC\View\GenericDataException; use Joomla\CMS\Pagination\Pagination; use Joomla\CMS\Toolbar\Toolbar; use Joomla\Component\Installer\Administrator\View\Installer\HtmlView as InstallerViewDefault; /** * Extension Manager Manage View * * @since 1.6 */ class HtmlView extends InstallerViewDefault { /** * List of updatesites * * @var \stdClass[] */ protected $items; /** * Pagination object * * @var Pagination */ protected $pagination; /** * Form object * * @var Form */ protected $form; /** * Display the view. * * @param string $tpl Template * * @return mixed|void * * @since 1.6 */ public function display($tpl = null) { // Get data from the model. $this->items = $this->get('Items'); $this->pagination = $this->get('Pagination'); $this->filterForm = $this->get('FilterForm'); $this->activeFilters = $this->get('ActiveFilters'); // Check for errors. if (count($errors = $this->get('Errors'))) { throw new GenericDataException(implode("\n", $errors), 500); } // Display the view. parent::display($tpl); } /** * Add the page title and toolbar. * * @return void * * @since 1.6 */ protected function addToolbar() { $toolbar = Toolbar::getInstance('toolbar'); $canDo = ContentHelper::getActions('com_installer'); if ($canDo->get('core.edit.state')) { $toolbar->publish('manage.publish') ->text('JTOOLBAR_ENABLE') ->listCheck(true); $toolbar->unpublish('manage.unpublish') ->text('JTOOLBAR_DISABLE') ->listCheck(true); $toolbar->divider(); } $toolbar->standardButton('refresh') ->text('JTOOLBAR_REFRESH_CACHE') ->task('manage.refresh') ->listCheck(true); $toolbar->divider(); if ($canDo->get('core.delete')) { $toolbar->delete('manage.remove') ->text('JTOOLBAR_UNINSTALL') ->message('COM_INSTALLER_CONFIRM_UNINSTALL') ->listCheck(true); $toolbar->divider(); } parent::addToolbar(); $toolbar->help('Extensions:_Manage'); } }
Fedik/joomla-cms
administrator/components/com_installer/src/View/Manage/HtmlView.php
PHP
gpl-2.0
2,446
<?php include_once 'hammer.php'; class Int16Test extends PHPUnit_Framework_TestCase { protected $parser; protected function setUp() { $this->parser = hammer_int16(); } public function testNegative() { $result = hammer_parse($this->parser, "\xfe\x00"); $this->assertEquals(-0x200, $result); } public function testPositive() { $result = hammer_parse($this->parser, "\x02\x00"); $this->assertEquals(0x200, $result); } public function testFailure() { $result = hammer_parse($this->parser, "\xfe"); $this->assertEquals(NULL, $result); $result = hammer_parse($this->parser, "\x02"); $this->assertEquals(NULL, $result); } } ?>
pesco/hammer
src/bindings/php/Tests/Int16Test.php
PHP
gpl-2.0
750
/** * neuroConstruct * Software for developing large scale 3D networks of biologically realistic neurons * * Copyright (c) 2009 Padraig Gleeson * UCL Department of Neuroscience, Physiology and Pharmacology * * Development of this software was made possible with funding from the * Medical Research Council and the Wellcome Trust * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package ucl.physiol.neuroconstruct.gui; /** * Used to build generic input requests * * @author Padraig Gleeson * */ public class InputRequestElement { private String ref = null; private String request = null; private String toolTip = null; private String value = null; private String units = null; public InputRequestElement(String ref, String request, String toolTip, String initialVal, String units) { this.ref = ref; this.request = request; this.toolTip = toolTip; this.value = initialVal; this.units = units; } public void setValue(String val) { this.value = val; } public String getRef() { return this.ref; } public String getRequest() { return this.request; } public String getToolTip() { return this.toolTip; } public String getValue() { return this.value; } public String getUnits() { return this.units; } }
rgerkin/neuroConstruct
src/ucl/physiol/neuroconstruct/gui/InputRequestElement.java
Java
gpl-2.0
2,112
<?php /** * Interfaces and abstract classes for upgraders. * * @package reason * @subpackage classes */ /** * Interface for upgrader classes */ interface reasonUpgraderInterface { /** * Set and get the Reason ID of the current user * @param integer $user_id * @return integer $user_id */ function user_id($user_id = NULL); /** * Get the title of the upgrader * @return string */ public function title(); /** * Get a description of what this upgrade script will do * @return string HTML description */ public function description(); /** * Do a test run of the upgrader * @return string HTML report */ public function test(); /** * Run the upgrader * @return string HTML report */ public function run(); } /** * Interface for upgrader classes * * Upgraders that support this interface are standalone upgraders that are provided a disco form and must declare these methods: * * - init (given a disco form, the upgrader should define callbacks at appropriate stages) */ interface reasonUpgraderInterfaceAdvanced { /** * Set and get the Reason ID of the current user * @param integer $user_id * @return integer $user_id */ function user_id($user_id = NULL); /** * Get the title of the upgrader * @return string */ public function title(); /** * Get a description of what this upgrade script will do * @return string HTML description */ public function description(); /** /** * Init the upgrader * @return string HTML report */ public function init($disco, $head_items); } /** * Interface for upgrader information classes */ interface reasonUpgraderInfoInterface { /** * Output information. * @return string HTML report */ public function run(); } /** * The user_id function is the same in every upgrader so lets make an abstract class we can extend * if we don't want to copy and paste the user_id function every time. */ abstract class reasonUpgraderDefault { /** * Set and get the Reason ID of the current user * @param integer $user_id * @return integer $user_id */ function user_id($user_id = NULL) { if(!empty($user_id)) { return $this->user_id = $user_id; } else { return $this->user_id; } } }
carleton/reason_package
reason_4.0/lib/core/classes/upgrade/upgrader_interface.php
PHP
gpl-2.0
2,245
<?php /** * HUBzero CMS * * Copyright 2005-2015 HUBzero Foundation, LLC. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * HUBzero is a registered trademark of Purdue University. * * @package hubzero-cms * @author Shawn Rice <zooley@purdue.edu> * @copyright Copyright 2005-2015 HUBzero Foundation, LLC. * @license http://opensource.org/licenses/MIT MIT */ namespace Plugins\Content\Formathtml\Macros; use Plugins\Content\Formathtml\Macro; /** * A wiki macro for embedding links */ class Link extends Macro { /** * Allow macro in partial parsing? * * @var string */ public $allowPartial = true; /** * Returns description of macro, use, and accepted arguments * * @return string */ public function description() { $txt = array(); $txt['wiki'] = "Embed a link. Examples: {{{ [[Link(/SomePage SomePage)]] }}} "; $txt['html'] = '<p>Embed a link.</p> <p>Examples:</p> <ul> <li><code>[[Link(/SomePage SomePage)]]</code></li> </ul>'; return $txt['html']; } /** * Generate macro output based on passed arguments * * @return string HTML image tag on success or error message on failure */ public function render() { $content = $this->args; // args will be null if the macro is called without parenthesis. if (!$content) { return ''; } $cls = 'wiki'; // Parse arguments // We expect the 1st argument to be a filename $args = explode(' ', $content); $href = array_shift($args); $title = (count($args) > 0) ? implode(' ', $args) : $href; $title = preg_replace('/\(.*?\)/', '', $title); $title = preg_replace('/^.*?\:/', '', $title); return '<a class="' . $cls . '" href="' . $href . '">' . trim($title) . '</a>'; } }
kevinwojo/hubzero-cms
core/plugins/content/formathtml/macros/link.php
PHP
gpl-2.0
2,750
// clang-format off /* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator https://www.lammps.org/, 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) OpenMP based threading support for LAMMPS ------------------------------------------------------------------------- */ #include "fix_omp.h" #include "thr_data.h" #include "atom.h" #include "comm.h" #include "error.h" #include "force.h" #include "neighbor.h" #include "neigh_request.h" #include "universe.h" #include "update.h" #include "pair_hybrid.h" #include "bond_hybrid.h" #include "angle_hybrid.h" #include "dihedral_hybrid.h" #include "improper_hybrid.h" #include "kspace.h" #include <cstring> #include "omp_compat.h" #if defined(_OPENMP) #include <omp.h> #endif #include "suffix.h" using namespace LAMMPS_NS; using namespace FixConst; static int get_tid() { int tid = 0; #if defined(_OPENMP) tid = omp_get_thread_num(); #endif return tid; } /* ---------------------------------------------------------------------- */ FixOMP::FixOMP(LAMMPS *lmp, int narg, char **arg) : Fix(lmp, narg, arg), thr(nullptr), last_omp_style(nullptr), last_pair_hybrid(nullptr), _nthr(-1), _neighbor(true), _mixed(false), _reduced(true), _pair_compute_flag(false), _kspace_compute_flag(false) { if (narg < 4) error->all(FLERR,"Illegal package omp command"); int nthreads = 1; if (narg > 3) { #if defined(_OPENMP) if (strcmp(arg[3],"0") == 0) #pragma omp parallel LMP_DEFAULT_NONE LMP_SHARED(nthreads) nthreads = omp_get_num_threads(); else nthreads = utils::inumeric(FLERR,arg[3],false,lmp); #endif } #if defined(_OPENMP) if (nthreads < 1) error->all(FLERR,"Illegal number of OpenMP threads requested"); int reset_thr = 0; #endif if (nthreads != comm->nthreads) { #if defined(_OPENMP) reset_thr = 1; omp_set_num_threads(nthreads); #endif comm->nthreads = nthreads; } // optional keywords int iarg = 4; while (iarg < narg) { if (strcmp(arg[iarg],"neigh") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal package omp command"); _neighbor = utils::logical(FLERR,arg[iarg+1],false,lmp) != 0; iarg += 2; } else error->all(FLERR,"Illegal package omp command"); } // print summary of settings if (comm->me == 0) { #if defined(_OPENMP) const char * const nmode = _neighbor ? "multi-threaded" : "serial"; if (reset_thr) utils::logmesg(lmp, "set {} OpenMP thread(s) per MPI task\n", nthreads); utils::logmesg(lmp, "using {} neighbor list subroutines\n", nmode); #else error->warning(FLERR,"OpenMP support not enabled during compilation; " "using 1 thread only."); #endif } // allocate list for per thread accumulator manager class instances // and then have each thread create an instance of this class to // encourage the OS to use storage that is "close" to each thread's CPU. thr = new ThrData *[nthreads]; _nthr = nthreads; #if defined(_OPENMP) #pragma omp parallel LMP_DEFAULT_NONE LMP_SHARED(lmp) #endif { const int tid = get_tid(); Timer *t = new Timer(lmp); thr[tid] = new ThrData(tid,t); } } /* ---------------------------------------------------------------------- */ FixOMP::~FixOMP() { for (int i=0; i < _nthr; ++i) delete thr[i]; delete[] thr; } /* ---------------------------------------------------------------------- */ int FixOMP::setmask() { int mask = 0; mask |= PRE_FORCE; mask |= PRE_FORCE_RESPA; mask |= MIN_PRE_FORCE; return mask; } /* ---------------------------------------------------------------------- */ void FixOMP::init() { // OPENMP package cannot be used with atom_style template if (atom->molecular == Atom::TEMPLATE) error->all(FLERR,"OPENMP package does not (yet) work with " "atom_style template"); // adjust number of data objects when the number of OpenMP // threads has been changed somehow const int nthreads = comm->nthreads; if (_nthr != nthreads) { if (comm->me == 0) utils::logmesg(lmp,"Re-init OPENMP for {} OpenMP thread(s)\n", nthreads); for (int i=0; i < _nthr; ++i) delete thr[i]; thr = new ThrData *[nthreads]; _nthr = nthreads; #if defined(_OPENMP) #pragma omp parallel LMP_DEFAULT_NONE #endif { const int tid = get_tid(); Timer *t = new Timer(lmp); thr[tid] = new ThrData(tid,t); } } // reset per thread timer for (int i=0; i < nthreads; ++i) { thr[i]->_timer_active=1; thr[i]->timer(Timer::RESET); thr[i]->_timer_active=-1; } if (utils::strmatch(update->integrate_style,"^respa") && !utils::strmatch(update->integrate_style,"^respa/omp")) error->all(FLERR,"Must use respa/omp for r-RESPA with /omp styles"); if (force->pair && force->pair->compute_flag) _pair_compute_flag = true; else _pair_compute_flag = false; if (force->kspace && force->kspace->compute_flag) _kspace_compute_flag = true; else _kspace_compute_flag = false; int check_hybrid, kspace_split; last_pair_hybrid = nullptr; last_omp_style = nullptr; const char *last_omp_name = nullptr; const char *last_hybrid_name = nullptr; const char *last_force_name = nullptr; // support for verlet/split operation. // kspace_split == 0 : regular processing // kspace_split < 0 : master partition, does not do kspace // kspace_split > 0 : slave partition, only does kspace if (strstr(update->integrate_style,"verlet/split") != nullptr) { if (universe->iworld == 0) kspace_split = -1; else kspace_split = 1; } else { kspace_split = 0; } // determine which is the last force style with OpenMP // support as this is the one that has to reduce the forces #define CheckStyleForOMP(name) \ check_hybrid = 0; \ if (force->name) { \ if ( (strcmp(force->name ## _style,"hybrid") == 0) || \ (strcmp(force->name ## _style,"hybrid/overlay") == 0) ) \ check_hybrid=1; \ if (force->name->suffix_flag & Suffix::OMP) { \ last_force_name = (const char *) #name; \ last_omp_name = force->name ## _style; \ last_omp_style = (void *) force->name; \ } \ } #define CheckHybridForOMP(name,Class) \ if (check_hybrid) { \ Class ## Hybrid *style = (Class ## Hybrid *) force->name; \ for (int i=0; i < style->nstyles; i++) { \ if (style->styles[i]->suffix_flag & Suffix::OMP) { \ last_force_name = (const char *) #name; \ last_omp_name = style->keywords[i]; \ last_omp_style = style->styles[i]; \ } \ } \ } if (_pair_compute_flag && (kspace_split <= 0)) { CheckStyleForOMP(pair); CheckHybridForOMP(pair,Pair); if (check_hybrid) { last_pair_hybrid = last_omp_style; last_hybrid_name = last_omp_name; } CheckStyleForOMP(bond); CheckHybridForOMP(bond,Bond); CheckStyleForOMP(angle); CheckHybridForOMP(angle,Angle); CheckStyleForOMP(dihedral); CheckHybridForOMP(dihedral,Dihedral); CheckStyleForOMP(improper); CheckHybridForOMP(improper,Improper); } if (_kspace_compute_flag && (kspace_split >= 0)) { CheckStyleForOMP(kspace); } #undef CheckStyleForOMP #undef CheckHybridForOMP set_neighbor_omp(); // diagnostic output if (comm->me == 0) { if (last_omp_style) { if (last_pair_hybrid) utils::logmesg(lmp,"Hybrid pair style last /omp style {}\n",last_hybrid_name); utils::logmesg(lmp,"Last active /omp style is {}_style {}\n",last_force_name,last_omp_name); } else { utils::logmesg(lmp,"No /omp style for force computation currently active\n"); } } } /* ---------------------------------------------------------------------- */ void FixOMP::set_neighbor_omp() { // select or deselect multi-threaded neighbor // list build depending on setting in package omp. // NOTE: since we are at the top of the list of // fixes, we cannot adjust neighbor lists from // other fixes. those have to be re-implemented // as /omp fix styles. :-( const int neigh_omp = _neighbor ? 1 : 0; const int nrequest = neighbor->nrequest; // flag *all* neighbor list requests as OPENMP threaded, // but skip lists already flagged as INTEL threaded for (int i = 0; i < nrequest; ++i) if (! neighbor->requests[i]->intel) neighbor->requests[i]->omp = neigh_omp; } /* ---------------------------------------------------------------------- */ void FixOMP::setup(int) { // we are post the force compute in setup. turn on timers for (int i=0; i < _nthr; ++i) thr[i]->_timer_active=0; } /* ---------------------------------------------------------------------- */ // adjust size and clear out per thread accumulator arrays void FixOMP::pre_force(int) { const int nall = atom->nlocal + atom->nghost; double **f = atom->f; double **torque = atom->torque; double *erforce = atom->erforce; double *desph = atom->desph; double *drho = atom->drho; #if defined(_OPENMP) #pragma omp parallel LMP_DEFAULT_NONE LMP_SHARED(f,torque,erforce,desph,drho) #endif { const int tid = get_tid(); thr[tid]->check_tid(tid); thr[tid]->init_force(nall,f,torque,erforce,desph,drho); } // end of omp parallel region _reduced = false; } /* ---------------------------------------------------------------------- */ double FixOMP::memory_usage() { double bytes = (double)_nthr * (sizeof(ThrData *) + sizeof(ThrData)); bytes += (double)_nthr * thr[0]->memory_usage(); return bytes; }
akohlmey/lammps
src/OPENMP/fix_omp.cpp
C++
gpl-2.0
10,683
jQuery(document).ready(function($) { $(".zilla-tabs").tabs(); $(".zilla-toggle").each( function () { var $this = $(this); if( $this.attr('data-id') == 'closed' ) { $this.accordion({ header: '.zilla-toggle-title', collapsible: true, active: false }); } else { $this.accordion({ header: '.zilla-toggle-title', collapsible: true}); } $this.on('accordionactivate', function( e, ui ) { $this.accordion('refresh'); }); $(window).on('resize', function() { $this.accordion('refresh'); }); }); });
XDocker/web
wp-content/themes/scrolle/admin/zilla-shortcodes/js/zilla-shortcodes-lib.js
JavaScript
gpl-2.0
529
<?php /** * LICENSE: 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. * * PHP version 5 * * @category Microsoft * @package WindowsAzure\ServiceManagement\Models * @author Azure PHP SDK <azurephpsdk@microsoft.com> * @copyright 2012 Microsoft Corporation * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://github.com/windowsazure/azure-sdk-for-php */ namespace WindowsAzure\ServiceManagement\Models; use WindowsAzure\Common\Internal\Resources; use WindowsAzure\Common\Internal\Utilities; /** * The affinity group class. * * @category Microsoft * @package WindowsAzure\ServiceManagement\Models * @author Azure PHP SDK <azurephpsdk@microsoft.com> * @copyright 2012 Microsoft Corporation * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @version Release: @package_version@ * @link https://github.com/windowsazure/azure-sdk-for-php */ class AffinityGroup extends Service { /** * Constructs new affinity group object. * * @param array $raw The array representation for affinity group. */ public function __construct($raw = null) { parent::__construct($raw); $this->setName(Utilities::tryGetValue($raw, Resources::XTAG_NAME)); } /** * Converts the current object into ordered array representation. * * @return array */ protected function toArray() { $arr = parent::toArray(); $order = array( Resources::XTAG_NAMESPACE, Resources::XTAG_NAME, Resources::XTAG_LABEL, Resources::XTAG_DESCRIPTION, Resources::XTAG_LOCATION ); Utilities::addIfNotEmpty(Resources::XTAG_NAME, $this->getName(), $arr); $ordered = Utilities::orderArray($arr, $order); return $ordered; } }
treznorx/RehabWithResults
wp-content/plugins/windows-azure-storage/library/WindowsAzure/ServiceManagement/Models/AffinityGroup.php
PHP
gpl-2.0
2,386
# -*- coding: utf-8 -*- # # papyon - a python client library for Msn # # Copyright (C) 2005-2006 Ali Sabil <ali.sabil@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 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 import xml.sax.saxutils as xml class LiveService(object): CONTACTS = ("contacts.msn.com", "MBI") MESSENGER = ("messenger.msn.com", "?id=507") MESSENGER_CLEAR = ("messengerclear.live.com", "MBI_KEY_OLD") MESSENGER_SECURE = ("messengersecure.live.com", "MBI_SSL") SPACES = ("spaces.live.com", "MBI") STORAGE = ("storage.msn.com", "MBI") TB = ("http://Passport.NET/tb", None) VOICE = ("voice.messenger.msn.com", "?id=69264") @classmethod def url_to_service(cls, url): for attr_name in dir(cls): if attr_name.startswith('_'): continue attr = getattr(cls, attr_name) if isinstance(attr, tuple) and attr[0] == url: return attr return None def transport_headers(): """Returns a dictionary, containing transport (http) headers to use for the request""" return {} def soap_action(): """Returns the SOAPAction value to pass to the transport or None if no SOAPAction needs to be specified""" return None def soap_header(account, password): """Returns the SOAP xml header""" return """ <ps:AuthInfo xmlns:ps="http://schemas.microsoft.com/Passport/SoapServices/PPCRL" Id="PPAuthInfo"> <ps:HostingApp>{7108E71A-9926-4FCB-BCC9-9A9D3F32E423}</ps:HostingApp> <ps:BinaryVersion>4</ps:BinaryVersion> <ps:UIVersion>1</ps:UIVersion> <ps:Cookies/> <ps:RequestParams>AQAAAAIAAABsYwQAAAAxMDMz</ps:RequestParams> </ps:AuthInfo> <wsse:Security xmlns:wsse="http://schemas.xmlsoap.org/ws/2003/06/secext"> <wsse:UsernameToken Id="user"> <wsse:Username>%(account)s</wsse:Username> <wsse:Password>%(password)s</wsse:Password> </wsse:UsernameToken> </wsse:Security>""" % {'account': xml.escape(account), 'password': xml.escape(password)} def soap_body(*tokens): """Returns the SOAP xml body""" token_template = """ <wst:RequestSecurityToken xmlns:wst="http://schemas.xmlsoap.org/ws/2004/04/trust" Id="RST%(id)d"> <wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType> <wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2002/12/policy"> <wsa:EndpointReference xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/03/addressing"> <wsa:Address>%(address)s</wsa:Address> </wsa:EndpointReference> </wsp:AppliesTo> %(policy_reference)s </wst:RequestSecurityToken>""" policy_reference_template = """ <wsse:PolicyReference xmlns:wsse="http://schemas.xmlsoap.org/ws/2003/06/secext" URI=%(uri)s/>""" tokens = list(tokens) if LiveService.TB in tokens: tokens.remove(LiveService.TB) assert(len(tokens) >= 1) body = token_template % \ {'id': 0, 'address': xml.escape(LiveService.TB[0]), 'policy_reference': ''} for id, token in enumerate(tokens): if token[1] is not None: policy_reference = policy_reference_template % \ {'uri': xml.quoteattr(token[1])} else: policy_reference = "" t = token_template % \ {'id': id + 1, 'address': xml.escape(token[0]), 'policy_reference': policy_reference} body += t return '<ps:RequestMultipleSecurityTokens ' \ 'xmlns:ps="http://schemas.microsoft.com/Passport/SoapServices/PPCRL" ' \ 'Id="RSTS">%s</ps:RequestMultipleSecurityTokens>' % body def process_response(soap_response): body = soap_response.body return body.findall("./wst:RequestSecurityTokenResponseCollection/" \ "wst:RequestSecurityTokenResponse")
billiob/papyon
papyon/service/description/SingleSignOn/RequestMultipleSecurityTokens.py
Python
gpl-2.0
4,656
<?php /** * Chunk Exception * * @package Less * @subpackage exception */ class Less_Exception_Chunk extends Less_Exception_Parser{ protected $parserCurrentIndex = 0; protected $emitFrom = 0; protected $input_len; /** * Constructor * * @param string $input * @param Exception $previous Previous exception * @param integer $index The current parser index * @param Less_FileInfo|string $currentFile The file * @param integer $code The exception code */ public function __construct($input, Exception $previous = null, $index = null, $currentFile = null, $code = 0){ $this->message = 'ParseError: Unexpected input'; //default message $this->index = $index; $this->currentFile = $currentFile; $this->input = $input; $this->input_len = strlen($input); $this->Chunks(); $this->genMessage(); } /** * See less.js chunks() * We don't actually need the chunks * */ function Chunks(){ $level = 0; $parenLevel = 0; $lastMultiCommentEndBrace = null; $lastOpening = null; $lastMultiComment = null; $lastParen = null; for( $this->parserCurrentIndex = 0; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++ ){ $cc = $this->CharCode($this->parserCurrentIndex); if ((($cc >= 97) && ($cc <= 122)) || ($cc < 34)) { // a-z or whitespace continue; } switch ($cc) { // ( case 40: $parenLevel++; $lastParen = $this->parserCurrentIndex; continue; // ) case 41: $parenLevel--; if( $parenLevel < 0 ){ return $this->fail("missing opening `(`"); } continue; // ; case 59: //if (!$parenLevel) { $this->emitChunk(); } continue; // { case 123: $level++; $lastOpening = $this->parserCurrentIndex; continue; // } case 125: $level--; if( $level < 0 ){ return $this->fail("missing opening `{`"); } //if (!$level && !$parenLevel) { $this->emitChunk(); } continue; // \ case 92: if ($this->parserCurrentIndex < $this->input_len - 1) { $this->parserCurrentIndex++; continue; } return $this->fail("unescaped `\\`"); // ", ' and ` case 34: case 39: case 96: $matched = 0; $currentChunkStartIndex = $this->parserCurrentIndex; for ($this->parserCurrentIndex = $this->parserCurrentIndex + 1; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++) { $cc2 = $this->CharCode($this->parserCurrentIndex); if ($cc2 > 96) { continue; } if ($cc2 == $cc) { $matched = 1; break; } if ($cc2 == 92) { // \ if ($this->parserCurrentIndex == $this->input_len - 1) { return $this->fail("unescaped `\\`"); } $this->parserCurrentIndex++; } } if ($matched) { continue; } return $this->fail("unmatched `" + chr($cc) + "`", $currentChunkStartIndex); // /, check for comment case 47: if ($parenLevel || ($this->parserCurrentIndex == $this->input_len - 1)) { continue; } $cc2 = $this->CharCode($this->parserCurrentIndex+1); if ($cc2 == 47) { // //, find lnfeed for ($this->parserCurrentIndex = $this->parserCurrentIndex + 2; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++) { $cc2 = $this->CharCode($this->parserCurrentIndex); if (($cc2 <= 13) && (($cc2 == 10) || ($cc2 == 13))) { break; } } } else if ($cc2 == 42) { // /*, find */ $lastMultiComment = $currentChunkStartIndex = $this->parserCurrentIndex; for ($this->parserCurrentIndex = $this->parserCurrentIndex + 2; $this->parserCurrentIndex < $this->input_len - 1; $this->parserCurrentIndex++) { $cc2 = $this->CharCode($this->parserCurrentIndex); if ($cc2 == 125) { $lastMultiCommentEndBrace = $this->parserCurrentIndex; } if ($cc2 != 42) { continue; } if ($this->CharCode($this->parserCurrentIndex+1) == 47) { break; } } if ($this->parserCurrentIndex == $this->input_len - 1) { return $this->fail("missing closing `*/`", $currentChunkStartIndex); } } continue; // *, check for unmatched */ case 42: if (($this->parserCurrentIndex < $this->input_len - 1) && ($this->CharCode($this->parserCurrentIndex+1) == 47)) { return $this->fail("unmatched `/*`"); } continue; } } if( $level !== 0 ){ if( ($lastMultiComment > $lastOpening) && ($lastMultiCommentEndBrace > $lastMultiComment) ){ return $this->fail("missing closing `}` or `*/`", $lastOpening); } else { return $this->fail("missing closing `}`", $lastOpening); } } else if ( $parenLevel !== 0 ){ return $this->fail("missing closing `)`", $lastParen); } //$this->emitChunk(true); } function CharCode($pos){ return ord($this->input[$pos]); } function fail( $msg, $index = null ){ if( !$index ){ $this->index = $this->parserCurrentIndex; }else{ $this->index = $index; } $this->message = 'ParseError: '.$msg; } /* function emitChunk( $force = false ){ $len = $this->parserCurrentIndex - $this->emitFrom; if ((($len < 512) && !$force) || !$len) { return; } $chunks[] = substr($this->input, $this->emitFrom, $this->parserCurrentIndex + 1 - $this->emitFrom ); $this->emitFrom = $this->parserCurrentIndex + 1; } */ }
mauricioabisay/loc
wp-content/themes/madison/wp-less/vendor/oyejorge/less.php/lib/Less/Exception/Chunk.php
PHP
gpl-2.0
5,537
<?php $customers = array(array( 'id'=>1, 'name'=>'Bread Barn', 'phone'=>'8436-365-256' ), array( 'id'=>2, 'name'=>'Icecream Island', 'phone'=>'8452-389-719' ), array( 'id'=>3, 'name'=>'Pizza Palace', 'phone'=>'9378-255-743' ) ); if (isset($_REQUEST['id'])) { $id = $_REQUEST['id']; foreach ($customers as &$customer) { if ($customer['id'] == $id) { echo json_encode($customer); break; } } } else { echo json_encode($customers); } ?>
mesocentrefc/Janua-SMS
janua-web/ext/examples/classic/data/customer.php
PHP
gpl-2.0
600
/* * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * Test to verify GetObjectSize does not overflow on a 600M element int[] * * @test * @bug 8027230 * @library /test/lib * @modules java.base/jdk.internal.misc * java.compiler * java.instrument * java.management * jdk.internal.jvmstat/sun.jvmstat.monitor * @requires vm.bits == 64 * @build GetObjectSizeOverflowAgent * @run driver ClassFileInstaller GetObjectSizeOverflowAgent * @run main GetObjectSizeOverflow */ import java.io.PrintWriter; import jdk.test.lib.JDKToolFinder; import jdk.test.lib.Platform; import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.process.ProcessTools; import jtreg.SkippedException; public class GetObjectSizeOverflow { public static void main(String[] args) throws Exception { PrintWriter pw = new PrintWriter("MANIFEST.MF"); pw.println("Premain-Class: GetObjectSizeOverflowAgent"); pw.close(); ProcessBuilder pb = new ProcessBuilder(); pb.command(new String[] { JDKToolFinder.getJDKTool("jar"), "cmf", "MANIFEST.MF", "agent.jar", "GetObjectSizeOverflowAgent.class"}); pb.start().waitFor(); ProcessBuilder pt = ProcessTools.createJavaProcessBuilder(true, "-Xmx4000m", "-javaagent:agent.jar", "GetObjectSizeOverflowAgent"); OutputAnalyzer output = new OutputAnalyzer(pt.start()); if (output.getStdout().contains("Could not reserve enough space") || output.getStderr().contains("java.lang.OutOfMemoryError")) { System.out.println("stdout: " + output.getStdout()); System.out.println("stderr: " + output.getStderr()); throw new SkippedException("Test could not reserve or allocate enough space"); } output.stdoutShouldContain("GetObjectSizeOverflow passed"); } }
md-5/jdk10
test/hotspot/jtreg/serviceability/jvmti/GetObjectSizeOverflow.java
Java
gpl-2.0
2,854
/**************************************************************** * RetroShare GUI is distributed under the following license: * * Copyright (C) 2012 by Thunder * * 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 "FeedReaderNotify.h" FeedReaderNotify::FeedReaderNotify() : QObject() { } void FeedReaderNotify::notifyFeedChanged(const std::string &feedId, int type) { emit feedChanged(QString::fromStdString(feedId), type); } void FeedReaderNotify::notifyMsgChanged(const std::string &feedId, const std::string &msgId, int type) { emit msgChanged(QString::fromStdString(feedId), QString::fromStdString(msgId), type); }
RedCraig/retroshare
plugins/FeedReader/gui/FeedReaderNotify.cpp
C++
gpl-2.0
1,390
/********************************************************************** Protein - Protein class Copyright (C) 2009 Tim Vandermeersch This file is part of the Avogadro molecular editor project. For more information, see <http://avogadro.cc/> Avogadro 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. Avogadro 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 "protein.h" #include <avogadro/molecule.h> #include <avogadro/residue.h> #include <avogadro/atom.h> #include <avogadro/neighborlist.h> #include <QVector> #include <QVariant> #include <QStringList> #include <QDebug> namespace Avogadro { class ProteinPrivate { public: Molecule *molecule; QVector<QVector<Residue*> > chains; QVector<QVector<Residue*> > hbondPairs; QByteArray structure; mutable int num3turnHelixes; mutable int num4turnHelixes; mutable int num5turnHelixes; }; Protein::Protein(Molecule *molecule) : d(new ProteinPrivate) { d->molecule = molecule; sortResiduesByChain(); if (!extractFromPDB()) { detectHBonds(); detectStructure(); } /* foreach (const QVector<Residue*> &residues, d->chains) { // for each chain qDebug() << "chain: " << d->chains.indexOf(residues); QByteArray chain; foreach (Residue *residue, residues) { // for each residue in the chain chain.append( d->structure.at(residue->index()) ); } qDebug() << chain; } */ } Protein::~Protein() { delete d; } QByteArray Protein::secondaryStructure() const { return d->structure; } const QVector<QVector<Residue*> >& Protein::chains() const { return d->chains; } bool Protein::isHelix(Residue *residue) const { char key = d->structure.at(residue->index()); switch(key) { case 'G': case 'H': case 'I': return true; default: return false; } } bool Protein::isSheet(Residue *residue) const { char key = d->structure.at(residue->index()); switch(key) { case 'E': case 'B': return true; default: return false; } } bool Protein::extractFromPDB() { bool found = false; /* COLUMNS DATA TYPE FIELD DEFINITION ----------------------------------------------------------------------------------- 1 - 6 Record name "HELIX " 8 - 10 Integer serNum Serial number of the helix. This starts at 1 and increases incrementally. 12 - 14 LString(3) helixID Helix identifier. In addition to a serial number, each helix is given an alphanumeric character helix identifier. 16 - 18 Residue name initResName Name of the initial residue. 20 Character initChainID Chain identifier for the chain containing this helix. 22 - 25 Integer initSeqNum Sequence number of the initial residue. 26 AChar initICode Insertion code of the initial residue. 28 - 30 Residue name endResName Name of the terminal residue of the helix. 32 Character endChainID Chain identifier for the chain containing this helix. 34 - 37 Integer endSeqNum Sequence number of the terminal residue. 38 AChar endICode Insertion code of the terminal residue. 39 - 40 Integer helixClass Helix class (see below). 41 - 70 String comment Comment about this helix. 72 - 76 Integer length Length of this helix. */ QVariant helix = d->molecule->property("HELIX"); if (helix.isValid()) { found = true; QStringList lines = helix.toString().split('\n'); foreach (const QString &line, lines) { //qDebug() << "line:" << line; bool ok; QString helixID = line.mid(5, 3); // // initial residue // QString initResName = line.mid(9, 3); QString initChainID = line.mid(13, 1); int initChainNum = -1; foreach (Residue *residue, d->molecule->residues()) { if (QString(residue->chainID()) != initChainID) continue; initChainNum = residue->chainNumber(); break; } if (initChainNum < 0) { qDebug() << "Protein: Error, invalid initChainID for helix" << helixID; return false; } int initSeqNum = line.mid(15, 4).toInt(&ok); if (!ok) { qDebug() << "Protein: Error, can't read interger from initSeqNum for helix" << helixID; return false; } Residue *initResidue = 0; foreach (Residue *residue, d->chains.at(initChainNum)) { if (residue->number().toInt() == initSeqNum) { initResidue = residue; break; } } if (!initResidue) { qDebug() << "Protein: Error, could not find initResidue in the chain for helix" << helixID; return false; } if (initResidue->name() != initResName) { qDebug() << "Protein: Error, initResName does not match the residue " "at the specified position for helix" << helixID; qDebug() << initResName << "!=" << initResidue->name(); return false; } // // end residue // QString endResName = line.mid(21, 3); QString endChainID = line.mid(25, 1); int endChainNum = -1; foreach (Residue *residue, d->molecule->residues()) { if (QString(residue->chainID()) != endChainID) continue; endChainNum = residue->chainNumber(); } if (endChainNum < 0) { qDebug() << "Protein: Error, invalid endChainID for helix" << helixID; return false; } int endSeqNum = line.mid(27, 4).toInt(&ok); if (!ok) { qDebug() << "Protein: Error, can't read interger from endSeqNum for helix" << helixID; return false; } Residue *endResidue = 0; foreach (Residue *residue, d->chains.at(endChainNum)) { if (residue->number().toInt() == endSeqNum) { endResidue = residue; break; } } if (!endResidue) { qDebug() << "Protein: Error, could not find endResidue in the chain for helix" << helixID; return false; } if (endResidue->name() != endResName) { qDebug() << "Protein: Error, endResName does not match the residue " "at the specified position for helix" << helixID; qDebug() << endResName << "!=" << endResidue->name(); return false; } int helixClass = line.mid(32, 2).toInt(&ok); if (!ok) { qDebug() << "Protein: Error, can't read helix class for helix" << helixID; return false; } /* CLASS NUMBER TYPE OF HELIX (COLUMNS 39 - 40) -------------------------------------------------------------- Right-handed alpha (default) 1 Right-handed omega 2 Right-handed pi 3 Right-handed gamma 4 Right-handed 3 - 10 5 Left-handed alpha 6 Left-handed omega 7 Left-handed gamma 8 2 - 7 ribbon/helix 9 Polyproline 10 */ char key; switch (helixClass) { case 1: key = 'H'; break; case 3: key = 'I'; break; case 5: key = 'G'; break; default: key = '-'; break; } int initIndex = d->chains.at(initChainNum).indexOf(initResidue); int endIndex = d->chains.at(initChainNum).indexOf(endResidue); for (int i = initIndex; i < endIndex; ++i) { Residue *residue = d->chains.at(initChainNum).at(i); d->structure.data()[residue->index()] = key; } } } /* COLUMNS DATA TYPE FIELD DEFINITION ------------------------------------------------------------------------------------- 1 - 6 Record name "SHEET " 8 - 10 Integer strand Strand number which starts at 1 for each strand within a sheet and increases by one. 12 - 14 LString(3) sheetID Sheet identifier. 15 - 16 Integer numStrands Number of strands in sheet. 18 - 20 Residue name initResName Residue name of initial residue. 22 Character initChainID Chain identifier of initial residue in strand. 23 - 26 Integer initSeqNum Sequence number of initial residue in strand. 27 AChar initICode Insertion code of initial residue in strand. 29 - 31 Residue name endResName Residue name of terminal residue. 33 Character endChainID Chain identifier of terminal residue. 34 - 37 Integer endSeqNum Sequence number of terminal residue. 38 AChar endICode Insertion code of terminal residue. 39 - 40 Integer sense Sense of strand with respect to previous strand in the sheet. 0 if first strand, 1 if parallel,and -1 if anti-parallel. 42 - 45 Atom curAtom Registration. Atom name in current strand. 46 - 48 Residue name curResName Registration. Residue name in current strand 50 Character curChainId Registration. Chain identifier in current strand. 51 - 54 Integer curResSeq Registration. Residue sequence number in current strand. 55 AChar curICode Registration. Insertion code in current strand. 57 - 60 Atom prevAtom Registration. Atom name in previous strand. 61 - 63 Residue name prevResName Registration. Residue name in previous strand. 65 Character prevChainId Registration. Chain identifier in previous strand. 66 - 69 Integer prevResSeq Registration. Residue sequence number in previous strand. 70 AChar prevICode Registration. Insertion code in previous strand. */ QVariant sheet = d->molecule->property("SHEET"); if (sheet.isValid()) { found = true; QStringList lines = sheet.toString().split('\n'); foreach (const QString &line, lines) { //qDebug() << "line:" << line; bool ok; QString sheetID = line.mid(5, 3); /* int numStrands = line.mid(8, 2).toInt(&ok); if (!ok) { qDebug() << "Protein: Error, can't read interger from numStrands for sheet" << sheetID; return false; } */ // // initial residue // QString initResName = line.mid(11, 3); QString initChainID = line.mid(15, 1); int initChainNum = -1; foreach (Residue *residue, d->molecule->residues()) { if (QString(residue->chainID()) != initChainID) continue; initChainNum = residue->chainNumber(); } if (initChainNum < 0) { qDebug() << "Protein: Error, invalid initChainID for sheet" << sheetID; return false; } int initSeqNum = line.mid(16, 4).toInt(&ok); if (!ok || !initSeqNum) { qDebug() << "Protein: Error, can't read interger from initSeqNum for sheet" << sheetID; return false; } Residue *initResidue = 0; foreach (Residue *residue, d->chains.at(initChainNum)) { if (residue->number().toInt() == initSeqNum) { initResidue = residue; break; } } if (!initResidue) { qDebug() << "Protein: Error, could not find initResidue in the chain for sheet" << sheetID; return false; } if (initResidue->name() != initResName) { qDebug() << "Protein: Error, initResName does not match the residue " "at the specified position for sheet" << sheetID; qDebug() << initResName << "!=" << initResidue->name(); return false; } // // end residue // QString endResName = line.mid(22, 3); QString endChainID = line.mid(26, 1); int endChainNum = -1; foreach (Residue *residue, d->molecule->residues()) { if (QString(residue->chainID()) != endChainID) continue; endChainNum = residue->chainNumber(); } if (endChainNum < 0) { qDebug() << "Protein: Error, invalid endChainID for sheet" << sheetID; return false; } int endSeqNum = line.mid(27, 4).toInt(&ok); if (!ok || !endSeqNum) { qDebug() << "Protein: Error, can't read interger from endSeqNum for sheet" << sheetID; return false; } Residue *endResidue = 0; foreach (Residue *residue, d->chains.at(endChainNum)) { if (residue->number().toInt() == endSeqNum) { endResidue = residue; break; } } if (!endResidue) { qDebug() << "Protein: Error, could not find endResidue in the chain for sheet" << sheetID; return false; } if (endResidue->name() != endResName) { qDebug() << "Protein: Error, endResName does not match the residue " "at the specified position for sheet" << sheetID; qDebug() << endResName << "!=" << endResidue->name(); return false; } char key = '-'; int length = endSeqNum - initSeqNum; if (length == 1) key = 'B'; if (length > 1) key = 'E'; int initIndex = d->chains.at(initChainNum).indexOf(initResidue); int endIndex = d->chains.at(initChainNum).indexOf(endResidue); for (int i = initIndex; i < endIndex; ++i) { Residue *residue = d->chains.at(initChainNum).at(i); d->structure.data()[residue->index()] = key; } } } d->num3turnHelixes = -1; d->num4turnHelixes = -1; d->num5turnHelixes = -1; return found; } int Protein::numChains() const { return d->chains.size(); } QList<unsigned long> Protein::chainAtoms(int index) const { QList<unsigned long> ids; if (index >= d->chains.size()) return ids; foreach (Residue *res, d->chains.at(index)) foreach (unsigned long id, res->atoms()) ids.append(id); return ids; } QList<unsigned long> Protein::chainResidues(int index) const { QList<unsigned long> ids; if (index >= d->chains.size()) return ids; foreach (Residue *res, d->chains.at(index)) ids.append(res->id()); return ids; } /* int Protein::numHelixes(char c) const { int count = 0; foreach (const QVector<Residue*> &residues, d->chains) { // for each chain for (int i = 0 ; i < residues.size(); ++i) { if (d->structure.at(residues.at(i)->index()) == c) { count++; while (d->structure.at(residues.at(i)->index()) == c) ++i; } } } return count; } int Protein::num3turnHelixes() const { if (d->num3turnHelixes >= 0) return d->num3turnHelixes; d->num3turnHelixes = numHelixes('G'); return d->num3turnHelixes; } int Protein::num4turnHelixes() const { if (d->num4turnHelixes >= 0) return d->num4turnHelixes; d->num4turnHelixes = numHelixes('H'); return d->num4turnHelixes; } int Protein::num5turnHelixes() const { if (d->num5turnHelixes >= 0) return d->num5turnHelixes; d->num5turnHelixes = numHelixes('I'); return d->num5turnHelixes; } */ QList<unsigned long> Protein::helixBackboneAtoms(char c, int index) { QList <unsigned long> ids; int count = 0; for (int i = 0 ; i < d->structure.size(); ++i) { if (d->structure.at(i) == c) { if (count == index) { while (d->structure.at(i) == c) { Residue *residue = d->molecule->residue(i); unsigned long O, N, C, CA; foreach (unsigned long id, residue->atoms()) { QString atomId = residue->atomId(id).trimmed(); if (atomId == "N" ) N = id; if (atomId == "CA") CA = id; if (atomId == "C" ) C = id; if (atomId == "O" ) O = id; } ids.append(N); ids.append(CA); ids.append(C); ids.append(O); ++i; } return ids; } count++; // skip to next non 'H' char while (d->structure.at(i) == c) ++i; } } return ids; } /* QList<unsigned long> Protein::helix3BackboneAtoms(int index) { return helixBackboneAtoms('G', index); } QList<unsigned long> Protein::helix4BackboneAtoms(int index) { return helixBackboneAtoms('H', index); } QList<unsigned long> Protein::helix5BackboneAtoms(int index) { return helixBackboneAtoms('I', index); } */ int Protein::residueIndex(Residue *residue) const { return d->chains.at(residue->chainNumber()).indexOf(residue); } bool isAminoAcid(Residue *residue) { QString resname = residue->name(); if (resname == "ALA") return true; if (resname == "ARG") return true; if (resname == "ASN") return true; if (resname == "ASP") return true; if (resname == "CYS") return true; if (resname == "GLU") return true; if (resname == "GLN") return true; if (resname == "GLY") return true; if (resname == "HIS") return true; if (resname == "ILE") return true; if (resname == "LEU") return true; if (resname == "LYS") return true; if (resname == "MET") return true; if (resname == "PHE") return true; if (resname == "PRO") return true; if (resname == "SER") return true; if (resname == "THR") return true; if (resname == "TRP") return true; if (resname == "TYR") return true; if (resname == "VAL") return true; return false; } void Protein::iterateBackward(Atom *prevN, Atom *currC, QVector<bool> &visited) { Residue *residue = currC->residue(); visited[residue->index()] = true; if (!isAminoAcid(residue)) return; d->chains[residue->chainNumber()].prepend(residue); foreach (unsigned long id1, currC->neighbors()) { Atom *nbr1 = d->molecule->atomById(id1); if (nbr1 == prevN) continue; QString nbr1Id = nbr1->residue()->atomId(nbr1->id()).trimmed(); if (nbr1Id == "CA") { foreach (unsigned long id2, nbr1->neighbors()) { Atom *nbr2 = d->molecule->atomById(id2); if (nbr2 == currC) continue; QString nbr2Id = nbr2->residue()->atomId(nbr2->id()).trimmed(); if (nbr2Id == "N") { foreach (unsigned long id3, nbr2->neighbors()) { Atom *nbr3 = d->molecule->atomById(id3); if (nbr3 == nbr1) continue; QString nbr3Id = nbr3->residue()->atomId(nbr3->id()).trimmed(); if (nbr3Id == "C") { if (!visited.at(nbr3->residue()->index())) iterateBackward(nbr2, nbr3, visited); } } } } } else if (nbr1Id == "N") { if (!visited.at(nbr1->residue()->index())) iterateForward(currC, nbr1, visited); } } } void Protein::iterateForward(Atom *prevC, Atom *currN, QVector<bool> &visited) { Residue *residue = currN->residue(); visited[residue->index()] = true; if (!isAminoAcid(residue)) return; d->chains[residue->chainNumber()].append(residue); foreach (unsigned long id1, currN->neighbors()) { Atom *nbr1 = d->molecule->atomById(id1); if (nbr1 == prevC) continue; QString nbr1Id = nbr1->residue()->atomId(nbr1->id()).trimmed(); if (nbr1Id == "CA") { foreach (unsigned long id2, nbr1->neighbors()) { Atom *nbr2 = d->molecule->atomById(id2); if (nbr2 == currN) continue; QString nbr2Id = nbr2->residue()->atomId(nbr2->id()).trimmed(); if (nbr2Id == "C") { foreach (unsigned long id3, nbr2->neighbors()) { Atom *nbr3 = d->molecule->atomById(id3); if (nbr3 == nbr1) continue; QString nbr3Id = nbr3->residue()->atomId(nbr3->id()).trimmed(); if (nbr3Id == "N") { if (!visited.at(nbr3->residue()->index())) iterateForward(nbr2, nbr3, visited); } } } } } else if (nbr1Id == "C") { if (!visited.at(nbr1->residue()->index())) iterateBackward(currN, nbr1, visited); } } } void Protein::sortResiduesByChain() { d->structure.resize(d->molecule->numResidues()); for (int i = 0 ; i < d->structure.size(); ++i) d->structure[i] = '-'; // determine the number of chains unsigned int numChains = 0; foreach (Residue *residue, d->molecule->residues()) { if (!isAminoAcid(residue)) continue; if (residue->chainNumber() > numChains) numChains = residue->chainNumber(); } d->chains.resize(numChains+1); QVector<bool> visited(d->molecule->numResidues()); foreach (Residue *residue, d->molecule->residues()) { if (residue->atoms().size() < 4) continue; foreach (unsigned long id, residue->atoms()) { Atom *atom = d->molecule->atomById(id); QString atomId = residue->atomId(id).trimmed(); if (visited.at(atom->residue()->index())) continue; if (atomId == "N") iterateForward(0, atom, visited); else if (atomId == "CA") iterateBackward(0, atom, visited); } // end atoms in residue } } void Protein::detectHBonds() { d->hbondPairs.resize(d->molecule->numResidues()); NeighborList neighborList(d->molecule, 4.0); for (unsigned int i = 0; i < d->molecule->numAtoms(); ++i) { Atom *atom = d->molecule->atom(i); QList<Atom*> nbrs = neighborList.nbrs(atom); foreach(Atom *nbr, nbrs) { Residue *residue1 = atom->residue(); if (!residue1) continue; Residue *residue2 = nbr->residue(); if (!residue2) continue; if (residue1 == residue2) continue; if (d->hbondPairs.at(residue1->index()).contains(residue2)) continue; int res1 = residueIndex(residue1); int res2 = residueIndex(residue2); int delta = abs(res1 - res2); if (delta <= 2) continue; // residue 1 has the N-H // residue 2 has the C=O if (residue1->atomId(atom->id()).trimmed() != "O") { if (residue2->atomId(nbr->id()).trimmed() != "O") continue; } else { Residue *swap = residue1; residue1 = residue2; residue2 = swap; } Eigen::Vector3d H_pos(Eigen::Vector3d::Zero()); Atom *H = 0, *N = 0, *C = 0, *O = 0; // find N in first residue foreach (unsigned long id, residue1->atoms()) { if (residue1->atomId(id).trimmed() == "N") N = d->molecule->atomById(id); } if (!N) continue; // find neighboring H, or compute it's position if there are no hydrogens foreach (unsigned long nbrId, N->neighbors()) { Atom *neighbor = d->molecule->atomById(nbrId); if (neighbor->isHydrogen()) { H = d->molecule->atomById(nbrId); H_pos = *H->pos(); break; } else { H_pos += *N->pos() - *neighbor->pos(); } } if (!H) { H_pos = *N->pos() + 1.1 * H_pos.normalized(); } // find C & O in residue 2 foreach (unsigned long id, residue2->atoms()) { if (residue2->atomId(id).trimmed() == "C") C = d->molecule->atomById(id); if (residue2->atomId(id).trimmed() == "O") O = d->molecule->atomById(id); } if (!C || !O) continue; // C=O ~ H-N // // C +0.42e O -0.42e // H +0.20e N -0.20e double rON = (*O->pos() - *N->pos()).norm(); double rCH = (*C->pos() - H_pos).norm(); double rOH = (*O->pos() - H_pos).norm(); double rCN = (*C->pos() - *N->pos()).norm(); double eON = 332 * (-0.42 * -0.20) / rON; double eCH = 332 * ( 0.42 * 0.20) / rCH; double eOH = 332 * (-0.42 * 0.20) / rOH; double eCN = 332 * ( 0.42 * -0.20) / rCN; double E = eON + eCH + eOH + eCN; if (E >= -0.5) continue; d->hbondPairs[residue1->index()].append(residue2); d->hbondPairs[residue2->index()].append(residue1); //qDebug() << atom->residue()->index() << "-" << nbr->residue()->index() << "=" << delta; } } } void Protein::detectStructure() { foreach (const QVector<Residue*> &residues, d->chains) { // for each chain foreach (Residue *residue, residues) { // for each residue in the chain //qDebug() << "extending 3-trun helix..."; extendHelix('G', 3, residue, residues); //qDebug() << "3 turn helix:" << d->structure; clearShortPatterns('G', 3); //qDebug() << " cleaned:" << d->structure; //qDebug() << "extending 4-trun helix..."; extendHelix('H', 4, residue, residues); //qDebug() << "4 trun helix:" << d->structure; clearShortPatterns('H', 4); //qDebug() << " cleaned:" << d->structure; //qDebug() << "extending 5-trun helix"; extendHelix('I', 5, residue, residues); //qDebug() << "5 trun helix:" << d->structure; clearShortPatterns('I', 5); //qDebug() << " cleaned:" << d->structure; if (d->structure.at(residue->index()) != '-') continue; //extendSheet(0, residue, residues); } } d->num3turnHelixes = -1; d->num4turnHelixes = -1; d->num5turnHelixes = -1; } void Protein::extendHelix(char c, int turn, Residue *residue, const QVector<Residue*> &residues) { if (d->structure.at(residue->index()) != '-') return; // 4-turn helix foreach (Residue *partner, d->hbondPairs.at(residue->index())) { // for each H-bond partner if (residue->chainNumber() != partner->chainNumber()) continue; int res1 = residues.indexOf(residue); int res2 = residues.indexOf(partner); int delta = abs(res1 - res2); if (delta == turn) { d->structure.data()[residue->index()] = c; int next = res1 + 1; if (next >= residues.size()) return; Residue *nextResidue = residues.at(next); extendHelix(c, turn, nextResidue, residues); } } } void Protein::extendSheet(int delta, Residue *residue, const QVector<Residue*> &residues) { // 4-turn helix foreach (Residue *partner, d->hbondPairs.at(residue->index())) { // for each H-bond partner int res1 = residues.indexOf(residue); int res2 = residues.indexOf(partner); int del = abs(res1 - res2); if ((del == delta) || !delta) { int next = res1 + 1; if (next == residues.size()) continue; Residue *nextResidue = residues.at(next); d->structure.data()[residue->index()] = 'B'; extendSheet(del, nextResidue, residues); } } } void Protein::clearShortPatterns() { clearShortPatterns('G', 3); clearShortPatterns('H', 4); } void Protein::clearShortPatterns(char c, int min) { for (int i = 0 ; i < d->structure.size(); ++i) { if (d->structure.at(i) == c) { QByteArray array; for (int j = i ; j < d->structure.size(); ++j) { if (d->structure.at(j) == c) array.append('-'); else break; } if (array.size() < min) d->structure.replace(i, array.size(), array); i += array.size(); } } } } // End namespace
psavery/avogadro
libavogadro/src/protein.cpp
C++
gpl-2.0
30,592
<?php /** * The language switcher widget * * @since 0.1 */ class PLL_Widget_Languages extends WP_Widget { /** * Constructor * * @since 0.1 */ function __construct() { parent::__construct( 'polylang', __( 'Language Switcher', 'polylang' ), array( 'description' => __( 'Displays a language switcher', 'polylang' ), 'customize_selective_refresh' => true, ) ); } /** * Displays the widget * * @since 0.1 * * @param array $args Display arguments including before_title, after_title, before_widget, and after_widget. * @param array $instance The settings for the particular instance of the widget */ function widget( $args, $instance ) { // Sets a unique id for dropdown $instance['dropdown'] = empty( $instance['dropdown'] ) ? 0 : $args['widget_id']; if ( $list = pll_the_languages( array_merge( $instance, array( 'echo' => 0 ) ) ) ) { $title = empty( $instance['title'] ) ? '' : $instance['title']; /** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */ $title = apply_filters( 'widget_title', $title, $instance, $this->id_base ); echo $args['before_widget']; if ( $title ) { echo $args['before_title'] . $title . $args['after_title']; } if ( $instance['dropdown'] ) { echo '<label class="screen-reader-text" for="' . esc_attr( 'lang_choice_' . $instance['dropdown'] ) . '">' . esc_html__( 'Choose a language', 'polylang' ). '</label>'; echo $list; } else { echo "<ul>\n" . $list . "</ul>\n"; } echo $args['after_widget']; } } /** * Updates the widget options * * @since 0.4 * * @param array $new_instance New settings for this instance as input by the user via form() * @param array $old_instance Old settings for this instance * @return array Settings to save or bool false to cancel saving */ function update( $new_instance, $old_instance ) { $instance['title'] = strip_tags( $new_instance['title'] ); foreach ( array_keys( PLL_Switcher::get_switcher_options( 'widget' ) ) as $key ) { $instance[ $key ] = ! empty( $new_instance[ $key ] ) ? 1 : 0; } return $instance; } /** * Displays the widget form * * @since 0.4 * * @param array $instance Current settings */ function form( $instance ) { // Default values $instance = wp_parse_args( (array) $instance, array_merge( array( 'title' => '' ), PLL_Switcher::get_switcher_options( 'widget', 'default' ) ) ); // Title printf( '<p><label for="%1$s">%2$s</label><input class="widefat" id="%1$s" name="%3$s" type="text" value="%4$s" /></p>', $this->get_field_id( 'title' ), esc_html__( 'Title:', 'polylang' ), $this->get_field_name( 'title' ), esc_attr( $instance['title'] ) ); $fields = ''; foreach ( PLL_Switcher::get_switcher_options( 'widget' ) as $key => $str ) { $fields .= sprintf( '<div%5$s%6$s><input type="checkbox" class="checkbox %7$s" id="%1$s" name="%2$s"%3$s /><label for="%1$s">%4$s</label></div>', $this->get_field_id( $key ), $this->get_field_name( $key ), $instance[ $key ] ? ' checked="checked"' : '', esc_html( $str ), in_array( $key, array( 'show_names', 'show_flags', 'hide_current' ) ) ? ' class="no-dropdown-' . $this->id . '"' : '', ! empty( $instance['dropdown'] ) && in_array( $key, array( 'show_names', 'show_flags', 'hide_current' ) ) ? ' style="display:none;"' : '', 'pll-' . $key ); } echo $fields; // FIXME echoing script in form is not very clean // but it does not work if enqueued properly : // clicking save on a widget makes this code unreachable for the just saved widget ( ?! ) $this->admin_print_script(); } /** * Add javascript to control the language switcher options * * @since 1.3 */ public function admin_print_script() { static $done = false; if ( $done ) { return; } $done = true; ?> <script type='text/javascript'> //<![CDATA[ jQuery( document ).ready( function( $ ) { function pll_toggle( a, test ) { test ? a.show() : a.hide(); } // Remove all options if dropdown is checked $( '.widgets-sortables,.control-section-sidebar' ).on( 'change', '.pll-dropdown', function() { var this_id = $( this ).parent().parent().parent().children( '.widget-id' ).attr( 'value' ); pll_toggle( $( '.no-dropdown-' + this_id ), 'checked' != $( this ).attr( 'checked' ) ); } ); // Disallow unchecking both show names and show flags var options = ['-show_flags', '-show_names']; $.each( options, function( i, v ) { $( '.widgets-sortables,.control-section-sidebar' ).on( 'change', '.pll' + v, function() { var this_id = $( this ).parent().parent().parent().children( '.widget-id' ).attr( 'value' ); if ( 'checked' != $( this ).attr( 'checked' ) ) { $( '#widget-' + this_id + options[ 1-i ] ).prop( 'checked', true ); } } ); } ); } ); //]]> </script><?php } }
leadershipdiamond/leadershipdiamond
wp-content/plugins/polylang/include/widget-languages.php
PHP
gpl-2.0
4,934
/* * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package nsk.jdi.ThreadReference.currentContendedMonitor; import nsk.share.*; import nsk.share.jpda.*; import nsk.share.jdi.*; import com.sun.jdi.*; import java.util.*; import java.io.*; import com.sun.jdi.event.*; import com.sun.jdi.request.*; /** * The test for the implementation of an object of the type <BR> * ThreadReference. <BR> * <BR> * The test checks up that results of the method <BR> * <code>com.sun.jdi.ThreadReference.currentContendedMonitor()</code> <BR> * complies with its spec. <BR> * <BR> * The test checks up that if a target VM doesn't support <BR> * this operation, that is, the method <BR> * VirtualMachine.canGetCurrentContendedMonitor() <BR> * returns false, and a thread in the target VM is suspended, <BR> * invoking the method currentContendedMonitor() on the thread <BR> * throws UnsupportedOperationException. <BR> */ public class currentcm001 { //----------------------------------------------------- templete section static final int PASSED = 0; static final int FAILED = 2; static final int PASS_BASE = 95; //----------------------------------------------------- templete parameters static final String sHeader1 = "\n==> nsk/jdi/ThreadReference/currentContendedMonitor/currentcm001 ", sHeader2 = "--> debugger: ", sHeader3 = "##> debugger: "; //----------------------------------------------------- main method public static void main (String argv[]) { int result = run(argv, System.out); System.exit(result + PASS_BASE); } public static int run (String argv[], PrintStream out) { return new currentcm001().runThis(argv, out); } //-------------------------------------------------- log procedures private static Log logHandler; private static void log1(String message) { logHandler.display(sHeader1 + message); } private static void log2(String message) { logHandler.display(sHeader2 + message); } private static void log3(String message) { logHandler.complain(sHeader3 + message); } // ************************************************ test parameters private String debuggeeName = "nsk.jdi.ThreadReference.currentContendedMonitor.currentcm001a"; private String testedClassName = "nsk.jdi.ThreadReference.currentContendedMonitor.Threadcurrentcm001a"; //String mName = "nsk.jdi.ThreadReference.currentContendedMonitor"; //====================================================== test program //------------------------------------------------------ common section static ArgumentHandler argsHandler; static int waitTime; static VirtualMachine vm = null; //static EventRequestManager eventRManager = null; //static EventQueue eventQueue = null; //static EventSet eventSet = null; ReferenceType testedclass = null; ThreadReference thread2 = null; ThreadReference mainThread = null; static int testExitCode = PASSED; static final int returnCode0 = 0; static final int returnCode1 = 1; static final int returnCode2 = 2; static final int returnCode3 = 3; static final int returnCode4 = 4; //------------------------------------------------------ methods private int runThis (String argv[], PrintStream out) { Debugee debuggee; argsHandler = new ArgumentHandler(argv); logHandler = new Log(out, argsHandler); Binder binder = new Binder(argsHandler, logHandler); if (argsHandler.verbose()) { debuggee = binder.bindToDebugee(debuggeeName + " -vbs"); } else { debuggee = binder.bindToDebugee(debuggeeName); } waitTime = argsHandler.getWaitTime(); IOPipe pipe = new IOPipe(debuggee); debuggee.redirectStderr(out); log2(debuggeeName + " debuggee launched"); debuggee.resume(); String line = pipe.readln(); if ((line == null) || !line.equals("ready")) { log3("signal received is not 'ready' but: " + line); return FAILED; } else { log2("'ready' recieved"); } vm = debuggee.VM(); //------------------------------------------------------ testing section log1(" TESTING BEGINS"); for (int i = 0; ; i++) { pipe.println("newcheck"); line = pipe.readln(); if (line.equals("checkend")) { log2(" : returned string is 'checkend'"); break ; } else if (!line.equals("checkready")) { log3("ERROR: returned string is not 'checkready'"); testExitCode = FAILED; break ; } log1("new checkready: #" + i); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ variable part int expresult = returnCode0; //eventRManager = vm.eventRequestManager(); //eventQueue = vm.eventQueue(); String threadName = "testedThread"; //String breakpointMethod1 = "runt1"; //String breakpointMethod2 = "runt2"; //String bpLine1 = "breakpointLineNumber1"; //String bpLine2 = "breakpointLineNumber2"; //String bpLine3 = "breakpointLineNumber3"; List allThreads = null; ObjectReference monitor = null; ListIterator listIterator = null; List classes = null; //BreakpointRequest breakpRequest1 = null; //BreakpointRequest breakpRequest2 = null; //BreakpointRequest breakpRequest3 = null; label0: { log2("getting ThreadReference objects"); try { allThreads = vm.allThreads(); // classes = vm.classesByName(testedClassName); // testedclass = (ReferenceType) classes.get(0); } catch ( Exception e) { log3("ERROR: Exception at very beginning !? : " + e); expresult = returnCode1; break label0; } listIterator = allThreads.listIterator(); for (;;) { try { mainThread = (ThreadReference) listIterator.next(); if (mainThread.name().equals("main")) break ; } catch ( NoSuchElementException e ) { log3("ERROR: NoSuchElementException for listIterator.next()"); log3("ERROR: NO 'main' thread ?????????!!!!!!!"); expresult = returnCode1; break label0; } } } label1: { if (expresult != 0 ) break label1; log2(" suspending the main thread"); mainThread.suspend(); log2("......checking up on canGetCurrentContendedMonitor()"); if (!vm.canGetCurrentContendedMonitor()) { log2(" !vm.canGetCurrentContendedMonitor()"); log2("......checking up throwing UnsupportedOperationException"); try { monitor = mainThread.currentContendedMonitor(); log3("ERROR: no UnsupportedOperationException thrown"); expresult = returnCode1; } catch ( UnsupportedOperationException e1 ) { log2(" UnsupportedOperationException is thrown"); } catch ( IncompatibleThreadStateException e2 ) { log3("ERROR: IncompatibleThreadStateException for a suspended thread"); expresult = returnCode1; } catch ( Exception e3 ) { log3("ERROR: unspecified Exception is thrown" + e3); expresult = returnCode1; } } log2(" resuming the main thread"); mainThread.resume(); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ log2(" the end of testing"); if (expresult != returnCode0) testExitCode = FAILED; } log1(" TESTING ENDS"); //-------------------------------------------------- test summary section //------------------------------------------------- standard end section pipe.println("quit"); log2("waiting for the debuggee to finish ..."); debuggee.waitFor(); int status = debuggee.getStatus(); if (status != PASSED + PASS_BASE) { log3("debuggee returned UNEXPECTED exit status: " + status + " != PASS_BASE"); testExitCode = FAILED; } else { log2("debuggee returned expected exit status: " + status + " == PASS_BASE"); } if (testExitCode != PASSED) { logHandler.complain("TEST FAILED"); } return testExitCode; } /* * private BreakpointRequest settingBreakpoint(String, String, String) * * It sets up a breakpoint within a given method at given line number * for the thread2 only. * Third parameter is required for any case in future debugging, as if. * * Return codes: * = BreakpointRequest object in case of success * = null in case of an Exception thrown within the method */ /* private BreakpointRequest settingBreakpoint ( String methodName, String bpLine, String property) { log2("setting up a breakpoint: method: '" + methodName + "' line: " + bpLine ); List alllineLocations = null; Location lineLocation = null; BreakpointRequest breakpRequest = null; try { Method method = (Method) testedclass.methodsByName(methodName).get(0); alllineLocations = method.allLineLocations(); int n = ( (IntegerValue) testedclass.getValue(testedclass.fieldByName(bpLine) ) ).value(); if (n > alllineLocations.size()) { log3("ERROR: TEST_ERROR_IN_settingBreakpoint(): number is out of bound of method's lines"); } else { lineLocation = (Location) alllineLocations.get(n); try { breakpRequest = eventRManager.createBreakpointRequest(lineLocation); breakpRequest.putProperty("number", property); breakpRequest.addThreadFilter(thread2); breakpRequest.setSuspendPolicy( EventRequest.SUSPEND_EVENT_THREAD); } catch ( Exception e1 ) { log3("ERROR: inner Exception within settingBreakpoint() : " + e1); breakpRequest = null; } } } catch ( Exception e2 ) { log3("ERROR: ATTENTION: outer Exception within settingBreakpoint() : " + e2); breakpRequest = null; } if (breakpRequest == null) log2(" A BREAKPOINT HAS NOT BEEN SET UP"); else log2(" a breakpoint has been set up"); return breakpRequest; } */ /* * private int breakpoint () * * It removes events from EventQueue until gets first BreakpointEvent. * To get next EventSet value, it uses the method * EventQueue.remove(int timeout) * The timeout argument passed to the method, is "waitTime*60000". * Note: the value of waitTime is set up with * the method ArgumentHandler.getWaitTime() at the beginning of the test. * * Return codes: * = returnCode0 - success; * = returnCode2 - Exception when "eventSet = eventQueue.remove()" is executed * = returnCode3 - default case when loop of processing an event, that is, * an unspecified event was taken from the EventQueue */ /* private int breakpoint () { int returnCode = returnCode0; log2(" waiting for BreakpointEvent"); labelBP: for (;;) { log2(" new: eventSet = eventQueue.remove();"); try { eventSet = eventQueue.remove(waitTime*60000); if (eventSet == null) { log3("ERROR: timeout for waiting for a BreakpintEvent"); returnCode = returnCode3; break labelBP; } } catch ( Exception e ) { log3("ERROR: Exception for eventSet = eventQueue.remove(); : " + e); returnCode = 1; break labelBP; } if (eventSet != null) { log2(" : eventSet != null; size == " + eventSet.size()); EventIterator eIter = eventSet.eventIterator(); Event ev = null; for (; eIter.hasNext(); ) { if (returnCode != returnCode0) break; ev = eIter.nextEvent(); ll: for (int ifor =0; ; ifor++) { try { switch (ifor) { case 0: AccessWatchpointEvent awe = (AccessWatchpointEvent) ev; log2(" AccessWatchpointEvent removed"); break ll; case 1: BreakpointEvent be = (BreakpointEvent) ev; log2(" BreakpointEvent removed"); break labelBP; case 2: ClassPrepareEvent cpe = (ClassPrepareEvent) ev; log2(" ClassPreparEvent removed"); break ll; case 3: ClassUnloadEvent cue = (ClassUnloadEvent) ev; log2(" ClassUnloadEvent removed"); break ll; case 4: ExceptionEvent ee = (ExceptionEvent) ev; log2(" ExceptionEvent removed"); break ll; case 5: MethodEntryEvent mene = (MethodEntryEvent) ev; log2(" MethodEntryEvent removed"); break ll; case 6: MethodExitEvent mexe = (MethodExitEvent) ev; log2(" MethodExiEvent removed"); break ll; case 7: ModificationWatchpointEvent mwe = (ModificationWatchpointEvent) ev; log2(" ModificationWatchpointEvent removed"); break ll; case 8: StepEvent se = (StepEvent) ev; log2(" StepEvent removed"); break ll; case 9: ThreadDeathEvent tde = (ThreadDeathEvent) ev; log2(" ThreadDeathEvent removed"); break ll; case 10: ThreadStartEvent tse = (ThreadStartEvent) ev; log2(" ThreadStartEvent removed"); break ll; case 11: VMDeathEvent vmde = (VMDeathEvent) ev; log2(" VMDeathEvent removed"); break ll; case 12: VMStartEvent vmse = (VMStartEvent) ev; log2(" VMStartEvent removed"); break ll; case 13: WatchpointEvent we = (WatchpointEvent) ev; log2(" WatchpointEvent removed"); break ll; default: log3("ERROR: default case for casting event"); returnCode = returnCode3; break ll; } // switch } catch ( ClassCastException e ) { } // try } // ll: for (int ifor =0; ; ifor++) } // for (; ev.hasNext(); ) } } if (returnCode == returnCode0) log2(" : eventSet == null: EventQueue is empty"); return returnCode; } */ }
md-5/jdk10
test/hotspot/jtreg/vmTestbase/nsk/jdi/ThreadReference/currentContendedMonitor/currentcm001.java
Java
gpl-2.0
18,431
<?php /** * @package EasyBlog * @copyright Copyright (C) 2010 Stack Ideas Private Limited. 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('Restricted access'); ?> <li class="blog-post micro-video<?php echo isset( $customClass ) ? ' item-' . $customClass : '';?>" itemscope itemtype="http://schema.org/Blog"> <!-- @template: Date --> <?php if( $this->getParam( 'show_created_date' ) ){ ?> <!-- Creation date --> <div class="blog-created"> <?php //echo JText::_( 'COM_EASYBLOG_ON' ); ?> <!-- @php --> <time datetime="<?php echo $this->formatDate( '%Y-%m-%d' , $row->{$this->getParam( 'creation_source')} ); ?>"> <div class="blog-text-date"> <?php echo $this->formatDate( '%d %B %Y' , $row->{$this->getParam( 'creation_source')} );?> </div> </time> </div> <?php } ?> <h3 class="blog-title rip" itemprop="name"> <a href="<?php echo EasyBlogRouter::_('index.php?option=com_easyblog&view=entry&id=' . $entry->id ); ?>" itemprop="url"><?php echo $entry->title; ?></a> <?php if( $entry->isFeatured ) { ?><sup class="tag-featured"><?php echo Jtext::_('COM_EASYBLOG_FEATURED_FEATURED'); ?></sup><?php } ?> </h3> <?php //echo $this->fetch( 'blog.meta.php' , array( 'entry' => $entry, 'postedText' => JText::_( 'COM_EASYBLOG_VIDEO_SHARED_BY' ) ) ); ?> <div class="blog-content mts"> <?php if( $entry->videos ){ ?> <p class="video-source"> <?php foreach( $entry->videos as $video ){ ?> <?php echo $video->html;?> <?php } ?> </p> <?php } ?> <?php echo JString::substr( strip_tags( $entry->text ) , 0 , 350 ); ?> ... <?php if( $entry->readmore ) { ?> <div class="blog-readmore mtl mbm"> <a href="<?php echo EasyBlogRouter::_('index.php?option=com_easyblog&view=entry&id=' . $entry->id ); ?>"> <span><?php echo JText::_('COM_EASYBLOG_CONTINUE_READING'); ?></span> </a> </div> <?php } ?> </div> <?php if( $this->getparam( 'show_tags' , true ) && !empty($entry->tags) ){ ?> <div class="mts"> <?php echo $this->fetch( 'tags.item.php' , array( 'tags' => $entry->tags ) ); ?> </div> <?php } ?> </li>
alexinteam/joomla3
components/com_easyblog/themes/vintage/blog.item.simple.video.php
PHP
gpl-2.0
2,454
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2000-2007 Donald N. Allingham # # 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. # # gen.filters.rules/Person/_ChangedSince.py #------------------------------------------------------------------------- # # Standard Python modules # #------------------------------------------------------------------------- from ....const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext #------------------------------------------------------------------------- # # Gramps modules # #------------------------------------------------------------------------- from .._changedsincebase import ChangedSinceBase #------------------------------------------------------------------------- # # ChangedSince # #------------------------------------------------------------------------- class ChangedSince(ChangedSinceBase): """Rule that checks for persons changed since a specific time.""" labels = [ _('Changed after:'), _('but before:') ] name = _('Persons changed after <date time>') description = _("Matches person records changed after a specified " "date-time (yyyy-mm-dd hh:mm:ss) or in the range, if a second " "date-time is given.")
prculley/gramps
gramps/gen/filters/rules/person/_changedsince.py
Python
gpl-2.0
1,921
<?php /* -------------------------------------------------------------- $Id: mail.php 899 2005-04-29 02:40:57Z hhgag $ XT-Commerce - community made shopping http://www.xt-commerce.com Copyright (c) 2003 XT-Commerce -------------------------------------------------------------- based on: (c) 2000-2001 The Exchange Project (earlier name of osCommerce) (c) 2002-2003 osCommerce(mail.php,v 1.9 2002/01/19); www.oscommerce.com (c) 2003 nextcommerce (mail.php,v 1.4 2003/08/14); www.nextcommerce.org Released under the GNU General Public License --------------------------------------------------------------*/ define('HEADING_TITLE', 'Send E-Mail To Customers'); define('TEXT_CUSTOMER', 'Customer:'); define('TEXT_SUBJECT', 'Subject:'); define('TEXT_FROM', 'From:'); define('TEXT_MESSAGE', 'Message:'); define('TEXT_SELECT_CUSTOMER', 'Select Customer'); define('TEXT_ALL_CUSTOMERS', 'All Customers'); define('TEXT_NEWSLETTER_CUSTOMERS', 'To All Newsletter Subscribers'); define('NOTICE_EMAIL_SENT_TO', 'Notice: E-Mail sent to: %s'); define('ERROR_NO_CUSTOMER_SELECTED', 'Error: No customer has been selected.'); ?>
shophelfer/shophelfer.com-shop
lang/french/admin/mail.php
PHP
gpl-2.0
1,158
/*************************************************************************** qgscurveeditorwidget.cpp ------------------------ begin : February 2017 copyright : (C) 2017 by Nyall Dawson email : nyall dot dawson at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgscurveeditorwidget.h" #include "qgsvectorlayer.h" #include <QPainter> #include <QVBoxLayout> #include <QMouseEvent> #include <algorithm> // QWT Charting widget #include <qwt_global.h> #include <qwt_plot_canvas.h> #include <qwt_plot.h> #include <qwt_plot_curve.h> #include <qwt_plot_grid.h> #include <qwt_plot_marker.h> #include <qwt_plot_picker.h> #include <qwt_picker_machine.h> #include <qwt_plot_layout.h> #include <qwt_symbol.h> #include <qwt_legend.h> #include <qwt_plot_renderer.h> #include <qwt_plot_histogram.h> QgsCurveEditorWidget::QgsCurveEditorWidget( QWidget *parent, const QgsCurveTransform &transform ) : QWidget( parent ) , mCurve( transform ) { mPlot = new QwtPlot(); mPlot->setMinimumSize( QSize( 0, 100 ) ); mPlot->setAxisScale( QwtPlot::yLeft, 0, 1 ); mPlot->setAxisScale( QwtPlot::yRight, 0, 1 ); mPlot->setAxisScale( QwtPlot::xBottom, 0, 1 ); mPlot->setAxisScale( QwtPlot::xTop, 0, 1 ); QVBoxLayout *vlayout = new QVBoxLayout(); vlayout->addWidget( mPlot ); setLayout( vlayout ); // hide the ugly canvas frame mPlot->setFrameStyle( QFrame::NoFrame ); QFrame *plotCanvasFrame = dynamic_cast<QFrame *>( mPlot->canvas() ); if ( plotCanvasFrame ) plotCanvasFrame->setFrameStyle( QFrame::NoFrame ); mPlot->enableAxis( QwtPlot::yLeft, false ); mPlot->enableAxis( QwtPlot::xBottom, false ); // add a grid QwtPlotGrid *grid = new QwtPlotGrid(); QwtScaleDiv gridDiv( 0.0, 1.0, QList<double>(), QList<double>(), QList<double>() << 0.2 << 0.4 << 0.6 << 0.8 ); grid->setXDiv( gridDiv ); grid->setYDiv( gridDiv ); grid->setPen( QPen( QColor( 0, 0, 0, 50 ) ) ); grid->attach( mPlot ); mPlotCurve = new QwtPlotCurve(); mPlotCurve->setTitle( QStringLiteral( "Curve" ) ); mPlotCurve->setPen( QPen( QColor( 30, 30, 30 ), 0.0 ) ), mPlotCurve->setRenderHint( QwtPlotItem::RenderAntialiased, true ); mPlotCurve->attach( mPlot ); mPlotFilter = new QgsCurveEditorPlotEventFilter( mPlot ); connect( mPlotFilter, &QgsCurveEditorPlotEventFilter::mousePress, this, &QgsCurveEditorWidget::plotMousePress ); connect( mPlotFilter, &QgsCurveEditorPlotEventFilter::mouseRelease, this, &QgsCurveEditorWidget::plotMouseRelease ); connect( mPlotFilter, &QgsCurveEditorPlotEventFilter::mouseMove, this, &QgsCurveEditorWidget::plotMouseMove ); mPlotCurve->setVisible( true ); updatePlot(); } QgsCurveEditorWidget::~QgsCurveEditorWidget() { if ( mGatherer && mGatherer->isRunning() ) { connect( mGatherer.get(), &QgsHistogramValuesGatherer::finished, mGatherer.get(), &QgsHistogramValuesGatherer::deleteLater ); mGatherer->stop(); ( void )mGatherer.release(); } } void QgsCurveEditorWidget::setCurve( const QgsCurveTransform &curve ) { mCurve = curve; updatePlot(); emit changed(); } void QgsCurveEditorWidget::setHistogramSource( const QgsVectorLayer *layer, const QString &expression ) { if ( !mGatherer ) { mGatherer.reset( new QgsHistogramValuesGatherer() ); connect( mGatherer.get(), &QgsHistogramValuesGatherer::calculatedHistogram, this, [ = ] { mHistogram.reset( new QgsHistogram( mGatherer->histogram() ) ); updateHistogram(); } ); } bool changed = mGatherer->layer() != layer || mGatherer->expression() != expression; if ( changed ) { mGatherer->setExpression( expression ); mGatherer->setLayer( layer ); mGatherer->start(); if ( mGatherer->isRunning() ) { //stop any currently running task mGatherer->stop(); while ( mGatherer->isRunning() ) { QCoreApplication::processEvents(); } } mGatherer->start(); } else { updateHistogram(); } } void QgsCurveEditorWidget::setMinHistogramValueRange( double minValueRange ) { mMinValueRange = minValueRange; updateHistogram(); } void QgsCurveEditorWidget::setMaxHistogramValueRange( double maxValueRange ) { mMaxValueRange = maxValueRange; updateHistogram(); } void QgsCurveEditorWidget::keyPressEvent( QKeyEvent *event ) { if ( event->key() == Qt::Key_Delete || event->key() == Qt::Key_Backspace ) { QList< QgsPointXY > cp = mCurve.controlPoints(); if ( mCurrentPlotMarkerIndex > 0 && mCurrentPlotMarkerIndex < cp.count() - 1 ) { cp.removeAt( mCurrentPlotMarkerIndex ); mCurve.setControlPoints( cp ); updatePlot(); emit changed(); } } } void QgsCurveEditorWidget::plotMousePress( QPointF point ) { mCurrentPlotMarkerIndex = findNearestControlPoint( point ); if ( mCurrentPlotMarkerIndex < 0 ) { // add a new point mCurve.addControlPoint( point.x(), point.y() ); mCurrentPlotMarkerIndex = findNearestControlPoint( point ); emit changed(); } updatePlot(); } int QgsCurveEditorWidget::findNearestControlPoint( QPointF point ) const { double minDist = 3.0 / mPlot->width(); int currentPlotMarkerIndex = -1; QList< QgsPointXY > controlPoints = mCurve.controlPoints(); for ( int i = 0; i < controlPoints.count(); ++i ) { QgsPointXY currentPoint = controlPoints.at( i ); double currentDist; currentDist = std::pow( point.x() - currentPoint.x(), 2.0 ) + std::pow( point.y() - currentPoint.y(), 2.0 ); if ( currentDist < minDist ) { minDist = currentDist; currentPlotMarkerIndex = i; } } return currentPlotMarkerIndex; } void QgsCurveEditorWidget::plotMouseRelease( QPointF ) { } void QgsCurveEditorWidget::plotMouseMove( QPointF point ) { if ( mCurrentPlotMarkerIndex < 0 ) return; QList< QgsPointXY > cp = mCurve.controlPoints(); bool removePoint = false; if ( mCurrentPlotMarkerIndex == 0 ) { point.setX( std::min( point.x(), cp.at( 1 ).x() - 0.01 ) ); } else { removePoint = point.x() <= cp.at( mCurrentPlotMarkerIndex - 1 ).x(); } if ( mCurrentPlotMarkerIndex == cp.count() - 1 ) { point.setX( std::max( point.x(), cp.at( mCurrentPlotMarkerIndex - 1 ).x() + 0.01 ) ); removePoint = false; } else { removePoint = removePoint || point.x() >= cp.at( mCurrentPlotMarkerIndex + 1 ).x(); } if ( removePoint ) { cp.removeAt( mCurrentPlotMarkerIndex ); mCurrentPlotMarkerIndex = -1; } else { cp[ mCurrentPlotMarkerIndex ] = QgsPointXY( point.x(), point.y() ); } mCurve.setControlPoints( cp ); updatePlot(); emit changed(); } void QgsCurveEditorWidget::addPlotMarker( double x, double y, bool isSelected ) { QColor borderColor( 0, 0, 0 ); QColor brushColor = isSelected ? borderColor : QColor( 255, 255, 255, 0 ); QwtPlotMarker *marker = new QwtPlotMarker(); marker->setSymbol( new QwtSymbol( QwtSymbol::Ellipse, QBrush( brushColor ), QPen( borderColor, isSelected ? 2 : 1 ), QSize( 8, 8 ) ) ); marker->setValue( x, y ); marker->attach( mPlot ); marker->setRenderHint( QwtPlotItem::RenderAntialiased, true ); mMarkers << marker; } void QgsCurveEditorWidget::updateHistogram() { if ( !mHistogram ) return; //draw histogram QBrush histoBrush( QColor( 0, 0, 0, 70 ) ); delete mPlotHistogram; mPlotHistogram = createPlotHistogram( histoBrush ); QVector<QwtIntervalSample> dataHisto; int bins = 40; QList<double> edges = mHistogram->binEdges( bins ); QList<int> counts = mHistogram->counts( bins ); // scale counts to 0->1 double max = *std::max_element( counts.constBegin(), counts.constEnd() ); // scale bin edges to fit in 0->1 range if ( !qgsDoubleNear( mMinValueRange, mMaxValueRange ) ) { std::transform( edges.begin(), edges.end(), edges.begin(), [this]( double d ) -> double { return ( d - mMinValueRange ) / ( mMaxValueRange - mMinValueRange ); } ); } for ( int bin = 0; bin < bins; ++bin ) { double binValue = counts.at( bin ) / max; double upperEdge = edges.at( bin + 1 ); dataHisto << QwtIntervalSample( binValue, edges.at( bin ), upperEdge ); } mPlotHistogram->setSamples( dataHisto ); mPlotHistogram->attach( mPlot ); mPlot->replot(); } void QgsCurveEditorWidget::updatePlot() { // remove existing markers Q_FOREACH ( QwtPlotMarker *marker, mMarkers ) { marker->detach(); delete marker; } mMarkers.clear(); QPolygonF curvePoints; QVector< double > x; int i = 0; Q_FOREACH ( const QgsPointXY &point, mCurve.controlPoints() ) { x << point.x(); addPlotMarker( point.x(), point.y(), mCurrentPlotMarkerIndex == i ); i++; } //add extra intermediate points for ( double p = 0; p <= 1.0; p += 0.01 ) { x << p; } std::sort( x.begin(), x.end() ); QVector< double > y = mCurve.y( x ); for ( int j = 0; j < x.count(); ++j ) { curvePoints << QPointF( x.at( j ), y.at( j ) ); } mPlotCurve->setSamples( curvePoints ); mPlot->replot(); } QwtPlotHistogram *QgsCurveEditorWidget::createPlotHistogram( const QBrush &brush, const QPen &pen ) const { QwtPlotHistogram *histogram = new QwtPlotHistogram( QString() ); histogram->setBrush( brush ); if ( pen != Qt::NoPen ) { histogram->setPen( pen ); } else if ( brush.color().lightness() > 200 ) { QPen p; p.setColor( brush.color().darker( 150 ) ); p.setWidth( 0 ); p.setCosmetic( true ); histogram->setPen( p ); } else { histogram->setPen( QPen( Qt::NoPen ) ); } return histogram; } /// @cond PRIVATE QgsCurveEditorPlotEventFilter::QgsCurveEditorPlotEventFilter( QwtPlot *plot ) : QObject( plot ) , mPlot( plot ) { mPlot->canvas()->installEventFilter( this ); } bool QgsCurveEditorPlotEventFilter::eventFilter( QObject *object, QEvent *event ) { if ( !mPlot->isEnabled() ) return QObject::eventFilter( object, event ); switch ( event->type() ) { case QEvent::MouseButtonPress: { const QMouseEvent *mouseEvent = static_cast<QMouseEvent * >( event ); if ( mouseEvent->button() == Qt::LeftButton ) { emit mousePress( mapPoint( mouseEvent->pos() ) ); } break; } case QEvent::MouseMove: { const QMouseEvent *mouseEvent = static_cast<QMouseEvent * >( event ); if ( mouseEvent->buttons() & Qt::LeftButton ) { // only emit when button pressed emit mouseMove( mapPoint( mouseEvent->pos() ) ); } break; } case QEvent::MouseButtonRelease: { const QMouseEvent *mouseEvent = static_cast<QMouseEvent * >( event ); if ( mouseEvent->button() == Qt::LeftButton ) { emit mouseRelease( mapPoint( mouseEvent->pos() ) ); } break; } default: break; } return QObject::eventFilter( object, event ); } QPointF QgsCurveEditorPlotEventFilter::mapPoint( QPointF point ) const { if ( !mPlot ) return QPointF(); return QPointF( mPlot->canvasMap( QwtPlot::xBottom ).invTransform( point.x() ), mPlot->canvasMap( QwtPlot::yLeft ).invTransform( point.y() ) ); } ///@endcond
geopython/QGIS
src/gui/qgscurveeditorwidget.cpp
C++
gpl-2.0
11,754
// License: GPL. For details, see LICENSE file. package org.openstreetmap.josm.gui.widgets; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.BorderFactory; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.JTextComponent; import org.openstreetmap.josm.tools.CheckParameterUtil; import org.openstreetmap.josm.tools.Utils; /** * This is an abstract class for a validator on a text component. * * Subclasses implement {@link #validate()}. {@link #validate()} is invoked whenever * <ul> * <li>the content of the text component changes (the validator is a {@link DocumentListener})</li> * <li>the text component loses focus (the validator is a {@link FocusListener})</li> * <li>the text component is a {@link JosmTextField} and an {@link ActionEvent} is detected</li> * </ul> * * */ public abstract class AbstractTextComponentValidator implements ActionListener, FocusListener, DocumentListener, PropertyChangeListener{ static final private Border ERROR_BORDER = BorderFactory.createLineBorder(Color.RED, 1); static final private Color ERROR_BACKGROUND = new Color(255,224,224); private JTextComponent tc; /** remembers whether the content of the text component is currently valid or not; null means, * we don't know yet */ private Boolean valid = null; // remember the message private String msg; protected void feedbackInvalid(String msg) { if (valid == null || valid || !Utils.equal(msg, this.msg)) { // only provide feedback if the validity has changed. This avoids // unnecessary UI updates. tc.setBorder(ERROR_BORDER); tc.setBackground(ERROR_BACKGROUND); tc.setToolTipText(msg); valid = false; this.msg = msg; } } protected void feedbackDisabled() { feedbackValid(null); } protected void feedbackValid(String msg) { if (valid == null || !valid || !Utils.equal(msg, this.msg)) { // only provide feedback if the validity has changed. This avoids // unnecessary UI updates. tc.setBorder(UIManager.getBorder("TextField.border")); tc.setBackground(UIManager.getColor("TextField.background")); tc.setToolTipText(msg == null ? "" : msg); valid = true; this.msg = msg; } } /** * Replies the decorated text component * * @return the decorated text component */ public JTextComponent getComponent() { return tc; } /** * Creates the validator and weires it to the text component <code>tc</code>. * * @param tc the text component. Must not be null. * @throws IllegalArgumentException thrown if tc is null */ public AbstractTextComponentValidator(JTextComponent tc) throws IllegalArgumentException { this(tc, true); } /** * Alternative constructor that allows to turn off the actionListener. * This can be useful if the enter key stroke needs to be forwarded to the default button in a dialog. */ public AbstractTextComponentValidator(JTextComponent tc, boolean addActionListener) throws IllegalArgumentException { this(tc, true, true, addActionListener); } public AbstractTextComponentValidator(JTextComponent tc, boolean addFocusListener, boolean addDocumentListener, boolean addActionListener) throws IllegalArgumentException { CheckParameterUtil.ensureParameterNotNull(tc, "tc"); this.tc = tc; if (addFocusListener) { tc.addFocusListener(this); } if (addDocumentListener) { tc.getDocument().addDocumentListener(this); } if (addActionListener) { if (tc instanceof JosmTextField) { JosmTextField tf = (JosmTextField)tc; tf.addActionListener(this); } } tc.addPropertyChangeListener("enabled", this); } /** * Implement in subclasses to validate the content of the text component. * */ public abstract void validate(); /** * Replies true if the current content of the decorated text component is valid; * false otherwise * * @return true if the current content of the decorated text component is valid */ public abstract boolean isValid(); /* -------------------------------------------------------------------------------- */ /* interface FocusListener */ /* -------------------------------------------------------------------------------- */ @Override public void focusGained(FocusEvent arg0) {} @Override public void focusLost(FocusEvent arg0) { validate(); } /* -------------------------------------------------------------------------------- */ /* interface ActionListener */ /* -------------------------------------------------------------------------------- */ @Override public void actionPerformed(ActionEvent arg0) { validate(); } /* -------------------------------------------------------------------------------- */ /* interface DocumentListener */ /* -------------------------------------------------------------------------------- */ @Override public void changedUpdate(DocumentEvent arg0) { validate(); } @Override public void insertUpdate(DocumentEvent arg0) { validate(); } @Override public void removeUpdate(DocumentEvent arg0) { validate(); } /* -------------------------------------------------------------------------------- */ /* interface PropertyChangeListener */ /* -------------------------------------------------------------------------------- */ @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("enabled")) { boolean enabled = (Boolean)evt.getNewValue(); if (enabled) { validate(); } else { feedbackDisabled(); } } } }
CURocketry/Ground_Station_GUI
src/org/openstreetmap/josm/gui/widgets/AbstractTextComponentValidator.java
Java
gpl-3.0
6,645
/* * Copyright (c) 2004-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #ifndef __ARCH_SPARC_KERNEL_STATS_HH__ #define __ARCH_SPARC_KERNEL_STATS_HH__ #include <map> #include <stack> #include <string> #include <vector> #include "kern/kernel_stats.hh" namespace SparcISA { namespace Kernel { class Statistics : public ::Kernel::Statistics { public: Statistics() : ::Kernel::Statistics() {} }; } // namespace AlphaISA::Kernel } // namespace AlphaISA #endif // __ARCH_SPARC_KERNEL_STATS_HH__
vineodd/PIMSim
GEM5Simulation/gem5/src/arch/sparc/kernel_stats.hh
C++
gpl-3.0
2,043
/* * Copyright 2008 Free Software Foundation, Inc. * * This software is distributed under the terms of the GNU Public License. * See the COPYING file in the main directory for details. 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/>. */ #define XNDEBUG #include "GSML1FEC.h" #include "GSMCommon.h" #include "RxBurst.h" //#include "GSMSAPMux.h" //#include "GSMConfig.h" #include "GSMTDMA.h" #include "GSM610Tables.h" #include "GSM660Tables.h" #include "GSM690Tables.h" #include "Assert.h" using namespace std; using namespace GSM; /* Compilation flags: NOCONTROL Compile without referencing control layer functions. */ /* Notes on reading the GSM specifications. Every FEC section in GSM 05.03 uses standard names for the bits at different stages of the encoding/decoding process. This is all described formally in GSM 05.03 2.2. "d" -- data bits. The actual payloads from L2 and the vocoders. "p" -- parity bits. These are calculated from d. "u" -- uncoded bits. A concatenation of d, p and inner tail bits. "c" -- coded bits. These are the convolutionally encoded from u. "i" -- interleaved bits. These are the output of the interleaver. "e" -- "encrypted" bits. These are the channel bits in the radio bursts. The "e" bits are call "encrypted" even when encryption is not used. The encoding process is: L2 -> d -> -> calc p -> u -> c -> i -> e -> radio bursts The decoding process is: radio bursts -> e -> i -> c -> u -> check p -> d -> L2 Bit ordering in d is LSB-first in each octet. Bit ordering everywhere else in the OpenBTS code is MSB-first in every field to give contiguous fields across byte boundaries. We use the BitVector::LSB8MSB() method to translate. */ TCHFACCHL1Decoder::TCHFACCHL1Decoder(const TDMAMapping& wMapping) : mTCHU(189), mTCHD(260), mC(456), mClass1_c(mC.head(378)), mClass1A_d(mTCHD.head(50)), mClass2_c(mC.segment(378, 78)), mTCHParity(0x0b, 3, 50), mMapping(wMapping), mMode(MODE_SPEECH_FR) { for (int i = 0; i < 8; i++) { mI[i] = SoftVector(114); } } void TCHFACCHL1Decoder::writeLowSide(const RxBurst& inBurst) { OBJDCOUT("TCHFACCHL1Decoder::writeLowSide " << inBurst); // If the channel is closed, ignore the burst. // if (!active()) { // OBJDCOUT("TCHFACCHL1Decoder::writeLowSide not active, ignoring input"); // return; // } processBurst(inBurst); } bool TCHFACCHL1Decoder::processBurst( const RxBurst& inBurst) { // Accept the burst into the deinterleaving buffer. // Return true if we are ready to interleave. // TODO -- One quick test of burst validity is to look at the tail bits. // We could do that as a double-check against putting garbage into // the interleaver or accepting bad parameters. // Get the physical parameters of the burst. // RSSI is dB wrt full scale. // mRSSI = inBurst.RSSI(); // Timing error is a float in symbol intervals. // mTimingError = inBurst.timingError(); // This flag is used as a half-ass semaphore. // It is cleared when the new value is read. // mPhyNew = true; // The reverse index runs 0..3 as the bursts arrive. // It is the "B" index of GSM 05.03 3.1.3 and 3.1.4. int B = mMapping.reverseMapping(inBurst.time().FN()) % 8; // A negative value means that the demux is misconfigured. assert(B >= 0); OBJDCOUT("TCHFACCHL1Decoder::processBurst B=" << B << " " << inBurst); OBJDCOUT("time=" << inBurst.time().FN() << " ts=" << inBurst.time().TN() << "\n"); // Pull the data fields (e-bits) out of the burst and put them into i[B][]. // GSM 05.03 3.1.4 inBurst.data1().copyToSegment(mI[B], 0); inBurst.data2().copyToSegment(mI[B], 57); // Every 4th frame is the start of a new block. // So if this isn't a "4th" frame, return now. if (B % 4 != 3) return false; // Deinterleave according to the diagonal "phase" of B. // See GSM 05.03 3.1.3. // Deinterleaves i[] to c[] if (B == 3) deinterleave(4); else deinterleave(0); // See if this was the end of a stolen frame, GSM 05.03 4.2.5. bool stolen = inBurst.Hl(); OBJDCOUT("TCHFACCHL!Decoder::processBurst Hl=" << inBurst.Hl() << " Hu=" << inBurst.Hu()); /* if (stolen) { if (decode()) { OBJDCOUT("TCHFACCHL1Decoder::processBurst good FACCH frame"); countGoodFrame(); handleGoodFrame(); } else { OBJDCOUT("TCHFACCHL1Decoder::processBurst bad FACCH frame"); countBadFrame(); } }*/ // Always feed the traffic channel, even on a stolen frame. // decodeTCH will handle the GSM 06.11 bad frmae processing. bool traffic = decodeTCH(stolen); // if (traffic) { OBJDCOUT("TCHFACCHL1Decoder::processBurst good TCH frame"); // countGoodFrame(); // Don't let the channel timeout. // mLock.lock(); // mT3109.set(); // mLock.unlock(); // } // else countBadFrame(); return traffic; } void TCHFACCHL1Decoder::deinterleave(int blockOffset ) { OBJDCOUT("TCHFACCHL1Decoder::deinterleave blockOffset=" << blockOffset); for (int k = 0; k < 456; k++) { int B = ( k + blockOffset ) % 8; int j = 2 * ((49 * k) % 57) + ((k % 8) / 4); mC[k] = mI[B][j]; mI[B][j] = 0.5F; //OBJDCOUT("deinterleave k="<<k<<" B="<<B<<" j="<<j); } } bool TCHFACCHL1Decoder::decodeTCH(bool stolen) { // GSM 05.02 3.1.2, but backwards // If the frame wasn't stolen, we'll update this with parity later. bool good = !stolen; if (!stolen) { // 3.1.2.2 // decode from c[] to u[] mClass1_c.decode(mVCoder, mTCHU); //mC.head(378).decode(mVCoder,mTCHU); // 3.1.2.2 // copy class 2 bits c[] to d[] mClass2_c.sliced().copyToSegment(mTCHD, 182); //mC.segment(378,78).sliced().copyToSegment(mTCHD,182); // 3.1.2.1 // copy class 1 bits u[] to d[] for (unsigned k = 0; k <= 90; k++) { mTCHD[2*k] = mTCHU[k]; mTCHD[2*k+1] = mTCHU[184-k]; } // 3.1.2.1 // check parity of class 1A unsigned sentParity = (~mTCHU.peekField(91, 3)) & 0x07; //unsigned calcParity = mTCHD.head(50).parity(mTCHParity) & 0x07; unsigned calcParity = mClass1A_d.parity(mTCHParity) & 0x07; // 3.1.2.2 // Check the tail bits, too. unsigned tail = mTCHU.peekField(185, 4); OBJDCOUT("TCHFACCHL1Decoder::decodeTCH c[]=" << mC); //OBJDCOUT("TCHFACCHL1Decoder::decodeTCH u[]=" << mTCHU); OBJDCOUT("TCHFACCHL1Decoder::decodeTCH d[]=" << mTCHD); OBJDCOUT("TCHFACCHL1Decoder::decodeTCH sentParity=" << sentParity << " calcParity=" << calcParity << " tail=" << tail); good = (sentParity == calcParity) && (tail == 0); if (good) { if (mMode == MODE_SPEECH_FR) { // Undo Um's importance-sorted bit ordering. // See GSM 05.03 3.1 and Tablee 2. BitVector payload = mVFrame.payload(); mTCHD.unmap(g610BitOrder, 260, payload); mVFrame.pack(mPrevGoodFrame); mPrevGoodFrameLength = 33; } else if (mMode == MODE_SPEECH_EFR) { BitVector payload = mVFrameAMR.payload(); BitVector TCHW(260), EFRBits(244); // Undo Um's EFR bit ordering. mTCHD.unmap(g660BitOrder, 260, TCHW); // Remove repeating bits and CRC to get raw EFR frame (244 bits) for (unsigned k=0; k<71; k++) EFRBits[k] = TCHW[k] & 1; for (unsigned k=73; k<123; k++) EFRBits[k-2] = TCHW[k] & 1; for (unsigned k=125; k<178; k++) EFRBits[k-4] = TCHW[k] & 1; for (unsigned k=180; k<230; k++) EFRBits[k-6] = TCHW[k] & 1; for (unsigned k=232; k<252; k++) EFRBits[k-8] = TCHW[k] & 1; // Map bits as AMR 12.2k EFRBits.map(g690_12_2_BitOrder, 244, payload); // Put the whole frame (hdr + payload) mVFrameAMR.pack(mPrevGoodFrame); mPrevGoodFrameLength = 32; } return true; } } return false; } // vim: ts=4 sw=4
r00tb0x/typhon-vx
mysrc/openbtsstuff/GSML1FEC.cpp
C++
gpl-3.0
8,424
<?php echo get_header(); ?> <?php echo get_partial('content_top'); ?> <?php if ($this->alert->get()) { ?> <div id="notification"> <div class="container"> <div class="row"> <div class="col-md-12"> <?php echo $this->alert->display(); ?> </div> </div> </div> </div> <?php } ?> <div id="page-content"> <div class="container top-spacing"> <div class="row"> <?php echo get_partial('content_left'); ?> <?php if (partial_exists('content_left') AND partial_exists('content_right')) { $class = "col-sm-6 col-md-6"; } else if (partial_exists('content_left') OR partial_exists('content_right')) { $class = "col-sm-9 col-md-9"; } else { $class = "col-md-12"; } ?> <div class="content-wrap <?php echo $class; ?>"> <div class="row"> <div class="col-md-12"> <div class="table-responsive"> <table class="table table-none"> <tr> <td><b><?php echo lang('column_restaurant'); ?></b></td> <td><?php echo $location_name; ?></td> </tr> <tr> <td><b><?php echo lang('column_sale_id'); ?></b></td> <td><?php echo $sale_id; ?> - <?php echo ucwords($sale_type); ?></td> </tr> <tr> <td><b><?php echo lang('column_author'); ?></b></td> <td><?php echo $author; ?></td> </tr> <tr> <td><b><?php echo lang('column_rating'); ?></b></td> <td> <ul class="list-inline rating-inline"> <li><b><?php echo lang('label_quality'); ?></b><br /> <div class="rating rating-star" data-score="<?php echo $quality; ?>" data-readonly="true"></div> </li> <li><b><?php echo lang('label_delivery'); ?></b><br /> <div class="rating rating-star" data-score="<?php echo $delivery; ?>" data-readonly="true"></div> </li> <li><b><?php echo lang('label_service'); ?></b><br /> <div class="rating rating-star" data-score="<?php echo $service; ?>" data-readonly="true"></div> </li> </ul> </td> </tr> <tr> <td><b><?php echo lang('label_review'); ?></b></td> <td><?php echo $review_text; ?></td> </tr> <tr> <td><b><?php echo lang('label_date'); ?></b></td> <td><?php echo $date; ?></td> </tr> </table> </div> </div> <div class="col-md-12"> <div class="buttons"> <a class="btn btn-default" href="<?php echo $back_url; ?>"><?php echo lang('button_back'); ?></a> </div> </div> </div> </div> <?php echo get_partial('content_right'); ?> <?php echo get_partial('content_bottom'); ?> </div> </div> </div> <script type="text/javascript"><!-- $(document).ready(function() { var ratings = <?php echo json_encode(array_values($ratings)); ?>; displayRatings(ratings); }); //--></script> <?php echo get_footer(); ?>
Delitex/test2
main/views/themes/tastyigniter-orange/account/review_view.php
PHP
gpl-3.0
2,971
/* =========================================================================== Copyright (c) 2010-2015 Darkstar Dev Teams 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/ This file is part of DarkStar-server source code. =========================================================================== */ #include "lua_ability.h" /************************************************************************ * * * Конструктор * * * ************************************************************************/ CLuaAbility::CLuaAbility(lua_State *L) { if( !lua_isnil(L,-1) ) { m_PLuaAbility = (CAbility*)(lua_touserdata(L,-1)); lua_pop(L,1); }else{ m_PLuaAbility = nullptr; } } /************************************************************************ * * * Конструктор * * * ************************************************************************/ CLuaAbility::CLuaAbility(CAbility* PAbility) { m_PLuaAbility = PAbility; } inline int32 CLuaAbility::getID(lua_State *L) { DSP_DEBUG_BREAK_IF(m_PLuaAbility == nullptr); lua_pushinteger(L, m_PLuaAbility->getID()); return 1; } inline int32 CLuaAbility::getRecast(lua_State* L) { DSP_DEBUG_BREAK_IF(m_PLuaAbility == nullptr); lua_pushinteger(L, m_PLuaAbility->getRecastTime()); return 1; } inline int32 CLuaAbility::getRange(lua_State* L) { DSP_DEBUG_BREAK_IF(m_PLuaAbility == nullptr); lua_pushinteger(L, m_PLuaAbility->getRange()); return 1; } inline int32 CLuaAbility::setMsg(lua_State *L) { DSP_DEBUG_BREAK_IF(m_PLuaAbility == nullptr); DSP_DEBUG_BREAK_IF(lua_isnil(L,-1) || !lua_isnumber(L,-1)); m_PLuaAbility->setMessage(lua_tointeger(L,-1)); return 0; } inline int32 CLuaAbility::setAnimation(lua_State *L) { DSP_DEBUG_BREAK_IF(m_PLuaAbility == nullptr); DSP_DEBUG_BREAK_IF(lua_isnil(L, -1) || !lua_isnumber(L, -1)); m_PLuaAbility->setAnimationID(lua_tointeger(L, -1)); return 0; } inline int32 CLuaAbility::setRecast(lua_State* L) { DSP_DEBUG_BREAK_IF(m_PLuaAbility == nullptr); DSP_DEBUG_BREAK_IF(lua_isnil(L, -1) || !lua_isnumber(L, -1)); m_PLuaAbility->setRecastTime(lua_tointeger(L, -1)); return 0; } inline int32 CLuaAbility::setCE(lua_State* L) { DSP_DEBUG_BREAK_IF(m_PLuaAbility == nullptr); DSP_DEBUG_BREAK_IF(lua_isnil(L, -1) || !lua_isnumber(L, -1)); m_PLuaAbility->setCE(lua_tointeger(L, -1)); return 0; } inline int32 CLuaAbility::setVE(lua_State* L) { DSP_DEBUG_BREAK_IF(m_PLuaAbility == nullptr); DSP_DEBUG_BREAK_IF(lua_isnil(L, -1) || !lua_isnumber(L, -1)); m_PLuaAbility->setVE(lua_tointeger(L, -1)); return 0; } inline int32 CLuaAbility::setRange(lua_State *L) { DSP_DEBUG_BREAK_IF(m_PLuaAbility == nullptr); DSP_DEBUG_BREAK_IF(lua_isnil(L, -1) || !lua_isnumber(L, -1)); m_PLuaAbility->setRange(lua_tointeger(L, -1)); return 0; } /************************************************************************ * * * Инициализация методов в lua * * * ************************************************************************/ const int8 CLuaAbility::className[] = "CAbility"; Lunar<CLuaAbility>::Register_t CLuaAbility::methods[] = { LUNAR_DECLARE_METHOD(CLuaAbility,getID), LUNAR_DECLARE_METHOD(CLuaAbility,getRecast), LUNAR_DECLARE_METHOD(CLuaAbility,getRange), LUNAR_DECLARE_METHOD(CLuaAbility,setMsg), LUNAR_DECLARE_METHOD(CLuaAbility,setAnimation), LUNAR_DECLARE_METHOD(CLuaAbility,setRecast), LUNAR_DECLARE_METHOD(CLuaAbility,setCE), LUNAR_DECLARE_METHOD(CLuaAbility,setVE), LUNAR_DECLARE_METHOD(CLuaAbility,setRange), {nullptr,nullptr} };
AresTao/darkstar
src/map/lua/lua_ability.cpp
C++
gpl-3.0
4,519
module ActsAsTaggableOn module ActiveRecord module Backports def self.included(base) base.class_eval do named_scope :where, lambda { |conditions| { :conditions => conditions } } named_scope :joins, lambda { |joins| { :joins => joins } } named_scope :group, lambda { |group| { :group => group } } named_scope :order, lambda { |order| { :order => order } } named_scope :select, lambda { |select| { :select => select } } named_scope :limit, lambda { |limit| { :limit => limit } } named_scope :readonly, lambda { |readonly| { :readonly => readonly } } end end end end end
mzemel/kpsu.org
vendor/gems/ruby/1.8/gems/acts-as-taggable-on-2.0.6/lib/acts_as_taggable_on/compatibility/active_record_backports.rb
Ruby
gpl-3.0
725
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2012, Stephen Fromm <sfromm@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: group version_added: "0.0.2" short_description: Add or remove groups requirements: - groupadd - groupdel - groupmod description: - Manage presence of groups on a host. - For Windows targets, use the M(win_group) module instead. options: name: description: - Name of the group to manage. type: str required: true gid: description: - Optional I(GID) to set for the group. type: int state: description: - Whether the group should be present or not on the remote host. type: str choices: [ absent, present ] default: present system: description: - If I(yes), indicates that the group created is a system group. type: bool default: no local: description: - Forces the use of "local" command alternatives on platforms that implement it. - This is useful in environments that use centralized authentication when you want to manipulate the local groups. (e.g. it uses C(lgroupadd) instead of C(groupadd)). - This requires that these commands exist on the targeted host, otherwise it will be a fatal error. type: bool default: no version_added: "2.6" non_unique: description: - This option allows to change the group ID to a non-unique value. Requires C(gid). - Not supported on macOS or BusyBox distributions. type: bool default: no version_added: "2.8" seealso: - module: user - module: win_group author: - Stephen Fromm (@sfromm) ''' EXAMPLES = ''' - name: Ensure group "somegroup" exists group: name: somegroup state: present - name: Ensure group "docker" exists with correct gid group: name: docker state: present gid: 1750 ''' RETURN = r''' gid: description: Group ID of the group. returned: When C(state) is 'present' type: int sample: 1001 name: description: Group name returned: always type: str sample: users state: description: Whether the group is present or not returned: always type: str sample: 'absent' system: description: Whether the group is a system group or not returned: When C(state) is 'present' type: bool sample: False ''' import grp import os from ansible.module_utils._text import to_bytes from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.common.sys_info import get_platform_subclass class Group(object): """ This is a generic Group manipulation class that is subclassed based on platform. A subclass may wish to override the following action methods:- - group_del() - group_add() - group_mod() All subclasses MUST define platform and distribution (which may be None). """ platform = 'Generic' distribution = None GROUPFILE = '/etc/group' def __new__(cls, *args, **kwargs): new_cls = get_platform_subclass(Group) return super(cls, new_cls).__new__(new_cls) def __init__(self, module): self.module = module self.state = module.params['state'] self.name = module.params['name'] self.gid = module.params['gid'] self.system = module.params['system'] self.local = module.params['local'] self.non_unique = module.params['non_unique'] def execute_command(self, cmd): return self.module.run_command(cmd) def group_del(self): if self.local: command_name = 'lgroupdel' else: command_name = 'groupdel' cmd = [self.module.get_bin_path(command_name, True), self.name] return self.execute_command(cmd) def _local_check_gid_exists(self): if self.gid: for gr in grp.getgrall(): if self.gid == gr.gr_gid and self.name != gr.gr_name: self.module.fail_json(msg="GID '{0}' already exists with group '{1}'".format(self.gid, gr.gr_name)) def group_add(self, **kwargs): if self.local: command_name = 'lgroupadd' self._local_check_gid_exists() else: command_name = 'groupadd' cmd = [self.module.get_bin_path(command_name, True)] for key in kwargs: if key == 'gid' and kwargs[key] is not None: cmd.append('-g') cmd.append(str(kwargs[key])) if self.non_unique: cmd.append('-o') elif key == 'system' and kwargs[key] is True: cmd.append('-r') cmd.append(self.name) return self.execute_command(cmd) def group_mod(self, **kwargs): if self.local: command_name = 'lgroupmod' self._local_check_gid_exists() else: command_name = 'groupmod' cmd = [self.module.get_bin_path(command_name, True)] info = self.group_info() for key in kwargs: if key == 'gid': if kwargs[key] is not None and info[2] != int(kwargs[key]): cmd.append('-g') cmd.append(str(kwargs[key])) if self.non_unique: cmd.append('-o') if len(cmd) == 1: return (None, '', '') if self.module.check_mode: return (0, '', '') cmd.append(self.name) return self.execute_command(cmd) def group_exists(self): # The grp module does not distinguish between local and directory accounts. # It's output cannot be used to determine whether or not a group exists locally. # It returns True if the group exists locally or in the directory, so instead # look in the local GROUP file for an existing account. if self.local: if not os.path.exists(self.GROUPFILE): self.module.fail_json(msg="'local: true' specified but unable to find local group file {0} to parse.".format(self.GROUPFILE)) exists = False name_test = '{0}:'.format(self.name) with open(self.GROUPFILE, 'rb') as f: reversed_lines = f.readlines()[::-1] for line in reversed_lines: if line.startswith(to_bytes(name_test)): exists = True break if not exists: self.module.warn( "'local: true' specified and group was not found in {file}. " "The local group may already exist if the local group database exists somewhere other than {file}.".format(file=self.GROUPFILE)) return exists else: try: if grp.getgrnam(self.name): return True except KeyError: return False def group_info(self): if not self.group_exists(): return False try: info = list(grp.getgrnam(self.name)) except KeyError: return False return info # =========================================== class SunOS(Group): """ This is a SunOS Group manipulation class. Solaris doesn't have the 'system' group concept. This overrides the following methods from the generic class:- - group_add() """ platform = 'SunOS' distribution = None GROUPFILE = '/etc/group' def group_add(self, **kwargs): cmd = [self.module.get_bin_path('groupadd', True)] for key in kwargs: if key == 'gid' and kwargs[key] is not None: cmd.append('-g') cmd.append(str(kwargs[key])) if self.non_unique: cmd.append('-o') cmd.append(self.name) return self.execute_command(cmd) # =========================================== class AIX(Group): """ This is a AIX Group manipulation class. This overrides the following methods from the generic class:- - group_del() - group_add() - group_mod() """ platform = 'AIX' distribution = None GROUPFILE = '/etc/group' def group_del(self): cmd = [self.module.get_bin_path('rmgroup', True), self.name] return self.execute_command(cmd) def group_add(self, **kwargs): cmd = [self.module.get_bin_path('mkgroup', True)] for key in kwargs: if key == 'gid' and kwargs[key] is not None: cmd.append('id=' + str(kwargs[key])) elif key == 'system' and kwargs[key] is True: cmd.append('-a') cmd.append(self.name) return self.execute_command(cmd) def group_mod(self, **kwargs): cmd = [self.module.get_bin_path('chgroup', True)] info = self.group_info() for key in kwargs: if key == 'gid': if kwargs[key] is not None and info[2] != int(kwargs[key]): cmd.append('id=' + str(kwargs[key])) if len(cmd) == 1: return (None, '', '') if self.module.check_mode: return (0, '', '') cmd.append(self.name) return self.execute_command(cmd) # =========================================== class FreeBsdGroup(Group): """ This is a FreeBSD Group manipulation class. This overrides the following methods from the generic class:- - group_del() - group_add() - group_mod() """ platform = 'FreeBSD' distribution = None GROUPFILE = '/etc/group' def group_del(self): cmd = [self.module.get_bin_path('pw', True), 'groupdel', self.name] return self.execute_command(cmd) def group_add(self, **kwargs): cmd = [self.module.get_bin_path('pw', True), 'groupadd', self.name] if self.gid is not None: cmd.append('-g') cmd.append(str(self.gid)) if self.non_unique: cmd.append('-o') return self.execute_command(cmd) def group_mod(self, **kwargs): cmd = [self.module.get_bin_path('pw', True), 'groupmod', self.name] info = self.group_info() cmd_len = len(cmd) if self.gid is not None and int(self.gid) != info[2]: cmd.append('-g') cmd.append(str(self.gid)) if self.non_unique: cmd.append('-o') # modify the group if cmd will do anything if cmd_len != len(cmd): if self.module.check_mode: return (0, '', '') return self.execute_command(cmd) return (None, '', '') class DragonFlyBsdGroup(FreeBsdGroup): """ This is a DragonFlyBSD Group manipulation class. It inherits all behaviors from FreeBsdGroup class. """ platform = 'DragonFly' # =========================================== class DarwinGroup(Group): """ This is a Mac macOS Darwin Group manipulation class. This overrides the following methods from the generic class:- - group_del() - group_add() - group_mod() group manipulation are done using dseditgroup(1). """ platform = 'Darwin' distribution = None def group_add(self, **kwargs): cmd = [self.module.get_bin_path('dseditgroup', True)] cmd += ['-o', 'create'] if self.gid is not None: cmd += ['-i', str(self.gid)] elif 'system' in kwargs and kwargs['system'] is True: gid = self.get_lowest_available_system_gid() if gid is not False: self.gid = str(gid) cmd += ['-i', str(self.gid)] cmd += ['-L', self.name] (rc, out, err) = self.execute_command(cmd) return (rc, out, err) def group_del(self): cmd = [self.module.get_bin_path('dseditgroup', True)] cmd += ['-o', 'delete'] cmd += ['-L', self.name] (rc, out, err) = self.execute_command(cmd) return (rc, out, err) def group_mod(self, gid=None): info = self.group_info() if self.gid is not None and int(self.gid) != info[2]: cmd = [self.module.get_bin_path('dseditgroup', True)] cmd += ['-o', 'edit'] if gid is not None: cmd += ['-i', str(gid)] cmd += ['-L', self.name] (rc, out, err) = self.execute_command(cmd) return (rc, out, err) return (None, '', '') def get_lowest_available_system_gid(self): # check for lowest available system gid (< 500) try: cmd = [self.module.get_bin_path('dscl', True)] cmd += ['/Local/Default', '-list', '/Groups', 'PrimaryGroupID'] (rc, out, err) = self.execute_command(cmd) lines = out.splitlines() highest = 0 for group_info in lines: parts = group_info.split(' ') if len(parts) > 1: gid = int(parts[-1]) if gid > highest and gid < 500: highest = gid if highest == 0 or highest == 499: return False return (highest + 1) except Exception: return False class OpenBsdGroup(Group): """ This is a OpenBSD Group manipulation class. This overrides the following methods from the generic class:- - group_del() - group_add() - group_mod() """ platform = 'OpenBSD' distribution = None GROUPFILE = '/etc/group' def group_del(self): cmd = [self.module.get_bin_path('groupdel', True), self.name] return self.execute_command(cmd) def group_add(self, **kwargs): cmd = [self.module.get_bin_path('groupadd', True)] if self.gid is not None: cmd.append('-g') cmd.append(str(self.gid)) if self.non_unique: cmd.append('-o') cmd.append(self.name) return self.execute_command(cmd) def group_mod(self, **kwargs): cmd = [self.module.get_bin_path('groupmod', True)] info = self.group_info() if self.gid is not None and int(self.gid) != info[2]: cmd.append('-g') cmd.append(str(self.gid)) if self.non_unique: cmd.append('-o') if len(cmd) == 1: return (None, '', '') if self.module.check_mode: return (0, '', '') cmd.append(self.name) return self.execute_command(cmd) # =========================================== class NetBsdGroup(Group): """ This is a NetBSD Group manipulation class. This overrides the following methods from the generic class:- - group_del() - group_add() - group_mod() """ platform = 'NetBSD' distribution = None GROUPFILE = '/etc/group' def group_del(self): cmd = [self.module.get_bin_path('groupdel', True), self.name] return self.execute_command(cmd) def group_add(self, **kwargs): cmd = [self.module.get_bin_path('groupadd', True)] if self.gid is not None: cmd.append('-g') cmd.append(str(self.gid)) if self.non_unique: cmd.append('-o') cmd.append(self.name) return self.execute_command(cmd) def group_mod(self, **kwargs): cmd = [self.module.get_bin_path('groupmod', True)] info = self.group_info() if self.gid is not None and int(self.gid) != info[2]: cmd.append('-g') cmd.append(str(self.gid)) if self.non_unique: cmd.append('-o') if len(cmd) == 1: return (None, '', '') if self.module.check_mode: return (0, '', '') cmd.append(self.name) return self.execute_command(cmd) # =========================================== class BusyBoxGroup(Group): """ BusyBox group manipulation class for systems that have addgroup and delgroup. It overrides the following methods: - group_add() - group_del() - group_mod() """ def group_add(self, **kwargs): cmd = [self.module.get_bin_path('addgroup', True)] if self.gid is not None: cmd.extend(['-g', str(self.gid)]) if self.system: cmd.append('-S') cmd.append(self.name) return self.execute_command(cmd) def group_del(self): cmd = [self.module.get_bin_path('delgroup', True), self.name] return self.execute_command(cmd) def group_mod(self, **kwargs): # Since there is no groupmod command, modify /etc/group directly info = self.group_info() if self.gid is not None and self.gid != info[2]: with open('/etc/group', 'rb') as f: b_groups = f.read() b_name = to_bytes(self.name) b_current_group_string = b'%s:x:%d:' % (b_name, info[2]) b_new_group_string = b'%s:x:%d:' % (b_name, self.gid) if b':%d:' % self.gid in b_groups: self.module.fail_json(msg="gid '{gid}' in use".format(gid=self.gid)) if self.module.check_mode: return 0, '', '' b_new_groups = b_groups.replace(b_current_group_string, b_new_group_string) with open('/etc/group', 'wb') as f: f.write(b_new_groups) return 0, '', '' return None, '', '' class AlpineGroup(BusyBoxGroup): platform = 'Linux' distribution = 'Alpine' def main(): module = AnsibleModule( argument_spec=dict( state=dict(type='str', default='present', choices=['absent', 'present']), name=dict(type='str', required=True), gid=dict(type='int'), system=dict(type='bool', default=False), local=dict(type='bool', default=False), non_unique=dict(type='bool', default=False), ), supports_check_mode=True, required_if=[ ['non_unique', True, ['gid']], ], ) group = Group(module) module.debug('Group instantiated - platform %s' % group.platform) if group.distribution: module.debug('Group instantiated - distribution %s' % group.distribution) rc = None out = '' err = '' result = {} result['name'] = group.name result['state'] = group.state if group.state == 'absent': if group.group_exists(): if module.check_mode: module.exit_json(changed=True) (rc, out, err) = group.group_del() if rc != 0: module.fail_json(name=group.name, msg=err) elif group.state == 'present': if not group.group_exists(): if module.check_mode: module.exit_json(changed=True) (rc, out, err) = group.group_add(gid=group.gid, system=group.system) else: (rc, out, err) = group.group_mod(gid=group.gid) if rc is not None and rc != 0: module.fail_json(name=group.name, msg=err) if rc is None: result['changed'] = False else: result['changed'] = True if out: result['stdout'] = out if err: result['stderr'] = err if group.group_exists(): info = group.group_info() result['system'] = group.system result['gid'] = info[2] module.exit_json(**result) if __name__ == '__main__': main()
indrajitr/ansible
lib/ansible/modules/group.py
Python
gpl-3.0
19,765
/* * This file is subject to the terms and conditions defined in * file 'license.txt', which is part of this source code package. */ using System.Collections.Generic; using System.Linq; using System.Text; using SteamKit2.Internal; namespace SteamKit2 { /// <summary> /// This handler handles all interaction with other users on the Steam3 network. /// </summary> public sealed partial class SteamFriends : ClientMsgHandler { object listLock = new object(); List<SteamID> friendList; List<SteamID> clanList; AccountCache cache; internal SteamFriends() { friendList = new List<SteamID>(); clanList = new List<SteamID>(); cache = new AccountCache(); } /// <summary> /// Gets the local user's persona name. /// </summary> /// <returns>The name.</returns> public string GetPersonaName() { return cache.LocalUser.Name; } /// <summary> /// Sets the local user's persona name and broadcasts it over the network. /// </summary> /// <param name="name">The name.</param> public void SetPersonaName( string name ) { // cache the local name right away, so that early calls to SetPersonaState don't reset the set name cache.LocalUser.Name = name; var stateMsg = new ClientMsgProtobuf<CMsgClientChangeStatus>( EMsg.ClientChangeStatus ); stateMsg.Body.persona_state = ( uint )cache.LocalUser.PersonaState; stateMsg.Body.player_name = name; this.Client.Send( stateMsg ); } /// <summary> /// Gets the local user's persona state. /// </summary> /// <returns>The persona state.</returns> public EPersonaState GetPersonaState() { return cache.LocalUser.PersonaState; } /// <summary> /// Sets the local user's persona state and broadcasts it over the network. /// </summary> /// <param name="state">The state.</param> public void SetPersonaState( EPersonaState state ) { cache.LocalUser.PersonaState = state; var stateMsg = new ClientMsgProtobuf<CMsgClientChangeStatus>( EMsg.ClientChangeStatus ); stateMsg.Body.persona_state = ( uint )state; stateMsg.Body.player_name = cache.LocalUser.Name; this.Client.Send( stateMsg ); } /// <summary> /// Gets the friend count of the local user. /// </summary> /// <returns>The number of friends.</returns> public int GetFriendCount() { lock ( listLock ) { return friendList.Count; } } /// <summary> /// Gets a friend by index. /// </summary> /// <param name="index">The index.</param> /// <returns>A valid steamid of a friend if the index is in range; otherwise a steamid representing 0.</returns> public SteamID GetFriendByIndex( int index ) { lock ( listLock ) { if ( index < 0 || index >= friendList.Count ) return 0; return friendList[ index ]; } } /// <summary> /// Gets the persona name of a friend. /// </summary> /// <param name="steamId">The steam id.</param> /// <returns>The name.</returns> public string GetFriendPersonaName( SteamID steamId ) { return cache.GetUser( steamId ).Name; } /// <summary> /// Gets the persona state of a friend. /// </summary> /// <param name="steamId">The steam id.</param> /// <returns>The persona state.</returns> public EPersonaState GetFriendPersonaState( SteamID steamId ) { return cache.GetUser( steamId ).PersonaState; } /// <summary> /// Gets the relationship of a friend. /// </summary> /// <param name="steamId">The steam id.</param> /// <returns>The relationship of the friend to the local user.</returns> public EFriendRelationship GetFriendRelationship( SteamID steamId ) { return cache.GetUser( steamId ).Relationship; } /// <summary> /// Gets the game name of a friend playing a game. /// </summary> /// <param name="steamId">The steam id.</param> /// <returns>The game name of a friend playing a game, or null if they haven't been cached yet.</returns> public string GetFriendGamePlayedName( SteamID steamId ) { return cache.GetUser( steamId ).GameName; } /// <summary> /// Gets the GameID of a friend playing a game. /// </summary> /// <param name="steamId">The steam id.</param> /// <returns>The gameid of a friend playing a game, or 0 if they haven't been cached yet.</returns> public GameID GetFriendGamePlayed( SteamID steamId ) { return cache.GetUser( steamId ).GameID; } /// <summary> /// Gets a SHA-1 hash representing the friend's avatar. /// </summary> /// <param name="steamId">The SteamID of the friend to get the avatar of.</param> /// <returns>A byte array representing a SHA-1 hash of the friend's avatar.</returns> public byte[] GetFriendAvatar( SteamID steamId ) { return cache.GetUser( steamId ).AvatarHash; } /// <summary> /// Gets the count of clans the local user is a member of. /// </summary> /// <returns>The number of clans this user is a member of.</returns> public int GetClanCount() { lock ( listLock ) { return clanList.Count; } } /// <summary> /// Gets a clan SteamID by index. /// </summary> /// <param name="index">The index.</param> /// <returns>A valid steamid of a clan if the index is in range; otherwise a steamid representing 0.</returns> public SteamID GetClanByIndex( int index ) { lock ( listLock ) { if ( index < 0 || index >= clanList.Count ) return 0; return clanList[ index ]; } } /// <summary> /// Gets the name of a clan. /// </summary> /// <param name="steamId">The clan SteamID.</param> /// <returns>The name.</returns> public string GetClanName( SteamID steamId ) { return cache.Clans.GetAccount( steamId ).Name; } /// <summary> /// Gets the relationship of a clan. /// </summary> /// <param name="steamId">The clan steamid.</param> /// <returns>The relationship of the clan to the local user.</returns> public EClanRelationship GetClanRelationship( SteamID steamId ) { return cache.Clans.GetAccount( steamId ).Relationship; } /// <summary> /// Gets a SHA-1 hash representing the clan's avatar. /// </summary> /// <param name="steamId">The SteamID of the clan to get the avatar of.</param> /// <returns>A byte array representing a SHA-1 hash of the clan's avatar, or null if the clan could not be found.</returns> public byte[] GetClanAvatar( SteamID steamId ) { return cache.Clans.GetAccount( steamId ).AvatarHash; } /// <summary> /// Sends a chat message to a friend. /// </summary> /// <param name="target">The target to send to.</param> /// <param name="type">The type of message to send.</param> /// <param name="message">The message to send.</param> public void SendChatMessage( SteamID target, EChatEntryType type, string message ) { var chatMsg = new ClientMsgProtobuf<CMsgClientFriendMsg>( EMsg.ClientFriendMsg ); chatMsg.Body.steamid = target; chatMsg.Body.chat_entry_type = ( int )type; chatMsg.Body.message = Encoding.UTF8.GetBytes( message ); this.Client.Send( chatMsg ); } /// <summary> /// Sends a friend request to a user. /// </summary> /// <param name="accountNameOrEmail">The account name or email of the user.</param> public void AddFriend( string accountNameOrEmail ) { var addFriend = new ClientMsgProtobuf<CMsgClientAddFriend>( EMsg.ClientAddFriend ); addFriend.Body.accountname_or_email_to_add = accountNameOrEmail; this.Client.Send( addFriend ); } /// <summary> /// Sends a friend request to a user. /// </summary> /// <param name="steamId">The SteamID of the friend to add.</param> public void AddFriend( SteamID steamId ) { var addFriend = new ClientMsgProtobuf<CMsgClientAddFriend>( EMsg.ClientAddFriend ); addFriend.Body.steamid_to_add = steamId; this.Client.Send( addFriend ); } /// <summary> /// Removes a friend from your friends list. /// </summary> /// <param name="steamId">The SteamID of the friend to remove.</param> public void RemoveFriend( SteamID steamId ) { var removeFriend = new ClientMsgProtobuf<CMsgClientRemoveFriend>( EMsg.ClientRemoveFriend ); removeFriend.Body.friendid = steamId; this.Client.Send( removeFriend ); } /// <summary> /// Attempts to join a chat room. /// </summary> /// <param name="steamId">The SteamID of the chat room.</param> public void JoinChat( SteamID steamId ) { SteamID chatId = steamId.ConvertToUInt64(); // copy the steamid so we don't modify it var joinChat = new ClientMsg<MsgClientJoinChat>(); if ( chatId.IsClanAccount ) { // this steamid is incorrect, so we'll fix it up chatId.AccountInstance = ( uint )SteamID.ChatInstanceFlags.Clan; chatId.AccountType = EAccountType.Chat; } joinChat.Body.SteamIdChat = chatId; Client.Send( joinChat ); } /// <summary> /// Attempts to leave a chat room. /// </summary> /// <param name="steamId">The SteamID of the chat room.</param> public void LeaveChat( SteamID steamId ) { SteamID chatId = steamId.ConvertToUInt64(); // copy the steamid so we don't modify it var leaveChat = new ClientMsg<MsgClientChatMemberInfo>(); if ( chatId.IsClanAccount ) { // this steamid is incorrect, so we'll fix it up chatId.AccountInstance = ( uint )SteamID.ChatInstanceFlags.Clan; chatId.AccountType = EAccountType.Chat; } leaveChat.Body.SteamIdChat = chatId; leaveChat.Body.Type = EChatInfoType.StateChange; leaveChat.Write( Client.SteamID.ConvertToUInt64() ); // ChatterActedOn leaveChat.Write( ( uint )EChatMemberStateChange.Left ); // StateChange leaveChat.Write( Client.SteamID.ConvertToUInt64() ); // ChatterActedBy Client.Send( leaveChat ); } /// <summary> /// Sends a message to a chat room. /// </summary> /// <param name="steamIdChat">The SteamID of the chat room.</param> /// <param name="type">The message type.</param> /// <param name="message">The message.</param> public void SendChatRoomMessage( SteamID steamIdChat, EChatEntryType type, string message ) { SteamID chatId = steamIdChat.ConvertToUInt64(); // copy the steamid so we don't modify it if ( chatId.IsClanAccount ) { // this steamid is incorrect, so we'll fix it up chatId.AccountInstance = ( uint )SteamID.ChatInstanceFlags.Clan; chatId.AccountType = EAccountType.Chat; } var chatMsg = new ClientMsg<MsgClientChatMsg>(); chatMsg.Body.ChatMsgType = type; chatMsg.Body.SteamIdChatRoom = chatId; chatMsg.Body.SteamIdChatter = Client.SteamID; chatMsg.WriteNullTermString( message, Encoding.UTF8 ); this.Client.Send( chatMsg ); } /// <summary> /// Invites a user to a chat room. /// The results of this action will be available through the <see cref="ChatActionResultCallback"/> callback. /// </summary> /// <param name="steamIdUser">The SteamID of the user to invite.</param> /// <param name="steamIdChat">The SteamID of the chat room to invite the user to.</param> public void InviteUserToChat( SteamID steamIdUser, SteamID steamIdChat ) { SteamID chatId = steamIdChat.ConvertToUInt64(); // copy the steamid so we don't modify it if ( chatId.IsClanAccount ) { // this steamid is incorrect, so we'll fix it up chatId.AccountInstance = (uint)SteamID.ChatInstanceFlags.Clan; chatId.AccountType = EAccountType.Chat; } var inviteMsg = new ClientMsgProtobuf<CMsgClientChatInvite>( EMsg.ClientChatInvite ); inviteMsg.Body.steam_id_chat = chatId; inviteMsg.Body.steam_id_invited = steamIdUser; // steamclient also sends the steamid of the user that did the invitation // we'll mimic that behavior inviteMsg.Body.steam_id_patron = Client.SteamID; this.Client.Send( inviteMsg ); } /// <summary> /// Kicks the specified chat member from the given chat room. /// </summary> /// <param name="steamIdChat">The SteamID of chat room to kick the member from.</param> /// <param name="steamIdMember">The SteamID of the member to kick from the chat.</param> public void KickChatMember( SteamID steamIdChat, SteamID steamIdMember ) { SteamID chatId = steamIdChat.ConvertToUInt64(); // copy the steamid so we don't modify it var kickMember = new ClientMsg<MsgClientChatAction>(); if ( chatId.IsClanAccount ) { // this steamid is incorrect, so we'll fix it up chatId.AccountInstance = ( uint )SteamID.ChatInstanceFlags.Clan; chatId.AccountType = EAccountType.Chat; } kickMember.Body.SteamIdChat = chatId; kickMember.Body.SteamIdUserToActOn = steamIdMember; kickMember.Body.ChatAction = EChatAction.Kick; this.Client.Send( kickMember ); } /// <summary> /// Bans the specified chat member from the given chat room. /// </summary> /// <param name="steamIdChat">The SteamID of chat room to ban the member from.</param> /// <param name="steamIdMember">The SteamID of the member to ban from the chat.</param> public void BanChatMember( SteamID steamIdChat, SteamID steamIdMember ) { SteamID chatId = steamIdChat.ConvertToUInt64(); // copy the steamid so we don't modify it var banMember = new ClientMsg<MsgClientChatAction>(); if ( chatId.IsClanAccount ) { // this steamid is incorrect, so we'll fix it up chatId.AccountInstance = ( uint )SteamID.ChatInstanceFlags.Clan; chatId.AccountType = EAccountType.Chat; } banMember.Body.SteamIdChat = chatId; banMember.Body.SteamIdUserToActOn = steamIdMember; banMember.Body.ChatAction = EChatAction.Ban; this.Client.Send( banMember ); } /// <summary> /// Unbans the specified SteamID from the given chat room. /// </summary> /// <param name="steamIdChat">The SteamID of chat room to unban the member from.</param> /// <param name="steamIdMember">The SteamID of the member to unban from the chat.</param> public void UnbanChatMember( SteamID steamIdChat, SteamID steamIdMember ) { SteamID chatId = steamIdChat.ConvertToUInt64(); // copy the steamid so we don't modify it var unbanMember = new ClientMsg<MsgClientChatAction>(); if ( chatId.IsClanAccount ) { // this steamid is incorrect, so we'll fix it up chatId.AccountInstance = ( uint )SteamID.ChatInstanceFlags.Clan; chatId.AccountType = EAccountType.Chat; } unbanMember.Body.SteamIdChat = chatId; unbanMember.Body.SteamIdUserToActOn = steamIdMember; unbanMember.Body.ChatAction = EChatAction.UnBan; this.Client.Send( unbanMember ); } // the default details to request in most situations const EClientPersonaStateFlag defaultInfoRequest = EClientPersonaStateFlag.PlayerName | EClientPersonaStateFlag.Presence | EClientPersonaStateFlag.SourceID | EClientPersonaStateFlag.GameExtraInfo; /// <summary> /// Requests persona state for a list of specified SteamID. /// Results are returned in <see cref="SteamFriends.PersonaStateCallback"/>. /// </summary> /// <param name="steamIdList">A list of SteamIDs to request the info of.</param> /// <param name="requestedInfo">The requested info flags.</param> public void RequestFriendInfo( IEnumerable<SteamID> steamIdList, EClientPersonaStateFlag requestedInfo = defaultInfoRequest ) { var request = new ClientMsgProtobuf<CMsgClientRequestFriendData>( EMsg.ClientRequestFriendData ); request.Body.friends.AddRange( steamIdList.Select( sID => sID.ConvertToUInt64() ) ); request.Body.persona_state_requested = ( uint )requestedInfo; this.Client.Send( request ); } /// <summary> /// Requests persona state for a specified SteamID. /// Results are returned in <see cref="SteamFriends.PersonaStateCallback"/>. /// </summary> /// <param name="steamId">A SteamID to request the info of.</param> /// <param name="requestedInfo">The requested info flags.</param> public void RequestFriendInfo( SteamID steamId, EClientPersonaStateFlag requestedInfo = defaultInfoRequest ) { RequestFriendInfo( new SteamID[] { steamId }, requestedInfo ); } /// <summary> /// Ignores or unignores a friend on Steam. /// Results are returned in a <see cref="IgnoreFriendCallback"/>. /// </summary> /// <param name="steamId">The SteamID of the friend to ignore or unignore.</param> /// <param name="setIgnore">if set to <c>true</c>, the friend will be ignored; otherwise, they will be unignored.</param> /// <returns>The Job ID of the request. This can be used to find the appropriate <see cref="IgnoreFriendCallback"/>.</returns> public JobID IgnoreFriend( SteamID steamId, bool setIgnore = true ) { var ignore = new ClientMsg<MsgClientSetIgnoreFriend>(); ignore.SourceJobID = Client.GetNextJobID(); ignore.Body.MySteamId = Client.SteamID; ignore.Body.Ignore = ( byte )( setIgnore ? 1 : 0 ); ignore.Body.SteamIdFriend = steamId; this.Client.Send( ignore ); return ignore.SourceJobID; } /// <summary> /// Requests profile information for the given <see cref="SteamID"/>. /// Results are returned in a <see cref="ProfileInfoCallback"/>. /// </summary> /// <param name="steamId">The SteamID of the friend to request the details of.</param> /// <returns>The Job ID of the request. This can be used to find the appropriate <see cref="ProfileInfoCallback"/>.</returns> public JobID RequestProfileInfo( SteamID steamId ) { var request = new ClientMsgProtobuf<CMsgClientFriendProfileInfo>( EMsg.ClientFriendProfileInfo ); request.SourceJobID = Client.GetNextJobID(); request.Body.steamid_friend = steamId; this.Client.Send( request ); return request.SourceJobID; } /// <summary> /// Handles a client message. This should not be called directly. /// </summary> /// <param name="packetMsg">The packet message that contains the data.</param> public override void HandleMsg( IPacketMsg packetMsg ) { switch ( packetMsg.MsgType ) { case EMsg.ClientPersonaState: HandlePersonaState( packetMsg ); break; case EMsg.ClientClanState: HandleClanState( packetMsg ); break; case EMsg.ClientFriendsList: HandleFriendsList( packetMsg ); break; case EMsg.ClientFriendMsgIncoming: HandleFriendMsg( packetMsg ); break; case EMsg.ClientFriendMsgEchoToSender: HandleFriendEchoMsg( packetMsg ); break; case EMsg.ClientAccountInfo: HandleAccountInfo( packetMsg ); break; case EMsg.ClientAddFriendResponse: HandleFriendResponse( packetMsg ); break; case EMsg.ClientChatEnter: HandleChatEnter( packetMsg ); break; case EMsg.ClientChatMsg: HandleChatMsg( packetMsg ); break; case EMsg.ClientChatMemberInfo: HandleChatMemberInfo( packetMsg ); break; case EMsg.ClientChatActionResult: HandleChatActionResult( packetMsg ); break; case EMsg.ClientChatInvite: HandleChatInvite( packetMsg ); break; case EMsg.ClientSetIgnoreFriendResponse: HandleIgnoreFriendResponse( packetMsg ); break; case EMsg.ClientFriendProfileInfoResponse: HandleProfileInfoResponse( packetMsg ); break; } } #region ClientMsg Handlers void HandleAccountInfo( IPacketMsg packetMsg ) { var accInfo = new ClientMsgProtobuf<CMsgClientAccountInfo>( packetMsg ); // cache off our local name cache.LocalUser.Name = accInfo.Body.persona_name; } void HandleFriendMsg( IPacketMsg packetMsg ) { var friendMsg = new ClientMsgProtobuf<CMsgClientFriendMsgIncoming>( packetMsg ); var callback = new FriendMsgCallback( friendMsg.Body ); this.Client.PostCallback( callback ); } void HandleFriendEchoMsg( IPacketMsg packetMsg ) { var friendEchoMsg = new ClientMsgProtobuf<CMsgClientFriendMsgIncoming>( packetMsg ); var callback = new FriendMsgEchoCallback( friendEchoMsg.Body ); this.Client.PostCallback( callback ); } void HandleFriendsList( IPacketMsg packetMsg ) { var list = new ClientMsgProtobuf<CMsgClientFriendsList>( packetMsg ); cache.LocalUser.SteamID = this.Client.SteamID; if ( !list.Body.bincremental ) { // if we're not an incremental update, the message contains all friends, so we should clear our current list lock ( listLock ) { friendList.Clear(); clanList.Clear(); } } // we have to request information for all of our friends because steam only sends persona information for online friends var reqInfo = new ClientMsgProtobuf<CMsgClientRequestFriendData>( EMsg.ClientRequestFriendData ); reqInfo.Body.persona_state_requested = ( uint )defaultInfoRequest; lock ( listLock ) { List<SteamID> friendsToRemove = new List<SteamID>(); List<SteamID> clansToRemove = new List<SteamID>(); foreach ( var friendObj in list.Body.friends ) { SteamID friendId = friendObj.ulfriendid; if ( friendId.IsIndividualAccount ) { var user = cache.GetUser( friendId ); user.Relationship = ( EFriendRelationship )friendObj.efriendrelationship; if ( friendList.Contains( friendId ) ) { // if this is a friend on our list, and they removed us, mark them for removal if ( user.Relationship == EFriendRelationship.None ) friendsToRemove.Add( friendId ); } else { // we don't know about this friend yet, lets add them friendList.Add( friendId ); } } else if ( friendId.IsClanAccount ) { var clan = cache.Clans.GetAccount( friendId ); clan.Relationship = ( EClanRelationship )friendObj.efriendrelationship; if ( clanList.Contains( friendId ) ) { // mark clans we were removed/kicked from // note: not actually sure about the kicked relationship, but i'm using it for good measure if ( clan.Relationship == EClanRelationship.None || clan.Relationship == EClanRelationship.Kicked ) clansToRemove.Add( friendId ); } else { // don't know about this clan, add it clanList.Add( friendId ); } } if ( !list.Body.bincremental ) { // request persona state for our friend & clan list when it's a non-incremental update reqInfo.Body.friends.Add( friendId ); } } // remove anything we marked for removal friendsToRemove.ForEach( f => friendList.Remove( f ) ); clansToRemove.ForEach( c => clanList.Remove( c ) ); } if ( reqInfo.Body.friends.Count > 0 ) { this.Client.Send( reqInfo ); } var callback = new FriendsListCallback( list.Body ); this.Client.PostCallback( callback ); } void HandlePersonaState( IPacketMsg packetMsg ) { var perState = new ClientMsgProtobuf<CMsgClientPersonaState>( packetMsg ); EClientPersonaStateFlag flags = ( EClientPersonaStateFlag )perState.Body.status_flags; foreach ( var friend in perState.Body.friends ) { SteamID friendId = friend.friendid; if ( friendId.IsIndividualAccount ) { User cacheFriend = cache.GetUser( friendId ); if ( ( flags & EClientPersonaStateFlag.PlayerName ) == EClientPersonaStateFlag.PlayerName ) cacheFriend.Name = friend.player_name; if ( ( flags & EClientPersonaStateFlag.Presence ) == EClientPersonaStateFlag.Presence ) { cacheFriend.AvatarHash = friend.avatar_hash; cacheFriend.PersonaState = ( EPersonaState )friend.persona_state; cacheFriend.PersonaStateFlags = ( EPersonaStateFlag )friend.persona_state_flags; } if ( ( flags & EClientPersonaStateFlag.GameDataBlob ) == EClientPersonaStateFlag.GameDataBlob ) { cacheFriend.GameName = friend.game_name; cacheFriend.GameID = friend.gameid; cacheFriend.GameAppID = friend.game_played_app_id; } } else if ( friendId.IsClanAccount ) { Clan cacheClan = cache.Clans.GetAccount( friendId ); if ( ( flags & EClientPersonaStateFlag.PlayerName ) == EClientPersonaStateFlag.PlayerName ) { cacheClan.Name = friend.player_name; } if ( (flags & EClientPersonaStateFlag.Presence) == EClientPersonaStateFlag.Presence ) { cacheClan.AvatarHash = friend.avatar_hash; } } else { } // todo: cache other details/account types? } foreach ( var friend in perState.Body.friends ) { var callback = new PersonaStateCallback( friend ); this.Client.PostCallback( callback ); } } void HandleClanState( IPacketMsg packetMsg ) { var clanState = new ClientMsgProtobuf<CMsgClientClanState>( packetMsg ); var callback = new ClanStateCallback( clanState.Body ); this.Client.PostCallback( callback ); } void HandleFriendResponse( IPacketMsg packetMsg ) { var friendResponse = new ClientMsgProtobuf<CMsgClientAddFriendResponse>( packetMsg ); var callback = new FriendAddedCallback( friendResponse.Body ); this.Client.PostCallback( callback ); } void HandleChatEnter( IPacketMsg packetMsg ) { var chatEnter = new ClientMsg<MsgClientChatEnter>( packetMsg ); var callback = new ChatEnterCallback( chatEnter.Body ); this.Client.PostCallback( callback ); } void HandleChatMsg( IPacketMsg packetMsg ) { var chatMsg = new ClientMsg<MsgClientChatMsg>( packetMsg ); byte[] msgData = chatMsg.Payload.ToArray(); var callback = new ChatMsgCallback( chatMsg.Body, msgData ); this.Client.PostCallback( callback ); } void HandleChatMemberInfo( IPacketMsg packetMsg ) { var membInfo = new ClientMsg<MsgClientChatMemberInfo>( packetMsg ); byte[] payload = membInfo.Payload.ToArray(); var callback = new ChatMemberInfoCallback( membInfo.Body, payload ); this.Client.PostCallback( callback ); } void HandleChatActionResult( IPacketMsg packetMsg ) { var actionResult = new ClientMsg<MsgClientChatActionResult>( packetMsg ); var callback = new ChatActionResultCallback( actionResult.Body ); this.Client.PostCallback( callback ); } void HandleChatInvite( IPacketMsg packetMsg ) { var chatInvite = new ClientMsgProtobuf<CMsgClientChatInvite>( packetMsg ); var callback = new ChatInviteCallback( chatInvite.Body ); this.Client.PostCallback( callback ); } void HandleIgnoreFriendResponse( IPacketMsg packetMsg ) { var response = new ClientMsg<MsgClientSetIgnoreFriendResponse>( packetMsg ); var callback = new IgnoreFriendCallback(response.TargetJobID, response.Body); this.Client.PostCallback( callback ); } void HandleProfileInfoResponse( IPacketMsg packetMsg ) { var response = new ClientMsgProtobuf<CMsgClientFriendProfileInfoResponse>( packetMsg ); var callback = new ProfileInfoCallback( packetMsg.TargetJobID, response.Body ); Client.PostCallback( callback ); } #endregion } }
HellsGuard/ARK-Dedicated-Server-Tool
SteamKit2/Steam/Handlers/SteamFriends/SteamFriends.cs
C#
gpl-3.0
32,668
package org.ovirt.engine.core.bll; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.ovirt.engine.core.bll.context.CommandContext; import org.ovirt.engine.core.common.action.RemoveAllVmImagesParameters; import org.ovirt.engine.core.common.action.RemoveImageParameters; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.VdcReturnValueBase; import org.ovirt.engine.core.common.businessentities.StorageDomain; import org.ovirt.engine.core.common.businessentities.StorageDomainType; import org.ovirt.engine.core.common.businessentities.storage.DiskImage; import org.ovirt.engine.core.common.businessentities.storage.ImageStatus; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.TransactionScopeOption; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.utils.transaction.TransactionMethod; import org.ovirt.engine.core.utils.transaction.TransactionSupport; /** * This command removes all Vm images and all created snapshots both from Irs * and Db. */ @InternalCommandAttribute @NonTransactiveCommandAttribute public class RemoveAllVmImagesCommand<T extends RemoveAllVmImagesParameters> extends VmCommand<T> { public RemoveAllVmImagesCommand(T parameters, CommandContext cmdContext) { super(parameters, cmdContext); } @Override protected void executeVmCommand() { Set<Guid> imagesToBeRemoved = new HashSet<>(); List<DiskImage> images = getParameters().images; if (images == null) { images = ImagesHandler.filterImageDisks(DbFacade.getInstance().getDiskDao().getAllForVm(getVmId()), true, false, true); } for (DiskImage image : images) { if (Boolean.TRUE.equals(image.getActive())) { imagesToBeRemoved.add(image.getImageId()); } } Collection<DiskImage> failedRemoving = new LinkedList<>(); for (final DiskImage image : images) { if (imagesToBeRemoved.contains(image.getImageId())) { VdcReturnValueBase vdcReturnValue = runInternalActionWithTasksContext( VdcActionType.RemoveImage, buildRemoveImageParameters(image) ); if (vdcReturnValue.getSucceeded()) { getReturnValue().getInternalVdsmTaskIdList().addAll(vdcReturnValue.getInternalVdsmTaskIdList()); } else { StorageDomain domain = getStorageDomainDao().get(image.getStorageIds().get(0)); failedRemoving.add(image); log.error("Can't remove image id '{}' for VM id '{}' from domain id '{}' due to: {}.", image.getImageId(), getParameters().getVmId(), image.getStorageIds().get(0), vdcReturnValue.getFault().getMessage()); if (domain.getStorageDomainType() == StorageDomainType.Data) { log.info("Image id '{}' will be set at illegal state with no snapshot id.", image.getImageId()); TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Object>() { @Override public Object runInTransaction() { // If VDSM task didn't succeed to initiate a task we change the disk to at illegal // state. updateDiskImagesToIllegal(image); return true; } }); } else { log.info("Image id '{}' is not on a data domain and will not be marked as illegal.", image.getImageId()); } } } } setActionReturnValue(failedRemoving); setSucceeded(true); } private RemoveImageParameters buildRemoveImageParameters(DiskImage image) { RemoveImageParameters result = new RemoveImageParameters(image.getImageId()); result.setParentCommand(getParameters().getParentCommand()); result.setParentParameters(getParameters().getParentParameters()); result.setDiskImage(image); result.setEntityInfo(getParameters().getEntityInfo()); result.setForceDelete(getParameters().getForceDelete()); result.setShouldLockImage(false); return result; } /** * Update all disks images of specific disk image to illegal state, and set the vm snapshot id to null, since now * they are not connected to any VM. * * @param diskImage - The disk to update. */ private void updateDiskImagesToIllegal(DiskImage diskImage) { List<DiskImage> snapshotDisks = getDbFacade().getDiskImageDao().getAllSnapshotsForImageGroup(diskImage.getId()); for (DiskImage diskSnapshot : snapshotDisks) { diskSnapshot.setVmSnapshotId(null); diskSnapshot.setImageStatus(ImageStatus.ILLEGAL); getDbFacade().getImageDao().update(diskSnapshot.getImage()); } } @Override protected void endVmCommand() { setSucceeded(true); } }
jtux270/translate
ovirt/3.6_source/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/RemoveAllVmImagesCommand.java
Java
gpl-3.0
5,661
#include "flow-stats-in.hh" namespace vigil { Flow_stats::Flow_stats(const ofp_flow_stats* ofs) { *(ofp_flow_stats*) this = *ofs; const ofp_action_header* headers = ofs->actions; size_t n_actions = (ntohs(ofs->length) - sizeof *ofs) / sizeof *headers; v_actions.assign(headers, headers + n_actions); } Flow_stats_in_event::Flow_stats_in_event(const datapathid& dpid, const ofp_stats_reply *osr, std::auto_ptr<Buffer> buf) : Event(static_get_name()), Ofp_msg_event(&osr->header, buf), more((osr->flags & htons(OFPSF_REPLY_MORE)) != 0) { datapath_id = dpid; size_t flow_len = htons(osr->header.length) - sizeof *osr; const ofp_flow_stats* ofs = (ofp_flow_stats*) osr->body; while (flow_len >= sizeof *ofs) { size_t length = ntohs(ofs->length); if (length > flow_len) { break; } flows.push_back(Flow_stats(ofs)); ofs = (const ofp_flow_stats*)((const char*) ofs + length); flow_len -= length; } } } // namespace vigil
zainabg/NOX
src/lib/flow-stats-in.cc
C++
gpl-3.0
1,114
// Copyright (c) Aura development team - Licensed under GNU GPL // For more information, see license file in the main folder namespace Aura.Mabi.Const { /// <summary> /// Race's gender /// </summary> public enum Gender : byte { None, Female, Male, Universal, } public enum SupportRace : byte { None, Elf, Giant, } }
Rai/aura
src/Mabi/Const/Races.cs
C#
gpl-3.0
344
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dot.junit.opcodes.iget_boolean.d; public class T_iget_boolean_12 extends T_iget_boolean_1 { @Override public boolean run(){ return false; } }
s20121035/rk3288_android5.1_repo
cts/tools/vm-tests-tf/src/dot/junit/opcodes/iget_boolean/d/T_iget_boolean_12.java
Java
gpl-3.0
793
// uniCenta oPOS - Touch Friendly Point Of Sale // Copyright (c) 2009-2014 uniCenta & previous Openbravo POS works // http://www.unicenta.com // // This file is part of uniCenta oPOS // // uniCenta oPOS 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. // // uniCenta oPOS 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 uniCenta oPOS. If not, see <http://www.gnu.org/licenses/>. package com.openbravo.data.user; import com.openbravo.basic.BasicException; import com.openbravo.data.loader.LocalRes; import java.util.*; import javax.swing.ListModel; import javax.swing.event.EventListenerList; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; /** * * @author JG uniCenta */ public class BrowsableData implements ListModel { /** * */ protected EventListenerList listeners = new EventListenerList(); private boolean m_bIsAdjusting; private ListProvider m_dataprov; private SaveProvider m_saveprov; private List m_aData; // List<Object> private Comparator m_comparer; /** Creates a new instance of BrowsableData * @param dataprov * @param saveprov * @param c */ public BrowsableData(ListProvider dataprov, SaveProvider saveprov, Comparator c) { m_dataprov = dataprov; m_saveprov = saveprov; m_comparer = c; m_bIsAdjusting = false; m_aData = new ArrayList(); } /** * * @param dataprov * @param saveprov */ public BrowsableData(ListProvider dataprov, SaveProvider saveprov) { this(dataprov, saveprov, null); } /** * * @param dataprov */ public BrowsableData(ListProvider dataprov) { this(dataprov, null, null); } public final void addListDataListener(ListDataListener l) { listeners.add(ListDataListener.class, l); } public final void removeListDataListener(ListDataListener l) { listeners.remove(ListDataListener.class, l); } // Metodos de acceso public final Object getElementAt(int index) { return m_aData.get(index); } public final int getSize() { return m_aData.size(); } /** * * @return */ public final boolean isAdjusting() { return m_bIsAdjusting; } /** * * @param index0 * @param index1 */ protected void fireDataIntervalAdded(int index0, int index1) { m_bIsAdjusting = true; EventListener[] l = listeners.getListeners(ListDataListener.class); ListDataEvent e = null; for (int i = 0; i < l.length; i++) { if (e == null) { e = new ListDataEvent(this, ListDataEvent.INTERVAL_ADDED, index0, index1); } ((ListDataListener) l[i]).intervalAdded(e); } m_bIsAdjusting = false; } /** * * @param index0 * @param index1 */ protected void fireDataContentsChanged(int index0, int index1) { m_bIsAdjusting = true; EventListener[] l = listeners.getListeners(ListDataListener.class); ListDataEvent e = null; for (int i = 0; i < l.length; i++) { if (e == null) { e = new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index0, index1); } ((ListDataListener) l[i]).contentsChanged(e); } m_bIsAdjusting = false; } /** * * @param index0 * @param index1 */ protected void fireDataIntervalRemoved(int index0, int index1) { m_bIsAdjusting = true; EventListener[] l = listeners.getListeners(ListDataListener.class); ListDataEvent e = null; for (int i = 0; i < l.length; i++) { if (e == null) { e = new ListDataEvent(this, ListDataEvent.INTERVAL_REMOVED, index0, index1); } ((ListDataListener) l[i]).intervalRemoved(e); } m_bIsAdjusting = false; } /** * * @throws BasicException */ public void refreshData() throws BasicException { putNewData(m_dataprov == null ? null : m_dataprov.refreshData()); } /** * * @throws BasicException */ public void loadData() throws BasicException { putNewData(m_dataprov == null ? null : m_dataprov.loadData()); } /** * * @throws BasicException */ public void unloadData() throws BasicException { putNewData(null); } /** * * @param l */ public void loadList(List l) { putNewData(l); } /** * * @param c * @throws BasicException */ public void sort(Comparator c) throws BasicException { Collections.sort(m_aData, c); putNewData(m_aData); } /** * * @return */ public final boolean canLoadData() { return m_dataprov != null; } /** * * @return */ public boolean canInsertData() { return m_saveprov != null && m_saveprov.canInsert(); } /** * * @return */ public boolean canDeleteData() { return m_saveprov != null && m_saveprov.canDelete(); } /** * * @return */ public boolean canUpdateData() { return m_saveprov != null && m_saveprov.canUpdate(); } /** * * @param index * @param f * @return * @throws BasicException */ public final int findNext(int index, Finder f) throws BasicException { int i = index + 1; // search up to the end of the recordset while (i < m_aData.size()) { if (f.match(this.getElementAt(i))) { return i; } i++; } // search from the begining i = 0; while (i < index) { if (f.match(this.getElementAt(i))) { return i; } i++; } // No se ha encontrado return -1; } /** * * @param index * @return * @throws BasicException */ public final int removeRecord(int index) throws BasicException { if (canDeleteData() && index >= 0 && index < m_aData.size()) { if (m_saveprov.deleteData(getElementAt(index)) > 0) { // borramos el elemento indicado m_aData.remove(index); // disparamos los eventos fireDataIntervalRemoved(index, index); int newindex; if (index < m_aData.size()) { newindex = index; } else { newindex = m_aData.size() - 1; } return newindex; } else { throw new BasicException(LocalRes.getIntString("exception.nodelete")); } } else { // indice no valido throw new BasicException(LocalRes.getIntString("exception.nodelete")); } } /** * * @param index * @param value * @return * @throws BasicException */ public final int updateRecord(int index, Object value) throws BasicException { if (canUpdateData() && index >= 0 && index < m_aData.size()) { if (m_saveprov.updateData(value) > 0) { // Modificamos el elemento indicado int newindex; if (m_comparer == null) { newindex = index; m_aData.set(newindex, value); } else { // lo movemos newindex = insertionPoint(value); if (newindex == index + 1) { newindex = index; m_aData.set(newindex, value); } else if (newindex > index + 1) { m_aData.remove(index); newindex --; m_aData.add(newindex, value); } else { m_aData.remove(index); m_aData.add(newindex, value); } } if (newindex >= index) { fireDataContentsChanged(index, newindex); } else { fireDataContentsChanged(newindex, index); } return newindex; } else { // fallo la actualizacion throw new BasicException(LocalRes.getIntString("exception.noupdate")); } } else { // registro invalido throw new BasicException(LocalRes.getIntString("exception.noupdate")); } } /** * * @param value * @return * @throws BasicException */ public final int insertRecord(Object value) throws BasicException { if (canInsertData() && m_saveprov.insertData(value) > 0) { int newindex; if (m_comparer == null) { // Anadimos el elemento indicado al final... newindex = m_aData.size(); } else { // lo insertamos en el lugar adecuado newindex = insertionPoint(value); } m_aData.add(newindex, value); // Disparamos la inserccion fireDataIntervalAdded(newindex, newindex); return newindex; } else { throw new BasicException(LocalRes.getIntString("exception.noinsert")); } } private void putNewData(List aData) { int oldSize = m_aData.size(); m_aData = (aData == null) ? new ArrayList() : aData; int newSize = m_aData.size(); // Ordeno si es un Browsabledata ordenado if (m_comparer != null) { Collections.sort(m_aData, m_comparer); } fireDataContentsChanged(0, newSize - 1); if (oldSize > newSize) { fireDataIntervalRemoved(newSize, oldSize - 1); } else if (oldSize < newSize) { fireDataIntervalAdded(oldSize, newSize - 1); } } private final int insertionPoint(Object value) { int low = 0; int high = m_aData.size() - 1; while (low <= high) { int mid = (low + high) >> 1; Object midVal = m_aData.get(mid); int cmp = m_comparer.compare(midVal, value); if (cmp <= 0) { low = mid + 1; } else { high = mid - 1; } } return low; } }
sbandur84/micro-Blagajna
src-data/com/openbravo/data/user/BrowsableData.java
Java
gpl-3.0
11,396
/************************************************************************* * Copyright 2014 Eucalyptus Systems, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. * * Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta * CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you * need additional information or have any questions. * * This file may incorporate work covered under the following copyright * and permission notice: * * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. ************************************************************************/ package com.eucalyptus.simpleworkflow.common.model; import static com.eucalyptus.simpleworkflow.common.model.SimpleWorkflowMessage.FieldRegex; import static com.eucalyptus.simpleworkflow.common.model.SimpleWorkflowMessage.FieldRegexValue; import java.io.Serializable; import javax.annotation.Nonnull; /** * <p> * Used to filter the closed workflow executions in visibility APIs by * their close status. * </p> */ public class CloseStatusFilter implements Serializable { /** * The close status that must match the close status of an execution for * it to meet the criteria of this filter. This field is required. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>COMPLETED, FAILED, CANCELED, TERMINATED, CONTINUED_AS_NEW, TIMED_OUT */ @Nonnull @FieldRegex( FieldRegexValue.CLOSE_STATUS ) private String status; /** * The close status that must match the close status of an execution for * it to meet the criteria of this filter. This field is required. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>COMPLETED, FAILED, CANCELED, TERMINATED, CONTINUED_AS_NEW, TIMED_OUT * * @return The close status that must match the close status of an execution for * it to meet the criteria of this filter. This field is required. * * @see CloseStatus */ public String getStatus() { return status; } /** * The close status that must match the close status of an execution for * it to meet the criteria of this filter. This field is required. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>COMPLETED, FAILED, CANCELED, TERMINATED, CONTINUED_AS_NEW, TIMED_OUT * * @param status The close status that must match the close status of an execution for * it to meet the criteria of this filter. This field is required. * * @see CloseStatus */ public void setStatus(String status) { this.status = status; } /** * The close status that must match the close status of an execution for * it to meet the criteria of this filter. This field is required. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>COMPLETED, FAILED, CANCELED, TERMINATED, CONTINUED_AS_NEW, TIMED_OUT * * @param status The close status that must match the close status of an execution for * it to meet the criteria of this filter. This field is required. * * @return A reference to this updated object so that method calls can be chained * together. * * @see CloseStatus */ public CloseStatusFilter withStatus(String status) { this.status = status; return this; } /** * The close status that must match the close status of an execution for * it to meet the criteria of this filter. This field is required. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>COMPLETED, FAILED, CANCELED, TERMINATED, CONTINUED_AS_NEW, TIMED_OUT * * @param status The close status that must match the close status of an execution for * it to meet the criteria of this filter. This field is required. * * @see CloseStatus */ public void setStatus(CloseStatus status) { this.status = status.toString(); } /** * The close status that must match the close status of an execution for * it to meet the criteria of this filter. This field is required. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>COMPLETED, FAILED, CANCELED, TERMINATED, CONTINUED_AS_NEW, TIMED_OUT * * @param status The close status that must match the close status of an execution for * it to meet the criteria of this filter. This field is required. * * @return A reference to this updated object so that method calls can be chained * together. * * @see CloseStatus */ public CloseStatusFilter withStatus(CloseStatus status) { this.status = status.toString(); return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getStatus() != null) sb.append("Status: " + getStatus() ); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CloseStatusFilter == false) return false; CloseStatusFilter other = (CloseStatusFilter)obj; if (other.getStatus() == null ^ this.getStatus() == null) return false; if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false) return false; return true; } }
eethomas/eucalyptus
clc/modules/simpleworkflow-common/src/main/java/com/eucalyptus/simpleworkflow/common/model/CloseStatusFilter.java
Java
gpl-3.0
7,268
#region license // This file is part of Vocaluxe. // // Vocaluxe 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. // // Vocaluxe 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 Vocaluxe. If not, see <http://www.gnu.org/licenses/>. #endregion using System; using System.Diagnostics; using System.Xml.Serialization; using VocaluxeLib.Draw; using VocaluxeLib.Xml; namespace VocaluxeLib.Menu { [XmlType("Static")] public struct SThemeStatic { [XmlAttribute(AttributeName = "Name")] public string Name; public string Skin; public SThemeColor Color; public SRectF Rect; public SReflection? Reflection; } public sealed class CStatic : CMenuElementBase, IMenuElement, IThemeable { private readonly int _PartyModeID; private SThemeStatic _Theme; public string GetThemeName() { return _Theme.Name; } public bool ThemeLoaded { get; private set; } public bool Selectable { get { return false; } } private CTextureRef _Texture; public CTextureRef Texture { get { return _Texture ?? CBase.Themes.GetSkinTexture(_Theme.Skin, _PartyModeID); } set { _Texture = value; } } public SColorF Color; public bool Reflection; public float ReflectionSpace; public float ReflectionHeight; public float Alpha = 1; public EAspect Aspect = EAspect.Stretch; public CStatic(int partyModeID) { _PartyModeID = partyModeID; } public CStatic(CStatic s) { _PartyModeID = s._PartyModeID; _Texture = s.Texture; Color = s.Color; MaxRect = s.MaxRect; Reflection = s.Reflection; ReflectionSpace = s.ReflectionHeight; ReflectionHeight = s.ReflectionSpace; Alpha = s.Alpha; Visible = s.Visible; } public CStatic(int partyModeID, CTextureRef texture, SColorF color, SRectF rect) { _PartyModeID = partyModeID; _Texture = texture; Color = color; MaxRect = rect; } public CStatic(int partyModeID, string textureSkinName, SColorF color, SRectF rect) { _PartyModeID = partyModeID; _Theme.Skin = textureSkinName; Color = color; MaxRect = rect; } public CStatic(SThemeStatic theme, int partyModeID) { _PartyModeID = partyModeID; _Theme = theme; ThemeLoaded = true; } public bool LoadTheme(string xmlPath, string elementName, CXmlReader xmlReader) { string item = xmlPath + "/" + elementName; ThemeLoaded = true; ThemeLoaded &= xmlReader.GetValue(item + "/Skin", out _Theme.Skin, String.Empty); ThemeLoaded &= xmlReader.TryGetFloatValue(item + "/X", ref _Theme.Rect.X); ThemeLoaded &= xmlReader.TryGetFloatValue(item + "/Y", ref _Theme.Rect.Y); ThemeLoaded &= xmlReader.TryGetFloatValue(item + "/Z", ref _Theme.Rect.Z); ThemeLoaded &= xmlReader.TryGetFloatValue(item + "/W", ref _Theme.Rect.W); ThemeLoaded &= xmlReader.TryGetFloatValue(item + "/H", ref _Theme.Rect.H); if (xmlReader.GetValue(item + "/Color", out _Theme.Color.Name, String.Empty)) ThemeLoaded &= _Theme.Color.Get(_PartyModeID, out Color); else { ThemeLoaded &= xmlReader.TryGetFloatValue(item + "/R", ref Color.R); ThemeLoaded &= xmlReader.TryGetFloatValue(item + "/G", ref Color.G); ThemeLoaded &= xmlReader.TryGetFloatValue(item + "/B", ref Color.B); ThemeLoaded &= xmlReader.TryGetFloatValue(item + "/A", ref Color.A); } _Theme.Color.Color = Color; if (xmlReader.ItemExists(item + "/Reflection")) { Reflection = true; ThemeLoaded &= xmlReader.TryGetFloatValue(item + "/Reflection/Space", ref ReflectionSpace); ThemeLoaded &= xmlReader.TryGetFloatValue(item + "/Reflection/Height", ref ReflectionHeight); _Theme.Reflection = new SReflection(ReflectionHeight, ReflectionSpace); } else { Reflection = false; _Theme.Reflection = null; } if (ThemeLoaded) { _Theme.Name = elementName; LoadSkin(); } return ThemeLoaded; } public void Draw() { Draw(Aspect); } public void Draw(EAspect aspect, float scale = 1f, float zModify = 0f, bool forceDraw = false) { CTextureRef texture = Texture; SRectF bounds = Rect.Scale(scale); bounds.Z += zModify; SRectF rect = texture == null ? bounds : CHelper.FitInBounds(bounds, texture.OrigAspect, aspect); var color = new SColorF(Color.R, Color.G, Color.B, Color.A * Alpha); if (Visible || forceDraw || (CBase.Settings.GetProgramState() == EProgramState.EditTheme)) { if (texture != null) { CBase.Drawing.DrawTexture(texture, rect, color, bounds); if (Reflection) CBase.Drawing.DrawTextureReflection(texture, rect, color, bounds, ReflectionSpace, ReflectionHeight); } else CBase.Drawing.DrawRect(color, rect); } if (Selected && (CBase.Settings.GetProgramState() == EProgramState.EditTheme)) CBase.Drawing.DrawRect(new SColorF(1f, 1f, 1f, 0.5f), rect); } public void UnloadSkin() {} public void LoadSkin() { if (!ThemeLoaded) return; _Theme.Color.Get(_PartyModeID, out Color); MaxRect = _Theme.Rect; Reflection = _Theme.Reflection.HasValue; if (Reflection) { Debug.Assert(_Theme.Reflection != null); ReflectionSpace = _Theme.Reflection.Value.Space; ReflectionHeight = _Theme.Reflection.Value.Height; } } public void ReloadSkin() { UnloadSkin(); LoadSkin(); } public object GetTheme() { return _Theme; } #region ThemeEdit public void MoveElement(int stepX, int stepY) { X += stepX; Y += stepY; _Theme.Rect.X += stepX; _Theme.Rect.Y += stepY; } public void ResizeElement(int stepW, int stepH) { W += stepW; if (W <= 0) W = 1; H += stepH; if (H <= 0) H = 1; _Theme.Rect.W = Rect.W; _Theme.Rect.H = Rect.H; } #endregion ThemeEdit } }
Shiroi/Vocaluxe
VocaluxeLib/Menu/CStatic.cs
C#
gpl-3.0
7,635
from openerp.osv import osv, fields class attributes(osv.Model): _name = "product.attribute" def _get_float_max(self, cr, uid, ids, field_name, arg, context=None): result = dict.fromkeys(ids, 0) if ids: cr.execute(""" SELECT attribute_id, MAX(value) FROM product_attribute_line WHERE attribute_id in (%s) GROUP BY attribute_id """ % ",".join(map(str, ids))) result.update(dict(cr.fetchall())) return result def _get_float_min(self, cr, uid, ids, field_name, arg, context=None): result = dict.fromkeys(ids, 0) if ids: cr.execute(""" SELECT attribute_id, MIN(value) FROM product_attribute_line WHERE attribute_id in (%s) GROUP BY attribute_id """ % ",".join(map(str, ids))) result.update(dict(cr.fetchall())) return result def _get_min_max(self, cr, uid, ids, context=None): result = {} for value in self.pool.get('product.attribute.line').browse(cr, uid, ids, context=context): if value.type == 'float': result[value.attribute_id.id] = True return result.keys() _columns = { 'name': fields.char('Name', translate=True, required=True), 'type': fields.selection([('distinct', 'Textual Value'), ('float', 'Numeric Value')], "Type", required=True), 'value_ids': fields.one2many('product.attribute.value', 'attribute_id', 'Values'), 'attr_product_ids': fields.one2many('product.attribute.line', 'attribute_id', 'Products'), 'float_max': fields.function(_get_float_max, type='float', string="Max", store={ 'product.attribute.line': (_get_min_max, ['value','attribute_id'], 20), }), 'float_min': fields.function(_get_float_min, type='float', string="Min", store={ 'product.attribute.line': (_get_min_max, ['value','attribute_id'], 20), }), 'visible': fields.boolean('Display Filter on Website'), } _defaults = { 'type': 'distinct', 'visible': True, } class attributes_value(osv.Model): _name = "product.attribute.value" _columns = { 'name': fields.char('Value', translate=True, required=True), 'attribute_id': fields.many2one('product.attribute', 'attribute', required=True), 'atr_product_ids': fields.one2many('product.attribute.line', 'value_id', 'Products'), } class attributes_product(osv.Model): _name = "product.attribute.line" _order = 'attribute_id, value_id, value' _columns = { 'value': fields.float('Numeric Value'), 'value_id': fields.many2one('product.attribute.value', 'Textual Value'), 'attribute_id': fields.many2one('product.attribute', 'attribute', required=True), 'product_tmpl_id': fields.many2one('product.template', 'Product', required=True), 'type': fields.related('attribute_id', 'type', type='selection', selection=[('distinct', 'Distinct'), ('float', 'Float')], string='Type'), } def onchange_attribute_id(self, cr, uid, ids, attribute_id, context=None): attribute = self.pool.get('product.attribute').browse(cr, uid, attribute_id, context=context) return {'value': {'type': attribute.type, 'value_id': False, 'value': ''}} class product_template(osv.Model): _inherit = "product.template" _columns = { 'attribute_lines': fields.one2many('product.attribute.line', 'product_tmpl_id', 'Product attributes'), }
ovnicraft/openerp-restaurant
website_sale/models/product_characteristics.py
Python
agpl-3.0
3,642
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.clinical.forms.patientassessmentlistandsearch; public final class FormInfo extends ims.framework.FormInfo { private static final long serialVersionUID = 1L; public FormInfo(Integer formId) { super(formId); } public String getNamespaceName() { return "Clinical"; } public String getFormName() { return "PatientAssessmentListAndSearch"; } public int getWidth() { return 848; } public int getHeight() { return 632; } public String[] getContextVariables() { return new String[] { "_cv_Clinical.PatientAssessment.SelectedAssessment", "_cv_Clinical.ReturnToFormName" }; } public String getLocalVariablesPrefix() { return "_lv_Clinical.PatientAssessmentListAndSearch.__internal_x_context__" + String.valueOf(getFormId()); } public ims.framework.FormInfo[] getComponentsFormInfo() { ims.framework.FormInfo[] componentsInfo = new ims.framework.FormInfo[1]; componentsInfo[0] = new ims.core.forms.mosquery.FormInfo(102256); return componentsInfo; } public String getImagePath() { return ""; } }
open-health-hub/openMAXIMS
openmaxims_workspace/Clinical/src/ims/clinical/forms/patientassessmentlistandsearch/FormInfo.java
Java
agpl-3.0
2,720
<?php /********************************************************************************* * Zurmo is a customer relationship management program developed by * Zurmo, Inc. Copyright (C) 2015 Zurmo Inc. * * Zurmo is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * Zurmo is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive * Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com. * * The interactive user interfaces in original and modified versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the Zurmo * logo and Zurmo copyright notice. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display the words * "Copyright Zurmo Inc. 2015. All rights reserved". ********************************************************************************/ /** * Helper class for working with CampaignItemActivity */ class CampaignItemActivityUtil extends EmailMessageActivityUtil { } ?>
raymondlamwu/zurmotest
app/protected/modules/campaigns/utils/CampaignItemActivityUtil.php
PHP
agpl-3.0
2,280
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5007.25751) * WARNING: DO NOT MODIFY the content of this file * Generated on 16/04/2014, 12:32 * */ package ims.emergency.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Bogdan Tofei */ public class DNWForOutcomeVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.emergency.vo.DNWForOutcomeVo copy(ims.emergency.vo.DNWForOutcomeVo valueObjectDest, ims.emergency.vo.DNWForOutcomeVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_DNW(valueObjectSrc.getID_DNW()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // CurrentStatus valueObjectDest.setCurrentStatus(valueObjectSrc.getCurrentStatus()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createDNWForOutcomeVoCollectionFromDNW(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.emergency.domain.objects.DNW objects. */ public static ims.emergency.vo.DNWForOutcomeVoCollection createDNWForOutcomeVoCollectionFromDNW(java.util.Set domainObjectSet) { return createDNWForOutcomeVoCollectionFromDNW(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.emergency.domain.objects.DNW objects. */ public static ims.emergency.vo.DNWForOutcomeVoCollection createDNWForOutcomeVoCollectionFromDNW(DomainObjectMap map, java.util.Set domainObjectSet) { ims.emergency.vo.DNWForOutcomeVoCollection voList = new ims.emergency.vo.DNWForOutcomeVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.emergency.domain.objects.DNW domainObject = (ims.emergency.domain.objects.DNW) iterator.next(); ims.emergency.vo.DNWForOutcomeVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.emergency.domain.objects.DNW objects. */ public static ims.emergency.vo.DNWForOutcomeVoCollection createDNWForOutcomeVoCollectionFromDNW(java.util.List domainObjectList) { return createDNWForOutcomeVoCollectionFromDNW(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.emergency.domain.objects.DNW objects. */ public static ims.emergency.vo.DNWForOutcomeVoCollection createDNWForOutcomeVoCollectionFromDNW(DomainObjectMap map, java.util.List domainObjectList) { ims.emergency.vo.DNWForOutcomeVoCollection voList = new ims.emergency.vo.DNWForOutcomeVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.emergency.domain.objects.DNW domainObject = (ims.emergency.domain.objects.DNW) domainObjectList.get(i); ims.emergency.vo.DNWForOutcomeVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.emergency.domain.objects.DNW set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractDNWSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.DNWForOutcomeVoCollection voCollection) { return extractDNWSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractDNWSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.DNWForOutcomeVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.emergency.vo.DNWForOutcomeVo vo = voCollection.get(i); ims.emergency.domain.objects.DNW domainObject = DNWForOutcomeVoAssembler.extractDNW(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.emergency.domain.objects.DNW list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractDNWList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.DNWForOutcomeVoCollection voCollection) { return extractDNWList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractDNWList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.DNWForOutcomeVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.emergency.vo.DNWForOutcomeVo vo = voCollection.get(i); ims.emergency.domain.objects.DNW domainObject = DNWForOutcomeVoAssembler.extractDNW(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.emergency.domain.objects.DNW object. * @param domainObject ims.emergency.domain.objects.DNW */ public static ims.emergency.vo.DNWForOutcomeVo create(ims.emergency.domain.objects.DNW domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.emergency.domain.objects.DNW object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.emergency.vo.DNWForOutcomeVo create(DomainObjectMap map, ims.emergency.domain.objects.DNW domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.emergency.vo.DNWForOutcomeVo valueObject = (ims.emergency.vo.DNWForOutcomeVo) map.getValueObject(domainObject, ims.emergency.vo.DNWForOutcomeVo.class); if ( null == valueObject ) { valueObject = new ims.emergency.vo.DNWForOutcomeVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.emergency.domain.objects.DNW */ public static ims.emergency.vo.DNWForOutcomeVo insert(ims.emergency.vo.DNWForOutcomeVo valueObject, ims.emergency.domain.objects.DNW domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.emergency.domain.objects.DNW */ public static ims.emergency.vo.DNWForOutcomeVo insert(DomainObjectMap map, ims.emergency.vo.DNWForOutcomeVo valueObject, ims.emergency.domain.objects.DNW domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_DNW(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // CurrentStatus valueObject.setCurrentStatus(ims.emergency.vo.domain.DNWStatusForTrackingVoAssembler.create(map, domainObject.getCurrentStatus()) ); return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.emergency.domain.objects.DNW extractDNW(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.DNWForOutcomeVo valueObject) { return extractDNW(domainFactory, valueObject, new HashMap()); } public static ims.emergency.domain.objects.DNW extractDNW(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.DNWForOutcomeVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_DNW(); ims.emergency.domain.objects.DNW domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.emergency.domain.objects.DNW)domMap.get(valueObject); } // ims.emergency.vo.DNWForOutcomeVo ID_DNW field is unknown domainObject = new ims.emergency.domain.objects.DNW(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_DNW()); if (domMap.get(key) != null) { return (ims.emergency.domain.objects.DNW)domMap.get(key); } domainObject = (ims.emergency.domain.objects.DNW) domainFactory.getDomainObject(ims.emergency.domain.objects.DNW.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_DNW()); domainObject.setCurrentStatus(ims.emergency.vo.domain.DNWStatusForTrackingVoAssembler.extractDNWStatus(domainFactory, valueObject.getCurrentStatus(), domMap)); return domainObject; } }
open-health-hub/openMAXIMS
openmaxims_workspace/ValueObjects/src/ims/emergency/vo/domain/DNWForOutcomeVoAssembler.java
Java
agpl-3.0
14,908
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5007.25751) * WARNING: DO NOT MODIFY the content of this file * Generated: 16/04/2014, 12:34 * */ package ims.core.admin.pas.domain.objects; /** * * @author Neil McAnaspie * Generated. */ public class AllocatedWardHistory extends ims.domain.DomainObject implements ims.domain.SystemInformationRetainer, java.io.Serializable { public static final int CLASSID = 1014100015; private static final long serialVersionUID = 1014100015L; public static final String CLASSVERSION = "${ClassVersion}"; @Override public boolean shouldCapQuery() { return true; } /** Allocated Ward */ private ims.core.resource.place.domain.objects.Location allocatedWard; /** Allocated Ward Date Time */ private java.util.Date allocatedWardDateTime; /** User who allocated the ward */ private ims.core.configuration.domain.objects.AppUser allocatingUser; /** SystemInformation */ private ims.domain.SystemInformation systemInformation = new ims.domain.SystemInformation(); public AllocatedWardHistory (Integer id, int ver) { super(id, ver); } public AllocatedWardHistory () { super(); } public AllocatedWardHistory (Integer id, int ver, Boolean includeRecord) { super(id, ver, includeRecord); } public Class getRealDomainClass() { return ims.core.admin.pas.domain.objects.AllocatedWardHistory.class; } public ims.core.resource.place.domain.objects.Location getAllocatedWard() { return allocatedWard; } public void setAllocatedWard(ims.core.resource.place.domain.objects.Location allocatedWard) { this.allocatedWard = allocatedWard; } public java.util.Date getAllocatedWardDateTime() { return allocatedWardDateTime; } public void setAllocatedWardDateTime(java.util.Date allocatedWardDateTime) { this.allocatedWardDateTime = allocatedWardDateTime; } public ims.core.configuration.domain.objects.AppUser getAllocatingUser() { return allocatingUser; } public void setAllocatingUser(ims.core.configuration.domain.objects.AppUser allocatingUser) { this.allocatingUser = allocatingUser; } public ims.domain.SystemInformation getSystemInformation() { if (systemInformation == null) systemInformation = new ims.domain.SystemInformation(); return systemInformation; } /** * isConfigurationObject * Taken from the Usage property of the business object, this method will return * a boolean indicating whether this is a configuration object or not * Configuration = true, Instantiation = false */ public static boolean isConfigurationObject() { if ( "Instantiation".equals("Configuration") ) return true; else return false; } public int getClassId() { return CLASSID; } public String getClassVersion() { return CLASSVERSION; } public String toAuditString() { StringBuffer auditStr = new StringBuffer(); auditStr.append("\r\n*allocatedWard* :"); if (allocatedWard != null) { auditStr.append(toShortClassName(allocatedWard)); auditStr.append(allocatedWard.getId()); } auditStr.append("; "); auditStr.append("\r\n*allocatedWardDateTime* :"); auditStr.append(allocatedWardDateTime); auditStr.append("; "); auditStr.append("\r\n*allocatingUser* :"); if (allocatingUser != null) { auditStr.append(toShortClassName(allocatingUser)); auditStr.append(allocatingUser.getId()); } auditStr.append("; "); return auditStr.toString(); } public String toXMLString() { return toXMLString(new java.util.HashMap()); } public String toXMLString(java.util.HashMap domMap) { StringBuffer sb = new StringBuffer(); sb.append("<class type=\"" + this.getClass().getName() + "\" "); sb.append(" id=\"" + this.getId() + "\""); sb.append(" source=\"" + ims.configuration.EnvironmentConfig.getImportExportSourceName() + "\" "); sb.append(" classVersion=\"" + this.getClassVersion() + "\" "); sb.append(" component=\"" + this.getIsComponentClass() + "\" >"); if (domMap.get(this) == null) { domMap.put(this, this); sb.append(this.fieldsToXMLString(domMap)); } sb.append("</class>"); String keyClassName = "AllocatedWardHistory"; String externalSource = ims.configuration.EnvironmentConfig.getImportExportSourceName(); ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + this.getId()); if (impObj == null) { impObj = new ims.configuration.ImportedObject(); impObj.setExternalId(this.getId()); impObj.setExternalSource(externalSource); impObj.setDomainObject(this); impObj.setLocalId(this.getId()); impObj.setClassName(keyClassName); domMap.put(keyClassName + "_" + externalSource + "_" + this.getId(), impObj); } return sb.toString(); } public String fieldsToXMLString(java.util.HashMap domMap) { StringBuffer sb = new StringBuffer(); if (this.getAllocatedWard() != null) { sb.append("<allocatedWard>"); sb.append(this.getAllocatedWard().toXMLString(domMap)); sb.append("</allocatedWard>"); } if (this.getAllocatedWardDateTime() != null) { sb.append("<allocatedWardDateTime>"); sb.append(new ims.framework.utils.DateTime(this.getAllocatedWardDateTime()).toString(ims.framework.utils.DateTimeFormat.MILLI)); sb.append("</allocatedWardDateTime>"); } if (this.getAllocatingUser() != null) { sb.append("<allocatingUser>"); sb.append(this.getAllocatingUser().toXMLString(domMap)); sb.append("</allocatingUser>"); } return sb.toString(); } public static java.util.List fromListXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.List list, java.util.HashMap domMap) throws Exception { if (list == null) list = new java.util.ArrayList(); fillListFromXMLString(list, el, factory, domMap); return list; } public static java.util.Set fromSetXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.Set set, java.util.HashMap domMap) throws Exception { if (set == null) set = new java.util.HashSet(); fillSetFromXMLString(set, el, factory, domMap); return set; } private static void fillSetFromXMLString(java.util.Set set, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return; java.util.List cl = el.elements("class"); int size = cl.size(); java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i); AllocatedWardHistory domainObject = getAllocatedWardHistoryfromXML(itemEl, factory, domMap); if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!set.contains(domainObject)) set.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = set.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { set.remove(iter.next()); } } private static void fillListFromXMLString(java.util.List list, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return; java.util.List cl = el.elements("class"); int size = cl.size(); for(int i=0; i<size; i++) { org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i); AllocatedWardHistory domainObject = getAllocatedWardHistoryfromXML(itemEl, factory, domMap); if (domainObject == null) { continue; } int domIdx = list.indexOf(domainObject); if (domIdx == -1) { list.add(i, domainObject); } else if (i != domIdx && i < list.size()) { Object tmp = list.get(i); list.set(i, list.get(domIdx)); list.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=list.size(); while (i1 > size) { list.remove(i1-1); i1=list.size(); } } public static AllocatedWardHistory getAllocatedWardHistoryfromXML(String xml, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { org.dom4j.Document doc = new org.dom4j.io.SAXReader().read(new org.xml.sax.InputSource(xml)); return getAllocatedWardHistoryfromXML(doc.getRootElement(), factory, domMap); } public static AllocatedWardHistory getAllocatedWardHistoryfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return null; String className = el.attributeValue("type"); if (!AllocatedWardHistory.class.getName().equals(className)) { Class clz = Class.forName(className); if (!AllocatedWardHistory.class.isAssignableFrom(clz)) throw new Exception("Element of type = " + className + " cannot be imported using the AllocatedWardHistory class"); String shortClassName = className.substring(className.lastIndexOf(".")+1); String methodName = "get" + shortClassName + "fromXML"; java.lang.reflect.Method m = clz.getMethod(methodName, new Class[]{org.dom4j.Element.class, ims.domain.DomainFactory.class, java.util.HashMap.class}); return (AllocatedWardHistory)m.invoke(null, new Object[]{el, factory, domMap}); } String impVersion = el.attributeValue("classVersion"); if(!impVersion.equals(AllocatedWardHistory.CLASSVERSION)) { throw new Exception("Incompatible class structure found. Cannot import instance."); } AllocatedWardHistory ret = null; int extId = Integer.parseInt(el.attributeValue("id")); String externalSource = el.attributeValue("source"); ret = (AllocatedWardHistory)factory.getImportedDomainObject(AllocatedWardHistory.class, externalSource, extId); if (ret == null) { ret = new AllocatedWardHistory(); } String keyClassName = "AllocatedWardHistory"; ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + extId); if (impObj != null) { return (AllocatedWardHistory)impObj.getDomainObject(); } else { impObj = new ims.configuration.ImportedObject(); impObj.setExternalId(extId); impObj.setExternalSource(externalSource); impObj.setDomainObject(ret); domMap.put(keyClassName + "_" + externalSource + "_" + extId, impObj); } fillFieldsfromXML(el, factory, ret, domMap); return ret; } public static void fillFieldsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, AllocatedWardHistory obj, java.util.HashMap domMap) throws Exception { org.dom4j.Element fldEl; fldEl = el.element("allocatedWard"); if(fldEl != null) { fldEl = fldEl.element("class"); obj.setAllocatedWard(ims.core.resource.place.domain.objects.Location.getLocationfromXML(fldEl, factory, domMap)); } fldEl = el.element("allocatedWardDateTime"); if(fldEl != null) { obj.setAllocatedWardDateTime(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim())); } fldEl = el.element("allocatingUser"); if(fldEl != null) { fldEl = fldEl.element("class"); obj.setAllocatingUser(ims.core.configuration.domain.objects.AppUser.getAppUserfromXML(fldEl, factory, domMap)); } } public static String[] getCollectionFields() { return new String[]{ }; } public static class FieldNames { public static final String ID = "id"; public static final String AllocatedWard = "allocatedWard"; public static final String AllocatedWardDateTime = "allocatedWardDateTime"; public static final String AllocatingUser = "allocatingUser"; } }
open-health-hub/openMAXIMS
openmaxims_workspace/DomainObjects/src/ims/core/admin/pas/domain/objects/AllocatedWardHistory.java
Java
agpl-3.0
13,658
;(function (window, document) { 'use strict'; /** * Global storage manager * * The storage manager provides a unified way to store items in the localStorage and sessionStorage. * It uses a polyfill that uses cookies as a fallback when no localStorage or sessionStore is available or working. * * @example * * Saving an item to localStorage: * * StorageManager.setItem('local', 'key', 'value'); * * Retrieving it: * * var item = StorageManager.getItem('local', 'key'); // item === 'value' * * Basically you can use every method of the Storage interface (http://www.w3.org/TR/webstorage/#the-storage-interface) * But notice that you have to pass the storage type ('local' | 'session') in the first parameter for every call. * * @example * * Getting the localStorage/sessionStorage (polyfill) object * * var localStorage = StorageManager.getStorage('local'); * var sessionStorage = StorageManager.getStorage('session'); * * You can also use its shorthands: * * var localStorage = StorageManager.getLocalStorage(); * var sessionStorage = StorageManager.getSessionStorage(); */ window.StorageManager = (function () { var storage = { local: window.localStorage, session: window.sessionStorage }, p; /** * Helper function to detect if cookies are enabled. * @returns {boolean} */ function hasCookiesSupport() { // if cookies are already present assume cookie support if ('cookie' in document && (document.cookie.length > 0)) { return true; } document.cookie = 'testcookie=1;'; var writeTest = (document.cookie.indexOf('testcookie') !== -1); document.cookie = 'testcookie=1' + ';expires=Sat, 01-Jan-2000 00:00:00 GMT'; return writeTest; } // test for safari's "QUOTA_EXCEEDED_ERR: DOM Exception 22" issue. for (p in storage) { if (!storage.hasOwnProperty(p)) { continue; } try { storage[p].setItem('storage', ''); storage[p].removeItem('storage'); } catch (err) { } } // Just return the public API instead of all available functions return { /** * Returns the storage object/polyfill of the given type. * * @returns {Storage|StoragePolyFill} */ getStorage: function (type) { return storage[type]; }, /** * Returns the sessionStorage object/polyfill. * * @returns {Storage|StoragePolyFill} */ getSessionStorage: function () { return this.getStorage('session'); }, /** * Returns the localStorage object/polyfill. * * @returns {Storage|StoragePolyFill} */ getLocalStorage: function () { return this.getStorage('local'); }, /** * Calls the clear() method of the storage from the given type. * * @param {String} type */ clear: function (type) { this.getStorage(type).clear(); }, /** * Calls the getItem() method of the storage from the given type. * * @param {String} type * @param {String} key * @returns {String} */ getItem: function (type, key) { return this.getStorage(type).getItem(key); }, /** * Calls the key() method of the storage from the given type. * * @param {String} type * @param {Number|String} i * @returns {String} */ key: function (type, i) { return this.getStorage(type).key(i); }, /** * Calls the removeItem() method of the storage from the given type. * * @param {String} type * @param {String} key */ removeItem: function (type, key) { this.getStorage(type).removeItem(key); }, /** * Calls the setItem() method of the storage from the given type. * * @param {String} type * @param {String} key * @param {String} value */ setItem: function (type, key, value) { this.getStorage(type).setItem(key, value); }, /** * Helper function call to check if cookies are enabled. */ hasCookiesSupport: hasCookiesSupport() }; })(); })(window, document);
jhit/shopware
themes/Frontend/Responsive/frontend/_public/src/js/jquery.storage-manager.js
JavaScript
agpl-3.0
5,074
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.core.domain; // Generated from form domain impl public interface PatientDocumentErrors extends ims.domain.DomainInterface { }
open-health-hub/openMAXIMS
openmaxims_workspace/Core/src/ims/core/domain/PatientDocumentErrors.java
Java
agpl-3.0
1,811
require 'rails_helper' RSpec.describe "Requirements" do before(:each) { sign_in_as('Editor') } # This can only be used if we have a factory that works with no arguments # get_nested_editor_views('task', 'requirement', ['minimum_people', 'maximum_people', 'desired_people']) let(:max_ppl) { 5 + rand(25) } let(:desired_ppl) { 1 + rand((max_ppl * 0.8).floor + 1) } let(:min_ppl) { 1 + rand((desired_ppl * 0.5).floor + 1) } describe "creates" do it "requirements" do @event = create(:event) @task = create(:task, event: @event) @skill = create(:skill) visit new_task_requirement_path(@task) select @skill.name, from: :requirement_skill_id fill_in "requirement_desired_people", with: desired_ppl fill_in "requirement_maximum_people", with: max_ppl fill_in "requirement_minimum_people", with: min_ppl click_on 'Create Requirement' expect(page).to have_content "Requirement was successfully created." expect(page).to have_content @skill.name expect(page).to have_content "#{desired_ppl}" expect(page).to have_content "#{min_ppl}" expect(page).to have_content "#{max_ppl}" visit task_path(@task) click_on @skill.name expect(page).to have_content @skill.name expect(page).to have_content "Desired People: #{desired_ppl}" expect(page).to have_content "Minimum People: #{min_ppl}" expect(page).to have_content "Maximum People: #{max_ppl}" end end end
pcai/lims
spec/features/requirements_spec.rb
Ruby
agpl-3.0
1,489
/* * ProActive Parallel Suite(TM): * The Open Source library for parallel and distributed * Workflows & Scheduling, Orchestration, Cloud Automation * and Big Data Analysis on Enterprise Grids & Clouds. * * Copyright (c) 2007 - 2017 ActiveEon * Contact: contact@activeeon.com * * This library is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation: version 3 of * the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. */ package org.ow2.proactive.resourcemanager.frontend; import org.apache.log4j.Logger; import org.objectweb.proactive.annotation.PublicAPI; import org.objectweb.proactive.core.util.URIBuilder; import org.ow2.proactive.authentication.Connection; import org.ow2.proactive.resourcemanager.authentication.RMAuthentication; import org.ow2.proactive.resourcemanager.common.RMConstants; import org.ow2.proactive.resourcemanager.exception.RMException; /** * This class provides means to connect to an existing RM. * As a result of connection returns {@link RMAuthentication} for further authentication. * * @author The ProActive Team * @since ProActive Scheduling 0.9 * */ @PublicAPI public class RMConnection extends Connection<RMAuthentication> { private static RMConnection instance; private RMConnection() { super(RMAuthentication.class); } public Logger getLogger() { return Logger.getLogger(RMConnection.class); } public static synchronized RMConnection getInstance() { if (instance == null) { instance = new RMConnection(); } return instance; } /** * Returns the {@link RMAuthentication} from the specified * URL. If resource manager is not available or initializing throws an exception. * * @param url the URL of the resource manager to join. * @return the resource manager authentication at the specified URL. * @throws RMException * thrown if the connection to the resource manager cannot be * established. */ public static RMAuthentication join(String url) throws RMException { try { return getInstance().connect(normalizeRM(url)); } catch (Exception e) { throw new RMException("Cannot join the Resource Manager at " + url + " due to " + e.getMessage(), e); } } /** * Connects to the resource manager using given URL. The current thread will be block until * connection established or an error occurs. */ public static RMAuthentication waitAndJoin(String url) throws RMException { return waitAndJoin(url, 0); } /** * Connects to the resource manager with a specified timeout value. A timeout of * zero is interpreted as an infinite timeout. The connection will then * block until established or an error occurs. */ public static RMAuthentication waitAndJoin(String url, long timeout) throws RMException { try { return getInstance().waitAndConnect(normalizeRM(url), timeout); } catch (Exception e) { throw new RMException("Cannot join the Resource Manager at " + url + " due to " + e.getMessage(), e); } } /** * Normalize the URL of the RESOURCE MANAGER.<br> * * @param url, the URL to normalize. * @return //localhost/RM_NAME if the given url is null.<br> * the given URL if it terminates by the RM_NAME<br> * the given URL with /RM_NAME appended if URL does not end with /<br> * the given URL with RM_NAME appended if URL does end with /<br> * the given URL with RM_NAME appended if URL does not end with RM_NAME */ private static String normalizeRM(String url) { return URIBuilder.buildURI(Connection.normalize(url), RMConstants.NAME_ACTIVE_OBJECT_RMAUTHENTICATION) .toString(); } }
marcocast/scheduling
rm/rm-client/src/main/java/org/ow2/proactive/resourcemanager/frontend/RMConnection.java
Java
agpl-3.0
4,454
package net.minecraftforge.debug; import java.util.ArrayList; import java.util.Collections; import java.util.List; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyInteger; import net.minecraft.block.state.BlockState; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.ItemCameraTransforms; import net.minecraft.client.renderer.block.statemap.StateMapperBase; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.resources.model.IBakedModel; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.Vec3; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.client.event.ModelBakeEvent; import net.minecraftforge.client.model.ISmartBlockModel; import net.minecraftforge.client.model.ISmartItemModel; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.property.ExtendedBlockState; import net.minecraftforge.common.property.IExtendedBlockState; import net.minecraftforge.common.property.IUnlistedProperty; import net.minecraftforge.common.property.Properties; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.registry.GameRegistry; import com.google.common.primitives.Ints; @SuppressWarnings("deprecation") @Mod(modid = ModelBakeEventDebug.MODID, version = ModelBakeEventDebug.VERSION) public class ModelBakeEventDebug { public static final String MODID = "ForgeDebugModelBakeEvent"; public static final String VERSION = "1.0"; public static final int cubeSize = 3; private static String blockName = MODID.toLowerCase() + ":" + CustomModelBlock.name; @SuppressWarnings("unchecked") public static final IUnlistedProperty<Integer>[] properties = new IUnlistedProperty[6]; static { for(EnumFacing f : EnumFacing.values()) { properties[f.ordinal()] = Properties.toUnlisted(PropertyInteger.create(f.getName(), 0, (1 << (cubeSize * cubeSize)) - 1)); } } @SidedProxy public static CommonProxy proxy; @EventHandler public void preInit(FMLPreInitializationEvent event) { proxy.preInit(event); } public static class CommonProxy { public void preInit(FMLPreInitializationEvent event) { GameRegistry.registerBlock(CustomModelBlock.instance, CustomModelBlock.name); GameRegistry.registerTileEntity(CustomTileEntity.class, MODID.toLowerCase() + ":custom_tile_entity"); } } public static class ServerProxy extends CommonProxy {} public static class ClientProxy extends CommonProxy { private static ModelResourceLocation blockLocation = new ModelResourceLocation(blockName, "normal"); private static ModelResourceLocation itemLocation = new ModelResourceLocation(blockName, "inventory"); @Override public void preInit(FMLPreInitializationEvent event) { super.preInit(event); Item item = Item.getItemFromBlock(CustomModelBlock.instance); ModelLoader.setCustomModelResourceLocation(item, 0, itemLocation); ModelLoader.setCustomStateMapper(CustomModelBlock.instance, new StateMapperBase(){ protected ModelResourceLocation getModelResourceLocation(IBlockState p_178132_1_) { return blockLocation; } }); MinecraftForge.EVENT_BUS.register(BakeEventHandler.instance); } } public static class BakeEventHandler { public static final BakeEventHandler instance = new BakeEventHandler(); private BakeEventHandler() {}; @SubscribeEvent public void onModelBakeEvent(ModelBakeEvent event) { TextureAtlasSprite base = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite("minecraft:blocks/slime"); TextureAtlasSprite overlay = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite("minecraft:blocks/redstone_block"); IBakedModel customModel = new CustomModel(base, overlay); event.modelRegistry.putObject(ClientProxy.blockLocation, customModel); event.modelRegistry.putObject(ClientProxy.itemLocation, customModel); } } public static class CustomModelBlock extends BlockContainer { public static final CustomModelBlock instance = new CustomModelBlock(); public static final String name = "custom_model_block"; private CustomModelBlock() { super(Material.iron); setCreativeTab(CreativeTabs.tabBlock); setUnlocalizedName(MODID + ":" + name); } @Override public int getRenderType() { return 3; } @Override public boolean isOpaqueCube() { return false; } @Override public boolean isFullCube() { return false; } @Override public boolean isVisuallyOpaque() { return false; } @Override public TileEntity createNewTileEntity(World world, int meta) { return new CustomTileEntity(); } @Override public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumFacing side, float hitX, float hitY, float hitZ) { TileEntity te = world.getTileEntity(pos); if(te instanceof CustomTileEntity) { CustomTileEntity cte = (CustomTileEntity) te; Vec3 vec = revRotate(new Vec3(hitX - .5, hitY - .5, hitZ - .5), side).addVector(.5, .5, .5); IUnlistedProperty<Integer> property = properties[side.ordinal()]; Integer value = cte.getState().getValue(property); if(value == null) value = 0; value ^= (1 << ( cubeSize * ((int)(vec.xCoord * (cubeSize - .0001))) + ((int)(vec.zCoord * (cubeSize - .0001))) )); cte.setState(cte.getState().withProperty(property, value)); world.markBlockRangeForRenderUpdate(pos, pos); } return true; } @Override public IBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) { TileEntity te = world.getTileEntity(pos); if(te instanceof CustomTileEntity) { CustomTileEntity cte = (CustomTileEntity) te; return cte.getState(); } return state; } @Override protected BlockState createBlockState() { return new ExtendedBlockState(this, new IProperty[0], properties); } } public static class CustomTileEntity extends TileEntity { private IExtendedBlockState state; public CustomTileEntity() {} public IExtendedBlockState getState() { if(state == null) { state = (IExtendedBlockState)getBlockType().getDefaultState(); } return state; } public void setState(IExtendedBlockState state) { this.state = state; } } public static class CustomModel implements IBakedModel, ISmartBlockModel, ISmartItemModel { private final TextureAtlasSprite base, overlay; //private boolean hasStateSet = false; private final IExtendedBlockState state; public CustomModel(TextureAtlasSprite base, TextureAtlasSprite overlay) { this(base, overlay, null); } public CustomModel(TextureAtlasSprite base, TextureAtlasSprite overlay, IExtendedBlockState state) { this.base = base; this.overlay = overlay; this.state = state; } @Override public List<BakedQuad> getFaceQuads(EnumFacing side) { return Collections.emptyList(); } private int[] vertexToInts(float x, float y, float z, int color, TextureAtlasSprite texture, float u, float v) { return new int[] { Float.floatToRawIntBits(x), Float.floatToRawIntBits(y), Float.floatToRawIntBits(z), color, Float.floatToRawIntBits(texture.getInterpolatedU(u)), Float.floatToRawIntBits(texture.getInterpolatedV(v)), 0 }; } private BakedQuad createSidedBakedQuad(float x1, float x2, float z1, float z2, float y, TextureAtlasSprite texture, EnumFacing side) { Vec3 v1 = rotate(new Vec3(x1 - .5, y - .5, z1 - .5), side).addVector(.5, .5, .5); Vec3 v2 = rotate(new Vec3(x1 - .5, y - .5, z2 - .5), side).addVector(.5, .5, .5); Vec3 v3 = rotate(new Vec3(x2 - .5, y - .5, z2 - .5), side).addVector(.5, .5, .5); Vec3 v4 = rotate(new Vec3(x2 - .5, y - .5, z1 - .5), side).addVector(.5, .5, .5); return new BakedQuad(Ints.concat( vertexToInts((float)v1.xCoord, (float)v1.yCoord, (float)v1.zCoord, -1, texture, 0, 0), vertexToInts((float)v2.xCoord, (float)v2.yCoord, (float)v2.zCoord, -1, texture, 0, 16), vertexToInts((float)v3.xCoord, (float)v3.yCoord, (float)v3.zCoord, -1, texture, 16, 16), vertexToInts((float)v4.xCoord, (float)v4.yCoord, (float)v4.zCoord, -1, texture, 16, 0) ), -1, side); } @Override public List<BakedQuad> getGeneralQuads() { int len = cubeSize * 5 + 1; List<BakedQuad> ret = new ArrayList<BakedQuad>(); for(EnumFacing f : EnumFacing.values()) { ret.add(createSidedBakedQuad(0, 1, 0, 1, 1, base, f)); for(int i = 0; i < cubeSize; i++) { for(int j = 0; j < cubeSize; j++) { if(state != null) { Integer value = state.getValue(properties[f.ordinal()]); if(value != null && (value & (1 << (i * cubeSize + j))) != 0) { ret.add(createSidedBakedQuad((float)(1 + i * 5) / len, (float)(5 + i * 5) / len, (float)(1 + j * 5) / len, (float)(5 + j * 5) / len, 1.0001f, overlay, f)); } } } } } return ret; } @Override public boolean isGui3d() { return true; } @Override public boolean isAmbientOcclusion() { return true; } @Override public boolean isBuiltInRenderer() { return false; } @Override public TextureAtlasSprite getParticleTexture() { return this.base; } @Override public ItemCameraTransforms getItemCameraTransforms() { return ItemCameraTransforms.DEFAULT; } @Override public IBakedModel handleBlockState(IBlockState state) { return new CustomModel(base, overlay, (IExtendedBlockState)state); } @Override public IBakedModel handleItemState(ItemStack stack) { IExtendedBlockState itemState = ((IExtendedBlockState)CustomModelBlock.instance.getDefaultState()).withProperty(properties[1], (1 << (cubeSize * cubeSize)) - 1); return new CustomModel(base, overlay, itemState); } } private static Vec3 rotate(Vec3 vec, EnumFacing side) { switch(side) { case DOWN: return new Vec3( vec.xCoord, -vec.yCoord, -vec.zCoord); case UP: return new Vec3( vec.xCoord, vec.yCoord, vec.zCoord); case NORTH: return new Vec3( vec.xCoord, vec.zCoord, -vec.yCoord); case SOUTH: return new Vec3( vec.xCoord, -vec.zCoord, vec.yCoord); case WEST: return new Vec3(-vec.yCoord, vec.xCoord, vec.zCoord); case EAST: return new Vec3( vec.yCoord, -vec.xCoord, vec.zCoord); } return null; } private static Vec3 revRotate(Vec3 vec, EnumFacing side) { switch(side) { case DOWN: return new Vec3( vec.xCoord, -vec.yCoord, -vec.zCoord); case UP: return new Vec3( vec.xCoord, vec.yCoord, vec.zCoord); case NORTH: return new Vec3( vec.xCoord, -vec.zCoord, vec.yCoord); case SOUTH: return new Vec3( vec.xCoord, vec.zCoord, -vec.yCoord); case WEST: return new Vec3( vec.yCoord, -vec.xCoord, vec.zCoord); case EAST: return new Vec3(-vec.yCoord, vec.xCoord, vec.zCoord); } return null; } }
luacs1998/MinecraftForge
src/test/java/net/minecraftforge/debug/ModelBakeEventDebug.java
Java
lgpl-2.1
13,609
'''Test cases for QImage''' import unittest import py3kcompat as py3k from PySide.QtGui import * from helper import UsesQApplication, adjust_filename xpm = [ "27 22 206 2", " c None", ". c #FEFEFE", "+ c #FFFFFF", "@ c #F9F9F9", "# c #ECECEC", "$ c #D5D5D5", "% c #A0A0A0", "& c #767676", "* c #525252", "= c #484848", "- c #4E4E4E", "; c #555555", "> c #545454", ", c #5A5A5A", "' c #4B4B4B", ") c #4A4A4A", "! c #4F4F4F", "~ c #585858", "{ c #515151", "] c #4C4C4C", "^ c #B1B1B1", "/ c #FCFCFC", "( c #FDFDFD", "_ c #C1C1C1", ": c #848484", "< c #616161", "[ c #5E5E5E", "} c #CECECE", "| c #E2E2E2", "1 c #E4E4E4", "2 c #DFDFDF", "3 c #D2D2D2", "4 c #D8D8D8", "5 c #D4D4D4", "6 c #E6E6E6", "7 c #F1F1F1", "8 c #838383", "9 c #8E8E8E", "0 c #8F8F8F", "a c #CBCBCB", "b c #CCCCCC", "c c #E9E9E9", "d c #F2F2F2", "e c #EDEDED", "f c #B5B5B5", "g c #A6A6A6", "h c #ABABAB", "i c #BBBBBB", "j c #B0B0B0", "k c #EAEAEA", "l c #6C6C6C", "m c #BCBCBC", "n c #F5F5F5", "o c #FAFAFA", "p c #B6B6B6", "q c #F3F3F3", "r c #CFCFCF", "s c #FBFBFB", "t c #CDCDCD", "u c #DDDDDD", "v c #999999", "w c #F0F0F0", "x c #2B2B2B", "y c #C3C3C3", "z c #A4A4A4", "A c #D7D7D7", "B c #E7E7E7", "C c #6E6E6E", "D c #9D9D9D", "E c #BABABA", "F c #AEAEAE", "G c #898989", "H c #646464", "I c #BDBDBD", "J c #CACACA", "K c #2A2A2A", "L c #212121", "M c #B7B7B7", "N c #F4F4F4", "O c #737373", "P c #828282", "Q c #4D4D4D", "R c #000000", "S c #151515", "T c #B2B2B2", "U c #D6D6D6", "V c #D3D3D3", "W c #2F2F2F", "X c #636363", "Y c #A1A1A1", "Z c #BFBFBF", "` c #E0E0E0", " . c #6A6A6A", ".. c #050505", "+. c #A3A3A3", "@. c #202020", "#. c #5F5F5F", "$. c #B9B9B9", "%. c #C7C7C7", "&. c #D0D0D0", "*. c #3E3E3E", "=. c #666666", "-. c #DBDBDB", ";. c #424242", ">. c #C2C2C2", ",. c #1A1A1A", "'. c #2C2C2C", "). c #F6F6F6", "!. c #AAAAAA", "~. c #DCDCDC", "{. c #2D2D2D", "]. c #2E2E2E", "^. c #A7A7A7", "/. c #656565", "(. c #333333", "_. c #464646", ":. c #C4C4C4", "<. c #B8B8B8", "[. c #292929", "}. c #979797", "|. c #EFEFEF", "1. c #909090", "2. c #8A8A8A", "3. c #575757", "4. c #676767", "5. c #C5C5C5", "6. c #7A7A7A", "7. c #797979", "8. c #989898", "9. c #EEEEEE", "0. c #707070", "a. c #C8C8C8", "b. c #111111", "c. c #AFAFAF", "d. c #474747", "e. c #565656", "f. c #E3E3E3", "g. c #494949", "h. c #5B5B5B", "i. c #222222", "j. c #353535", "k. c #D9D9D9", "l. c #0A0A0A", "m. c #858585", "n. c #E5E5E5", "o. c #0E0E0E", "p. c #9A9A9A", "q. c #6F6F6F", "r. c #868686", "s. c #060606", "t. c #1E1E1E", "u. c #E8E8E8", "v. c #A5A5A5", "w. c #0D0D0D", "x. c #030303", "y. c #272727", "z. c #131313", "A. c #1F1F1F", "B. c #757575", "C. c #F7F7F7", "D. c #414141", "E. c #080808", "F. c #6B6B6B", "G. c #313131", "H. c #C0C0C0", "I. c #C9C9C9", "J. c #0B0B0B", "K. c #232323", "L. c #434343", "M. c #3D3D3D", "N. c #282828", "O. c #7C7C7C", "P. c #252525", "Q. c #3A3A3A", "R. c #F8F8F8", "S. c #1B1B1B", "T. c #949494", "U. c #3B3B3B", "V. c #242424", "W. c #383838", "X. c #6D6D6D", "Y. c #818181", "Z. c #939393", "`. c #9E9E9E", " + c #929292", ".+ c #7D7D7D", "++ c #ADADAD", "@+ c #DADADA", "#+ c #919191", "$+ c #E1E1E1", "%+ c #BEBEBE", "&+ c #ACACAC", "*+ c #9C9C9C", "=+ c #B3B3B3", "-+ c #808080", ";+ c #A8A8A8", ">+ c #393939", ",+ c #747474", "'+ c #7F7F7F", ")+ c #D1D1D1", "!+ c #606060", "~+ c #5C5C5C", "{+ c #686868", "]+ c #7E7E7E", "^+ c #787878", "/+ c #595959", ". . . + @ # $ % & * = - ; > , ' ) ! ~ { ] ^ / . . + + ", ". ( + _ : < [ & } | 1 2 $ 3 4 5 3 6 7 + + 8 9 + . + . ", ". + 0 9 a ( 3 a b c d e c f g h i g j $ k + l m + . + ", "+ 2 8 n o p | ( q r s . # t + + + u ^ v e w + x + + + ", "+ y z . @ A k B 7 n + ( s | p 8 C D 2 E 4 + + F G + . ", "# H I $ J G K L - M N . 2 O P Q R R S T U s s V W j + ", "X Y Z @ o ` _ g ...+.( 4 @.#.m G $.%.7 &.X *.=.-.;.&.", "Q >.C ,.'.} e + ).!.k + . + + . ~.{.> ].x f 7 ^./.k (.", "_.:.4 @ <.[.}.|.1.2.+ + + >.} 4 B + ( @ _ 3.4.5.6.r 7.", "3.8.9.~ 0.+ a.Q b.+ + c.d.#.=.$ |.b #.e.z ^ ; ^. .f.g.", "-.h.+ i.S M + # p j.% n 9.5.k.H l.m.V ^.n.o.M + M p.q.", "7 r.N s.1.R t.<.|.| u.v.~ w.x.E + s y.z.A.B.C.+ 5 D.q ", ").p.2 E.0.9 F.%.O {._ @.+ + i { [ i.G.H.P I.+ s q.} + ", ").p.6 J.R b.K.L.M.A.! b.g.K [.R M k + N.I + + >.O.+ . ", ").8.9.N.P...R R R R E.t.W n.+ Q.R.6 @.| + . + S.+ + . ", "n }.w T.U.B.<.i.@ Y + + U.+ c u V.= B B 7 u.W.c + . + ", "N T.# + }.X.Y.,.8.F.8 Z.[.`. +.+}.4 ++@+O.< ~.+ ( . + ", "d #+1 + _ ~.u.$+b $.y @+| $+%+I.&+k.h W +.9.+ ( . + . ", "w 0 |.*+. >.<.=+++++p a.p -+;+5.k.>+,+@ + . . + . + + ", "q '+9.R.^ I.t b %.I.)+4 $+n.I.,+ .|.+ . . . + . + + + ", ". p !+( + + + + + + E 0. .-+8.f.+ + . . + + . + + + + ", ". ( A ~+{+]+^+l > /+D f.c q . + . . + + . + + + + + + " ] class QImageTest(UsesQApplication): '''Test case for calling setPixel with float as argument''' def testQImageStringBuffer(self): '''Test if the QImage signatures receiving string buffers exist.''' img0 = QImage(adjust_filename('sample.png', __file__)) # btw let's test the bits() method img1 = QImage(img0.bits(), img0.width(), img0.height(), img0.format()) self.assertEqual(img0, img1) img2 = QImage(img0.bits(), img0.width(), img0.height(), img0.bytesPerLine(), img0.format()) self.assertEqual(img0, img2) ## test scanLine method data1 = img0.scanLine(0) data2 = img1.scanLine(0) self.assertEqual(data1, data2) # PySide python 3.x does not support slice yet if not py3k.IS_PY3K: buff = py3k.buffer(img0.bits()[:img0.bytesPerLine()]) self.assertEqual(data1, buff) self.assertEqual(data2, buff) def testEmptyBuffer(self): img = QImage(py3k.buffer(''), 100, 100, QImage.Format_ARGB32) def testEmptyStringAsBuffer(self): img = QImage(py3k.b(''), 100, 100, QImage.Format_ARGB32) def testXpmConstructor(self): label = QLabel() img = QImage(xpm) self.assertFalse(img.isNull()) self.assertEqual(img.width(), 27) self.assertEqual(img.height(), 22) if __name__ == '__main__': unittest.main()
enthought/pyside
tests/QtGui/qimage_test.py
Python
lgpl-2.1
7,077
// [Name] SVGFECompositeElement-dom-k1-attr.js // [Expected rendering result] Four circle with different opacity merged with feComposite filter - and a series of PASS messages description("Tests dynamic updates of the 'k1' attribute of the SVGFECompositeElement object") createSVGTestCase(); var defsElement = createSVGElement("defs"); rootSVGElement.appendChild(defsElement); var off1 = createSVGElement("feOffset"); off1.setAttribute("dx", "35"); off1.setAttribute("dy", "25"); off1.setAttribute("result", "off1"); var flood1 = createSVGElement("feFlood"); flood1.setAttribute("flood-color", "#408067"); flood1.setAttribute("flood-opacity", ".8"); flood1.setAttribute("result", "F1"); var overComposite1 = createSVGElement("feComposite"); overComposite1.setAttribute("in", "F1"); overComposite1.setAttribute("in2", "off1"); overComposite1.setAttribute("operator", "arithmetic"); overComposite1.setAttribute("k1", "1.9"); overComposite1.setAttribute("k2", ".1"); overComposite1.setAttribute("k3", ".5"); overComposite1.setAttribute("k4", ".3"); overComposite1.setAttribute("result", "C1"); var off2 = createSVGElement("feOffset"); off2.setAttribute("in", "SourceGraphic"); off2.setAttribute("dx", "60"); off2.setAttribute("dy", "50"); off2.setAttribute("result", "off2"); var flood2 = createSVGElement("feFlood"); flood2.setAttribute("flood-color", "#408067"); flood2.setAttribute("flood-opacity", ".6"); flood2.setAttribute("result", "F2"); var overComposite2 = createSVGElement("feComposite"); overComposite2.setAttribute("in", "F2"); overComposite2.setAttribute("in2", "off2"); overComposite2.setAttribute("operator", "in"); overComposite2.setAttribute("result", "C2"); var off3 = createSVGElement("feOffset"); off3.setAttribute("in", "SourceGraphic"); off3.setAttribute("dx", "85"); off3.setAttribute("dy", "75"); off3.setAttribute("result", "off3"); var flood3 = createSVGElement("feFlood"); flood3.setAttribute("flood-color", "#408067"); flood3.setAttribute("flood-opacity", ".4"); flood3.setAttribute("result", "F3"); var overComposite3 = createSVGElement("feComposite"); overComposite3.setAttribute("in2", "off3"); overComposite3.setAttribute("operator", "in"); overComposite3.setAttribute("result", "C3"); var merge = createSVGElement("feMerge"); var mergeNode1 = createSVGElement("feMergeNode"); mergeNode1.setAttribute("in", "C1"); var mergeNode2 = createSVGElement("feMergeNode"); mergeNode2.setAttribute("in", "C2"); var mergeNode3 = createSVGElement("feMergeNode"); mergeNode3.setAttribute("in", "C3"); var mergeNode4 = createSVGElement("feMergeNode"); mergeNode4.setAttribute("in", "SourceGraphic"); merge.appendChild(mergeNode3); merge.appendChild(mergeNode2); merge.appendChild(mergeNode1); merge.appendChild(mergeNode4); var overFilter = createSVGElement("filter"); overFilter.setAttribute("id", "overFilter"); overFilter.setAttribute("filterUnits", "objectBoundingBox"); overFilter.setAttribute("x", "0"); overFilter.setAttribute("y", "0"); overFilter.setAttribute("width", "3.5"); overFilter.setAttribute("height", "4"); overFilter.appendChild(off1); overFilter.appendChild(flood1); overFilter.appendChild(overComposite1); overFilter.appendChild(off2); overFilter.appendChild(flood2); overFilter.appendChild(overComposite2); overFilter.appendChild(off3); overFilter.appendChild(flood3); overFilter.appendChild(overComposite3); overFilter.appendChild(merge); defsElement.appendChild(overFilter); rootSVGElement.setAttribute("height", "200"); var rect1 = createSVGElement("circle"); rect1.setAttribute("cx", "100"); rect1.setAttribute("cy", "50"); rect1.setAttribute("r", "50"); rect1.setAttribute("fill", "#408067"); rect1.setAttribute("filter", "url(#overFilter)"); rootSVGElement.appendChild(rect1); shouldBeEqualToString("overComposite1.getAttribute('k1')", "1.9"); function repaintTest() { overComposite1.setAttribute("k1", ".5"); shouldBeEqualToString("overComposite1.getAttribute('k1')", ".5"); completeTest(); } var successfullyParsed = true;
youfoh/webkit-efl
LayoutTests/svg/dynamic-updates/script-tests/SVGFECompositeElement-dom-k1-attr.js
JavaScript
lgpl-2.1
4,008
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Remotion.Linq; using Remotion.Linq.Clauses; namespace NHibernate.Linq.ReWriters { public class MoveOrderByToEndRewriter { public static void ReWrite(QueryModel queryModel) { int len = queryModel.BodyClauses.Count; for(int i=0; i<len; i++) { if (queryModel.BodyClauses[i] is OrderByClause clause) { // If we find an order by clause, move it to the end of the list. // This preserves the ordering of multiple orderby clauses if there are any. queryModel.BodyClauses.RemoveAt(i); queryModel.BodyClauses.Add(clause); i--; len--; } } } } }
ngbrown/nhibernate-core
src/NHibernate/Linq/ReWriters/MoveOrderByToEndRewriter.cs
C#
lgpl-2.1
694
package cofh.api.transport; import net.minecraft.item.ItemStack; import net.minecraftforge.common.ForgeDirection; /** * This interface is implemented on Item Conduits. Use it to attempt to eject items into an entry point. * * @author Zeldo Kavira, King Lemming * */ public interface IItemConduit { /** * Insert an ItemStack into the IItemConduit. Will only accept items if there is a valid destination. This returns what is remaining of the original stack - * a null return means that the entire stack was accepted/routed! * * @param from * Orientation the item is inserted from. * @param item * ItemStack to be inserted. The size of this stack corresponds to the maximum amount to insert. * @return An ItemStack representing how much is remaining after the item was inserted (or would have been, if simulated) into the Conduit. */ public ItemStack insertItem(ForgeDirection from, ItemStack item); /* THE FOLLOWING WILL BE REMOVED IN 3.0.1.X */ @Deprecated public ItemStack insertItem(ForgeDirection from, ItemStack item, boolean simulate); @Deprecated public ItemStack sendItems(ItemStack item, ForgeDirection from); }
tterrag1098/EnderiumPowerArmor
src/main/java/cofh/api/transport/IItemConduit.java
Java
lgpl-3.0
1,180
/* * Copyright (c) 2008, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "Gradient.h" #include "CSSParser.h" #include "GraphicsContext.h" #include "SkColorShader.h" #include "SkGradientShader.h" #include "SkiaUtils.h" namespace WebCore { void Gradient::platformDestroy() { SkSafeUnref(m_gradient); m_gradient = 0; } static inline U8CPU F2B(float x) { return static_cast<int>(x * 255); } static SkColor makeSkColor(float a, float r, float g, float b) { return SkColorSetARGB(F2B(a), F2B(r), F2B(g), F2B(b)); } // Determine the total number of stops needed, including pseudo-stops at the // ends as necessary. static size_t totalStopsNeeded(const Gradient::ColorStop* stopData, size_t count) { // N.B.: The tests in this function should kept in sync with the ones in // fillStops(), or badness happens. const Gradient::ColorStop* stop = stopData; size_t countUsed = count; if (count < 1 || stop->stop > 0.0) countUsed++; stop += count - 1; if (count < 1 || stop->stop < 1.0) countUsed++; return countUsed; } // Collect sorted stop position and color information into the pos and colors // buffers, ensuring stops at both 0.0 and 1.0. The buffers must be large // enough to hold information for all stops, including the new endpoints if // stops at 0.0 and 1.0 aren't already included. static void fillStops(const Gradient::ColorStop* stopData, size_t count, SkScalar* pos, SkColor* colors) { const Gradient::ColorStop* stop = stopData; size_t start = 0; if (count < 1) { // A gradient with no stops must be transparent black. pos[0] = WebCoreFloatToSkScalar(0.0); colors[0] = makeSkColor(0.0, 0.0, 0.0, 0.0); start = 1; } else if (stop->stop > 0.0) { // Copy the first stop to 0.0. The first stop position may have a slight // rounding error, but we don't care in this float comparison, since // 0.0 comes through cleanly and people aren't likely to want a gradient // with a stop at (0 + epsilon). pos[0] = WebCoreFloatToSkScalar(0.0); colors[0] = makeSkColor(stop->alpha, stop->red, stop->green, stop->blue); start = 1; } for (size_t i = start; i < start + count; i++) { pos[i] = WebCoreFloatToSkScalar(stop->stop); colors[i] = makeSkColor(stop->alpha, stop->red, stop->green, stop->blue); ++stop; } // Copy the last stop to 1.0 if needed. See comment above about this float // comparison. if (count < 1 || (--stop)->stop < 1.0) { pos[start + count] = WebCoreFloatToSkScalar(1.0); colors[start + count] = colors[start + count - 1]; } } SkShader* Gradient::platformGradient() { if (m_gradient) return m_gradient; sortStopsIfNecessary(); ASSERT(m_stopsSorted); size_t countUsed = totalStopsNeeded(m_stops.data(), m_stops.size()); ASSERT(countUsed >= 2); ASSERT(countUsed >= m_stops.size()); // FIXME: Why is all this manual pointer math needed?! SkAutoMalloc storage(countUsed * (sizeof(SkColor) + sizeof(SkScalar))); SkColor* colors = (SkColor*)storage.get(); SkScalar* pos = (SkScalar*)(colors + countUsed); fillStops(m_stops.data(), m_stops.size(), pos, colors); SkShader::TileMode tile = SkShader::kClamp_TileMode; switch (m_spreadMethod) { case SpreadMethodReflect: tile = SkShader::kMirror_TileMode; break; case SpreadMethodRepeat: tile = SkShader::kRepeat_TileMode; break; case SpreadMethodPad: tile = SkShader::kClamp_TileMode; break; } if (m_radial) { // Since the two-point radial gradient is slower than the plain radial, // only use it if we have to. if (m_p0 == m_p1 && m_r0 <= 0.0f) { m_gradient = SkGradientShader::CreateRadial(m_p1, m_r1, colors, pos, static_cast<int>(countUsed), tile); } else { // The radii we give to Skia must be positive. If we're given a // negative radius, ask for zero instead. SkScalar radius0 = m_r0 >= 0.0f ? WebCoreFloatToSkScalar(m_r0) : 0; SkScalar radius1 = m_r1 >= 0.0f ? WebCoreFloatToSkScalar(m_r1) : 0; m_gradient = SkGradientShader::CreateTwoPointConical(m_p0, radius0, m_p1, radius1, colors, pos, static_cast<int>(countUsed), tile); } if (aspectRatio() != 1) { // CSS3 elliptical gradients: apply the elliptical scaling at the // gradient center point. m_gradientSpaceTransformation.translate(m_p0.x(), m_p0.y()); m_gradientSpaceTransformation.scale(1, 1 / aspectRatio()); m_gradientSpaceTransformation.translate(-m_p0.x(), -m_p0.y()); ASSERT(m_p0 == m_p1); } } else { SkPoint pts[2] = { m_p0, m_p1 }; m_gradient = SkGradientShader::CreateLinear(pts, colors, pos, static_cast<int>(countUsed), tile); } if (!m_gradient) // use last color, since our "geometry" was degenerate (e.g. radius==0) m_gradient = new SkColorShader(colors[countUsed - 1]); else m_gradient->setLocalMatrix(m_gradientSpaceTransformation); return m_gradient; } void Gradient::fill(GraphicsContext* context, const FloatRect& rect) { context->setFillGradient(this); context->fillRect(rect); } void Gradient::setPlatformGradientSpaceTransform(const AffineTransform& matrix) { if (m_gradient) m_gradient->setLocalMatrix(m_gradientSpaceTransformation); } } // namespace WebCore
nawawi/wkhtmltopdf
webkit/Source/WebCore/platform/graphics/skia/GradientSkia.cpp
C++
lgpl-3.0
7,115
/* See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Esri Inc. licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.esri.gpt.catalog.harvest.protocols; import com.esri.gpt.control.webharvest.IterationContext; import com.esri.gpt.control.webharvest.client.arcims.ArcImsQueryBuilder; import com.esri.gpt.framework.collection.StringAttributeMap; import com.esri.gpt.framework.resource.query.QueryBuilder; import com.esri.gpt.framework.util.Val; /** * ArcIMS protocol. */ public class HarvestProtocolArcIms extends AbstractHTTPHarvestProtocol { // class variables ============================================================= public static final int DEFAULT_PORT_NO = 80; // instance variables ========================================================== /** Port number. */ private int _portNo = DEFAULT_PORT_NO; /** Port number as string. */ private String _portNoAsString = Integer.toString(_portNo); /** Service name. */ private String _serviceName = ""; /** Root folder. */ private String _rootFolder = ""; // constructors ================================================================ // properties ================================================================== /** * Gets port number. * @return port number */ public int getPortNo() { return _portNo; } /** * Sets port number. * @param portNo port number */ public void setPortNo(int portNo) { _portNo = portNo >= 0 && portNo < 65536 ? portNo : DEFAULT_PORT_NO; _portNoAsString = Integer.toString(_portNo); } /** * Gets port number as string. * @return port number as string */ public String getPortNoAsString() { return _portNoAsString; } /** * Sets port number as string. * @param portNoAsString port number as string */ public void setPortNoAsString(String portNoAsString) { _portNoAsString = Val.chkStr(portNoAsString); try { int portNo = Integer.parseInt(_portNoAsString); if (portNo >= 0 && portNo < 65536) { _portNo = portNo; } } catch (NumberFormatException ex) { } } /** * Gets service name. * @return service name */ public String getServiceName() { return _serviceName; } /** * Sets servie name. * @param serviceName service name */ public void setServiceName(String serviceName) { _serviceName = Val.chkStr(serviceName); } /** * Gets root folder. * @return root folder */ public String getRootFolder() { return _rootFolder; } /** * Sets root folder. * @param rootFolder root folder */ public void setRootFolder(String rootFolder) { _rootFolder = Val.chkStr(rootFolder); } // methods ===================================================================== /** * Gets protocol type. * @return protocol type * @deprecated */ @Override @Deprecated public final ProtocolType getType() { return ProtocolType.ArcIms; } @Override public String getKind() { return "ArcIms"; } /** * Gets all the attributes. * @return attributes as attribute map */ @Override public StringAttributeMap extractAttributeMap() { StringAttributeMap properties = new StringAttributeMap(); properties.set("username", encryptString(getUserName())); properties.set("password", encryptString(getUserPassword())); properties.set("service", getServiceName()); properties.set("port", Integer.toString(getPortNo())); properties.set("rootFolder", getRootFolder()); return properties; } /** * Gets all the attributes. * @return attributes as attribute map */ @Override public StringAttributeMap getAttributeMap() { StringAttributeMap properties = new StringAttributeMap(); properties.set("arcims.username", getUserName()); properties.set("arcims.password", getUserPassword()); properties.set("service", getServiceName()); properties.set("port", Integer.toString(getPortNo())); properties.set("rootFolder", getRootFolder()); return properties; } /** * Sets all the attributes. * @param attributeMap attributes as attribute map */ @Override public void applyAttributeMap(StringAttributeMap attributeMap) { setUserName(decryptString(chckAttr(attributeMap.get("username")))); setUserPassword(decryptString(chckAttr(attributeMap.get("password")))); setServiceName(chckAttr(attributeMap.get("service"))); setPortNo(Val.chkInt(chckAttr(attributeMap.get("port")), DEFAULT_PORT_NO)); setRootFolder(chckAttr(attributeMap.get("rootFolder"))); } /** * Sets all the attributes. * @param attributeMap attributes as attribute map */ @Override public void setAttributeMap(StringAttributeMap attributeMap) { setUserName(chckAttr(attributeMap.get("arcims.username"))); setUserPassword(chckAttr(attributeMap.get("arcims.password"))); setServiceName(chckAttr(attributeMap.get("service"))); setPortNo(Val.chkInt(chckAttr(attributeMap.get("port")), DEFAULT_PORT_NO)); setRootFolder(chckAttr(attributeMap.get("rootFolder"))); } @Override public QueryBuilder newQueryBuilder(IterationContext context, String url) { return new ArcImsQueryBuilder(context, this, url); } }
GeoinformationSystems/GeoprocessingAppstore
src/com/esri/gpt/catalog/harvest/protocols/HarvestProtocolArcIms.java
Java
apache-2.0
5,810
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.cloudkms.v1.model; /** * Request message for KeyManagementService.RestoreCryptoKeyVersion. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Key Management Service (KMS) API. For a * detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class RestoreCryptoKeyVersionRequest extends com.google.api.client.json.GenericJson { @Override public RestoreCryptoKeyVersionRequest set(String fieldName, Object value) { return (RestoreCryptoKeyVersionRequest) super.set(fieldName, value); } @Override public RestoreCryptoKeyVersionRequest clone() { return (RestoreCryptoKeyVersionRequest) super.clone(); } }
googleapis/google-api-java-client-services
clients/google-api-services-cloudkms/v1/1.31.0/com/google/api/services/cloudkms/v1/model/RestoreCryptoKeyVersionRequest.java
Java
apache-2.0
1,679
/* * Copyright (C) 2015 Twitter, 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. * */ package com.example.app.digits; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import com.example.app.R; public class ContactsReceiver extends BroadcastReceiver { static final int NOTIFICATION_ID = 0; @Override public void onReceive(Context context, Intent intent) { final NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); final Intent notifIntent = new Intent(context, FoundFriendsActivity.class); final PendingIntent notifPendingIntent = PendingIntent.getActivity(context, 0, notifIntent, 0); final String notifString = context.getString(R.string.you_have_new_friends); final Notification notification = new NotificationCompat.Builder(context) .setContentTitle(notifString) .setContentIntent(notifPendingIntent) .setSmallIcon(android.R.drawable.sym_def_app_icon) .build(); notificationManager.notify(NOTIFICATION_ID, notification); } }
vivekkiran/digits-android
samples/app/src/main/java/com/example/app/digits/ContactsReceiver.java
Java
apache-2.0
1,897
/* * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.security.spec; /** * This immutable class specifies the set of parameters used for * generating elliptic curve (EC) domain parameters. * * @see AlgorithmParameterSpec * * @author Valerie Peng * * @since 1.5 */ public class ECGenParameterSpec implements AlgorithmParameterSpec { private String name; /** * Creates a parameter specification for EC parameter * generation using a standard (or predefined) name * {@code stdName} in order to generate the corresponding * (precomputed) elliptic curve domain parameters. For the * list of supported names, please consult the documentation * of provider whose implementation will be used. * @param stdName the standard name of the to-be-generated EC * domain parameters. * @exception NullPointerException if {@code stdName} * is null. */ public ECGenParameterSpec(String stdName) { if (stdName == null) { throw new NullPointerException("stdName is null"); } this.name = stdName; } /** * Returns the standard or predefined name of the * to-be-generated EC domain parameters. * @return the standard or predefined name. */ public String getName() { return name; } }
shun634501730/java_source_cn
src_en/java/security/spec/ECGenParameterSpec.java
Java
apache-2.0
1,494
/* * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.synapse.rest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.synapse.MessageContext; import org.apache.synapse.SynapseException; /** * Abstract representation of an entity that can process REST messages. The caller can * first invoke the canProcess method of the processor to validate whether this processor * can process the given request or not. */ public abstract class AbstractRESTProcessor { protected Log log = LogFactory.getLog(getClass()); protected String name; public AbstractRESTProcessor(String name) { this.name = name; } /** * Check whether this processor can handle the given request * * @param synCtx MessageContext of the message to be processed * @return true if the processor is suitable for handling the message */ abstract boolean canProcess(MessageContext synCtx); /** * Process the given message through this processor instance * * @param synCtx MessageContext of the message to be processed */ abstract void process(MessageContext synCtx); protected void handleException(String msg) { log.error(msg); throw new SynapseException(msg); } protected void handleException(String msg, Exception e) { log.error(msg, e); throw new SynapseException(msg, e); } }
maheshika/wso2-synapse
modules/core/src/main/java/org/apache/synapse/rest/AbstractRESTProcessor.java
Java
apache-2.0
2,067
package com.redhat.ceylon.compiler.java.metadata; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation applied to a Java class which had a compile time error but * got generated anyway because of error recovery. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface CompileTimeError { }
unratito/ceylon.language
runtime/com/redhat/ceylon/compiler/java/metadata/CompileTimeError.java
Java
apache-2.0
449
from lib.actions import BaseAction class ApprovalAction(BaseAction): def run(self, number): s = self.client s.table = 'change_request' res = s.get({'number': number}) sys_id = res[0]['sys_id'] response = s.update({'approval': 'approved'}, sys_id) return response
armab/st2contrib
packs/servicenow/actions/approve_change.py
Python
apache-2.0
317
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.operator.aggregation; import com.google.common.collect.ImmutableList; import io.trino.spi.block.Block; import io.trino.spi.block.BlockBuilder; import io.trino.spi.type.Type; import org.apache.commons.math3.stat.descriptive.moment.Variance; import java.util.List; import static io.trino.spi.type.BigintType.BIGINT; public class TestLongVarianceAggregation extends AbstractTestAggregationFunction { @Override protected Block[] getSequenceBlocks(int start, int length) { BlockBuilder blockBuilder = BIGINT.createBlockBuilder(null, length); for (int i = start; i < start + length; i++) { BIGINT.writeLong(blockBuilder, i); } return new Block[] {blockBuilder.build()}; } @Override protected Number getExpectedValue(int start, int length) { if (length < 2) { return null; } double[] values = new double[length]; for (int i = 0; i < length; i++) { values[i] = start + i; } Variance variance = new Variance(); return variance.evaluate(values); } @Override protected String getFunctionName() { return "variance"; } @Override protected List<Type> getFunctionParameterTypes() { return ImmutableList.of(BIGINT); } }
ebyhr/presto
core/trino-main/src/test/java/io/trino/operator/aggregation/TestLongVarianceAggregation.java
Java
apache-2.0
1,904
// register-web-ui-test.js // // Test that the home page shows an invitation to join // // Copyright 2012, E14N https://e14n.com/ // // 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. var assert = require("assert"), vows = require("vows"), oauthutil = require("./lib/oauth"), Browser = require("zombie"), Step = require("step"), setupApp = oauthutil.setupApp, setupAppConfig = oauthutil.setupAppConfig; var suite = vows.describe("layout test"); // A batch to test some of the layout basics suite.addBatch({ "When we set up the app": { topic: function() { setupAppConfig({site: "Test"}, this.callback); }, teardown: function(app) { if (app && app.close) { app.close(); } }, "it works": function(err, app) { assert.ifError(err); }, "and we visit the root URL": { topic: function() { var browser, callback = this.callback; browser = new Browser(); browser.visit("http://localhost:4815/main/register", function(err, br) { callback(err, br); }); }, "it works": function(err, br) { assert.ifError(err); assert.isTrue(br.success); }, "and we check the content": { topic: function(br) { var callback = this.callback; callback(null, br); }, "it includes a registration div": function(err, br) { assert.ok(br.query("div#registerpage")); }, "it includes a registration form": function(err, br) { assert.ok(br.query("div#registerpage form")); }, "the registration form has a nickname field": function(err, br) { assert.ok(br.query("div#registerpage form input[name=\"nickname\"]")); }, "the registration form has a password field": function(err, br) { assert.ok(br.query("div#registerpage form input[name=\"password\"]")); }, "the registration form has a password repeat field": function(err, br) { assert.ok(br.query("div#registerpage form input[name=\"repeat\"]")); }, "the registration form has a submit button": function(err, br) { assert.ok(br.query("div#registerpage form button[type=\"submit\"]")); }, "and we submit the form": { topic: function() { var callback = this.callback, br = arguments[0]; Step( function() { br.fill("nickname", "sparks", this); }, function(err) { if (err) throw err; br.fill("password", "redplainsrider1", this); }, function(err) { if (err) throw err; br.fill("repeat", "redplainsrider1", this); }, function(err) { if (err) throw err; br.pressButton("button[type=\"submit\"]", this); }, function(err) { if (err) { callback(err, null); } else { callback(null, br); } } ); }, "it works": function(err, br) { assert.ifError(err); assert.isTrue(br.success); } } } } } }); suite["export"](module);
OpenSocial/pump.io
test/register-web-ui-test.js
JavaScript
apache-2.0
4,694
<?php namespace Drupal\Driver\Cores; use Drupal\Component\Utility\Random; use Symfony\Component\DependencyInjection\Container; /** * Base class for core drivers. */ abstract class AbstractCore implements CoreInterface { /** * System path to the Drupal installation. * * @var string */ protected $drupalRoot; /** * URI for the Drupal installation. * * @var string */ protected $uri; /** * Random generator. * * @var \Drupal\Component\Utility\Random */ protected $random; /** * {@inheritdoc} */ public function __construct($drupal_root, $uri = 'default', Random $random = NULL) { $this->drupalRoot = realpath($drupal_root); $this->uri = $uri; if (!isset($random)) { $random = new Random(); } $this->random = $random; } /** * {@inheritdoc} */ public function getRandom() { return $this->random; } /** * {@inheritdoc} */ public function getFieldHandler($entity, $entity_type, $field_name) { $reflection = new \ReflectionClass($this); $core_namespace = $reflection->getShortName(); $field_types = $this->getEntityFieldTypes($entity_type); $camelized_type = Container::camelize($field_types[$field_name]); $default_class = sprintf('\Drupal\Driver\Fields\%s\DefaultHandler', $core_namespace); $class_name = sprintf('\Drupal\Driver\Fields\%s\%sHandler', $core_namespace, $camelized_type); if (class_exists($class_name)) { return new $class_name($entity, $entity_type, $field_name); } return new $default_class($entity, $entity_type, $field_name); } /** * Expands properties on the given entity object to the expected structure. * * @param \stdClass $entity * Entity object. */ protected function expandEntityFields($entity_type, \stdClass $entity) { $field_types = $this->getEntityFieldTypes($entity_type); foreach ($field_types as $field_name => $type) { if (isset($entity->$field_name)) { $entity->$field_name = $this->getFieldHandler($entity, $entity_type, $field_name) ->expand($entity->$field_name); } } } /** * {@inheritdoc} */ public function clearStaticCaches() { } }
rlnorthcutt/acquia-cd-demo
vendor/drupal/drupal-driver/src/Drupal/Driver/Cores/AbstractCore.php
PHP
apache-2.0
2,215
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.orc.impl; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.io.IntWritable; import org.apache.orc.impl.RedBlackTree; import org.apache.orc.impl.StringRedBlackTree; import org.junit.Test; import java.io.IOException; import static junit.framework.Assert.assertEquals; /** * Test the red-black tree with string keys. */ public class TestStringRedBlackTree { /** * Checks the red-black tree rules to make sure that we have correctly built * a valid tree. * * Properties: * 1. Red nodes must have black children * 2. Each node must have the same black height on both sides. * * @param node The id of the root of the subtree to check for the red-black * tree properties. * @return The black-height of the subtree. */ private int checkSubtree(RedBlackTree tree, int node, IntWritable count ) throws IOException { if (node == RedBlackTree.NULL) { return 1; } count.set(count.get() + 1); boolean is_red = tree.isRed(node); int left = tree.getLeft(node); int right = tree.getRight(node); if (is_red) { if (tree.isRed(left)) { printTree(tree, "", tree.root); throw new IllegalStateException("Left node of " + node + " is " + left + " and both are red."); } if (tree.isRed(right)) { printTree(tree, "", tree.root); throw new IllegalStateException("Right node of " + node + " is " + right + " and both are red."); } } int left_depth = checkSubtree(tree, left, count); int right_depth = checkSubtree(tree, right, count); if (left_depth != right_depth) { printTree(tree, "", tree.root); throw new IllegalStateException("Lopsided tree at node " + node + " with depths " + left_depth + " and " + right_depth); } if (is_red) { return left_depth; } else { return left_depth + 1; } } /** * Checks the validity of the entire tree. Also ensures that the number of * nodes visited is the same as the size of the set. */ void checkTree(RedBlackTree tree) throws IOException { IntWritable count = new IntWritable(0); if (tree.isRed(tree.root)) { printTree(tree, "", tree.root); throw new IllegalStateException("root is red"); } checkSubtree(tree, tree.root, count); if (count.get() != tree.size) { printTree(tree, "", tree.root); throw new IllegalStateException("Broken tree! visited= " + count.get() + " size=" + tree.size); } } void printTree(RedBlackTree tree, String indent, int node ) throws IOException { if (node == RedBlackTree.NULL) { System.err.println(indent + "NULL"); } else { System.err.println(indent + "Node " + node + " color " + (tree.isRed(node) ? "red" : "black")); printTree(tree, indent + " ", tree.getLeft(node)); printTree(tree, indent + " ", tree.getRight(node)); } } private static class MyVisitor implements StringRedBlackTree.Visitor { private final String[] words; private final int[] order; private final DataOutputBuffer buffer = new DataOutputBuffer(); int current = 0; MyVisitor(String[] args, int[] order) { words = args; this.order = order; } @Override public void visit(StringRedBlackTree.VisitorContext context ) throws IOException { String word = context.getText().toString(); assertEquals("in word " + current, words[current], word); assertEquals("in word " + current, order[current], context.getOriginalPosition()); buffer.reset(); context.writeBytes(buffer); assertEquals(word, new String(buffer.getData(),0,buffer.getLength())); current += 1; } } void checkContents(StringRedBlackTree tree, int[] order, String... params ) throws IOException { tree.visit(new MyVisitor(params, order)); } StringRedBlackTree buildTree(String... params) throws IOException { StringRedBlackTree result = new StringRedBlackTree(1000); for(String word: params) { result.add(word); checkTree(result); } return result; } @Test public void test1() throws Exception { StringRedBlackTree tree = new StringRedBlackTree(5); assertEquals(0, tree.getSizeInBytes()); checkTree(tree); assertEquals(0, tree.add("owen")); checkTree(tree); assertEquals(1, tree.add("ashutosh")); checkTree(tree); assertEquals(0, tree.add("owen")); checkTree(tree); assertEquals(2, tree.add("alan")); checkTree(tree); assertEquals(2, tree.add("alan")); checkTree(tree); assertEquals(1, tree.add("ashutosh")); checkTree(tree); assertEquals(3, tree.add("greg")); checkTree(tree); assertEquals(4, tree.add("eric")); checkTree(tree); assertEquals(5, tree.add("arun")); checkTree(tree); assertEquals(6, tree.size()); checkTree(tree); assertEquals(6, tree.add("eric14")); checkTree(tree); assertEquals(7, tree.add("o")); checkTree(tree); assertEquals(8, tree.add("ziggy")); checkTree(tree); assertEquals(9, tree.add("z")); checkTree(tree); checkContents(tree, new int[]{2,5,1,4,6,3,7,0,9,8}, "alan", "arun", "ashutosh", "eric", "eric14", "greg", "o", "owen", "z", "ziggy"); assertEquals(32888, tree.getSizeInBytes()); // check that adding greg again bumps the count assertEquals(3, tree.add("greg")); assertEquals(41, tree.getCharacterSize()); // add some more strings to test the different branches of the // rebalancing assertEquals(10, tree.add("zak")); checkTree(tree); assertEquals(11, tree.add("eric1")); checkTree(tree); assertEquals(12, tree.add("ash")); checkTree(tree); assertEquals(13, tree.add("harry")); checkTree(tree); assertEquals(14, tree.add("john")); checkTree(tree); tree.clear(); checkTree(tree); assertEquals(0, tree.getSizeInBytes()); assertEquals(0, tree.getCharacterSize()); } @Test public void test2() throws Exception { StringRedBlackTree tree = buildTree("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"); assertEquals(26, tree.size()); checkContents(tree, new int[]{0,1,2, 3,4,5, 6,7,8, 9,10,11, 12,13,14, 15,16,17, 18,19,20, 21,22,23, 24,25}, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j","k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"); } @Test public void test3() throws Exception { StringRedBlackTree tree = buildTree("z", "y", "x", "w", "v", "u", "t", "s", "r", "q", "p", "o", "n", "m", "l", "k", "j", "i", "h", "g", "f", "e", "d", "c", "b", "a"); assertEquals(26, tree.size()); checkContents(tree, new int[]{25,24,23, 22,21,20, 19,18,17, 16,15,14, 13,12,11, 10,9,8, 7,6,5, 4,3,2, 1,0}, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"); } }
BUPTAnderson/apache-hive-2.1.1-src
orc/src/test/org/apache/orc/impl/TestStringRedBlackTree.java
Java
apache-2.0
8,010
/*** Copyright (c) 2008-2012 CommonsWare, LLC 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 _The Busy Coder's Guide to Android Development_ http://commonsware.com/Android */ package com.commonsware.android.fakeplayer; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class FakePlayer extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void startPlayer(View v) { Intent i=new Intent(this, PlayerService.class); i.putExtra(PlayerService.EXTRA_PLAYLIST, "main"); i.putExtra(PlayerService.EXTRA_SHUFFLE, true); startService(i); } public void stopPlayer(View v) { stopService(new Intent(this, PlayerService.class)); } }
atishagrawal/cw-android
Service/FakePlayer/src/com/commonsware/android/fakeplayer/FakePlayer.java
Java
apache-2.0
1,352
/* * Copyright (c) 2012-2015 S-Core Co., Ltd. * * 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. */ /** * This file handles the search result data. * * @since 1.4.1 * @author minsung.jin@samsung.com */ define([ './search-result-model', ], function ( model ) { 'use strict'; /** * search with the given metadata. * @param {Object} metadata - search condition(keyword, replace with, scope, options) * @param {viewCallback} callback - out-param(search results) */ function handleFind(metadata, callback) { model.makeFindData(metadata, function (err, title, store) { if (err) { callback(err); } else { callback(null, { title : title, store : store }); } }); } /** * replace the code with the given metadata. * @param {Object} metadata - replacing condition(keyword, replace with, scope, options) * @param {viewCallback} callback - out-param(the replacement result) */ function handleReplace(metadata, callback) { model.makeReplaceData(metadata, function (err, title) { if (err) { callback(err); } else { callback(null, title); } }); } /** * set the search scope * @param {string} scope - set the range of scope(selection, project, workspace) * @param {ViewCallback} callback - out-param(a path of scope) */ function handleSelection(scope, callback) { model.getScopePath(scope, function (err, scope) { if (err) { callback(err); } else { callback(null, scope); } }); } /** * select item replaced * @param {object} item - item replaced or not * @param {boolean} checked - item value * @param {ViewCallback} callback - set a value in the view. */ function handleCheckbox(item, checked, callback) { model.updateReplacePaths(item, checked, function () { callback(); }); } return { handleFind : handleFind, handleReplace : handleReplace, handleSelection : handleSelection, handleCheckbox : handleCheckbox }; });
kyungmi/webida-client
apps/ide/src/plugins/webida.ide.search-result/search-result-controller.js
JavaScript
apache-2.0
2,843
# -*- coding:utf-8 -*- # Copyright 2015 NEC Corporation. # # # # 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 org.o3project.odenos.core.component.network.flow.basic.flow_action import ( FlowAction ) class OFPFlowActionPopMpls(FlowAction): MPLS_UNICAST = 0x8847 MPLS_MULTICAST = 0x8848 # property key ETH_TYPE = "eth_type" def __init__(self, type_, eth_type): super(OFPFlowActionPopMpls, self).__init__(type_) self._body[self.ETH_TYPE] = eth_type @property def eth_type(self): return self._body[self.ETH_TYPE] @classmethod def create_from_packed(cls, packed): return cls(packed[cls.TYPE], packed[cls.ETH_TYPE]) def packed_object(self): return self._body
haizawa/odenos
src/main/python/org/o3project/odenos/core/component/network/flow/ofpflow/ofp_flow_action_pop_mpls.py
Python
apache-2.0
1,666
/* * Copyright 2014 Goldman Sachs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.impl.multimap.list; import java.io.Externalizable; import com.gs.collections.api.block.predicate.Predicate2; import com.gs.collections.api.list.MutableList; import com.gs.collections.api.map.MutableMap; import com.gs.collections.api.multimap.Multimap; import com.gs.collections.api.multimap.bag.MutableBagMultimap; import com.gs.collections.api.tuple.Pair; import com.gs.collections.impl.list.mutable.MultiReaderFastList; import com.gs.collections.impl.map.mutable.ConcurrentHashMap; import com.gs.collections.impl.utility.Iterate; public final class MultiReaderFastListMultimap<K, V> extends AbstractMutableListMultimap<K, V> implements Externalizable { private static final long serialVersionUID = 1L; // Default from FastList private static final int DEFAULT_CAPACITY = 1; private int initialListCapacity; public MultiReaderFastListMultimap() { this.initialListCapacity = DEFAULT_CAPACITY; } public MultiReaderFastListMultimap(int distinctKeys, int valuesPerKey) { super(Math.max(distinctKeys * 2, 16)); if (distinctKeys < 0 || valuesPerKey < 0) { throw new IllegalArgumentException("Both arguments must be positive."); } this.initialListCapacity = valuesPerKey; } public MultiReaderFastListMultimap(Multimap<? extends K, ? extends V> multimap) { this( multimap.keysView().size(), multimap instanceof MultiReaderFastListMultimap ? ((MultiReaderFastListMultimap<?, ?>) multimap).initialListCapacity : DEFAULT_CAPACITY); this.putAll(multimap); } public MultiReaderFastListMultimap(Pair<K, V>... pairs) { super(pairs); } public MultiReaderFastListMultimap(Iterable<Pair<K, V>> inputIterable) { super(inputIterable); } public static <K, V> MultiReaderFastListMultimap<K, V> newMultimap() { return new MultiReaderFastListMultimap<K, V>(); } public static <K, V> MultiReaderFastListMultimap<K, V> newMultimap(Multimap<? extends K, ? extends V> multimap) { return new MultiReaderFastListMultimap<K, V>(multimap); } public static <K, V> MultiReaderFastListMultimap<K, V> newMultimap(Pair<K, V>... pairs) { return new MultiReaderFastListMultimap<K, V>(pairs); } public static <K, V> MultiReaderFastListMultimap<K, V> newMultimap(Iterable<Pair<K, V>> inputIterable) { return new MultiReaderFastListMultimap<K, V>(inputIterable); } @Override protected MutableMap<K, MutableList<V>> createMap() { return ConcurrentHashMap.newMap(); } @Override protected MutableMap<K, MutableList<V>> createMapWithKeyCount(int keyCount) { return ConcurrentHashMap.newMap(keyCount); } @Override protected MutableList<V> createCollection() { return MultiReaderFastList.newList(this.initialListCapacity); } public MultiReaderFastListMultimap<K, V> newEmpty() { return new MultiReaderFastListMultimap<K, V>(); } public MutableBagMultimap<V, K> flip() { return Iterate.flip(this); } public FastListMultimap<K, V> selectKeysValues(Predicate2<? super K, ? super V> predicate) { return this.selectKeysValues(predicate, FastListMultimap.<K, V>newMultimap()); } public FastListMultimap<K, V> rejectKeysValues(Predicate2<? super K, ? super V> predicate) { return this.rejectKeysValues(predicate, FastListMultimap.<K, V>newMultimap()); } public FastListMultimap<K, V> selectKeysMultiValues(Predicate2<? super K, ? super Iterable<V>> predicate) { return this.selectKeysMultiValues(predicate, FastListMultimap.<K, V>newMultimap()); } public FastListMultimap<K, V> rejectKeysMultiValues(Predicate2<? super K, ? super Iterable<V>> predicate) { return this.rejectKeysMultiValues(predicate, FastListMultimap.<K, V>newMultimap()); } }
gabby2212/gs-collections
collections/src/main/java/com/gs/collections/impl/multimap/list/MultiReaderFastListMultimap.java
Java
apache-2.0
4,667
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.pc.analytics.core.generic.internal; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; import org.wso2.carbon.pc.core.ProcessCenterService; import static org.wso2.carbon.pc.analytics.core.generic.internal.AnalyticsServerHolder.getInstance; /** * @scr.component name="org.wso2.carbon.pc.analytics.core.kpi.internal.PCAnalticsServiceComponent" immediate="true" * @scr.reference name="process.center" interface="org.wso2.carbon.pc.core.ProcessCenterService" * cardinality="1..1" policy="dynamic" bind="setProcessCenter" unbind="unsetProcessCenter" */ public class AnalyticsServiceComponent { private static Log log = LogFactory.getLog(AnalyticsServiceComponent.class); protected void activate(ComponentContext ctxt) { log.info("Initializing the Process Center Analytics component"); } protected void deactivate(ComponentContext ctxt) { log.info("Stopping the Process Center Analytics core component"); } protected void setProcessCenter(ProcessCenterService processCenterService) { if (log.isDebugEnabled()) { log.debug("ProcessCenter bound to Process Center Analytics Publisher component"); } getInstance().setProcessCenter(processCenterService.getProcessCenter()); } protected void unsetProcessCenter( ProcessCenterService processCenterService) { if (log.isDebugEnabled()) { log.debug("ProcessCenter unbound from the Process Center Analytics Publisher component"); } getInstance().setProcessCenter(null); } }
rmsamitha/product-pc
modules/components/analytics/core/generic/org.wso2.carbon.pc.analytics.core.generic/src/main/java/org/wso2/carbon/pc/analytics/core/generic/internal/AnalyticsServiceComponent.java
Java
apache-2.0
2,302
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2015 Alec Jacobson <alecjacobson@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "is_vertex_manifold.h" #include "triangle_triangle_adjacency.h" #include "vertex_triangle_adjacency.h" #include "unique.h" #include <vector> #include <cassert> #include <map> #include <queue> #include <iostream> template <typename DerivedF,typename DerivedB> IGL_INLINE bool igl::is_vertex_manifold( const Eigen::PlainObjectBase<DerivedF>& F, Eigen::PlainObjectBase<DerivedB>& B) { using namespace std; using namespace Eigen; assert(F.cols() == 3 && "F must contain triangles"); typedef typename DerivedF::Scalar Index; typedef typename DerivedF::Index FIndex; const FIndex m = F.rows(); const Index n = F.maxCoeff()+1; vector<vector<vector<FIndex > > > TT; vector<vector<vector<FIndex > > > TTi; triangle_triangle_adjacency(F,TT,TTi); vector<vector<FIndex > > V2F,_1; vertex_triangle_adjacency(n,F,V2F,_1); const auto & check_vertex = [&](const Index v)->bool { vector<FIndex> uV2Fv; { vector<size_t> _1,_2; unique(V2F[v],uV2Fv,_1,_2); } const FIndex one_ring_size = uV2Fv.size(); if(one_ring_size == 0) { return false; } const FIndex g = uV2Fv[0]; queue<Index> Q; Q.push(g); map<FIndex,bool> seen; while(!Q.empty()) { const FIndex f = Q.front(); Q.pop(); if(seen.count(f)==1) { continue; } seen[f] = true; // Face f's neighbor lists opposite opposite each corner for(const auto & c : TT[f]) { // Each neighbor for(const auto & n : c) { bool contains_v = false; for(Index nc = 0;nc<F.cols();nc++) { if(F(n,nc) == v) { contains_v = true; break; } } if(seen.count(n)==0 && contains_v) { Q.push(n); } } } } return one_ring_size == (FIndex) seen.size(); }; // Unreferenced vertices are considered non-manifold B.setConstant(n,1,false); // Loop over all vertices touched by F bool all = true; for(Index v = 0;v<n;v++) { all &= B(v) = check_vertex(v); } return all; } #ifdef IGL_STATIC_LIBRARY template bool igl::is_vertex_manifold<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&); #endif
ygling2008/direct_edge_imu
thirdparty/igl/is_vertex_manifold.cpp
C++
apache-2.0
2,784
//// [stringLiteralTypesOverloads03.ts] interface Base { x: string; y: number; } interface HelloOrWorld extends Base { p1: boolean; } interface JustHello extends Base { p2: boolean; } interface JustWorld extends Base { p3: boolean; } let hello: "hello"; let world: "world"; let helloOrWorld: "hello" | "world"; function f(p: "hello"): JustHello; function f(p: "hello" | "world"): HelloOrWorld; function f(p: "world"): JustWorld; function f(p: string): Base; function f(...args: any[]): any { return undefined; } let fResult1 = f(hello); let fResult2 = f(world); let fResult3 = f(helloOrWorld); function g(p: string): Base; function g(p: "hello"): JustHello; function g(p: "hello" | "world"): HelloOrWorld; function g(p: "world"): JustWorld; function g(...args: any[]): any { return undefined; } let gResult1 = g(hello); let gResult2 = g(world); let gResult3 = g(helloOrWorld); //// [stringLiteralTypesOverloads03.js] var hello; var world; var helloOrWorld; function f() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return undefined; } var fResult1 = f(hello); var fResult2 = f(world); var fResult3 = f(helloOrWorld); function g() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return undefined; } var gResult1 = g(hello); var gResult2 = g(world); var gResult3 = g(helloOrWorld); //// [stringLiteralTypesOverloads03.d.ts] interface Base { x: string; y: number; } interface HelloOrWorld extends Base { p1: boolean; } interface JustHello extends Base { p2: boolean; } interface JustWorld extends Base { p3: boolean; } declare let hello: "hello"; declare let world: "world"; declare let helloOrWorld: "hello" | "world"; declare function f(p: "hello"): JustHello; declare function f(p: "hello" | "world"): HelloOrWorld; declare function f(p: "world"): JustWorld; declare function f(p: string): Base; declare let fResult1: JustHello; declare let fResult2: JustWorld; declare let fResult3: HelloOrWorld; declare function g(p: string): Base; declare function g(p: "hello"): JustHello; declare function g(p: "hello" | "world"): HelloOrWorld; declare function g(p: "world"): JustWorld; declare let gResult1: JustHello; declare let gResult2: JustWorld; declare let gResult3: Base;
jwbay/TypeScript
tests/baselines/reference/stringLiteralTypesOverloads03.js
JavaScript
apache-2.0
2,432
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sample.camel; import java.util.ArrayList; import java.util.List; import org.apache.camel.LoggingLevel; import org.apache.camel.builder.RouteBuilder; import org.apache.http.ProtocolException; import org.hl7.fhir.dstu3.model.Patient; import org.springframework.stereotype.Component; /** * A simple Camel route that triggers from a file and pushes to a FHIR server. * <p/> * Use <tt>@Component</tt> to make Camel auto detect this route when starting. */ @Component public class MyCamelRouter extends RouteBuilder { @Override public void configure() throws Exception { from("file:{{input}}").routeId("fhir-example") .onException(ProtocolException.class) .handled(true) .log(LoggingLevel.ERROR, "Error connecting to FHIR server with URL:{{serverUrl}}, please check the application.properties file ${exception.message}") .end() .log("Converting ${file:name}") .unmarshal().csv() .process(exchange -> { List<Patient> bundle = new ArrayList<>(); @SuppressWarnings("unchecked") List<List<String>> patients = (List<List<String>>) exchange.getIn().getBody(); for (List<String> patient: patients) { Patient fhirPatient = new Patient(); fhirPatient.setId(patient.get(0)); fhirPatient.addName().addGiven(patient.get(1)); fhirPatient.getNameFirstRep().setFamily(patient.get(2)); bundle.add(fhirPatient); } exchange.getIn().setBody(bundle); }) // create Patient in our FHIR server .to("fhir://transaction/withResources?inBody=resources&serverUrl={{serverUrl}}&username={{serverUser}}&password={{serverPassword}}&fhirVersion={{fhirVersion}}") // log the outcome .log("Patients created successfully: ${body}"); } }
kevinearls/camel
examples/camel-example-fhir-auth-tx-spring-boot/src/main/java/sample/camel/MyCamelRouter.java
Java
apache-2.0
2,786
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package upgrade import ( "fmt" "os" "path/filepath" "time" "github.com/pkg/errors" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" errorsutil "k8s.io/apimachinery/pkg/util/errors" "k8s.io/apimachinery/pkg/util/version" clientset "k8s.io/client-go/kubernetes" certutil "k8s.io/client-go/util/cert" kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm" kubeadmapiv1beta1 "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1beta1" kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants" "k8s.io/kubernetes/cmd/kubeadm/app/phases/addons/dns" "k8s.io/kubernetes/cmd/kubeadm/app/phases/addons/proxy" "k8s.io/kubernetes/cmd/kubeadm/app/phases/bootstraptoken/clusterinfo" nodebootstraptoken "k8s.io/kubernetes/cmd/kubeadm/app/phases/bootstraptoken/node" certsphase "k8s.io/kubernetes/cmd/kubeadm/app/phases/certs" kubeletphase "k8s.io/kubernetes/cmd/kubeadm/app/phases/kubelet" patchnodephase "k8s.io/kubernetes/cmd/kubeadm/app/phases/patchnode" "k8s.io/kubernetes/cmd/kubeadm/app/phases/uploadconfig" "k8s.io/kubernetes/cmd/kubeadm/app/util/apiclient" dryrunutil "k8s.io/kubernetes/cmd/kubeadm/app/util/dryrun" ) var expiry = 180 * 24 * time.Hour // PerformPostUpgradeTasks runs nearly the same functions as 'kubeadm init' would do // Note that the mark-control-plane phase is left out, not needed, and no token is created as that doesn't belong to the upgrade func PerformPostUpgradeTasks(client clientset.Interface, cfg *kubeadmapi.InitConfiguration, newK8sVer *version.Version, dryRun bool) error { errs := []error{} // Upload currently used configuration to the cluster // Note: This is done right in the beginning of cluster initialization; as we might want to make other phases // depend on centralized information from this source in the future if err := uploadconfig.UploadConfiguration(cfg, client); err != nil { errs = append(errs, err) } // Create the new, version-branched kubelet ComponentConfig ConfigMap if err := kubeletphase.CreateConfigMap(cfg.ClusterConfiguration.ComponentConfigs.Kubelet, cfg.KubernetesVersion, client); err != nil { errs = append(errs, errors.Wrap(err, "error creating kubelet configuration ConfigMap")) } // Write the new kubelet config down to disk and the env file if needed if err := writeKubeletConfigFiles(client, cfg, newK8sVer, dryRun); err != nil { errs = append(errs, err) } // Annotate the node with the crisocket information, sourced either from the InitConfiguration struct or // --cri-socket. // TODO: In the future we want to use something more official like NodeStatus or similar for detecting this properly if err := patchnodephase.AnnotateCRISocket(client, cfg.NodeRegistration.Name, cfg.NodeRegistration.CRISocket); err != nil { errs = append(errs, errors.Wrap(err, "error uploading crisocket")) } // Create/update RBAC rules that makes the bootstrap tokens able to post CSRs if err := nodebootstraptoken.AllowBootstrapTokensToPostCSRs(client); err != nil { errs = append(errs, err) } // Create/update RBAC rules that makes the bootstrap tokens able to get their CSRs approved automatically if err := nodebootstraptoken.AutoApproveNodeBootstrapTokens(client); err != nil { errs = append(errs, err) } // Create/update RBAC rules that makes the nodes to rotate certificates and get their CSRs approved automatically if err := nodebootstraptoken.AutoApproveNodeCertificateRotation(client); err != nil { errs = append(errs, err) } // TODO: Is this needed to do here? I think that updating cluster info should probably be separate from a normal upgrade // Create the cluster-info ConfigMap with the associated RBAC rules // if err := clusterinfo.CreateBootstrapConfigMapIfNotExists(client, kubeadmconstants.GetAdminKubeConfigPath()); err != nil { // return err //} // Create/update RBAC rules that makes the cluster-info ConfigMap reachable if err := clusterinfo.CreateClusterInfoRBACRules(client); err != nil { errs = append(errs, err) } // Rotate the kube-apiserver cert and key if needed if err := BackupAPIServerCertIfNeeded(cfg, dryRun); err != nil { errs = append(errs, err) } // Upgrade kube-dns/CoreDNS and kube-proxy if err := dns.EnsureDNSAddon(&cfg.ClusterConfiguration, client); err != nil { errs = append(errs, err) } // Remove the old DNS deployment if a new DNS service is now used (kube-dns to CoreDNS or vice versa) if err := removeOldDNSDeploymentIfAnotherDNSIsUsed(&cfg.ClusterConfiguration, client, dryRun); err != nil { errs = append(errs, err) } if err := proxy.EnsureProxyAddon(&cfg.ClusterConfiguration, &cfg.LocalAPIEndpoint, client); err != nil { errs = append(errs, err) } return errorsutil.NewAggregate(errs) } func removeOldDNSDeploymentIfAnotherDNSIsUsed(cfg *kubeadmapi.ClusterConfiguration, client clientset.Interface, dryRun bool) error { return apiclient.TryRunCommand(func() error { installedDeploymentName := kubeadmconstants.KubeDNSDeploymentName deploymentToDelete := kubeadmconstants.CoreDNSDeploymentName if cfg.DNS.Type == kubeadmapi.CoreDNS { installedDeploymentName = kubeadmconstants.CoreDNSDeploymentName deploymentToDelete = kubeadmconstants.KubeDNSDeploymentName } // If we're dry-running, we don't need to wait for the new DNS addon to become ready if !dryRun { dnsDeployment, err := client.AppsV1().Deployments(metav1.NamespaceSystem).Get(installedDeploymentName, metav1.GetOptions{}) if err != nil { return err } if dnsDeployment.Status.ReadyReplicas == 0 { return errors.New("the DNS deployment isn't ready yet") } } // We don't want to wait for the DNS deployment above to become ready when dryrunning (as it never will) // but here we should execute the DELETE command against the dryrun clientset, as it will only be logged err := apiclient.DeleteDeploymentForeground(client, metav1.NamespaceSystem, deploymentToDelete) if err != nil && !apierrors.IsNotFound(err) { return err } return nil }, 10) } // BackupAPIServerCertIfNeeded rotates the kube-apiserver certificate if older than 180 days func BackupAPIServerCertIfNeeded(cfg *kubeadmapi.InitConfiguration, dryRun bool) error { certAndKeyDir := kubeadmapiv1beta1.DefaultCertificatesDir shouldBackup, err := shouldBackupAPIServerCertAndKey(certAndKeyDir) if err != nil { // Don't fail the upgrade phase if failing to determine to backup kube-apiserver cert and key. return errors.Wrap(err, "[postupgrade] WARNING: failed to determine to backup kube-apiserver cert and key") } if !shouldBackup { return nil } // If dry-running, just say that this would happen to the user and exit if dryRun { fmt.Println("[postupgrade] Would rotate the API server certificate and key.") return nil } // Don't fail the upgrade phase if failing to backup kube-apiserver cert and key, just continue rotating the cert // TODO: We might want to reconsider this choice. if err := backupAPIServerCertAndKey(certAndKeyDir); err != nil { fmt.Printf("[postupgrade] WARNING: failed to backup kube-apiserver cert and key: %v", err) } return certsphase.CreateCertAndKeyFilesWithCA( &certsphase.KubeadmCertAPIServer, &certsphase.KubeadmCertRootCA, cfg, ) } func writeKubeletConfigFiles(client clientset.Interface, cfg *kubeadmapi.InitConfiguration, newK8sVer *version.Version, dryRun bool) error { kubeletDir, err := GetKubeletDir(dryRun) if err != nil { // The error here should never occur in reality, would only be thrown if /tmp doesn't exist on the machine. return err } errs := []error{} // Write the configuration for the kubelet down to disk so the upgraded kubelet can start with fresh config if err := kubeletphase.DownloadConfig(client, newK8sVer, kubeletDir); err != nil { // Tolerate the error being NotFound when dryrunning, as there is a pretty common scenario: the dryrun process // *would* post the new kubelet-config-1.X configmap that doesn't exist now when we're trying to download it // again. if !(apierrors.IsNotFound(err) && dryRun) { errs = append(errs, errors.Wrap(err, "error downloading kubelet configuration from the ConfigMap")) } } if dryRun { // Print what contents would be written dryrunutil.PrintDryRunFile(kubeadmconstants.KubeletConfigurationFileName, kubeletDir, kubeadmconstants.KubeletRunDirectory, os.Stdout) } envFilePath := filepath.Join(kubeadmconstants.KubeletRunDirectory, kubeadmconstants.KubeletEnvFileName) if _, err := os.Stat(envFilePath); os.IsNotExist(err) { // Write env file with flags for the kubelet to use. We do not need to write the --register-with-taints for the control-plane, // as we handle that ourselves in the mark-control-plane phase // TODO: Maybe we want to do that some time in the future, in order to remove some logic from the mark-control-plane phase? if err := kubeletphase.WriteKubeletDynamicEnvFile(&cfg.ClusterConfiguration, &cfg.NodeRegistration, false, kubeletDir); err != nil { errs = append(errs, errors.Wrap(err, "error writing a dynamic environment file for the kubelet")) } if dryRun { // Print what contents would be written dryrunutil.PrintDryRunFile(kubeadmconstants.KubeletEnvFileName, kubeletDir, kubeadmconstants.KubeletRunDirectory, os.Stdout) } } return errorsutil.NewAggregate(errs) } // GetKubeletDir gets the kubelet directory based on whether the user is dry-running this command or not. func GetKubeletDir(dryRun bool) (string, error) { if dryRun { return kubeadmconstants.CreateTempDirForKubeadm("kubeadm-upgrade-dryrun") } return kubeadmconstants.KubeletRunDirectory, nil } // backupAPIServerCertAndKey backups the old cert and key of kube-apiserver to a specified directory. func backupAPIServerCertAndKey(certAndKeyDir string) error { subDir := filepath.Join(certAndKeyDir, "expired") if err := os.Mkdir(subDir, 0766); err != nil { return errors.Wrapf(err, "failed to created backup directory %s", subDir) } filesToMove := map[string]string{ filepath.Join(certAndKeyDir, kubeadmconstants.APIServerCertName): filepath.Join(subDir, kubeadmconstants.APIServerCertName), filepath.Join(certAndKeyDir, kubeadmconstants.APIServerKeyName): filepath.Join(subDir, kubeadmconstants.APIServerKeyName), } return moveFiles(filesToMove) } // moveFiles moves files from one directory to another. func moveFiles(files map[string]string) error { filesToRecover := map[string]string{} for from, to := range files { if err := os.Rename(from, to); err != nil { return rollbackFiles(filesToRecover, err) } filesToRecover[to] = from } return nil } // rollbackFiles moves the files back to the original directory. func rollbackFiles(files map[string]string, originalErr error) error { errs := []error{originalErr} for from, to := range files { if err := os.Rename(from, to); err != nil { errs = append(errs, err) } } return errors.Errorf("couldn't move these files: %v. Got errors: %v", files, errorsutil.NewAggregate(errs)) } // shouldBackupAPIServerCertAndKey checks if the cert of kube-apiserver will be expired in 180 days. func shouldBackupAPIServerCertAndKey(certAndKeyDir string) (bool, error) { apiServerCert := filepath.Join(certAndKeyDir, kubeadmconstants.APIServerCertName) certs, err := certutil.CertsFromFile(apiServerCert) if err != nil { return false, errors.Wrapf(err, "couldn't load the certificate file %s", apiServerCert) } if len(certs) == 0 { return false, errors.New("no certificate data found") } if time.Since(certs[0].NotBefore) > expiry { return true, nil } return false, nil }
bsalamat/kubernetes
cmd/kubeadm/app/phases/upgrade/postupgrade.go
GO
apache-2.0
12,164
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.jackrabbit.oak.upgrade.cli.blob; import org.apache.jackrabbit.oak.spi.blob.BlobOptions; import org.apache.jackrabbit.oak.spi.blob.BlobStore; import org.jetbrains.annotations.NotNull; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import static com.google.common.base.Preconditions.checkNotNull; /** * Utility BlobStore implementation to be used in tooling that can work with a * FileStore without the need of the DataStore being present locally. * * Additionally instead of failing it tries to mimic and return blob reference * passed in by <b>caller</b> by passing it back as a binary. * * Example: requesting <code>blobId = e7c22b994c59d9</code> it will return the * <code>e7c22b994c59d9</code> text as a UTF-8 encoded binary file. */ public class LoopbackBlobStore implements BlobStore { @Override public String writeBlob(InputStream in) { throw new UnsupportedOperationException(); } @Override public String writeBlob(InputStream in, BlobOptions options) throws IOException { return writeBlob(in); } @Override public int readBlob(String blobId, long pos, byte[] buff, int off, int length) { // Only a part of binary can be requested! final int binaryLength = blobId.length(); checkBinaryOffsetInRange(pos, binaryLength); final int effectiveSrcPos = Math.toIntExact(pos); final int effectiveBlobLengthToBeRead = Math.min( binaryLength - effectiveSrcPos, length); checkForBufferOverflow(buff, off, effectiveBlobLengthToBeRead); final byte[] blobIdBytes = getBlobIdStringAsByteArray(blobId); System.arraycopy(blobIdBytes, effectiveSrcPos, buff, off, effectiveBlobLengthToBeRead); return effectiveBlobLengthToBeRead; } private void checkForBufferOverflow(final byte[] buff, final int off, final int effectiveBlobLengthToBeRead) { if (buff.length < effectiveBlobLengthToBeRead + off) { // We cannot recover if buffer used to write is too small throw new UnsupportedOperationException("Edge case: cannot fit " + "blobId in a buffer (buffer too small)"); } } private void checkBinaryOffsetInRange(final long pos, final int binaryLength) { if (pos > binaryLength) { throw new IllegalArgumentException( String.format("Offset %d out of range of %d", pos, binaryLength)); } } private byte[] getBlobIdStringAsByteArray(final String blobId) { return blobId.getBytes(StandardCharsets.UTF_8); } @Override public long getBlobLength(String blobId) throws IOException { return blobId.length(); } @Override public InputStream getInputStream(String blobId) throws IOException { checkNotNull(blobId); return new ByteArrayInputStream(getBlobIdStringAsByteArray(blobId)); } @Override public String getBlobId(@NotNull String reference) { return checkNotNull(reference); } @Override public String getReference(@NotNull String blobId) { return checkNotNull(blobId); } @Override public void close() throws Exception { } }
mreutegg/jackrabbit-oak
oak-upgrade/src/main/java/org/apache/jackrabbit/oak/upgrade/cli/blob/LoopbackBlobStore.java
Java
apache-2.0
4,214
// Copyright 2014 Invex Games http://invexgames.com // 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. using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.EventSystems; namespace MaterialUI { [ExecuteInEditMode()] public class SliderConfig : MonoBehaviour, IPointerDownHandler, IPointerUpHandler { [Header("Options")] public bool textHasDecimal; public bool hasPopup = true; public float animationDuration = 0.5f; public Color enabledColor; public Color disabledColor; [Header("References")] public RectTransform handle; public RectTransform popup; public Text popupText; public Text valueText; public Image fill; private Slider slider; private bool lastInteractableState; // Used to keep track of the Slider 'interactable' bool so SliderConfig isn't being enabled/disabled every frame private CanvasGroup canvasGroup; private Image handleImage; private Color onColor; float currentPopupScale; float currentHandleScale; float currentPos; bool isSelected; int state; float animStartTime; float animDeltaTime; Vector3 tempVec3; void Start () { slider = gameObject.GetComponent<Slider> (); popup.gameObject.GetComponent<Image> ().color = handle.gameObject.GetComponent<Image> ().color; handleImage = handle.GetComponent<Image>(); canvasGroup = gameObject.GetComponent<CanvasGroup>(); UpdateText(); } // This is triggered from toggling the 'interactable' bool on the Slider component private void EnableSlider () { canvasGroup.interactable = true; canvasGroup.blocksRaycasts = true; fill.color = enabledColor; } // This is triggered from toggling the 'interactable' bool on the Slider component private void DisableSlider() { canvasGroup.interactable = false; canvasGroup.blocksRaycasts = false; fill.color = disabledColor; } void Update () { if (state == 1) { // Updates the animDeltaTime every frame animDeltaTime = Time.realtimeSinceStartup - animStartTime; if (animDeltaTime <= animationDuration) { // Animation in progress // Resize handle tempVec3 = handle.localScale; tempVec3.x = Anim.Quint.Out(currentHandleScale, 1f, animDeltaTime, animationDuration); tempVec3.y = tempVec3.x; tempVec3.z = tempVec3.x; handle.localScale = tempVec3; // If there's a popup, resize it if (hasPopup) { tempVec3 = popup.localScale; tempVec3.x = Anim.Quint.Out(currentPopupScale, 1f, animDeltaTime, animationDuration); tempVec3.y = tempVec3.x; tempVec3.z = tempVec3.x; popup.localScale = tempVec3; tempVec3 = popup.localPosition; tempVec3.y = Anim.Quint.Out(currentPos, 16f, animDeltaTime, animationDuration); popup.localPosition = tempVec3; } } else { // Animation has completed state = 0; } } else if (state == 2) { // Updates animDeltaTime each frame animDeltaTime = Time.realtimeSinceStartup - animStartTime; if (animDeltaTime <= animationDuration) { // Animation in progess // Resize handle tempVec3 = handle.localScale; tempVec3.x = Anim.Quint.Out(currentHandleScale, 0.6f, animDeltaTime, animationDuration); tempVec3.y = tempVec3.x; tempVec3.z = tempVec3.x; handle.localScale = tempVec3; // If there's a popup, resize it if (hasPopup) { tempVec3 = popup.localScale; tempVec3.x = Anim.Quint.Out(currentPopupScale, 0f, animDeltaTime, animationDuration); tempVec3.y = tempVec3.x; tempVec3.z = tempVec3.x; popup.localScale = tempVec3; tempVec3 = popup.localPosition; tempVec3.y = Anim.Quint.Out(currentPos, 0f, animDeltaTime, animationDuration); popup.localPosition = tempVec3; } } else { // Animation has finished state = 0; } } // If in edit mode, update the fill color to either the enabledColor or Disabled color, depending if the slider is enabled or not if (!Application.isPlaying) { if (slider.interactable) { if (fill.color != enabledColor) fill.color = enabledColor; } else { if (fill.color != disabledColor) fill.color = disabledColor; } } // If the 'interactable' bool on the Slider has been changed, enable or disable the SliderConfig accordingly if (slider.interactable != lastInteractableState) { lastInteractableState = slider.interactable; if (slider.interactable) { EnableSlider(); } else { DisableSlider(); } } } // Updates the popup text to reflect the slider value public void UpdateText () { if (textHasDecimal) { popupText.text = slider.value.ToString("0.0"); if (valueText) valueText.text = slider.value.ToString("0.00"); } else { string tempText = slider.value.ToString("0"); popupText.text = tempText; if (valueText) valueText.text = tempText; } } public void OnPointerDown (PointerEventData data) { // Updates the 'current' values to animate from currentHandleScale = handle.localScale.x; currentPopupScale = popup.localScale.x; currentPos = popup.localPosition.y; animStartTime = Time.realtimeSinceStartup; // Starts animation isSelected = true; state = 1; } public void OnPointerUp (PointerEventData data) { if (isSelected) { // Updates the 'current' values to animate from currentHandleScale = handle.localScale.x; currentPopupScale = popup.localScale.x; currentPos = popup.localPosition.y; animStartTime = Time.realtimeSinceStartup; // Starts animation isSelected = false; state = 2; } } } }
QuantumCD/MaterialUI
Scripts/SliderConfig.cs
C#
apache-2.0
6,750
/* * reserved comment block * DO NOT REMOVE OR ALTER! */ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.org.apache.bcel.internal.generic; import java.io.DataOutputStream; import java.io.IOException; import com.sun.org.apache.bcel.internal.Const; import com.sun.org.apache.bcel.internal.ExceptionConst; import com.sun.org.apache.bcel.internal.classfile.ConstantPool; import com.sun.org.apache.bcel.internal.util.ByteSequence; /** * INVOKEINTERFACE - Invoke interface method * <PRE>Stack: ..., objectref, [arg1, [arg2 ...]] -&gt; ...</PRE> * * @see * <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-6.html#jvms-6.5.invokeinterface"> * The invokeinterface instruction in The Java Virtual Machine Specification</a> */ public final class INVOKEINTERFACE extends InvokeInstruction { private int nargs; // Number of arguments on stack (number of stack slots), called "count" in vmspec2 /** * Empty constructor needed for Instruction.readInstruction. * Not to be used otherwise. */ INVOKEINTERFACE() { } public INVOKEINTERFACE(final int index, final int nargs) { super(Const.INVOKEINTERFACE, index); super.setLength(5); if (nargs < 1) { throw new ClassGenException("Number of arguments must be > 0 " + nargs); } this.nargs = nargs; } /** * Dump instruction as byte code to stream out. * @param out Output stream */ @Override public void dump( final DataOutputStream out ) throws IOException { out.writeByte(super.getOpcode()); out.writeShort(super.getIndex()); out.writeByte(nargs); out.writeByte(0); } /** * The <B>count</B> argument according to the Java Language Specification, * Second Edition. */ public int getCount() { return nargs; } /** * Read needed data (i.e., index) from file. */ @Override protected void initFromFile( final ByteSequence bytes, final boolean wide ) throws IOException { super.initFromFile(bytes, wide); super.setLength(5); nargs = bytes.readUnsignedByte(); bytes.readByte(); // Skip 0 byte } /** * @return mnemonic for instruction with symbolic references resolved */ @Override public String toString( final ConstantPool cp ) { return super.toString(cp) + " " + nargs; } @Override public int consumeStack( final ConstantPoolGen cpg ) { // nargs is given in byte-code return nargs; // nargs includes this reference } @Override public Class<?>[] getExceptions() { return ExceptionConst.createExceptions(ExceptionConst.EXCS.EXCS_INTERFACE_METHOD_RESOLUTION, ExceptionConst.UNSATISFIED_LINK_ERROR, ExceptionConst.ABSTRACT_METHOD_ERROR, ExceptionConst.ILLEGAL_ACCESS_ERROR, ExceptionConst.INCOMPATIBLE_CLASS_CHANGE_ERROR); } /** * Call corresponding visitor method(s). The order is: * Call visitor methods of implemented interfaces first, then * call methods according to the class hierarchy in descending order, * i.e., the most specific visitXXX() call comes last. * * @param v Visitor object */ @Override public void accept( final Visitor v ) { v.visitExceptionThrower(this); v.visitTypedInstruction(this); v.visitStackConsumer(this); v.visitStackProducer(this); v.visitLoadClass(this); v.visitCPInstruction(this); v.visitFieldOrMethod(this); v.visitInvokeInstruction(this); v.visitINVOKEINTERFACE(this); } }
mirkosertic/Bytecoder
classlib/java.xml/src/main/resources/META-INF/modules/java.xml/classes/com/sun/org/apache/bcel/internal/generic/INVOKEINTERFACE.java
Java
apache-2.0
4,443
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.math.curve; import com.opengamma.analytics.math.function.Function; import com.opengamma.util.ArgumentChecker; /** * A function that performs subtraction on each of the constituent curves. * <p> * Given a number of curves $C_1(x_{i_1}, y_{i_1}) , C_2(x_{i_2}, y_{i_2}), \ldots C_n(x_{i_n}, y_{i_n})$, returns a function $F$ * that for a value $x$ will return: * $$ * \begin{eqnarray*} * F(x) = C_1 |_x - C_2 |_x - \ldots - C_n |_x * \end{eqnarray*} * $$ */ public class SubtractCurveSpreadFunction implements CurveSpreadFunction { /** The operation name */ public static final String NAME = "-"; /** An instance of this function */ private static final SubtractCurveSpreadFunction INSTANCE = new SubtractCurveSpreadFunction(); /** * Gets an instance of this function * @return The instance */ public static CurveSpreadFunction getInstance() { return INSTANCE; } /** * @deprecated Use {@link #getInstance()} */ @Deprecated public SubtractCurveSpreadFunction() { } /** * @param curves An array of curves, not null or empty * @return A function that will find the value of each curve at the given input <i>x</i> and subtract each in turn */ @SuppressWarnings("unchecked") @Override public Function<Double, Double> evaluate(final Curve<Double, Double>... curves) { ArgumentChecker.notEmpty(curves, "curves"); return new Function<Double, Double>() { @Override public Double evaluate(final Double... x) { ArgumentChecker.notEmpty(x, "x"); final double x0 = x[0]; double y = curves[0].getYValue(x0); for (int i = 1; i < curves.length; i++) { y -= curves[i].getYValue(x0); } return y; } }; } @Override public String getOperationName() { return NAME; } @Override public String getName() { return NAME; } }
jeorme/OG-Platform
projects/OG-Analytics/src/main/java/com/opengamma/analytics/math/curve/SubtractCurveSpreadFunction.java
Java
apache-2.0
2,054
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.siddhi.core.query.selector.attribute.aggregator; import io.siddhi.annotation.Example; import io.siddhi.annotation.Extension; import io.siddhi.annotation.Parameter; import io.siddhi.annotation.ParameterOverload; import io.siddhi.annotation.ReturnAttribute; import io.siddhi.annotation.util.DataType; import io.siddhi.core.config.SiddhiQueryContext; import io.siddhi.core.exception.OperationNotSupportedException; import io.siddhi.core.executor.ExpressionExecutor; import io.siddhi.core.query.processor.ProcessingMode; import io.siddhi.core.util.config.ConfigReader; import io.siddhi.core.util.snapshot.state.State; import io.siddhi.core.util.snapshot.state.StateFactory; import io.siddhi.query.api.definition.Attribute; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * {@link AttributeAggregatorExecutor} to calculate max value for life time based on an event attribute. */ @Extension( name = "maxForever", namespace = "", description = "This is the attribute aggregator to store the maximum value for a given attribute throughout " + "the lifetime of the query regardless of any windows in-front.", parameters = { @Parameter(name = "arg", description = "The value that needs to be compared to find the maximum value.", type = {DataType.INT, DataType.LONG, DataType.DOUBLE, DataType.FLOAT}, dynamic = true) }, parameterOverloads = { @ParameterOverload(parameterNames = {"arg"}) }, returnAttributes = @ReturnAttribute( description = "Returns the maximum value in the same data type as the input.", type = {DataType.INT, DataType.LONG, DataType.DOUBLE, DataType.FLOAT}), examples = @Example( syntax = "from inputStream\n" + "select maxForever(temp) as max\n" + "insert into outputStream;", description = "maxForever(temp) returns the maximum temp value recorded for all the events throughout" + " the lifetime of the query." ) ) public class MaxForeverAttributeAggregatorExecutor extends AttributeAggregatorExecutor<MaxForeverAttributeAggregatorExecutor.MaxAggregatorState> { private Attribute.Type returnType; /** * The initialization method for FunctionExecutor * * @param attributeExpressionExecutors are the executors of each attributes in the function * @param processingMode query processing mode * @param outputExpectsExpiredEvents is expired events sent as output * @param configReader this hold the {@link MaxForeverAttributeAggregatorExecutor} * configuration reader. * @param siddhiQueryContext Siddhi query runtime context */ @Override protected StateFactory<MaxAggregatorState> init(ExpressionExecutor[] attributeExpressionExecutors, ProcessingMode processingMode, boolean outputExpectsExpiredEvents, ConfigReader configReader, SiddhiQueryContext siddhiQueryContext) { if (attributeExpressionExecutors.length != 1) { throw new OperationNotSupportedException("MaxForever aggregator has to have exactly 1 parameter, " + "currently " + attributeExpressionExecutors.length + " parameters provided"); } returnType = attributeExpressionExecutors[0].getReturnType(); return new StateFactory<MaxAggregatorState>() { @Override public MaxAggregatorState createNewState() { switch (returnType) { case FLOAT: return new MaxForeverAttributeAggregatorStateFloat(); case INT: return new MaxForeverAttributeAggregatorStateInt(); case LONG: return new MaxForeverAttributeAggregatorStateLong(); case DOUBLE: return new MaxForeverAttributeAggregatorStateDouble(); default: throw new OperationNotSupportedException("MaxForever not supported for " + returnType); } } }; } public Attribute.Type getReturnType() { return returnType; } @Override public Object processAdd(Object data, MaxAggregatorState state) { if (data == null) { return state.currentValue(); } return state.processAdd(data); } @Override public Object processAdd(Object[] data, MaxAggregatorState state) { // will not occur return new IllegalStateException("MaxForever cannot process data array, but found " + Arrays.deepToString(data)); } @Override public Object processRemove(Object data, MaxAggregatorState state) { if (data == null) { return state.currentValue(); } return state.processRemove(data); } @Override public Object processRemove(Object[] data, MaxAggregatorState state) { // will not occur return new IllegalStateException("MaxForever cannot process data array, but found " + Arrays.deepToString(data)); } @Override public Object reset(MaxAggregatorState state) { return state.reset(); } class MaxForeverAttributeAggregatorStateDouble extends MaxAggregatorState { private volatile Double maxValue = null; @Override public Object processAdd(Object data) { Double value = (Double) data; if (maxValue == null || maxValue < value) { maxValue = value; } return maxValue; } @Override public Object processRemove(Object data) { Double value = (Double) data; if (maxValue == null || maxValue < value) { maxValue = value; } return maxValue; } @Override public Object reset() { return maxValue; } @Override public boolean canDestroy() { return maxValue == null; } @Override public Map<String, Object> snapshot() { Map<String, Object> state = new HashMap<>(); state.put("MaxValue", maxValue); return state; } @Override public void restore(Map<String, Object> state) { maxValue = (Double) state.get("MaxValue"); } protected Object currentValue() { return maxValue; } } class MaxForeverAttributeAggregatorStateFloat extends MaxAggregatorState { private volatile Float maxValue = null; @Override public Object processAdd(Object data) { Float value = (Float) data; if (maxValue == null || maxValue < value) { maxValue = value; } return maxValue; } @Override public Object processRemove(Object data) { Float value = (Float) data; if (maxValue == null || maxValue < value) { maxValue = value; } return maxValue; } @Override public Object reset() { return maxValue; } @Override public boolean canDestroy() { return maxValue == null; } @Override public Map<String, Object> snapshot() { Map<String, Object> state = new HashMap<>(); state.put("MaxValue", maxValue); return state; } @Override public void restore(Map<String, Object> state) { maxValue = (Float) state.get("MaxValue"); } protected Object currentValue() { return maxValue; } } class MaxForeverAttributeAggregatorStateInt extends MaxAggregatorState { private volatile Integer maxValue = null; @Override public Object processAdd(Object data) { Integer value = (Integer) data; if (maxValue == null || maxValue < value) { maxValue = value; } return maxValue; } @Override public Object processRemove(Object data) { Integer value = (Integer) data; if (maxValue == null || maxValue < value) { maxValue = value; } return maxValue; } @Override public Object reset() { return maxValue; } @Override public boolean canDestroy() { return maxValue == null; } @Override public Map<String, Object> snapshot() { Map<String, Object> state = new HashMap<>(); state.put("MaxValue", maxValue); return state; } @Override public void restore(Map<String, Object> state) { maxValue = (Integer) state.get("MaxValue"); } protected Object currentValue() { return maxValue; } } class MaxForeverAttributeAggregatorStateLong extends MaxAggregatorState { private volatile Long maxValue = null; @Override public Object processAdd(Object data) { Long value = (Long) data; if (maxValue == null || maxValue < value) { maxValue = value; } return maxValue; } @Override public Object processRemove(Object data) { Long value = (Long) data; if (maxValue == null || maxValue < value) { maxValue = value; } return maxValue; } @Override public Object reset() { return maxValue; } @Override public boolean canDestroy() { return maxValue == null; } @Override public Map<String, Object> snapshot() { Map<String, Object> state = new HashMap<>(); state.put("MaxValue", maxValue); return state; } @Override public void restore(Map<String, Object> state) { maxValue = (Long) state.get("MaxValue"); } protected Object currentValue() { return maxValue; } } abstract class MaxAggregatorState extends State { public abstract Object processAdd(Object data); public abstract Object processRemove(Object data); public abstract Object reset(); protected abstract Object currentValue(); } }
wso2/siddhi
modules/siddhi-core/src/main/java/io/siddhi/core/query/selector/attribute/aggregator/MaxForeverAttributeAggregatorExecutor.java
Java
apache-2.0
11,651
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.ode.bpel.dao; import javax.sql.DataSource; /** * Extension of the {@link BpelDAOConnectionFactory} interface for DAOs that * are based on J2EE/JDBC data sources. * * @author Maciej Szefler - m s z e f l e r @ g m a i l . c o m */ public interface BpelDAOConnectionFactoryJDBC extends BpelDAOConnectionFactory { /** * Set the managed data source (transactions tied to transaction manager). * @param ds */ public void setDataSource(DataSource ds); /** * Set the unmanaged data source. * @param ds */ public void setUnmanagedDataSource(DataSource ds); /** * Set the transaction manager. * @param tm */ public void setTransactionManager(Object tm); }
mproch/apache-ode
bpel-dao/src/main/java/org/apache/ode/bpel/dao/BpelDAOConnectionFactoryJDBC.java
Java
apache-2.0
1,565
// // MessagePack for C++ static resolution routine // // Copyright (C) 2008-2015 FURUHASHI Sadayuki // // 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. // #ifndef MSGPACK_TYPE_SET_HPP #define MSGPACK_TYPE_SET_HPP #include "msgpack/versioning.hpp" #include "msgpack/adaptor/adaptor_base.hpp" #include "msgpack/adaptor/check_container_size.hpp" #include <set> namespace msgpack { /// @cond MSGPACK_API_VERSION_NAMESPACE(v1) { /// @endcond namespace adaptor { template <typename T> struct convert<std::set<T> > { msgpack::object const& operator()(msgpack::object const& o, std::set<T>& v) const { if(o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); } msgpack::object* p = o.via.array.ptr + o.via.array.size; msgpack::object* const pbegin = o.via.array.ptr; std::set<T> tmp; while(p > pbegin) { --p; tmp.insert(p->as<T>()); } #if __cplusplus >= 201103L v = std::move(tmp); #else tmp.swap(v); #endif return o; } }; template <typename T> struct pack<std::set<T> > { template <typename Stream> msgpack::packer<Stream>& operator()(msgpack::packer<Stream>& o, const std::set<T>& v) const { uint32_t size = checked_get_container_size(v.size()); o.pack_array(size); for(typename std::set<T>::const_iterator it(v.begin()), it_end(v.end()); it != it_end; ++it) { o.pack(*it); } return o; } }; template <typename T> struct object_with_zone<std::set<T> > { void operator()(msgpack::object::with_zone& o, const std::set<T>& v) const { o.type = msgpack::type::ARRAY; if(v.empty()) { o.via.array.ptr = nullptr; o.via.array.size = 0; } else { uint32_t size = checked_get_container_size(v.size()); msgpack::object* p = static_cast<msgpack::object*>(o.zone.allocate_align(sizeof(msgpack::object)*size)); msgpack::object* const pend = p + size; o.via.array.ptr = p; o.via.array.size = size; typename std::set<T>::const_iterator it(v.begin()); do { *p = msgpack::object(*it, o.zone); ++p; ++it; } while(p < pend); } } }; template <typename T> struct convert<std::multiset<T> > { msgpack::object const& operator()(msgpack::object const& o, std::multiset<T>& v) const { if(o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); } msgpack::object* p = o.via.array.ptr + o.via.array.size; msgpack::object* const pbegin = o.via.array.ptr; std::multiset<T> tmp; while(p > pbegin) { --p; tmp.insert(p->as<T>()); } #if __cplusplus >= 201103L v = std::move(tmp); #else tmp.swap(v); #endif return o; } }; template <typename T> struct pack<std::multiset<T> > { template <typename Stream> msgpack::packer<Stream>& operator()(msgpack::packer<Stream>& o, const std::multiset<T>& v) const { uint32_t size = checked_get_container_size(v.size()); o.pack_array(size); for(typename std::multiset<T>::const_iterator it(v.begin()), it_end(v.end()); it != it_end; ++it) { o.pack(*it); } return o; } }; template <typename T> struct object_with_zone<std::multiset<T> > { void operator()(msgpack::object::with_zone& o, const std::multiset<T>& v) const { o.type = msgpack::type::ARRAY; if(v.empty()) { o.via.array.ptr = nullptr; o.via.array.size = 0; } else { uint32_t size = checked_get_container_size(v.size()); msgpack::object* p = static_cast<msgpack::object*>(o.zone.allocate_align(sizeof(msgpack::object)*size)); msgpack::object* const pend = p + size; o.via.array.ptr = p; o.via.array.size = size; typename std::multiset<T>::const_iterator it(v.begin()); do { *p = msgpack::object(*it, o.zone); ++p; ++it; } while(p < pend); } } }; } // namespace adaptor /// @cond } // MSGPACK_API_VERSION_NAMESPACE(v1) /// @endcond } // namespace msgpack #endif // MSGPACK_TYPE_SET_HPP
vashstorm/msgpack-c
include/msgpack/adaptor/set.hpp
C++
apache-2.0
4,878
(function() { 'use strict'; angular.module('replicationControllers', []) .service('replicationControllerService', ['$q', ReplicationControllerDataService]); /** * Replication Controller DataService * Mock async data service. * * @returns {{loadAll: Function}} * @constructor */ function ReplicationControllerDataService($q) { var replicationControllers = { "kind": "List", "apiVersion": "v1", "metadata": {}, "items": [ { "kind": "ReplicationController", "apiVersion": "v1", "metadata": { "name": "redis-master", "namespace": "default", "selfLink": "/api/v1/namespaces/default/replicationcontrollers/redis-master", "uid": "f12969e0-ff77-11e4-8f2d-080027213276", "resourceVersion": "28", "creationTimestamp": "2015-05-21T05:12:14Z", "labels": { "name": "redis-master" } }, "spec": { "replicas": 1, "selector": { "name": "redis-master" }, "template": { "metadata": { "creationTimestamp": null, "labels": { "name": "redis-master" } }, "spec": { "containers": [ { "name": "master", "image": "redis", "ports": [ { "containerPort": 6379, "protocol": "TCP" } ], "resources": {}, "terminationMessagePath": "/dev/termination-log", "imagePullPolicy": "IfNotPresent", "capabilities": {}, "securityContext": { "capabilities": {}, "privileged": false } } ], "restartPolicy": "Always", "dnsPolicy": "ClusterFirst", "serviceAccount": "" } } }, "status": { "replicas": 1 } } ]}; // Uses promises return { loadAll: function() { // Simulate async call return $q.when(replicationControllers); } }; } })();
kubernetes-ui/kube-ui
master/components/dashboard/js/modules/services/replicationControllersMock.js
JavaScript
apache-2.0
2,865
/******************************************************************************* * (c) Copyright 2014 Hewlett-Packard Development Company, L.P. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License v2.0 which accompany this distribution. * * The Apache License is available at * http://www.apache.org/licenses/LICENSE-2.0 * *******************************************************************************/ package io.cloudslang.worker.management.services; /** * Date: 6/13/13 * * Manages the worker internal recovery. * Holds the current WRV (worker recovery version) as known to worker. */ public interface WorkerRecoveryManager { void doRecovery(); boolean isInRecovery(); String getWRV(); void setWRV(String newWrv); }
narry/score
worker/worker-manager/score-worker-manager-api/src/main/java/io/cloudslang/worker/management/services/WorkerRecoveryManager.java
Java
apache-2.0
810
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.managers.systemview.walker; import org.apache.ignite.spi.systemview.view.SystemViewRowAttributeWalker; import org.apache.ignite.spi.systemview.view.datastructures.ReentrantLockView; /** * Generated by {@code org.apache.ignite.codegen.SystemViewRowAttributeWalkerGenerator}. * {@link ReentrantLockView} attributes walker. * * @see ReentrantLockView */ public class ReentrantLockViewWalker implements SystemViewRowAttributeWalker<ReentrantLockView> { /** {@inheritDoc} */ @Override public void visitAll(AttributeVisitor v) { v.accept(0, "name", String.class); v.accept(1, "locked", boolean.class); v.accept(2, "hasQueuedThreads", boolean.class); v.accept(3, "failoverSafe", boolean.class); v.accept(4, "fair", boolean.class); v.accept(5, "broken", boolean.class); v.accept(6, "groupName", String.class); v.accept(7, "groupId", int.class); v.accept(8, "removed", boolean.class); } /** {@inheritDoc} */ @Override public void visitAll(ReentrantLockView row, AttributeWithValueVisitor v) { v.accept(0, "name", String.class, row.name()); v.acceptBoolean(1, "locked", row.locked()); v.acceptBoolean(2, "hasQueuedThreads", row.hasQueuedThreads()); v.acceptBoolean(3, "failoverSafe", row.failoverSafe()); v.acceptBoolean(4, "fair", row.fair()); v.acceptBoolean(5, "broken", row.broken()); v.accept(6, "groupName", String.class, row.groupName()); v.acceptInt(7, "groupId", row.groupId()); v.acceptBoolean(8, "removed", row.removed()); } /** {@inheritDoc} */ @Override public int count() { return 9; } }
ascherbakoff/ignite
modules/core/src/main/java/org/apache/ignite/internal/managers/systemview/walker/ReentrantLockViewWalker.java
Java
apache-2.0
2,529
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.application; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.util.BuildNumber; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.util.Calendar; public abstract class ApplicationInfo { public abstract Calendar getBuildDate(); public abstract BuildNumber getBuild(); public abstract String getApiVersion(); public abstract String getMajorVersion(); public abstract String getMinorVersion(); public abstract String getMicroVersion(); public abstract String getPatchVersion(); public abstract String getVersionName(); @Nullable public abstract String getHelpURL(); /** * Use this method to refer to the company in official contexts where it may have any legal implications. * @see #getShortCompanyName() * @return full name of the product vendor, e.g. 'JetBrains s.r.o.' for JetBrains products */ public abstract String getCompanyName(); /** * Use this method to refer to the company in a less formal way, e.g. in UI messages or directory names. * @see #getCompanyName() * @return shortened name of the product vendor without 'Inc.' or similar suffixes, e.g. 'JetBrains' for JetBrains products */ public abstract String getShortCompanyName(); public abstract String getCompanyURL(); @Nullable public abstract String getThirdPartySoftwareURL(); public abstract String getJetbrainsTvUrl(); public abstract String getEvalLicenseUrl(); public abstract String getKeyConversionUrl(); @Nullable public abstract Rectangle getAboutLogoRect(); public abstract boolean hasHelp(); public abstract boolean hasContextHelp(); public abstract String getFullVersion(); public abstract String getStrictVersion(); public static ApplicationInfo getInstance() { return ServiceManager.getService(ApplicationInfo.class); } public static boolean helpAvailable() { return ApplicationManager.getApplication() != null && getInstance() != null && getInstance().hasHelp(); } public static boolean contextHelpAvailable() { return ApplicationManager.getApplication() != null && getInstance() != null && getInstance().hasContextHelp(); } /** @deprecated use {@link #getBuild()} instead (to remove in IDEA 16) */ @SuppressWarnings("UnusedDeclaration") public String getBuildNumber() { return getBuild().asString(); } }
asedunov/intellij-community
platform/core-api/src/com/intellij/openapi/application/ApplicationInfo.java
Java
apache-2.0
2,993