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 |
|---|---|---|---|---|---|
<?php
class sfGuardGroupUtf8Table extends sfGuardGroupTable
{
public static function getInstance()
{
return Doctrine_Core::getTable('sfGuardGroupUtf8');
}
} | simonoche/wterritoires | lib/model/doctrine/sfGuardGroupUtf8Table.class.php | PHP | agpl-3.0 | 183 |
<?php
require_once("conf.php");
$text = $head;
$text .= $body;
$text .= menu("");
$text .= main();
$text .= $foot;
echo gzipoutput($text);
// ===========================================================================
function main()
{
global $email, $pass, $pass2, $mysql_db, $name;
if (($email != "") and ($pass != "")) { // Variablen nicht leer?
if ((validateEmail($email))) { // Email in Ordnung?
if ($pass == $pass2) { // Passwort nicht verschrieben?
$lk = connect();
$db = mysql_db_query($mysql_db, "SELECT * FROM pricewatch_user WHERE EMAIL=\"" . trim(addslashes(strtolower($email))) . "\" LIMIT 1", $lk);
if (!$arr = mysql_fetch_array($db, MYSQL_ASSOC)) { // E-Mail schon eingetragen?
$db = mysql_db_query($mysql_db, "INSERT pricewatch_user (EMAIL, PASSWORT) VALUES (\"" . trim(addslashes(strtolower($email))) . "\", \"" . addslashes($pass) . "\")", $lk);
if ($db == true) { // DB Eintrag erfolgreich?
sendemail ($email, "Anmeldung bei $name", anmeldetext($email, $pass));
$str .= "<br><br><table width='400' align='center' class='rand'>";
$str .= "<tr><td>";
$str .= "<p align='center'><b>Anmeldung erfolgreich abgeschlossen!</b></p>";
$str .= "<p align='justify'>Sie können sich jetzt mit ihrer E-Mail und Passwort auf der Startseite einloggen. Zur Bestätigung haben wir ihnen eine E-Mail mit den angegeben Daten geschickt.</p>";
$str .= "<p align='center'><a href='index.php'>Zurück zur Startseite</a></p>";
$str .= "</td></tr></table><br><br>";
} else { // DB Eintrag erfolgreich?
$fehler = "Es ist ein Datenbankproblem aufgetreten. Bitte probieren sie es später noch einmal.";
} //DB Eintrag erfolgreich? - Else
} else { // E-Mail schon eingetragen?
$fehler = "Die E-Mail Adresse ist bereits bei uns angemeldet!";
} // E-Mail schon eingetragen? - Else
mysql_close($lk);
} else { // Passwort nicht verschrieben?
$fehler = "Das Feld Passwort und das Feld Passwort Wiederholung stimmen nicht überein!";
} // Passwort nicht verschrieben? - Else
} else { // Email in Ordnung?
$fehler = "Bitte geben sie eine echte E-Mail Adresse an!";
} // Email in Ordnung? - Else
} // Variablen nicht leer?
if ((isset($fehler)) OR ($email == "") OR ($pass == "")) {
$str = "<br><br>";
if (isset($fehler)) {
$str .= "<table width='400' align='center' class='rand'>";
$str .= "<tr><td>";
$str .= "<p align='center'><b>Es ist ein Fehler aufgetreten!</b></p><p align='justify'>$fehler</p></td></tr>";
$str .= "</table><br>";
}
$str .= "<table width='400' align='center' class='rand'>";
$str .= "<tr><td>";
$str .= "<p align='justify'>Bitte füllen sie das folgende Formular <b>komplett</b> aus und klicken sie auf anmelden! Nach ihrer Anmeldung wird ihnen eine Bestätigungs per E-Mail zugesandt.<br><br></p></td></tr>";
$str .= "<tr><td><table width='75%' align='center'>";
$str .= "<form method='post' action='anmelden.php'>";
$str .= "<tr><td>E-Mail:</td>";
$str .= "<td align='center'><input type='text' name='email' class='input' value='$email'></td></tr>";
$str .= "<tr><td>Passwort:</td>";
$str .= "<td align='center'><input type='password' name='pass' class='input'></td></tr>";
$str .= "<tr><td>Passwort Wdh.:</td>";
$str .= "<td align='center'><input type='password' name='pass2' class='input'></td></tr>";
$str .= "<tr><td colspan='2' align='center'><br><input type='submit' name='Anmelden' class='forminput' value=' Anmelden '></fotm></td></tr>";
$str .= "</table></td></tr>";
$str .= "</table>";
$str .= "<br><br><br>";
}
return $str;
}
?> | jbreitbart/priceguard_classic | branches/first/anmelden.php | PHP | agpl-3.0 | 4,179 |
import * as React from 'react';
import _ from 'lodash';
import {
civicSortValue,
DEFAULT_ANNOTATION_DATA,
GenericAnnotation,
IAnnotation,
USE_DEFAULT_PUBLIC_INSTANCE_FOR_ONCOKB,
oncoKbAnnotationSortValue,
} from 'react-mutation-mapper';
import { CancerStudy, StructuralVariant } from 'cbioportal-ts-api-client';
import { IAnnotationColumnProps } from 'shared/components/mutationTable/column/AnnotationColumnFormatter';
import { CancerGene, IndicatorQueryResp } from 'oncokb-ts-api-client';
import {
RemoteData,
IOncoKbData,
generateQueryStructuralVariantId,
OncoKbCardDataType,
calculateOncoKbAvailableDataType,
} from 'cbioportal-utils';
import AnnotationHeader from 'shared/components/mutationTable/column/annotation/AnnotationHeader';
export default class AnnotationColumnFormatter {
public static getData(
structuralVariantData: StructuralVariant[] | undefined,
oncoKbCancerGenes?: RemoteData<CancerGene[] | Error | undefined>,
oncoKbData?: RemoteData<IOncoKbData | Error | undefined>,
usingPublicOncoKbInstance?: boolean,
uniqueSampleKeyToTumorType?: { [sampleId: string]: string },
studyIdToStudy?: { [studyId: string]: CancerStudy }
) {
let value: IAnnotation;
if (structuralVariantData) {
let oncoKbIndicator: IndicatorQueryResp | undefined = undefined;
let oncoKbStatus: IAnnotation['oncoKbStatus'] = 'complete';
let oncoKbGeneExist = false;
let isOncoKbCancerGene = false;
let isSite1GeneOncoKbAnnotated = false;
let isSite1oncoKbCancerGene = false;
let isSite2GeneOncoKbAnnotated = false;
let isSite2oncoKbCancerGene = false;
if (
oncoKbCancerGenes &&
!(oncoKbCancerGenes instanceof Error) &&
!(oncoKbCancerGenes.result instanceof Error)
) {
const oncoKbCancerGeneSetByEntrezGeneId = _.keyBy(
oncoKbCancerGenes.result,
gene => gene.entrezGeneId
);
isSite1oncoKbCancerGene =
oncoKbCancerGeneSetByEntrezGeneId[
structuralVariantData[0].site1EntrezGeneId
] !== undefined;
isSite2oncoKbCancerGene =
oncoKbCancerGeneSetByEntrezGeneId[
structuralVariantData[0].site2EntrezGeneId
] !== undefined;
isSite1GeneOncoKbAnnotated =
isSite1oncoKbCancerGene &&
oncoKbCancerGeneSetByEntrezGeneId[
structuralVariantData[0].site1EntrezGeneId
].oncokbAnnotated;
isSite2GeneOncoKbAnnotated =
isSite2oncoKbCancerGene &&
oncoKbCancerGeneSetByEntrezGeneId[
structuralVariantData[0].site2EntrezGeneId
].oncokbAnnotated;
oncoKbGeneExist =
isSite1GeneOncoKbAnnotated || isSite2GeneOncoKbAnnotated;
isOncoKbCancerGene =
isSite1oncoKbCancerGene || isSite2oncoKbCancerGene;
}
// Always show oncogenicity icon even when the indicatorMapResult is empty.
// We want to show an icon for genes that haven't been annotated by OncoKB
let oncoKbAvailableDataTypes: OncoKbCardDataType[] = [
OncoKbCardDataType.BIOLOGICAL,
];
// oncoKbData may exist but it might be an instance of Error, in that case we flag the status as error
if (oncoKbData && oncoKbData.result instanceof Error) {
oncoKbStatus = 'error';
} else if (oncoKbGeneExist) {
// actually, oncoKbData.result shouldn't be an instance of Error in this case (we already check it above),
// but we need to check it again in order to avoid TS errors/warnings
if (
oncoKbData &&
oncoKbData.result &&
!(oncoKbData.result instanceof Error) &&
oncoKbData.isComplete
) {
oncoKbIndicator = this.getIndicatorData(
structuralVariantData,
oncoKbData.result,
uniqueSampleKeyToTumorType,
studyIdToStudy
);
oncoKbAvailableDataTypes = _.uniq([
...oncoKbAvailableDataTypes,
...calculateOncoKbAvailableDataType(
_.values(oncoKbData.result.indicatorMap)
),
]);
}
oncoKbStatus = oncoKbData ? oncoKbData.status : 'pending';
}
const site1HugoSymbol = structuralVariantData[0].site1HugoSymbol;
const site2HugoSymbol = structuralVariantData[0].site2HugoSymbol;
let hugoGeneSymbol = site1HugoSymbol;
if (oncoKbGeneExist) {
hugoGeneSymbol = isSite1GeneOncoKbAnnotated
? site1HugoSymbol
: site2HugoSymbol;
} else if (isOncoKbCancerGene) {
hugoGeneSymbol = isSite1oncoKbCancerGene
? site1HugoSymbol
: site2HugoSymbol;
}
value = {
hugoGeneSymbol,
oncoKbStatus,
oncoKbIndicator,
oncoKbGeneExist,
isOncoKbCancerGene,
usingPublicOncoKbInstance:
usingPublicOncoKbInstance === undefined
? USE_DEFAULT_PUBLIC_INSTANCE_FOR_ONCOKB
: usingPublicOncoKbInstance,
civicEntry: undefined,
civicStatus: 'complete',
hasCivicVariants: false,
myCancerGenomeLinks: [],
hotspotStatus: 'complete',
isHotspot: false,
is3dHotspot: false,
oncoKbAvailableDataTypes,
};
} else {
value = DEFAULT_ANNOTATION_DATA;
}
return value;
}
public static getIndicatorData(
structuralVariantData: StructuralVariant[],
oncoKbData: IOncoKbData,
uniqueSampleKeyToTumorType?: { [sampleId: string]: string },
studyIdToStudy?: { [studyId: string]: CancerStudy }
): IndicatorQueryResp | undefined {
if (
uniqueSampleKeyToTumorType === null ||
oncoKbData.indicatorMap === null
) {
return undefined;
}
const id = generateQueryStructuralVariantId(
structuralVariantData[0].site1EntrezGeneId,
structuralVariantData[0].site2EntrezGeneId,
uniqueSampleKeyToTumorType![
structuralVariantData[0].uniqueSampleKey
],
structuralVariantData[0].variantClass.toUpperCase() as any
);
if (oncoKbData.indicatorMap[id]) {
let indicator = oncoKbData.indicatorMap[id];
if (indicator.query.tumorType === null && studyIdToStudy) {
const studyMetaData =
studyIdToStudy[structuralVariantData[0].studyId];
if (studyMetaData.cancerTypeId !== 'mixed') {
indicator.query.tumorType = studyMetaData.cancerType.name;
}
}
return indicator;
} else {
return undefined;
}
}
public static sortValue(
data: StructuralVariant[],
oncoKbCancerGenes?: RemoteData<CancerGene[] | Error | undefined>,
usingPublicOncoKbInstance?: boolean,
oncoKbData?: RemoteData<IOncoKbData | Error | undefined>,
uniqueSampleKeyToTumorType?: { [sampleId: string]: string }
): number[] {
const annotationData: IAnnotation = this.getData(
data,
oncoKbCancerGenes,
oncoKbData,
usingPublicOncoKbInstance,
uniqueSampleKeyToTumorType
);
return _.flatten([
oncoKbAnnotationSortValue(annotationData.oncoKbIndicator),
civicSortValue(annotationData.civicEntry),
annotationData.isOncoKbCancerGene ? 1 : 0,
]);
}
public static headerRender(
name: string,
width: number,
mergeOncoKbIcons?: boolean,
onOncoKbIconToggle?: (mergeIcons: boolean) => void
) {
return (
<AnnotationHeader
name={name}
width={width}
mergeOncoKbIcons={mergeOncoKbIcons}
onOncoKbIconToggle={onOncoKbIconToggle}
/>
);
}
public static renderFunction(
data: StructuralVariant[],
columnProps: IAnnotationColumnProps
) {
const annotation: IAnnotation = this.getData(
data,
columnProps.oncoKbCancerGenes,
columnProps.oncoKbData,
columnProps.usingPublicOncoKbInstance,
columnProps.uniqueSampleKeyToTumorType,
columnProps.studyIdToStudy
);
return <GenericAnnotation {...columnProps} annotation={annotation} />;
}
}
| cBioPortal/cbioportal-frontend | src/pages/patientView/structuralVariant/column/AnnotationColumnFormatter.tsx | TypeScript | agpl-3.0 | 9,418 |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'repository/tag query' do
let(:context) { {} }
let(:query_string) do
<<-QUERY
query ($repositoryId: ID!, $name: String!) {
repository(id: $repositoryId) {
tag(name: $name) {
name
target {
id
}
annotation
}
}
}
QUERY
end
let(:repository) do
create(:repository_compound, :not_empty,
public_access: false,
owner: current_user)
end
let(:git) { repository.git }
let!(:tag) { create(:tag, repository: repository, message: message) }
let(:current_user) { create(:user) }
let(:variables_base) { {'repositoryId' => repository.to_param} }
let(:variables_existent) { variables_base.merge('name' => tag.name) }
let(:variables_not_existent) { variables_base.merge('name' => 'bad') }
let(:expectation_signed_in_existent) do
tag_data = {
'name' => tag.name,
'annotation' => message,
'target' => {'id' => git.commit(tag.target).id},
}
match('data' => {'repository' => {'tag' => tag_data}})
end
let(:expectation_signed_in_not_existent) do
match('data' => {'repository' => {'tag' => nil}})
end
let(:expectation_not_signed_in_existent) do
match('data' => {'repository' => nil})
end
let(:expectation_not_signed_in_not_existent) do
expectation_not_signed_in_existent
end
context 'with annotation' do
let(:message) { 'message' }
it_behaves_like 'a GraphQL query', %w(repository tag)
end
context 'without annotation' do
let(:message) { nil }
it_behaves_like 'a GraphQL query', %w(repository tag)
end
end
| ontohub/ontohub-backend | spec/graphql/queries/repository/tag_query_spec.rb | Ruby | agpl-3.0 | 1,684 |
<?php
/*
Question2Answer (c) Gideon Greenspan
http://www.question2answer.org/
File: qa-include/qa-ajax-version.php
Version: See define()s at top of qa-include/qa-base.php
Description: Server-side response to Ajax version check requests
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.
More about this license: http://www.question2answer.org/license.php
*/
require_once QA_INCLUDE_DIR.'qa-app-admin.php';
$uri=qa_post_text('uri');
$versionkey=qa_post_text('versionkey');
$urikey=qa_post_text('urikey');
$version=qa_post_text('version');
$metadata=qa_admin_addon_metadata(qa_retrieve_url($uri), array(
'version' => $versionkey,
'uri' => $urikey,
// these two elements are only present for plugins, not themes, so we can hard code them here
'min_q2a' => 'Plugin Minimum Question2Answer Version',
'min_php' => 'Plugin Minimum PHP Version',
));
if (strlen(@$metadata['version'])) {
if (strcmp($metadata['version'], $version)) {
if (qa_qa_version_below(@$metadata['min_q2a']))
$response=strtr(qa_lang_html('admin/version_requires_q2a'), array(
'^1' => qa_html('v'.$metadata['version']),
'^2' => qa_html($metadata['min_q2a']),
));
elseif (qa_php_version_below(@$metadata['min_php']))
$response=strtr(qa_lang_html('admin/version_requires_php'), array(
'^1' => qa_html('v'.$metadata['version']),
'^2' => qa_html($metadata['min_php']),
));
else {
$response=qa_lang_html_sub('admin/version_get_x', qa_html('v'.$metadata['version']));
if (strlen(@$metadata['uri']))
$response='<A HREF="'.qa_html($metadata['uri']).'" STYLE="color:#d00;">'.$response.'</A>';
}
} else
$response=qa_lang_html('admin/version_latest');
} else
$response=qa_lang_html('admin/version_latest_unknown');
echo "QA_AJAX_RESPONSE\n1\n".$response;
/*
Omit PHP closing tag to help avoid accidental output
*/ | teleiakaipavla/diafthoratelos.gr | php/wordpress/qa/qa-include/qa-ajax-version.php | PHP | agpl-3.0 | 2,412 |
# -*- coding: utf-8 -*-
import os.path
import posixpath
import re
import urllib
from docutils import nodes
from sphinx import addnodes, util
from sphinx.locale import admonitionlabels
def _parents(node):
while node.parent:
node = node.parent
yield node
class BootstrapTranslator(nodes.NodeVisitor, object):
head_prefix = 'head_prefix'
head = 'head'
stylesheet = 'stylesheet'
body_prefix = 'body_prefix'
body_pre_docinfo = 'body_pre_docinfo'
docinfo = 'docinfo'
body_suffix = 'body_suffix'
subtitle = 'subtitle'
header = 'header'
footer = 'footer'
html_prolog = 'html_prolog'
html_head = 'html_head'
html_title = 'html_title'
html_subtitle = 'html_subtitle'
# <meta> tags
meta = [
'<meta http-equiv="X-UA-Compatible" content="IE=edge">',
'<meta name="viewport" content="width=device-width, initial-scale=1">'
]
def __init__(self, builder, document):
super(BootstrapTranslator, self).__init__(document)
self.builder = builder
self.body = []
self.fragment = self.body
self.html_body = self.body
# document title
self.title = []
self.start_document_title = 0
self.first_title = False
self.context = []
self.section_level = 0
self.highlightlang = self.highlightlang_base = self.builder.config.highlight_language
self.highlightopts = getattr(builder.config, 'highlight_options', {})
self.first_param = 1
self.optional_param_level = 0
self.required_params_left = 0
self.param_separator = ','
def encode(self, text):
return unicode(text).translate({
ord('&'): u'&',
ord('<'): u'<',
ord('"'): u'"',
ord('>'): u'>',
0xa0: u' '
})
def starttag(self, node, tagname, **attributes):
tagname = unicode(tagname).lower()
# extract generic attributes
attrs = {name.lower(): value for name, value in attributes.iteritems()}
attrs.update(
(name, value) for name, value in node.attributes.iteritems()
if name.startswith('data-')
)
prefix = []
postfix = []
# handle possibly multiple ids
assert 'id' not in attrs, "starttag can't be passed a single id attribute, use a list of ids"
ids = node.get('ids', []) + attrs.pop('ids', [])
if ids:
_ids = iter(ids)
attrs['id'] = next(_ids)
postfix.extend(u'<i id="{}"></i>'.format(_id) for _id in _ids)
# set CSS class
classes = set(node.get('classes', []) + attrs.pop('class', '').split())
if classes:
attrs['class'] = u' '.join(classes)
return u'{prefix}<{tag} {attrs}>{postfix}'.format(
prefix=u''.join(prefix),
tag=tagname,
attrs=u' '.join(u'{}="{}"'.format(name, self.attval(value))
for name, value in attrs.iteritems()),
postfix=u''.join(postfix),
)
# only "space characters" SPACE, CHARACTER TABULATION, LINE FEED,
# FORM FEED and CARRIAGE RETURN should be collapsed, not al White_Space
def attval(self, value, whitespace=re.compile(u'[ \t\n\f\r]')):
return self.encode(whitespace.sub(u' ', unicode(value)))
def astext(self):
return u''.join(self.body)
def unknown_visit(self, node):
print "unknown node", node.__class__.__name__
self.body.append(u'[UNKNOWN NODE {}]'.format(node.__class__.__name__))
raise nodes.SkipNode
def visit_highlightlang(self, node):
self.highlightlang = node['lang']
def depart_highlightlang(self, node):
pass
def visit_document(self, node):
self.first_title = True
def depart_document(self, node):
pass
def visit_section(self, node):
# close "parent" or preceding section, unless this is the opening of
# the first section
if self.section_level:
self.body.append(u'</section>')
self.section_level += 1
self.body.append(self.starttag(node, 'section'))
def depart_section(self, node):
self.section_level -= 1
# close last section of document
if not self.section_level:
self.body.append(u'</section>')
def is_compact_paragraph(self, node):
parent = node.parent
if isinstance(parent, (nodes.document, nodes.compound,
addnodes.desc_content,
addnodes.versionmodified)):
# Never compact paragraphs in document or compound.
return False
for key, value in node.attlist():
# we can ignore a few specific classes, all other non-default
# attributes require that a <p> node remains
if key != 'classes' or value not in ([], ['first'], ['last'], ['first', 'last']):
return False
first = isinstance(node.parent[0], nodes.label)
for child in parent.children[first:]:
# only first paragraph can be compact
if isinstance(child, nodes.Invisible):
continue
if child is node:
break
return False
parent_length = len([
1 for n in parent
if not isinstance(n, (nodes.Invisible, nodes.label))
])
return parent_length == 1
def visit_paragraph(self, node):
if self.is_compact_paragraph(node):
self.context.append(u'')
return
self.body.append(self.starttag(node, 'p'))
self.context.append(u'</p>')
def depart_paragraph(self, node):
self.body.append(self.context.pop())
def visit_compact_paragraph(self, node):
pass
def depart_compact_paragraph(self, node):
pass
def visit_literal_block(self, node):
if node.rawsource != node.astext():
# most probably a parsed-literal block -- don't highlight
self.body.append(self.starttag(node, 'pre'))
return
lang = self.highlightlang
highlight_args = node.get('highlight_args', {})
if 'language' in node:
# code-block directives
lang = node['language']
highlight_args['force'] = True
linenos = node.get('linenos', False)
if lang is self.highlightlang_base:
# only pass highlighter options for original language
opts = self.highlightopts
else:
opts = {}
def warner(msg):
self.builder.warn(msg, (self.builder.current_docname, node.line))
highlighted = self.builder.highlighter.highlight_block(
node.rawsource, lang, opts=opts, warn=warner, linenos=linenos,
**highlight_args)
self.body.append(self.starttag(node, 'div', CLASS='highlight-%s' % lang))
self.body.append(highlighted)
self.body.append(u'</div>\n')
raise nodes.SkipNode
def depart_literal_block(self, node):
self.body.append(u'</pre>')
def visit_bullet_list(self, node):
self.body.append(self.starttag(node, 'ul'))
def depart_bullet_list(self, node):
self.body.append(u'</ul>')
def visit_enumerated_list(self, node):
self.body.append(self.starttag(node, 'ol'))
def depart_enumerated_list(self, node):
self.body.append(u'</ol>')
def visit_list_item(self, node):
self.body.append(self.starttag(node, 'li'))
def depart_list_item(self, node):
self.body.append(u'</li>')
def visit_definition_list(self, node):
self.body.append(self.starttag(node, 'dl'))
def depart_definition_list(self, node):
self.body.append(u'</dl>')
def visit_definition_list_item(self, node):
pass
def depart_definition_list_item(self, node):
pass
def visit_term(self, node):
self.body.append(self.starttag(node, 'dt'))
def depart_term(self, node):
self.body.append(u'</dt>')
def visit_termsep(self, node):
self.body.append(self.starttag(node, 'br'))
raise nodes.SkipNode
def visit_definition(self, node):
self.body.append(self.starttag(node, 'dd'))
def depart_definition(self, node):
self.body.append(u'</dd>')
def visit_admonition(self, node, type=None):
clss = {
# ???: 'alert-success',
'note': 'alert-info',
'hint': 'alert-info',
'tip': 'alert-info',
'seealso': 'alert-info',
'warning': 'alert-warning',
'attention': 'alert-warning',
'caution': 'alert-warning',
'important': 'alert-warning',
'danger': 'alert-danger',
'error': 'alert-danger',
'exercise': 'alert-exercise',
}
self.body.append(self.starttag(node, 'div', role='alert', CLASS='alert {}'.format(
clss.get(type, '')
)))
if 'alert-dismissible' in node.get('classes', []):
self.body.append(
u'<button type="button" class="close" data-dismiss="alert" aria-label="Close">'
u'<span aria-hidden="true">×</span>'
u'</button>')
if type:
node.insert(0, nodes.title(type, admonitionlabels[type]))
def depart_admonition(self, node):
self.body.append(u'</div>')
visit_note = lambda self, node: self.visit_admonition(node, 'note')
visit_warning = lambda self, node: self.visit_admonition(node, 'warning')
visit_attention = lambda self, node: self.visit_admonition(node, 'attention')
visit_caution = lambda self, node: self.visit_admonition(node, 'caution')
visit_danger = lambda self, node: self.visit_admonition(node, 'danger')
visit_error = lambda self, node: self.visit_admonition(node, 'error')
visit_hint = lambda self, node: self.visit_admonition(node, 'hint')
visit_important = lambda self, node: self.visit_admonition(node, 'important')
visit_tip = lambda self, node: self.visit_admonition(node, 'tip')
visit_exercise = lambda self, node: self.visit_admonition(node, 'exercise')
visit_seealso = lambda self, node: self.visit_admonition(node, 'seealso')
depart_note = depart_admonition
depart_warning = depart_admonition
depart_attention = depart_admonition
depart_caution = depart_admonition
depart_danger = depart_admonition
depart_error = depart_admonition
depart_hint = depart_admonition
depart_important = depart_admonition
depart_tip = depart_admonition
depart_exercise = depart_admonition
depart_seealso = depart_admonition
def visit_versionmodified(self, node):
self.body.append(self.starttag(node, 'div', CLASS=node['type']))
def depart_versionmodified(self, node):
self.body.append(u'</div>')
def visit_title(self, node):
parent = node.parent
closing = u'</p>'
if isinstance(parent, nodes.Admonition):
self.body.append(self.starttag(node, 'p', CLASS='alert-title'))
elif isinstance(node.parent, nodes.document):
self.body.append(self.starttag(node, 'h1'))
closing = u'</h1>'
self.start_document_title = len(self.body)
else:
assert isinstance(parent, nodes.section), "expected a section node as parent to the title, found {}".format(parent)
if self.first_title:
self.first_title = False
raise nodes.SkipNode()
nodename = 'h{}'.format(self.section_level)
self.body.append(self.starttag(node, nodename))
closing = u'</{}>'.format(nodename)
self.context.append(closing)
def depart_title(self, node):
self.body.append(self.context.pop())
if self.start_document_title:
self.title = self.body[self.start_document_title:-1]
self.start_document_title = 0
del self.body[:]
# the rubric should be a smaller heading than the current section, up to
# h6... maybe "h7" should be a ``p`` instead?
def visit_rubric(self, node):
self.body.append(self.starttag(node, 'h{}'.format(min(self.section_level + 1, 6))))
def depart_rubric(self, node):
self.body.append(u'</h{}>'.format(min(self.section_level + 1, 6)))
def visit_block_quote(self, node):
self.body.append(self.starttag(node, 'blockquote'))
def depart_block_quote(self, node):
self.body.append(u'</blockquote>')
def visit_attribution(self, node):
self.body.append(self.starttag(node, 'footer'))
def depart_attribution(self, node):
self.body.append(u'</footer>')
def visit_container(self, node):
self.body.append(self.starttag(node, 'div'))
def depart_container(self, node):
self.body.append(u'</div>')
def visit_compound(self, node):
self.body.append(self.starttag(node, 'div'))
def depart_compound(self, node):
self.body.append(u'</div>')
def visit_image(self, node):
uri = node['uri']
if uri in self.builder.images:
uri = posixpath.join(self.builder.imgpath,
self.builder.images[uri])
attrs = {'src': uri, 'class': 'img-responsive'}
if 'alt' in node:
attrs['alt'] = node['alt']
# todo: explicit width/height/scale?
self.body.append(self.starttag(node, 'img', **attrs))
def depart_image(self, node): pass
def visit_figure(self, node):
self.body.append(self.starttag(node, 'div'))
def depart_figure(self, node):
self.body.append(u'</div>')
def visit_caption(self, node):
# first paragraph of figure content
self.body.append(self.starttag(node, 'h4'))
def depart_caption(self, node):
self.body.append(u'</h4>')
def visit_legend(self, node): pass
def depart_legend(self, node): pass
def visit_line(self, node):
self.body.append(self.starttag(node, 'div', CLASS='line'))
# ensure the line still takes the room it needs
if not len(node): self.body.append(u'<br />')
def depart_line(self, node):
self.body.append(u'</div>')
def visit_line_block(self, node):
self.body.append(self.starttag(node, 'div', CLASS='line-block'))
def depart_line_block(self, node):
self.body.append(u'</div>')
def visit_table(self, node):
self.body.append(self.starttag(node, 'table', CLASS='table'))
def depart_table(self, node):
self.body.append(u'</table>')
def visit_tgroup(self, node): pass
def depart_tgroup(self, node): pass
def visit_colspec(self, node): raise nodes.SkipNode
def visit_thead(self, node):
self.body.append(self.starttag(node, 'thead'))
def depart_thead(self, node):
self.body.append(u'</thead>')
def visit_tbody(self, node):
self.body.append(self.starttag(node, 'tbody'))
def depart_tbody(self, node):
self.body.append(u'</tbody>')
def visit_row(self, node):
self.body.append(self.starttag(node, 'tr'))
def depart_row(self, node):
self.body.append(u'</tr>')
def visit_entry(self, node):
if isinstance(node.parent.parent, nodes.thead):
tagname = 'th'
else:
tagname = 'td'
self.body.append(self.starttag(node, tagname))
self.context.append(tagname)
def depart_entry(self, node):
self.body.append(u'</{}>'.format(self.context.pop()))
def visit_Text(self, node):
self.body.append(self.encode(node.astext()))
def depart_Text(self, node):
pass
def visit_literal(self, node):
self.body.append(self.starttag(node, 'code'))
def depart_literal(self, node):
self.body.append(u'</code>')
visit_literal_emphasis = visit_literal
depart_literal_emphasis = depart_literal
def visit_emphasis(self, node):
self.body.append(self.starttag(node, 'em'))
def depart_emphasis(self, node):
self.body.append(u'</em>')
def visit_strong(self, node):
self.body.append(self.starttag(node, 'strong'))
def depart_strong(self, node):
self.body.append(u'</strong>')
visit_literal_strong = visit_strong
depart_literal_strong = depart_strong
def visit_inline(self, node):
self.body.append(self.starttag(node, 'span'))
def depart_inline(self, node):
self.body.append(u'</span>')
def visit_abbreviation(self, node):
attrs = {}
if 'explanation' in node:
attrs['title'] = node['explanation']
self.body.append(self.starttag(node, 'abbr', **attrs))
def depart_abbreviation(self, node):
self.body.append(u'</abbr>')
def visit_reference(self, node):
attrs = {
'class': 'reference',
'href': node['refuri'] if 'refuri' in node else '#' + node['refid']
}
attrs['class'] += ' internal' if (node.get('internal') or 'refuri' not in node) else ' external'
if any(isinstance(ancestor, nodes.Admonition) for ancestor in _parents(node)):
attrs['class'] += ' alert-link'
if 'reftitle' in node:
attrs['title'] = node['reftitle']
self.body.append(self.starttag(node, 'a', **attrs))
def depart_reference(self, node):
self.body.append(u'</a>')
def visit_target(self, node): pass
def depart_target(self, node): pass
def visit_footnote(self, node):
self.body.append(self.starttag(node, 'div', CLASS='footnote'))
self.footnote_backrefs(node)
def depart_footnote(self, node):
self.body.append(u'</div>')
def visit_footnote_reference(self, node):
self.body.append(self.starttag(
node, 'a', href='#' + node['refid'], CLASS="footnote-ref"))
def depart_footnote_reference(self, node):
self.body.append(u'</a>')
def visit_label(self, node):
self.body.append(self.starttag(node, 'span', CLASS='footnote-label'))
self.body.append(u'%s[' % self.context.pop())
def depart_label(self, node):
# Context added in footnote_backrefs.
self.body.append(u']%s</span> %s' % (self.context.pop(), self.context.pop()))
def footnote_backrefs(self, node):
# should store following data on context stack (in that order since
# they'll be popped so LIFO)
#
# * outside (after) label
# * after label text
# * before label text
backrefs = node['backrefs']
if not backrefs:
self.context.extend(['', '', ''])
elif len(backrefs) == 1:
self.context.extend([
'',
'</a>',
'<a class="footnote-backref" href="#%s">' % backrefs[0]
])
else:
backlinks = (
'<a class="footnote-backref" href="#%s">%s</a>' % (backref, i)
for i, backref in enumerate(backrefs, start=1)
)
self.context.extend([
'<em class="footnote-backrefs">(%s)</em> ' % ', '.join(backlinks),
'',
''
])
def visit_desc(self, node):
self.body.append(self.starttag(node, 'section', CLASS='code-' + node['objtype']))
def depart_desc(self, node):
self.body.append(u'</section>')
def visit_desc_signature(self, node):
self.body.append(self.starttag(node, 'h6'))
self.body.append(u'<code>')
def depart_desc_signature(self, node):
self.body.append(u'</code>')
self.body.append(u'</h6>')
def visit_desc_addname(self, node): pass
def depart_desc_addname(self, node): pass
def visit_desc_type(self, node): pass
def depart_desc_type(self, node): pass
def visit_desc_returns(self, node):
self.body.append(u' → ')
def depart_desc_returns(self, node):
pass
def visit_desc_name(self, node): pass
def depart_desc_name(self, node): pass
def visit_desc_parameterlist(self, node):
self.body.append(u'(')
self.first_param = True
self.optional_param_level = 0
# How many required parameters are left.
self.required_params_left = sum(isinstance(c, addnodes.desc_parameter) for c in node.children)
self.param_separator = node.child_text_separator
def depart_desc_parameterlist(self, node):
self.body.append(u')')
# If required parameters are still to come, then put the comma after
# the parameter. Otherwise, put the comma before. This ensures that
# signatures like the following render correctly (see issue #1001):
#
# foo([a, ]b, c[, d])
#
def visit_desc_parameter(self, node):
if self.first_param:
self.first_param = 0
elif not self.required_params_left:
self.body.append(self.param_separator)
if self.optional_param_level == 0:
self.required_params_left -= 1
if 'noemph' not in node: self.body.append(u'<em>')
def depart_desc_parameter(self, node):
if 'noemph' not in node: self.body.append(u'</em>')
if self.required_params_left:
self.body.append(self.param_separator)
def visit_desc_optional(self, node):
self.optional_param_level += 1
self.body.append(u'[')
def depart_desc_optional(self, node):
self.optional_param_level -= 1
self.body.append(u']')
def visit_desc_annotation(self, node):
self.body.append(self.starttag(node, 'em'))
def depart_desc_annotation(self, node):
self.body.append(u'</em>')
def visit_desc_content(self, node): pass
def depart_desc_content(self, node): pass
def visit_field_list(self, node):
self.body.append(self.starttag(node, 'div', CLASS='code-fields'))
def depart_field_list(self, node):
self.body.append(u'</div>')
def visit_field(self, node):
self.body.append(self.starttag(node, 'div', CLASS='code-field'))
def depart_field(self, node):
self.body.append(u'</div>')
def visit_field_name(self, node):
self.body.append(self.starttag(node, 'div', CLASS='code-field-name'))
def depart_field_name(self, node):
self.body.append(u'</div>')
def visit_field_body(self, node):
self.body.append(self.starttag(node, 'div', CLASS='code-field-body'))
def depart_field_body(self, node):
self.body.append(u'</div>')
def visit_glossary(self, node): pass
def depart_glossary(self, node): pass
def visit_comment(self, node): raise nodes.SkipNode
def visit_toctree(self, node):
# div class=row {{ section_type }}
# h2 class=col-sm-12
# {{ section title }}
# div class=col-sm-6 col-md-3
# figure class=card
# a href=current_link style=background-image: document-image-attribute class=card-img
# figcaption
# {{ card title }}
env = self.builder.env
conf = self.builder.app.config
for title, ref in ((e[0], e[1]) for e in node['entries']):
# external URL, no toc, can't recurse into
if ref not in env.tocs:
continue
toc = env.tocs[ref].traverse(addnodes.toctree)
classes = env.metadata[ref].get('types', 'tutorials')
classes += ' toc-single-entry' if not toc else ' toc-section'
self.body.append(self.starttag(node, 'div', CLASS="row " + classes))
self.body.append(u'<h2 class="col-sm-12">')
self.body.append(title if title else util.nodes.clean_astext(env.titles[ref]))
self.body.append(u'</h2>')
entries = [(title, ref)] if not toc else ((e[0], e[1]) for e in toc[0]['entries'])
for subtitle, subref in entries:
baseuri = self.builder.get_target_uri(node['parent'])
if subref in env.metadata:
cover = env.metadata[subref].get('banner', conf.odoo_cover_default)
elif subref in conf.odoo_cover_external:
cover = conf.odoo_cover_external[subref]
else:
cover = conf.odoo_cover_default_external
if cover:
banner = '_static/' + cover
base, ext = os.path.splitext(banner)
small = "{}.small{}".format(base, ext)
if os.path.isfile(urllib.url2pathname(small)):
banner = small
style = u"background-image: url('{}')".format(
util.relative_uri(baseuri, banner) or '#')
else:
style = u''
self.body.append(u"""
<div class="col-sm-6 col-md-3">
<figure class="card">
<a href="{link}" class="card-img">
<span style="{style}"></span>
<figcaption>{title}</figcaption>
</a>
</figure>
</div>
""".format(
link=subref if util.url_re.match(subref) else util.relative_uri(
baseuri, self.builder.get_target_uri(subref)),
style=style,
title=subtitle if subtitle else util.nodes.clean_astext(env.titles[subref]),
))
self.body.append(u'</div>')
raise nodes.SkipNode
def visit_index(self, node): raise nodes.SkipNode
def visit_raw(self, node):
if 'html' in node.get('format', '').split():
t = 'span' if isinstance(node.parent, nodes.TextElement) else 'div'
if node['classes']:
self.body.append(self.starttag(node, t))
self.body.append(node.astext())
if node['classes']:
self.body.append('</%s>' % t)
# Keep non-HTML raw text out of output:
raise nodes.SkipNode
| xujb/odoo | doc/_extensions/odoo/translator.py | Python | agpl-3.0 | 26,143 |
"""Laposte XML -> Python."""
from datetime import datetime
from lxml import objectify
from ...codec import DecoderGetLabel
from ...codec import DecoderGetPackingSlip
import base64
class _UNSPECIFIED:
pass
def _get_text(xml, tag, default=_UNSPECIFIED):
"""
Returns the text content of a tag to avoid returning an lxml instance
If no default is specified, it will raises the original exception of accessing
to an inexistant tag
"""
if not hasattr(xml, tag):
if default is _UNSPECIFIED:
# raise classic attr error
return getattr(xml, tag)
return default
return getattr(xml, tag).text
def _get_cid(tag, tree):
element = tree.find(tag)
if element is None:
return None
href = element.getchildren()[0].attrib["href"]
# href contains cid:236212...-38932@cfx.apache.org
return href[len("cid:") :] # remove prefix
class LaposteFrDecoderGetLabel(DecoderGetLabel):
"""Laposte XML -> Python."""
def decode(self, response, input_payload):
"""Laposte XML -> Python."""
body = response["body"]
parts = response["parts"]
output_format = input_payload["output_format"]
xml = objectify.fromstring(body)
msg = xml.xpath("//return")[0]
rep = msg.labelV2Response
cn23_cid = _get_cid("cn23", rep)
label_cid = _get_cid("label", rep)
annexes = []
if cn23_cid:
data = parts.get(cn23_cid)
annexes.append(
{"name": "cn23", "data": base64.b64encode(data), "type": "pdf"}
)
if rep.find("pdfUrl"):
annexes.append({"name": "label", "data": rep.find("pdfUrl"), "type": "url"})
parcel = {
"id": 1, # no multi parcel management for now.
"reference": self._get_parcel_number(input_payload),
"tracking": {
# we need to force to real string because of those data can be reused
# and cerberus won't accept an ElementString insteadof a string.
"number": _get_text(rep, "parcelNumber"),
"url": "",
"partner": _get_text(rep, "parcelNumberPartner", ""),
},
"label": {
"data": base64.b64encode(parts.get(label_cid)),
"name": "label_1",
"type": output_format,
},
}
if hasattr(rep, "fields") and hasattr(rep.fields, "field"):
for field in rep.fields.field:
parcel["tracking"][_get_text(field, "key")] = _get_text(field, "value")
self.result["parcels"].append(parcel)
self.result["annexes"] += annexes
class LaposteFrDecoderGetPackingSlip(DecoderGetPackingSlip):
"""Laposte Bordereau Response XML -> Python."""
def decode(self, response, input_payload):
body = response["body"]
parts = response["parts"]
xml = objectify.fromstring(body)
msg = xml.xpath("//return")[0]
header = msg.bordereau.bordereauHeader
published_dt = _get_text(header, "publishingDate", None)
if published_dt:
if "." in published_dt:
# get packing slip with it's number does not return microseconds
# but when creating a new one, it does... We remove microseconds in result
# to have a better homogeneity
published_dt = published_dt.split(".")
published_dt = "%s+%s" % (
published_dt[0],
published_dt[1].split("+")[1],
)
published_datetime = datetime.strptime(published_dt, "%Y-%m-%dT%H:%M:%S%z")
self.result["packing_slip"] = {
"number": _get_text(header, "bordereauNumber", None),
"published_datetime": published_datetime,
"number_of_parcels": int(_get_text(header, "numberOfParcels", 0)),
"site_pch": {
"code": _get_text(header, "codeSitePCH", None),
"name": _get_text(header, "nameSitePCH", None),
},
"client": {
"number": _get_text(header, "clientNumber", None),
"adress": _get_text(header, "Address", None),
"company": _get_text(header, "Company", None),
},
}
packing_slip_cid = _get_cid("bordereauDataHandler", msg.bordereau)
if packing_slip_cid:
self.result["annexes"].append(
{
"name": "packing_slip",
"data": base64.b64encode(parts.get(packing_slip_cid)),
"type": "pdf",
}
)
return self.result
| akretion/roulier | roulier/carriers/laposte_fr/decoder.py | Python | agpl-3.0 | 4,729 |
"""alloccli subcommand for editing alloc reminders."""
from alloc import alloc
import re
class reminder(alloc):
"""Add or edit a reminder."""
# Setup the options that this cli can accept
ops = []
ops.append(('', 'help ', 'Show this help.'))
ops.append(('q', 'quiet ', 'Run with less output.\n'))
ops.append(('r.', ' ', 'Edit a reminder. Specify an ID or omit -r to create.'))
ops.append(('t.', 'task=ID|NAME ', 'A task ID, or a fuzzy match for a task name.'))
ops.append(('p.', 'project=ID|NAME', 'A project ID, or a fuzzy match for a project name.'))
ops.append(('c.', 'client=ID|NAME ', 'A client ID, or a fuzzy match for a client name.'))
ops.append(('s.', 'subject=TEXT ', 'The subject line of the reminder.'))
ops.append(('b.', 'body=TEXT ', 'The text body of the reminder.'))
ops.append(('', 'frequency=FREQ ', 'How often this reminder is to recur.\n'
'Specify as [number][unit], where unit is one of:\n'
'[h]our, [d]ay, [w]eek, [m]onth, [y]ear.'))
ops.append(('', 'notice=WARNING ', 'Advance warning for this reminder. Same format as frequency.'))
ops.append(('d.', 'date=DATE ', 'When this reminder is to trigger.'))
ops.append(('', 'active=1|0 ', 'Whether this reminder is active or not.'))
ops.append(('T:', 'to=PEOPLE ', 'Recipients. Can be usernames, full names and/or email.'))
ops.append(('D:', 'remove=PEOPLE ', 'Recipients to remove.'))
# Specify some header and footer text for the help text
help_text = "Usage: %s [OPTIONS]\n"
help_text += __doc__
help_text += """\n\n%s
This program allows editing of the fields on a reminder.
Examples:
# Edit a particular reminder.
alloc reminder -r 1234 --title 'Name for the reminder.' --to alla
# Omit -r to create a new reminder
alloc reminder --title 'Name for the reminder.' --to alla"""
def run(self, command_list):
"""Execute subcommand."""
# Get the command line arguments into a dictionary
o, remainder_ = self.get_args(command_list, self.ops, self.help_text)
# Got this far, then authenticate
self.authenticate()
personID = self.get_my_personID()
args = {}
if not o['r']:
o['r'] = 'new'
args['entity'] = 'reminder'
args['id'] = o['r']
if o['date']:
o['date'] = self.parse_date(o['date'])
if o['project'] and not self.is_num(o['project']):
o['project'] = self.search_for_project(o['project'], personID)
if o['task'] and not self.is_num(o['task']):
o['task'] = self.search_for_task({'taskName': o['task']})
if o['client'] and not self.is_num(o['client']):
o['client'] = self.search_for_client({'clientName': o['client']})
if o['frequency'] and not re.match(r'\d+[hdwmy]', o['frequency'], re.IGNORECASE):
self.die("Invalid frequency specification")
if o['notice'] and not re.match(r'\d+[hdwmy]', o['notice'], re.IGNORECASE):
self.die("Invalid advance notice specification")
if o['to']:
o['recipients'] = [x['personID']
for x in self.get_people(o['to']).values()]
if o['remove']:
o['recipients_remove'] = [x['personID']
for x in self.get_people(o['remove']).values()]
package = {}
for key, val in o.items():
if val:
package[key] = val
if isinstance(val, str) and val.lower() == 'null':
package[key] = ''
package['command'] = 'edit_reminder'
args['options'] = package
args['method'] = 'edit_entity'
rtn = self.make_request(args)
self.handle_server_response(rtn, not o['quiet'])
| mattcen/alloc | bin/alloccli/reminder.py | Python | agpl-3.0 | 3,917 |
import React from 'react';
import { DragSource, DropTarget } from 'react-dnd';
import { compose } from 'redux';
import DragDropItemTypes from './DragDropItemTypes';
import { HeaderDeleted, HeaderNormal } from './SampleDetailsContainersAux';
const orderSource = {
beginDrag(props) {
const { container, sample } = props;
return { cId: container.id, sId: sample.id };
},
};
const orderTarget = {
drop(targetProps, monitor) {
const { container, sample, handleMove } = targetProps;
const tgTag = { cId: container.id, sId: sample.id };
const scTag = monitor.getItem();
if (tgTag.sId === scTag.sId && tgTag.cId !== scTag.cId) {
handleMove(scTag, tgTag);
}
},
};
const orderDragCollect = (connect, monitor) => ({
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging(),
});
const orderDropCollect = (connect, monitor) => ({
connectDropTarget: connect.dropTarget(),
isOver: monitor.isOver(),
canDrop: monitor.canDrop(),
});
const ContainerRow = ({
sample, container, mode, readOnly, isDisabled, handleRemove,
handleSubmit, handleAccordionOpen, toggleAddToReport, handleUndo,
connectDragSource, connectDropTarget, isDragging, isOver, canDrop,
}) => {
const style = {};
if (canDrop) {
style.borderStyle = 'dashed';
style.borderWidth = 2;
}
if (isOver) {
style.borderColor = '#337ab7';
}
if (isDragging) {
style.opacity = 0.2;
}
const oPanelCN = container.is_deleted ? "order-panel-delete" : "order-panel";
return compose(connectDragSource, connectDropTarget)(
<div className={oPanelCN} style={style}>
<div className="dnd-btn">
<span className="text-info fa fa-arrows" />
</div>
{
container.is_deleted
? <HeaderDeleted
container={container}
handleUndo={handleUndo}
mode={mode}
/>
: <HeaderNormal
sample={sample}
container={container}
mode={mode}
handleUndo={handleUndo}
readOnly={readOnly}
isDisabled={isDisabled}
handleRemove={handleRemove}
handleSubmit={handleSubmit}
handleAccordionOpen={handleAccordionOpen}
toggleAddToReport={toggleAddToReport}
/>
}
</div>,
);
};
export default compose(
DragSource(DragDropItemTypes.CONTAINER, orderSource, orderDragCollect),
DropTarget(DragDropItemTypes.CONTAINER, orderTarget, orderDropCollect),
)(ContainerRow);
| ComPlat/chemotion_ELN | app/packs/src/components/SampleDetailsContainersDnd.js | JavaScript | agpl-3.0 | 2,510 |
<?php
/**
* @author Jaap Jansma <jaap.jansma@civicoop.org>
* @license AGPL-3.0
*/
class CRM_Oppgavexml_LoadQueue {
const QUEUE_NAME = 'no.maf.oppgavexml.load.queue';
private $queue;
static $singleton;
/**
* @return CRM_Queuehowto_Helper
*/
public static function singleton() {
if (!self::$singleton) {
self::$singleton = new CRM_Oppgavexml_LoadQueue();
}
return self::$singleton;
}
private function __construct() {
$this->queue = CRM_Queue_Service::singleton()->create(array(
'type' => 'Sql',
'name' => self::QUEUE_NAME,
'reset' => true, //do not flush queue upon creation
));
}
public function getQueue() {
return $this->queue;
}
} | CiviCooP/no.maf.oppgavexml | CRM/Oppgavexml/LoadQueue.php | PHP | agpl-3.0 | 716 |
# -*- coding: utf-8 -*-
# (c) 2017 Daniel Campos - AvanzOSC
# (c) 2017 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import fields, models, api, exceptions, _
import base64
import cStringIO
import tempfile
import csv
class ImportPriceFile(models.TransientModel):
_name = 'import.price.file'
_description = 'Wizard for import price list file'
data = fields.Binary(string='File', required=True)
name = fields.Char(string='Filename', required=False)
delimeter = fields.Char(
string='Delimeter', default=',', help='Default delimeter is ","')
file_type = fields.Selection([('csv', 'CSV'),
('xls', 'XLS')], string='File type',
required=True, default='csv')
def _prepare_data_dict(self, data_dict):
return data_dict
def _import_csv(self, load_id, file_data, delimeter=';'):
""" Imports data from a CSV file in defined object.
@param load_id: Loading id
@param file_data: Input data to load
@param delimeter: CSV file data delimeter
@return: Imported file number
"""
file_line_obj = self.env['product.supplierinfo.load.line']
data = base64.b64decode(file_data)
file_input = cStringIO.StringIO(data)
file_input.seek(0)
reader_info = []
reader = csv.reader(file_input, delimiter=str(delimeter),
lineterminator='\r\n')
try:
reader_info.extend(reader)
except Exception:
raise exceptions.Warning(_("Not a valid file!"))
keys = reader_info[0]
counter = 0
if not isinstance(keys, list):
raise exceptions.Warning(_("Not a valid file!"))
del reader_info[0]
for i in range(len(reader_info)):
field = reader_info[i]
values = dict(zip(keys, field))
data_dict = self._prepare_data_dict(
{'supplier': values.get('Supplier', ''),
'code': values.get('ProductCode', ''),
'sequence': values.get('Sequence', 0),
'supplier_code': values.get('ProductSupplierCode', ''),
'info': values.get('ProductSupplierName', ''),
'delay': values.get('Delay', 0),
'price': values.get('Price', 0.00).replace(',', '.'),
'min_qty': values.get('MinQty', 0.00),
'fail': True,
'fail_reason': _('No processed'),
'file_load': load_id})
file_line_obj.create(data_dict)
counter += 1
return counter
def _import_xls(self, load_id, file_data):
""" Imports data from a XLS file in defined object.
@param load_id: Loading id
@param file_data: Input data to load
@return: Imported file number
"""
try:
import xlrd
except ImportError:
exceptions.Warning(_("xlrd python lib not installed"))
file_line_obj = self.env['product.supplierinfo.load.line']
file_1 = base64.decodestring(file_data)
(fileno, fp_name) = tempfile.mkstemp('.xls', 'openerp_')
openfile = open(fp_name, "w")
openfile.write(file_1)
openfile.seek(0)
book = xlrd.open_workbook(fp_name)
sheet = book.sheet_by_index(0)
values = {}
keys = sheet.row_values(0, 0, end_colx=sheet.ncols)
for counter in range(sheet.nrows - 1):
# grab the current row
rowValues = sheet.row_values(counter + 1, 0,
end_colx=sheet.ncols)
row_lst = []
for val in rowValues: # codification format control
if isinstance(val, unicode):
valor = val.encode('utf8')
row_lst.append(valor)
elif isinstance(val, float):
if float(val) % 1 == 0.0:
row_lst.append(
'{0:.5f}'.format(float(val)).split('.')[0])
else:
row_lst.append('{0:g}'.format(float(val)))
else:
row_lst.append(val)
row = map(lambda x: str(x), row_lst)
values = dict(zip(keys, row))
data_dict = self._prepare_data_dict(
{'supplier': values.get('Supplier', ''),
'code': values.get('ProductCode', ''),
'sequence': values.get('Sequence', 0),
'supplier_code': values.get('ProductSupplierCode', ''),
'info': values.get('ProductSupplierName', ''),
'delay': values.get('Delay', 0),
'price': values.get('Price', 0.00).replace(',', '.'),
'min_qty': values.get('MinQty', 0.00),
'fail': True,
'fail_reason': _('No processed'),
'file_load': load_id
})
file_line_obj.create(data_dict)
counter += 1
return counter
@api.multi
def action_import(self):
file_load_obj = self.env['product.supplierinfo.load']
if self.env.context.get('active_id', False):
load_id = self.env.context.get('active_id')
file_load = file_load_obj.browse(load_id)
for line in file_load.file_lines:
line.unlink()
for wiz in self:
if not wiz.data:
raise exceptions.Warning(_("You need to select a file!"))
date_hour = fields.datetime.now()
actual_date = fields.date.today()
filename = wiz.name
if wiz.file_type == 'csv':
counter = self._import_csv(load_id, wiz.data, wiz.delimeter)
elif wiz.file_type == 'xls':
counter = self._import_xls(load_id, wiz.data)
else:
raise exceptions.Warning(_("Not a .csv/.xls file found"))
file_load.write({'name': ('%s_%s') % (filename, actual_date),
'date': date_hour, 'fails': counter,
'file_name': filename, 'process': counter})
return counter
| esthermm/odoo-addons | product_supplierinfo_import/wizard/import_price_files.py | Python | agpl-3.0 | 6,282 |
package gdev.gawt;
import gdev.gawt.utils.ItemList;
import gdev.gen.AssignValueException;
import gdev.gen.IComponentData;
import gdev.gen.IComponentListener;
import gdev.gen.NotValidValueException;
import gdev.gfld.GFormEnumerated;
import gdev.gfld.GFormField;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.ItemSelectable;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyListener;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import dynagent.common.communication.docServer;
import dynagent.common.utils.IUserMessageListener;
import dynagent.common.utils.IdObjectForm;
/**
* Esta clase extiende a GComponent y creará una lista seleccionable.
* Una vez creada se podrá representar en la interfaz gráfica.
* @author Juan
* @author Francisco
*/
public class GListBox implements IComponentData,/*field,*/ ItemListener
{
String m_id2;
String m_id;
ItemList currentValidatedValue=null;//un valor de un item nunca puede ser 0 que corresponde a null
/*fieldControl m_control;*/
public Vector<ItemList> m_listaInicial;
String m_label;
boolean m_nullable, m_modoConsulta, m_modoFilter;
Font m_font;
ItemSelectable m_select;
JComponent m_comp;
docServer m_server;
Dimension m_dim;
/*session m_session;*/
GComponent m_component;
GFormEnumerated m_ff;
boolean m_multivalued;
IComponentListener m_componentListener;
boolean inicializationState;
ItemList[] m_currentListItemList;
boolean itemEvent;
IUserMessageListener m_messageListener;
KeyListener m_keyListener;
public GListBox(GFormField ff,/*session ses,*/docServer server,/*fieldControl control,*/IComponentListener controlValue,IUserMessageListener messageListener,KeyListener keyListener,Font fuente,boolean modoConsulta,boolean modoFilter)
{
/*m_session=ses;*/
m_server=server;
/*m_dim=dim;*/
m_modoConsulta=modoConsulta;
m_multivalued=ff.isMultivalued();
m_font=fuente;
m_nullable= ff.isNullable();
m_label=ff.getLabel();
/*m_listaInicial= (Vector)lista.clone();*/
/*m_listaInicial= (Vector)((GFormEnumerated)ff).getValues().clone();*/
/*m_control= control;*/
m_id= ff.getId();
m_id2=ff.getId2();
//////////////////////////////////////////////////////
m_componentListener=controlValue;
m_messageListener=messageListener;
m_keyListener=keyListener;
m_modoFilter=modoFilter;
m_ff=(GFormEnumerated)ff;
inicializationState=true;
itemEvent=false;
/////////////YA ESTABA COMENTADO/////////////////
//System.out.println("LB_"+getValue());
/*if(color!=null){
if(color.equals("BLUE")) m_comp.setForeground(Color.blue);
if(color.equals("GREEN")) m_comp.setForeground(Color.green);
if(color.equals("RED")) m_comp.setForeground(Color.red);
}*/
////////////////////////////////////////////////
/* System.out.println("Modo filtro GListBox "+m_modoFilter);
if( m_modoFilter ){
/*m_select= new GList( m_dim,lista, new ImageIcon( m_com.getImage("list")) );
m_comp= ((GList)m_select).getComponent();*/
/* GList list=new GList(ff,com,fuente,colorFondo);
m_select=list;
m_comp=list.getComponent();
//m_select=m_comp;
}else{
GComboBox comboBox=new GComboBox(ff);
comboBox.create();
m_select= (JComboBox)comboBox.getComponent();
m_comp=comboBox;
/*m_select= new JComboBox(lista);
m_comp=(JComponent)m_select;*/
/* }
m_select.addItemListener(this);
*/
/* m_comp.setFont(m_font.deriveFont(Font.BOLD));*/
initLista();
/* setInitialSelection();*/
//System.out.println("LB_2"+getValue());
}
/* protected void createComponent()
{
/*LISTA TIENE QUE LEERSE DE LOS ATRIBUTOS DE FF*/
/* Vector lista=new Vector();//Esto es provisional
/*initLista( lista );*/
/////////////////////////////////////////////////
/* if( m_modoFilter ){
/*m_select= new GList( m_dim,lista, new ImageIcon( m_com.getImage("list")) );
m_comp= ((GList)m_select).getComponent();*/
/* }else{
m_component=new GComboBox(ff);
/*m_select= new JComboBox(lista);
m_comp=(JComponent)m_select;*/
/* }
m_select.addItemListener(this);
}
*/
/*public JComponent getComponent(){
return (JComponent)m_select;
}*/
public GComponent getComponent(){
/*if( m_select instanceof GComponent )
return (GComponent)m_select;
if( m_comp instanceof GComponent )*/
return (GComponent)m_comp;
/*return null;*/
}
public void setItemSelectable(ItemSelectable itemSelectable){
m_select=itemSelectable;
}
public void setComponent(GComponent component){
m_comp=component;
}
private void initLista(){
if( m_modoFilter || m_multivalued ){
/*m_select= new GList( m_dim,lista, new ImageIcon( m_com.getImage("list")) );
m_comp= ((GList)m_select).getComponent();*/
GList list=new GList(m_ff,m_server,m_font,m_modoConsulta,m_modoFilter,this);
/*m_select=list;
m_comp=list.getComponent();*///Ultimo
//m_select=m_comp;
m_listaInicial=list.getListaInicial();
currentValidatedValue=list.getValorInicial().get(0);
//Esto lo comprobamos porque segun como se haya construido los datos pasados a la lista no se puede castear
//directamente de Object[] a ItemList[]. Por ejemplo si se ha pasado un vector este internamente crea un new Object[]
//por lo que luego no podemos hacer el casting a ItemList. Ejemplos de creacion de los datos:
// Object[] o=new Object[] No se puede castear directamente a ItemList[]
// Object[] o=new ItemList[] Si se puede castear directamente a ItemList[]
Object[] selected=list.getValorInicial().toArray();
if(selected instanceof ItemList[])
m_currentListItemList=(ItemList[])selected;
else m_currentListItemList= Arrays.copyOf(selected,selected.length,ItemList[].class);
}else{
GComboBox comboBox=new GComboBox(m_ff,m_font,m_modoConsulta,m_modoFilter,this);
/*m_select= (JComboBox)comboBox.getComponent();
m_comp=comboBox;*///Ultimo
/*m_select= new JComboBox(lista);
m_comp=(JComponent)m_select;*/
m_listaInicial=comboBox.getListaInicial();
currentValidatedValue=comboBox.getValorInicial();
m_currentListItemList=new ItemList[1];
m_currentListItemList[0]=comboBox.getValorInicial();
}
/*m_select.addItemListener(this);*/
}
public String getLabel(){
return m_label;
}
public void commitValorInicial(){
if( /*m_modoFilter*/m_multivalued ) return;
Iterator itr= m_listaInicial.iterator();
while(itr.hasNext()){
ItemList it= (ItemList) itr.next();
it.initialSelection=false;
}
ItemList current= (ItemList)m_select.getSelectedObjects()[0];
current.initialSelection=true;
}
private void setSelectedItem( ItemList[] lista ){
Vector<ItemList> v=new Vector<ItemList>();
int size=lista.length;
for(int i=0;i<size;i++)
v.addElement(lista[i]);
setSelectedItem(v);
}
private void setSelectedItem( Vector<ItemList> lista ){
//System.out.println("PRE SETSEL "+lista.size());
if( lista==null || lista.size()==0 ) return;
if( m_select instanceof JComboBox )
((JComboBox)m_select).setSelectedItem(lista.get(0));
if( m_select instanceof GList ){
//System.out.println("ES BOX FILTER");
((GList)m_select).setSelectedValue(lista);
}
}
private boolean isPopupVisible(){
boolean visible=false;
if( m_select instanceof JComboBox )
visible=((JComboBox)m_select).isPopupVisible();
if( m_select instanceof GList ){
//System.out.println("ES BOX FILTER");
visible=((GList)m_select).isPopupVisible();
}
return visible;
}
private void setSelectedItem( ItemList it ){
if( m_select instanceof JComboBox )
((JComboBox)m_select).setSelectedItem(it);
if( m_select instanceof GList )
((GList)m_select).setSelectedValue(it);
}
public int getSize(){
if( m_select instanceof JComboBox )
return ((JComboBox)m_select).getModel().getSize();
if( m_select instanceof GList ){
//System.outprintln("VALORES "+m_select+" "+(((GList)m_select).getComponent()).getModel());
//System.outprintln("VALORES TAMANO"+(((GList)m_select).getComponent()).getModel().getSize());
return (((GList)m_select).getComponent()).getModel().getSize();
}
return 0;
}
public ItemList getItemAt(int i){
if( m_select instanceof JComboBox )
return (ItemList)((JComboBox)m_select).getItemAt(i);
if( m_select instanceof GList )
return (ItemList)(((GList)m_select).getComponent()).getModel().getElementAt(i);
return null;
}
public void setValue(Object newValue,Object oldValue) throws AssignValueException{
//TODO Cuando estamos aun gestionando un itemStateChanged si se llama a este metodo desde el metodo se produce inconsistencia.
//if(!itemEvent)
setValue( false, newValue, oldValue );
}
//Si new es null y old es null entonces no mantenemos ningun valor de la lista
private void setValue(boolean notificar,Object value,Object oldValue) throws AssignValueException{
//TODO Cambiar Object de value por String¿?¿
/*if( value!=null && !(value instanceof Integer)){
System.out.println("LIST BOX: setValue: error en cast");
return;
}*/
//System.out.println("LIST BOX:PRE SET");
// if( (m_modoFilter || m_multivalued) && m_select instanceof GList ){
// //System.out.println("LIST BOX:RESET");
// ((GList)m_select).initLista(m_listaInicial);
// }
int valor= value!=null?(Integer)value:0;
int valorOld= oldValue!=null?(Integer)oldValue:0;
//Si ya esta seleccionado no hacemos nada
Object[] lista= m_select.getSelectedObjects();
int size=lista.length;
for(int i=0;i<size;i++)
if(((ItemList)lista[i]).getIntId()==valor)
return;
Vector<ItemList> addItemList=new Vector<ItemList>();
if(! (valor==0 && valorOld==0)){
for(int i=0;i<size;i++){
if(((ItemList)lista[i]).getIntId()!=valorOld/* && ((ItemList)lista[i]).getIntId()!=0 Esto no es necesario si viene bien el valor y el valorOld en todo momento*/)
addItemList.addElement((ItemList)lista[i]);
}
}
if(valor!=0 || (valor==0 && addItemList.isEmpty())){
//System.err.println("ListaInicial:"+m_listaInicial.toString());
int sizePossibleValues=m_listaInicial.size();
for(int i=0;i<sizePossibleValues;i++){
ItemList it=m_listaInicial.get(i);
//System.err.println("Compara: it.getIntId:"+it.getIntId()+" valor:"+valor);
if(it.getIntId()==valor)
addItemList.addElement(it);
}
}
// try{
// for(int i=0;i< getSize();i++){
// ItemList it= getItemAt(i);
// if(it.getIntId()==valor){
//
// if( /*m_control*/m_controlValue!=null ){
// // if( /*m_control.estateInicialization()*/inicializationState){
// // System.out.println("WARNING:Entra en GListBox.setValue.inicializationState");
// //
// // m_select.removeItemListener(this);
// // setSelectedItem(it);
// // m_select.addItemListener(this);
// // currentValidatedValue = it;
// // inicializationState=false;
// // return;
// // }
// if(notificar && !m_modoConsulta){
// /*if(m_control.changeRequest(m_session,-1,-1,m_idForm, value))
// m_control.eventDataChanged(m_session,-1,-1,m_idForm);
// else{
// String msg="Error, ha sido asignado un valor incorrecto.";
// if(!isNullable() && isNull())
// msg+=" El campo " + getLabel() + " no admite valores nulos";
// m_messageListener.showMessage(msg);
// setSelectedItem(currentValidatedValue);
// }*/
// /*String[] buf = m_id.split(":");
// Integer valueCls = !buf[2].equals("null")?Integer.parseInt(buf[0]):null;*/
// IdObjectForm idObjectForm=new IdObjectForm(m_id);
// Integer valueCls = idObjectForm.getValueCls();
// String valueOld=null;
// /*String value=currValue;*/
// if(valueOld!=null){
// if(value!=null)
// m_controlValue.setValueField(m_id,(String)value,valueOld, valueCls, valueCls);
// else m_controlValue.removeValueField(m_id,valueOld, valueCls);
// }else{
// if(value!=null)
// m_controlValue.addValueField(m_id,(String)value,valueCls);
// //else m_controlValue.removeValueField(m_id, value, valueCls);
// }
// }
// }
// m_select.removeItemListener(this);
// setSelectedItem(it);
// m_select.addItemListener(this);
//
// currentValidatedValue = it;
// /*for(int i=0;i<size;i++)
// m_currentListItemList[i]=(ItemList)lista[i];*/
//
// Object[] listaSelect= m_select.getSelectedObjects();
// int sizeSelect=listaSelect.length;
// //Esto lo comprobamos porque segun como se haya construido los datos pasados a la lista no se puede castear
// //directamente de Object[] a ItemList[]. Por ejemplo si se ha pasado un vector este internamente crea un new Object[]
// //por lo que luego no podemos hacer el casting a ItemList. Ejemplos de creacion de los datos:
// // Object[] o=new Object[] No se puede castear directamente a ItemList[]
// // Object[] o=new ItemList[] Si se puede castear directamente a ItemList[]
// if(listaSelect instanceof ItemList[])
// m_currentListItemList=(ItemList[])listaSelect;
// else m_currentListItemList= Arrays.copyOf(listaSelect,sizeSelect,ItemList[].class);
// }
// }
// }catch(NotValidValueException ex){
// m_messageListener.showErrorMessage(ex.getUserMessage());
// }
m_select.removeItemListener(this);
setSelectedItem(addItemList);
m_select.addItemListener(this);
// Para asignar el current se hace esto porque si en GList solo se deseleccionan valores usando control no habra valor, por lo que tendriamos current
currentValidatedValue= lista.length>0?(ItemList)lista[0]:null;
/*for(int i=0;i<size;i++)
m_currentListItemList[i]=(ItemList)lista[i];*/
Object[] listaSelect= m_select.getSelectedObjects();
int sizeSelect=listaSelect.length;
//Esto lo comprobamos porque segun como se haya construido los datos pasados a la lista no se puede castear
//directamente de Object[] a ItemList[]. Por ejemplo si se ha pasado un vector este internamente crea un new Object[]
//por lo que luego no podemos hacer el casting a ItemList. Ejemplos de creacion de los datos:
// Object[] o=new Object[] No se puede castear directamente a ItemList[]
// Object[] o=new ItemList[] Si se puede castear directamente a ItemList[]
if(listaSelect instanceof ItemList[])
m_currentListItemList=(ItemList[])listaSelect;
else m_currentListItemList= Arrays.copyOf(listaSelect,sizeSelect,ItemList[].class);
}
boolean hasNullItem(){
ItemList it= getItemAt(0);
return it.getId().equals(0);
}
String getId2(){
return m_id2;
}
/* public String getValueToString(){
Object[] lista= m_select.getSelectedObjects();
if( lista.length==0 ) return null;
for( int i=0;i<lista.length;i++)
lista[i]=((ItemList)lista[i]).getId();
return jdomParser.buildMultivalue(lista);
}
public Object getValue(){
if( m_select.getSelectedObjects().length==0 ) return null;
if(m_select.getSelectedObjects().length==1){
ItemList it = (ItemList) m_select.getSelectedObjects()[0];
return new Integer(it.getId());
}else{
ArrayList res= new ArrayList();
for( int i=0;i<m_select.getSelectedObjects().length;i++)
res.add(new Integer((((ItemList)m_select.getSelectedObjects()[i]).getIntId())));
return res;
}
}
*/ public String getId(){
return m_id;
}
public boolean isNull(){
Object[] lista=m_select.getSelectedObjects();
if(lista == null || lista.length==0 ) return true;
return (((ItemList)m_select.getSelectedObjects()[0]).getIntId()==0);
}
public boolean isNull(Object val){
if( val instanceof Integer )
return ((Integer)val).intValue()==0;
if( val instanceof ItemList )
return ((ItemList)val).getIntId()==0;
return true;
}
public boolean isNullable(){
return m_nullable;
}
public void itemStateChanged(ItemEvent e){
//System.err.println(e);
itemEvent=true;
ItemList[] listItemListOld=null;
try{
//Este metodo es llamado tanto para indicar el item seleccionado y para indicar el item que ha sido quitado
//Asi que solo nos interesa uno de ellos, en este caso el seleccionado
if(e.getStateChange()==ItemEvent.SELECTED/* && !isPopupVisible()*/){
if( /*m_control*/m_componentListener==null || m_modoConsulta){
itemEvent=false;
return;
}
// if( /*m_control*/m_controlValue!=null ){
// if( /*m_control.estateInicialization()*/inicializationState){
// currentValidatedValue= (ItemList)m_select.getSelectedObjects()[0];
// /*for(int i=0;i<size;i++)
// m_currentListItemList[i]=(ItemList)lista[i];*/
// Object[] selected=m_select.getSelectedObjects();
//
// //Esto lo comprobamos porque segun como se haya construido los datos pasados a la lista no se puede castear
// //directamente de Object[] a ItemList[]. Por ejemplo si se ha pasado un vector este internamente crea un new Object[]
// //por lo que luego no podemos hacer el casting a ItemList. Ejemplos de creacion de los datos:
// // Object[] o=new Object[] No se puede castear directamente a ItemList[]
// // Object[] o=new ItemList[] Si se puede castear directamente a ItemList[]
// if(selected instanceof ItemList[])
// m_currentListItemList=(ItemList[])selected;
// else m_currentListItemList= Arrays.copyOf(selected,selected.length,ItemList[].class);
//
// inicializationState=false;
// return;
// }
// }
// Obtenemos los objetos seleccionados
Object[] lista= m_select.getSelectedObjects();
int size=lista.length;
listItemListOld=m_currentListItemList.clone();
ArrayList<ItemList> addItemList=new ArrayList<ItemList>();
for(int i=0;i<size;i++){
addItemList.add((ItemList)lista[i]);
}
IdObjectForm idObjectForm=new IdObjectForm(m_id);
Integer valueCls = idObjectForm.getValueCls();
ArrayList<ItemList> replacedItemList=new ArrayList<ItemList>();
for( int i=0;i<size;i++){
ItemList it=(ItemList)lista[i];
/*if(!m_control.changeRequest(m_session,-1,-1,m_idForm,new Integer(it.getIntId()))){
String msg = "Ha escrito un valor incorrecto.";
if (!isNullable() && isNull())
msg += " El campo " + getLabel() +
" no admite valores nulos";
m_messageListener.showErrorMessage(msg);
setSelectedItem(currentValidatedValue);
return;
}*/
/*String[] buf = m_id.split(":");
Integer valueCls = !buf[2].equals("null")?Integer.parseInt(buf[0]):null;;
String value=String.valueOf(it.getIntId());
*/
if(!hasValue(it)){
Integer value=it.getIntId();
if(value.equals(0))
value=null;
Integer valueOld=getNextValueOld(addItemList,replacedItemList);
if(valueOld!=null && valueOld.equals(0))
valueOld=null;
/*if(value.equals(""))
value=null;*/
if(!m_multivalued){
if(valueOld!=null){
if(value!=null)
m_componentListener.setValueField(m_id,value,valueOld, valueCls, valueCls);
else m_componentListener.removeValueField(m_id,valueOld, valueCls);
}else{
if(value!=null)
m_componentListener.addValueField(m_id,value,valueCls);
//else m_controlValue.removeValueField(m_id, value, valueCls);
}
}else{
/*Si es multivalued no reutilizamos el fact haciendo un set como para los de un unico valor ya que:
Si, por ejemplo, tenemos dos valores, primero quitamos uno, y luego sustituimos el dejado por el quitado, se estaría enviando a base de datos un del y un set,
procesando base de datos antes el set que el del por lo que finalmente se quedaría sin ningun valor
*/
if(valueOld!=null)
m_componentListener.removeValueField(m_id,valueOld, valueCls);
if(value!=null)
m_componentListener.addValueField(m_id,value,valueCls);
}
}
}
int sizeOld=listItemListOld.length;
if(size<sizeOld){
for(int i=0;i<sizeOld;i++){
ItemList itemList=listItemListOld[i];
if(!replacedItemList.contains(itemList) && !addItemList.contains(itemList)){
Integer value=itemList.getIntId();
m_componentListener.removeValueField(m_id,value, valueCls);
}
}
}
lista= m_select.getSelectedObjects();//Volvemos a pedir los objetos seleccionados porque las acciones anteriores han podido provocar cambios
// Para asignar el current se hace esto porque si en GList solo se deseleccionan valores usando control no habra valor, por lo que tendriamos current
currentValidatedValue= lista.length>0?(ItemList)lista[0]:null;
/*for(int i=0;i<size;i++)
m_currentListItemList[i]=(ItemList)lista[i];*/
//Esto lo comprobamos porque segun como se haya construido los datos pasados a la lista no se puede castear
//directamente de Object[] a ItemList[]. Por ejemplo si se ha pasado un vector este internamente crea un new Object[]
//por lo que luego no podemos hacer el casting a ItemList. Ejemplos de creacion de los datos:
// Object[] o=new Object[] No se puede castear directamente a ItemList[]
// Object[] o=new ItemList[] Si se puede castear directamente a ItemList[]
if(lista instanceof ItemList[])
m_currentListItemList=(ItemList[])lista;
else m_currentListItemList= Arrays.copyOf(lista,lista.length,ItemList[].class);
itemEvent=false;
/*m_control.eventDataChanged(m_session,-1,-1,m_idForm);*/
}
}catch(NotValidValueException ex){
m_messageListener.showErrorMessage(ex.getUserMessage(),SwingUtilities.getWindowAncestor(this.getComponent()));
setSelectedItem(listItemListOld);
}catch(Exception ex){
m_server.logError(SwingUtilities.getWindowAncestor(this.getComponent()),ex,"Error al seleccionar elemento");
setSelectedItem(listItemListOld);
ex.printStackTrace();
}
}
/*
Obtiene el siguiente valueOld que se puede utilizar para hacer un setValueField. Si en la lista
de los anteriores valores hay un valor que no aparece en addItemList(nuevos valores) ni en
replacedItemList(valores ya usados) sera el valueOld que utilizaremos. Una vez elegido se añade a
la lista replacedItemList para que en las llamadas de los otros values de addItemList no se utilicen
los mismos antiguos valores. Si no hay valores para elegir se devuelve null.
*/
private Integer getNextValueOld(ArrayList<ItemList> addItemList,ArrayList<ItemList> replacedItemList){
Integer valueOld=null;
if(m_currentListItemList!=null){//Si hay alguna seleccion
ArrayList<ItemList> currentList=new ArrayList<ItemList>();
int size=m_currentListItemList.length;
for(int i=0;i<size;i++){
currentList.add(m_currentListItemList[i]);
}
Iterator<ItemList> itr=currentList.iterator();
boolean found=false;
while(!found && itr.hasNext()){
ItemList itemL=itr.next();
if(!addItemList.contains(itemL) && !replacedItemList.contains(itemL)){
valueOld=itemL.getIntId();
replacedItemList.add(itemL);
found=true;
}
}
}
return valueOld;
}
private boolean hasValue(ItemList it){
int size=m_currentListItemList.length;
for(int i=0;i<size;i++){
if(m_currentListItemList[i].equals(it))
return true;
}
return false;
}
public boolean hasChanged() {
//int seleccion= getSelectedIndex();
// ItemList itemSelected= (ItemList)m_select.getSelectedObjects()[0];
// return !itemSelected.isInitialSelected();
/*for(int i= 0; i< seleccion.length; i++){
if(((itemList)getModel().getElementAt(seleccion[i])).isInitialSelected()!=
isSelectedIndex(seleccion[i])) return true;
}*/
ArrayList<ItemList> arrayOld=new ArrayList<ItemList>();
Object[] selected=m_select.getSelectedObjects();
int sizeOld=m_currentListItemList.length;
int size=selected.length;
if(size!=sizeOld) return true;
for(int i=0;i<sizeOld;i++)
arrayOld.add(m_currentListItemList[i]);
for(int i=0;i<size;i++){
ItemList itemList=(ItemList)selected[i];
if(!arrayOld.contains(itemList))
return true;
}
return false;
}
public void initValue() {
// if( /*m_modoFilter*/m_multivalued ) return;
// Iterator itr= m_listaInicial.iterator();
// while(itr.hasNext()){
// ItemList it= (ItemList) itr.next();
// it.initialSelection=false;
// }
// ItemList current= (ItemList)m_select.getSelectedObjects()[0];
// current.initialSelection=true;
if(m_modoFilter || m_multivalued)
((GList)getComponent()).initValue();
else ((GComboBox)getComponent()).initValue();
}
public Object getValue() {
String values=null;
int size=m_currentListItemList.length;
if(size!=0)
values=m_currentListItemList[0].getId();
for(int i=1;i<size;i++)
values+=":"+m_currentListItemList[i].getId();
//System.err.println("WARNING: Llamada al metodo GListBox.getValue() el cual no esta implementado");
return null;
}
public void clean() throws ParseException, AssignValueException {
setValue(false, null, null);
}
public IComponentListener getComponentListener() {
return m_componentListener;
}
}
| semantic-web-software/dynagent | Elecom/src/gdev/gawt/GListBox.java | Java | agpl-3.0 | 26,370 |
var round = function(number, increment, offset) {
return Math.ceil((number - offset) / increment) * increment + offset;
};
Partup.client.chatmessages = {
groupByDelay: function(messages, options) {
var delay = options.seconds ? options.seconds * 1000 : 1000;
var outputArray = [];
messages.forEach(function(item, index) {
var outputLastIndex = outputArray.length - 1;
var lastCreatedAt;
if (outputArray[outputLastIndex]) {
lastCreatedAt = new Date(outputArray[outputLastIndex].messages[outputArray[outputLastIndex].messages.length - 1].created_at).getTime();
}
var currentCreatedAt = new Date(item.created_at).getTime();
if (outputArray[outputLastIndex] && lastCreatedAt && (currentCreatedAt - lastCreatedAt) < delay) {
outputArray[outputLastIndex].messages.push(item);
} else {
outputArray.push({
messages: [item]
});
}
});
return outputArray.reverse();
},
groupByCreationDay: function(messages) {
var outputArray = [];
messages.forEach(function(item, index) {
var outputLastIndex = outputArray.length - 1;
if (outputArray[outputLastIndex] && outputArray[outputLastIndex].day === new Date(item.created_at).setHours(0, 0, 0, 0, 0)) {
outputArray[outputLastIndex].messages.push(item);
} else {
outputArray.push({
day: new Date(item.created_at).setHours(0, 0, 0, 0, 0),
messages: [item]
});
}
});
return outputArray.reverse();
},
groupByCreatorId: function(messages) {
var outputArray = [];
messages.forEach(function(item, index) {
var outputLastIndex = outputArray.length - 1;
if (outputArray[outputLastIndex] && outputArray[outputLastIndex].creator_id === item.creator_id) {
outputArray[outputLastIndex].messages.push(item);
} else {
outputArray.push({
creator_id: item.creator_id,
messages: [item]
});
}
});
return outputArray.reverse();
},
groupByChat: function(messages) {
var outputObject = {};
messages.forEach(function(item, index) {
if (outputObject[item.chat_id] && outputObject[item.chat_id].chat_id === item.chat_id) {
outputObject[item.chat_id].messages.push(item);
} else {
outputObject[item.chat_id] = {
chat_id: item.chat_id,
messages: [item]
};
}
});
var outputArray = _.values(outputObject);
return outputArray;
}
};
| part-up/part-up | app/packages/partup-client-base/client/chatmessages.js | JavaScript | agpl-3.0 | 2,893 |
/*
* DataCruncher
* Copyright (c) Mario Altimari. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.datacruncher.datastreams;
import com.datacruncher.datastreams.threads.PersistStreamsAndSendAlertsThread;
import com.datacruncher.constants.GenericType;
import com.datacruncher.constants.SchemaType;
import com.datacruncher.constants.StreamType;
import com.datacruncher.fileupload.FileExtensionType;
import com.datacruncher.fileupload.FileReadObject;
import com.datacruncher.fileupload.FileReadObjectFactory;
import com.datacruncher.jpa.ReadList;
import com.datacruncher.jpa.dao.DaoSet;
import com.datacruncher.jpa.entity.ApplicationEntity;
import com.datacruncher.jpa.entity.EventTriggerEntity;
import com.datacruncher.jpa.entity.SchemaEntity;
import com.datacruncher.jpa.entity.TasksEntity;
import com.datacruncher.utils.generic.CommonUtils;
import com.datacruncher.utils.generic.I18n;
import com.datacruncher.validation.Logical;
import com.datacruncher.validation.ResultStepValidation;
import com.datacruncher.validation.Temporary;
import org.apache.log4j.Logger;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.*;
public class DatastreamsInput implements DaoSet {
private final static Logger log = Logger.getLogger(DatastreamsInput.class);
private String uploadedFileName;
List<EventTriggerEntity> okEventList;
List<EventTriggerEntity> koEventList;
List<EventTriggerEntity> warnEventList;
private boolean okEvent = false;
private boolean koEvent = false;
private boolean warnEvent = false;
private boolean bTotalSuccess;
private String resultMsg = "";
public final static String _SINGLE_SUCC_RESP = "bTotalSuccess";
public final static String _SINGLE_STR_RESP = "bTotalResultString";
public final static String _SINGLE_STREAMENT_RESP = "streamEntityResonse";
private static int poolSize = 7;
static {
Properties properties = new Properties();
InputStream in = DatastreamsInput.class.getClassLoader().getResourceAsStream("main.properties");
try {
properties.load(in);
poolSize = Integer.parseInt(properties.get("validation.pool_size").toString());
} catch (IOException e) {
log.error("error reading main.properties", e);
}
}
public void setUploadedFileName(String uploadedFileName) {
this.uploadedFileName = uploadedFileName;
}
public DatastreamsInput() {
}
public String datastreamsInput(String datastream, Long idSchema,byte[] bytes){
return datastreamsInput(datastream, idSchema, bytes, null);
}
public String datastreamsInput(String datastream, Long idSchema, byte[] bytes, Object object) {
SchemaEntity schemaEntity = schemasDao.find(idSchema);
if (schemaEntity != null && schemaEntity.getIsPlanned() && schemaEntity.getPlannedName() > 0) {
TasksEntity tasksEntity = tasksDao.find(schemaEntity.getPlannedName());
boolean isPlanned = true;
Calendar calendar = Calendar.getInstance();
if (tasksEntity != null) {
if (tasksEntity.getIsOneShoot()) {
Date shootDate = tasksEntity.getShootDate();
String shootTime = tasksEntity.getShootTime();
Calendar shootDateTime = Calendar.getInstance();
shootDateTime.setTime(shootDate);
if (calendar.get(Calendar.YEAR) != shootDateTime.get(Calendar.YEAR)) {
isPlanned = false;
} else if (calendar.get(Calendar.MONTH) != shootDateTime.get(Calendar.MONTH)) {
isPlanned = false;
} else if (calendar.get(Calendar.DAY_OF_MONTH) != shootDateTime.get(Calendar.DAY_OF_MONTH)) {
isPlanned = false;
} else if (shootTime.trim().length() > 0 && !shootTime.equalsIgnoreCase("hh:mm")) {
int hour = Integer.parseInt(shootTime.substring(0, shootTime.indexOf(":")));
int min = Integer.parseInt(shootTime.substring(shootTime.indexOf(":") + 1));
if (calendar.get(Calendar.HOUR_OF_DAY) != hour) {
isPlanned = false;
} else if (calendar.get(Calendar.MINUTE) != min) {
isPlanned = false;
}
}
} else if (tasksEntity.getIsPeriodically()) {
if (tasksEntity.getMonth() >= 0 && (calendar.get(Calendar.MONTH) + 1) != tasksEntity.getMonth()) {
isPlanned = false;
} else if (tasksEntity.getDay() >= 0 && calendar.get(Calendar.DAY_OF_MONTH) != tasksEntity.getDay()) {
isPlanned = false;
} else if (tasksEntity.getWeek() >= 0 && calendar.get(Calendar.DAY_OF_WEEK) != tasksEntity.getWeek()) {
isPlanned = false;
} else if (tasksEntity.getHour() >= 0 && calendar.get(Calendar.HOUR_OF_DAY) != tasksEntity.getHour()) {
isPlanned = false;
} else if (tasksEntity.getMinute() >= 0 && calendar.get(Calendar.MINUTE) != tasksEntity.getMinute()) {
isPlanned = false;
}
}
}
if (!isPlanned) {
return I18n.getMessage("error.datastreamnotplanned.invalid");
}
}
return datastreamsInput(datastream, idSchema, bytes, false, object);
}
public String datastreamsInput(String datastream, Long idSchema, byte[] bytes, boolean isUnitTest){
return datastreamsInput(datastream, idSchema, bytes, isUnitTest, null);
}
public String datastreamsInput(String datastream, Long idSchema, byte[] bytes, boolean isUnitTest, Object object){
String resultMsg = "";
SchemaEntity schemaEntity = schemasDao.find(idSchema);
if (schemaEntity == null) {
resultMsg = I18n.getMessage("error.schema.invalid");
return isUnitTest ? "false" : resultMsg;
}
int idStreamType = schemaEntity.getIdStreamType();
ApplicationEntity appEntity = appDao.find(schemaEntity.getIdApplication());
Temporary temporary = new Temporary();
ResultStepValidation resultValidation = temporary.temporaryValidation(schemaEntity, appEntity);
if (resultValidation.isValid()) {
List<String> streamsList = parseStream(datastream, bytes, idSchema, idStreamType);
int i = 1;
if (streamsList.size() > 0) {
long numEvents = schemaTriggerStatusDao.findEventByIdSchema(idSchema);
bTotalSuccess = true;
if (numEvents > 0) {
checkEventTrigger(idSchema);
}
ExecutorService executor = Executors.newFixedThreadPool(poolSize);
// On case of IndexIncrement thread executor is forced to be
// single thred to guarantee order of task executions
if ( schemaEntity.getIsIndexedIncrement() ) {
executor = Executors.newSingleThreadExecutor();
}
long numElemChecked = schemaFieldsDao.findNumExtraCheck(idSchema);
String defaultNsLib = schemaEntity.getIdSchemaLib() == 0 ? null : schemaLibDao.find(schemaEntity.getIdSchemaLib()).getDefaultNsLib();
List<Future<Map<String, Object>>> list = new ArrayList<Future<Map<String, Object>>>();
boolean skipHeader =
schemaEntity.getIdStreamType() == StreamType.flatFileDelimited &&
schemaEntity.getIdSchemaType() == SchemaType.VALIDATION &&
schemaEntity.isNoHeader();
int index = -1;
for (String stream : streamsList) {
index ++;
if ( index == 0 && skipHeader ) {
continue;
}
Callable<Map<String, Object>> callee = new ValidationCallable(
idSchema,
schemaEntity,
stream,
bytes,
isUnitTest,
okEvent,
koEvent,
warnEvent,
okEventList,
koEventList,
warnEventList,
object,
numElemChecked,
appEntity,
defaultNsLib,
index == streamsList.size() - 1,
skipHeader ? index == 1 : index == 0 );
Future<Map<String, Object>> submit = executor.submit(callee);
list.add(submit);
}
Map<String, Object> futureRes;
try {
if (!isUnitTest) {
PersistStreamsAndSendAlertsThread persStreams = new PersistStreamsAndSendAlertsThread(list, executor);
persStreams.start();
persStreams.join();
}
for (Future<Map<String, Object>> future : list) {
try {
futureRes = future.get();
resultMsg += (streamsList.size() == 1 ? "" : i++ + ".Stream: ")
+ futureRes.get(_SINGLE_STR_RESP) + "<br><br>";
bTotalSuccess = bTotalSuccess && (Boolean) futureRes.get(_SINGLE_SUCC_RESP);
} catch (ExecutionException e) {
log.error("ExecutionException", e);
}
}
} catch (InterruptedException e1) {
log.error("InterruptedException", e1);
}
executor.shutdown();
Logical.mapExtraCheck = new HashMap<String, Set<String>>();
} else {
bTotalSuccess = false;
resultMsg = I18n.getMessage("error.validationTraceNoValid");
}
} else {
bTotalSuccess = false;
resultMsg = resultValidation.getMessageResult();
}
this.resultMsg = resultMsg;
return isUnitTest ? String.valueOf(bTotalSuccess) : resultMsg;
}
@SuppressWarnings("unchecked")
private void checkEventTrigger(Long idSchema){
ReadList readList = eventTriggerDao.findByIdSchemaAndIdStatus(idSchema, GenericType.okEvent);
if (readList.getResults() != null && readList.getResults().size() > 0) {
okEvent = true;
okEventList = (List<EventTriggerEntity>) readList.getResults();
}else{
okEvent = false;
}
readList = eventTriggerDao.findByIdSchemaAndIdStatus(idSchema,GenericType.koEvent);
if (readList.getResults() != null && readList.getResults().size() > 0) {
koEvent = true;
koEventList = (List<EventTriggerEntity>) readList.getResults();
}else{
koEvent = false;
}
readList = eventTriggerDao.findByIdSchemaAndIdStatus(idSchema,GenericType.warnEvent);
if (readList.getResults() != null && readList.getResults().size() > 0) {
warnEvent = true;
warnEventList = (List<EventTriggerEntity>) readList.getResults();
}else{
warnEvent = false;
}
}
/**
* Parses current multi datastream.
*
* @param datastream DataStream
* @param idStreamType
* - xml/exi/..
* @return separated streams
*/
private List<String> parseStream(String datastream, byte[] bytes,
Long idSchema, int idStreamType) {
List<String> streamsList = new ArrayList<String>();
try {
if(schemasDao.find(idSchema).getIdSchemaType() == SchemaType.STANDARD){
String defNameSpace = schemaLibDao.find(schemasDao.find(idSchema).getIdSchemaLib()).getDefaultNsLib();
String str = datastream.replaceAll("\\r|\\n|\\t", " ").trim();
if (str.startsWith("<?xml")) {
// xml prolog remove
str = str.replaceFirst("<\\?xml .*\\?>", "");
str = str.trim();
}
if (str.startsWith("<")) {
int r= str.lastIndexOf("</");
String closingNode = str.substring(r);
closingNode = closingNode.trim();
String nodeName = closingNode.substring(closingNode.indexOf("/")+1, closingNode.length()-1);
streamsList = Arrays.asList(str.split(closingNode));
for (int i = 0; i < streamsList.size(); i++) {
String stream=streamsList.get(i).replaceFirst(nodeName,nodeName+" xmlns="+ defNameSpace +" ");
streamsList.set(i, stream + closingNode);
}
}
}else{
if (idStreamType == StreamType.XML ) {
String str = datastream.replaceAll("\\r|\\n|\\t", " ").trim();
if (str.startsWith("<?xml")) {
// xml prolog remove
str = str.replaceFirst("<\\?xml .*\\?>", "");
str = str.trim();
}
if (str.startsWith("<")) {
int r= str.lastIndexOf("</");
String closingNode = str.substring(r);
closingNode = closingNode.trim();
streamsList = Arrays.asList(str.split(closingNode));
for (int i = 0; i < streamsList.size(); i++) {
streamsList.set(i, streamsList.get(i) + closingNode);
}
}
}else if (idStreamType == StreamType.flatFileFixedPosition) {
datastream= datastream.replaceAll("\\r\\n", "\\\n");
datastream= datastream.replaceAll("\\r", "\\\n");
streamsList = Arrays.asList(datastream.split("\\n"));
for (int i = 0; i < streamsList.size(); i++) {
// '/r' appear in file with '/r/n' but in textarea appear
// only '/n'
streamsList
.set(i, streamsList.get(i).replaceAll("\\r", ""));
}
} else if (idStreamType == StreamType.flatFileDelimited) {
datastream= datastream.replaceAll("\\r\\n", "\\\n");
datastream= datastream.replaceAll("\\r", "\\\n");
Character chrDelim = schemasDao.find(idSchema).getChrDelimiter().charAt(0);
if (chrDelim.toString().trim().length() == 1) {
streamsList = Arrays.asList(CommonUtils.lineSplit(datastream, schemasDao.find(idSchema).getDelimiter(),chrDelim));
}else{
streamsList = Arrays.asList(datastream.split("\\n"));
}
for (int i = 0; i < streamsList.size(); i++) {
// '/r' appear in file with '/r/n' but in textarea appear
// only '/n'
streamsList.set(i, streamsList.get(i).replaceAll("\\r", ""));
}
} else if (idStreamType == StreamType.XMLEXI) {
streamsList.add(datastream);
} else if (idStreamType == StreamType.JSON) {
String str = datastream.replaceAll("\\r|\\n|\\t", "").trim();
datastream = str.replaceAll("\\}\\{", "\\}--\\{");
streamsList = Arrays.asList(datastream.split("--"));
for (int i = 0; i < streamsList.size(); i++) {
streamsList.set(i, streamsList.get(i));
}
} else if (idStreamType == StreamType.EXCEL) {
if (!(uploadedFileName.endsWith(FileExtensionType.EXCEL_97
.getAbbreviation()) || uploadedFileName
.endsWith(FileExtensionType.EXCEL_2007
.getAbbreviation()))) {
streamsList.add("File is not a MS Excel file.");
return streamsList;
}
FileReadObject fileReadObject = FileReadObjectFactory
.getFileReadObject(uploadedFileName);
datastream = fileReadObject.parseStream(idSchema,
new ByteArrayInputStream(bytes));
String str = datastream.replaceAll("\\r|\\n|\\t", " ").trim();
if (str.startsWith("<?xml")) {
// xml prolog remove
str = str.replaceFirst("<\\?xml .*\\?>", "");
str = str.trim();
}
if (str.startsWith("<")) {
String rootNodeName = str.substring(1, str.indexOf(">"));
String closingNode = "</" + rootNodeName + ">";
streamsList = Arrays.asList(str.split(closingNode));
for (int i = 0; i < streamsList.size(); i++) {
streamsList.set(i, streamsList.get(i) + closingNode);
}
} else {
streamsList.add(datastream);
}
}
}
} catch (Exception e) {
log.error("Error while parsing stream", e);
}
return streamsList;
}
public boolean getTotalSuccess() {
return bTotalSuccess;
}
public String getResultMsg() {
return resultMsg;
}
} | see-r/SeerDataCruncher | src/main/java/com/datacruncher/datastreams/DatastreamsInput.java | Java | agpl-3.0 | 18,067 |
<?php
/**
* Copyright 2015-2018 ppy Pty. Ltd.
*
* This file is part of osu!web. osu!web is distributed with the hope of
* attracting more community contributions to the core ecosystem of osu!.
*
* osu!web is free software: you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License version 3
* as published by the Free Software Foundation.
*
* osu!web is distributed 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 osu!web. If not, see <http://www.gnu.org/licenses/>.
*/
return [
'discussion-posts' => [
'store' => [
'error' => '保存失败',
],
],
'discussion-votes' => [
'update' => [
'error' => '更新投票失败',
],
],
'discussions' => [
'allow_kudosu' => '给予 kudosu',
'delete' => '删除',
'deleted' => '被 :editor 于 :delete_time 删除。',
'deny_kudosu' => '收回 kudosu',
'edit' => '编辑',
'edited' => '最后由 :editor 编辑于 :update_time 。',
'kudosu_denied' => 'kudosu 被收回',
'message_placeholder_deleted_beatmap' => '该难度已被删除,无法继续讨论',
'message_type_select' => '选择回复类型',
'reply_notice' => '按下回车以提交',
'reply_placeholder' => '在此处输入您的回复',
'require-login' => '登录以继续',
'resolved' => '已解决',
'restore' => '已修复',
'title' => '讨论',
'collapse' => [
'all-collapse' => '全部折叠',
'all-expand' => '全部展开',
],
'empty' => [
'empty' => '还没有讨论!',
'hidden' => '没有符合过滤条件的讨论。',
],
'message_hint' => [
'in_general' => '这个信息将提交到整个谱面讨论中。如果需要单独针对某处,请在开头使用时间戳 (例如: 00:12:345)。',
'in_timeline' => '需要 Mod 多处,请在每一个时间戳后写下意见并发表。',
],
'message_placeholder' => [
'general' => '在此处输入以发布到常规 (:version)',
'generalAll' => '在此处输入以发布到常规 (所有难度)',
'timeline' => '在此处输入以发布到时间线 (:version)',
],
'message_type' => [
'disqualify' => '取消提名',
'hype' => '推荐!',
'mapper_note' => '备注',
'nomination_reset' => '重置提名',
'praise' => '赞',
'problem' => '问题',
'suggestion' => '建议',
],
'mode' => [
'events' => '历史',
'general' => '常规 :scope',
'timeline' => '时间线',
'scopes' => [
'general' => '当前难度',
'generalAll' => '所有难度',
],
],
'new' => [
'timestamp' => '时间戳',
'timestamp_missing' => '在编辑模式下按 Ctrl+C 然后在您的输入框中粘贴以添加时间戳!',
'title' => '新的讨论',
],
'show' => [
'title' => '由 :mapper 制作的 :title',
],
'sort' => [
'_' => '排序:',
'created_at' => '创建时间',
'timeline' => '时间轴',
'updated_at' => '最后更新时间',
],
'stats' => [
'deleted' => '已删除',
'mapper_notes' => '备注',
'mine' => '我的',
'pending' => '未解决',
'praises' => '赞',
'resolved' => '已解决',
'total' => '所有',
],
'status-messages' => [
'approved' => '这张谱面于 :date 被 Approved !',
'graveyard' => "这张谱面自 :date 就未更新了,或许它已经被作者抛弃了 ;w;",
'loved' => '这张谱面于 :date 被 Loved !',
'ranked' => '这张谱面于 :date 被 Ranked !',
'wip' => '注意:这张谱面被作者标记为 WIP(work-in-progress)',
],
],
'hype' => [
'button' => '推荐谱面!',
'button_done' => '已经推荐!',
'confirm' => "你确定吗?这将会使用你剩下的 :n 次推荐次数并且无法撤销。",
'explanation' => '推荐这张谱面让它更容易被提名然后 ranked !',
'explanation_guest' => '登录并推荐这张谱面让它更容易被提名然后 ranked !',
'new_time' => "你将在 :new_time 后获得新的推荐次数。",
'remaining' => '你还可以推荐 :remaining 次。',
'required_text' => '推荐进度: :current/:required',
'section_title' => '推荐进度',
'title' => '推荐',
],
'feedback' => [
'button' => '留下建议',
],
'nominations' => [
'disqualification_prompt' => 'DQ 的理由?',
'disqualified_at' => '于 :time_ago 被 DQ (:reason)。',
'disqualified_no_reason' => '没有指定原因',
'disqualify' => 'Disqualify',
'incorrect_state' => '操作出错了,请刷新页面。',
'love' => '喜欢',
'love_confirm' => '喜欢这张谱面吗?',
'nominate' => '提名',
'nominate_confirm' => '提名这张谱面?',
'nominated_by' => '被 :users 提名',
'qualified' => '如果没有问题,预计将于 :date 被 Ranked 。',
'qualified_soon' => '如果没有问题,预计不久将被 Ranked 。',
'required_text' => '提名数: :current/:required',
'reset_message_deleted' => '已删除',
'title' => '提名状态',
'unresolved_issues' => '仍然有需解决的问题 。',
'reset_at' => [
'nomination_reset' => '提名于 :time_ago 被新问题 :discussion 重置。',
'disqualify' => ':time_ago 被 :user 因为新问题 :discussion (:message) 而 DQ.',
],
'reset_confirm' => [
'nomination_reset' => '你确定吗?提出新的问题会重置提名。',
],
],
'listing' => [
'search' => [
'prompt' => '输入关键字...',
'login_required' => '登录以搜索。',
'options' => '更多搜索选项',
'supporter_filter' => '按 :filters 筛选需要成为支持者',
'not-found' => '没有结果',
'not-found-quote' => '呃,什么也没有...',
'filters' => [
'general' => '常规',
'mode' => '模式',
'status' => '分类',
'genre' => '流派',
'language' => '语言',
'extra' => '额外',
'rank' => '有成绩',
'played' => '玩过',
],
'sorting' => [
'title' => '标题',
'artist' => '艺术家',
'difficulty' => '难度',
'updated' => '更新时间',
'ranked' => 'rank时间',
'rating' => '评分',
'plays' => '游玩次数',
'relevance' => '相关性',
'nominations' => '提名状态',
],
'supporter_filter_quote' => [
'_' => '按 :filters 筛选需要成为 :link',
'link_text' => '支持者',
],
],
],
'general' => [
'recommended' => '推荐难度',
'converts' => '包括转谱',
],
'mode' => [
'any' => '所有',
'osu' => 'osu!',
'taiko' => 'osu!taiko',
'fruits' => 'osu!catch',
'mania' => 'osu!mania',
],
'status' => [
'any' => '所有',
'ranked-approved' => 'Ranked & Approved',
'approved' => 'Approved',
'qualified' => 'Qualified',
'loved' => 'Loved',
'faves' => 'Favourites',
'pending' => 'Pending & WIP',
'graveyard' => 'Graveyard',
'my-maps' => '我的',
],
'genre' => [
'any' => '所有',
'unspecified' => '尚未指定',
'video-game' => '电子游戏',
'anime' => '动漫',
'rock' => '摇滚',
'pop' => '流行乐',
'other' => '其他',
'novelty' => '新奇',
'hip-hop' => '嘻哈',
'electronic' => '电子',
],
'mods' => [
'4K' => '4K',
'5K' => '5K',
'6K' => '6K',
'7K' => '7K',
'8K' => '8K',
'9K' => '9K',
'AP' => 'Auto Pliot',
'DT' => 'Double Time',
'EZ' => 'Easy Mode',
'FI' => 'Fade In',
'FL' => 'Flashlight',
'HD' => 'Hidden',
'HR' => 'Hard Rock',
'HT' => 'Half Time',
'NC' => 'Nightcore',
'NF' => 'No Fail',
'NM' => 'No mods',
'PF' => 'Perfect',
'Relax' => 'Relax',
'SD' => 'Sudden Death',
'SO' => 'Spun Out',
'TD' => 'Touch Device',
],
'language' => [
'any' => '所有',
'english' => '英语',
'chinese' => '汉语',
'french' => '法语',
'german' => '德语',
'italian' => '意大利语',
'japanese' => '日语',
'korean' => '韩语',
'spanish' => '西班牙语',
'swedish' => '瑞典语',
'instrumental' => '器乐',
'other' => '其他',
],
'played' => [
'any' => '任意',
'played' => '玩过',
'unplayed' => '没玩过',
],
'extra' => [
'video' => '有视频',
'storyboard' => '有 Storyboard',
],
'rank' => [
'any' => '任意',
'XH' => '白银 SS',
'X' => 'SS',
'SH' => '白银 S',
'S' => 'S',
'A' => 'A',
'B' => 'B',
'C' => 'C',
'D' => 'D',
],
];
| kj415j45/osu-web | resources/lang/zh/beatmaps.php | PHP | agpl-3.0 | 10,212 |
""" IMAPClient wrapper for the Nilas Sync Engine. """
import contextlib
import re
import time
import imaplib
import imapclient
# Even though RFC 2060 says that the date component must have two characters
# (either two digits or space+digit), it seems that some IMAP servers only
# return one digit. Fun times.
imaplib.InternalDate = re.compile(
r'.*INTERNALDATE "'
r'(?P<day>[ 0123]?[0-9])-' # insert that `?` to make first digit optional
r'(?P<mon>[A-Z][a-z][a-z])-'
r'(?P<year>[0-9][0-9][0-9][0-9])'
r' (?P<hour>[0-9][0-9]):'
r'(?P<min>[0-9][0-9]):'
r'(?P<sec>[0-9][0-9])'
r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
r'"')
import functools
import threading
from email.parser import HeaderParser
from collections import namedtuple, defaultdict
import gevent
from gevent import socket
from gevent.lock import BoundedSemaphore
from gevent.queue import Queue
from inbox.util.concurrency import retry
from inbox.util.itert import chunk
from inbox.util.misc import or_none
from inbox.basicauth import GmailSettingError
from inbox.models.session import session_scope
from inbox.models.account import Account
from nylas.logging import get_logger
log = get_logger()
__all__ = ['CrispinClient', 'GmailCrispinClient']
# Unify flags API across IMAP and Gmail
Flags = namedtuple('Flags', 'flags')
# Flags includes labels on Gmail because Gmail doesn't use \Draft.
GmailFlags = namedtuple('GmailFlags', 'flags labels')
GMetadata = namedtuple('GMetadata', 'g_msgid g_thrid size')
RawMessage = namedtuple(
'RawImapMessage',
'uid internaldate flags body g_thrid g_msgid g_labels')
RawFolder = namedtuple('RawFolder', 'display_name role')
# Lazily-initialized map of account ids to lock objects.
# This prevents multiple greenlets from concurrently creating duplicate
# connection pools for a given account.
_lock_map = defaultdict(threading.Lock)
CONN_DISCARD_EXC_CLASSES = (socket.error, imaplib.IMAP4.error)
class FolderMissingError(Exception):
pass
def _get_connection_pool(account_id, pool_size, pool_map, readonly):
with _lock_map[account_id]:
if account_id not in pool_map:
pool_map[account_id] = CrispinConnectionPool(
account_id, num_connections=pool_size, readonly=readonly)
return pool_map[account_id]
def connection_pool(account_id, pool_size=3, pool_map=dict()):
""" Per-account crispin connection pool.
Use like this:
with crispin.connection_pool(account_id).get() as crispin_client:
# your code here
pass
Note that the returned CrispinClient could have ANY folder selected, or
none at all! It's up to the calling code to handle folder sessions
properly. We don't reset to a certain select state because it's slow.
"""
return _get_connection_pool(account_id, pool_size, pool_map, True)
def writable_connection_pool(account_id, pool_size=1, pool_map=dict()):
""" Per-account crispin connection pool, with *read-write* connections.
Use like this:
conn_pool = crispin.writable_connection_pool(account_id)
with conn_pool.get() as crispin_client:
# your code here
pass
"""
return _get_connection_pool(account_id, pool_size, pool_map, False)
class CrispinConnectionPool(object):
"""
Connection pool for Crispin clients.
Connections in a pool are specific to an IMAPAccount.
Parameters
----------
account_id : int
Which IMAPAccount to open up a connection to.
num_connections : int
How many connections in the pool.
readonly : bool
Is the connection to the IMAP server read-only?
"""
def __init__(self, account_id, num_connections, readonly):
log.info('Creating Crispin connection pool for account {} with {} '
'connections'.format(account_id, num_connections))
self.account_id = account_id
self.readonly = readonly
self._queue = Queue(num_connections, items=num_connections * [None])
self._sem = BoundedSemaphore(num_connections)
self._set_account_info()
@contextlib.contextmanager
def get(self):
""" Get a connection from the pool, or instantiate a new one if needed.
If `num_connections` connections are already in use, block until one is
available.
"""
# A gevent semaphore is granted in the order that greenlets tried to
# acquire it, so we use a semaphore here to prevent potential
# starvation of greenlets if there is high contention for the pool.
# The queue implementation does not have that property; having
# greenlets simply block on self._queue.get(block=True) could cause
# individual greenlets to block for arbitrarily long.
self._sem.acquire()
client = self._queue.get()
try:
if client is None:
client = self._new_connection()
yield client
except CONN_DISCARD_EXC_CLASSES as exc:
# Discard the connection on socket or IMAP errors. Technically this
# isn't always necessary, since if you got e.g. a FETCH failure you
# could reuse the same connection. But for now it's the simplest
# thing to do.
log.info('IMAP connection error; discarding connection',
exc_info=True)
if client is not None:
try:
client.logout()
except:
log.error('Error on IMAP logout', exc_info=True)
client = None
raise exc
except:
raise
finally:
self._queue.put(client)
self._sem.release()
def _set_account_info(self):
with session_scope() as db_session:
account = db_session.query(Account).get(self.account_id)
self.sync_state = account.sync_state
self.provider_info = account.provider_info
self.email_address = account.email_address
self.auth_handler = account.auth_handler
if account.provider == 'gmail':
self.client_cls = GmailCrispinClient
else:
self.client_cls = CrispinClient
def _new_raw_connection(self):
"""Returns a new, authenticated IMAPClient instance for the account."""
with session_scope() as db_session:
account = db_session.query(Account).get(self.account_id)
return self.auth_handler.connect_account(account)
def _new_connection(self):
conn = self._new_raw_connection()
return self.client_cls(self.account_id, self.provider_info,
self.email_address, conn,
readonly=self.readonly)
def _exc_callback():
log.info('Connection broken with error; retrying with new connection',
exc_info=True)
gevent.sleep(5)
retry_crispin = functools.partial(
retry, retry_classes=CONN_DISCARD_EXC_CLASSES, exc_callback=_exc_callback)
class CrispinClient(object):
"""
Generic IMAP client wrapper.
One thing to note about crispin clients is that *all* calls operate on
the currently selected folder.
Crispin will NEVER implicitly select a folder for you.
This is very important! IMAP only guarantees that folder message UIDs
are valid for a "session", which is defined as from the time you
SELECT a folder until the connection is closed or another folder is
selected.
Crispin clients *always* return long ints rather than strings for number
data types, such as message UIDs, Google message IDs, and Google thread
IDs.
All inputs are coerced to strings before being passed off to the IMAPClient
connection.
You should really be interfacing with this class via a connection pool,
see `connection_pool()`.
Parameters
----------
account_id : int
Database id of the associated IMAPAccount.
conn : IMAPClient
Open IMAP connection (should be already authed).
readonly : bool
Whether or not to open IMAP connections as readonly.
"""
def __init__(self, account_id, provider_info, email_address, conn,
readonly=True):
self.account_id = account_id
self.provider_info = provider_info
self.email_address = email_address
# IMAP isn't stateless :(
self.selected_folder = None
self._folder_names = None
self.conn = conn
self.readonly = readonly
def _fetch_folder_list(self):
""" NOTE: XLIST is deprecated, so we just use LIST.
An example response with some other flags:
* LIST (\HasNoChildren) "/" "INBOX"
* LIST (\Noselect \HasChildren) "/" "[Gmail]"
* LIST (\HasNoChildren \All) "/" "[Gmail]/All Mail"
* LIST (\HasNoChildren \Drafts) "/" "[Gmail]/Drafts"
* LIST (\HasNoChildren \Important) "/" "[Gmail]/Important"
* LIST (\HasNoChildren \Sent) "/" "[Gmail]/Sent Mail"
* LIST (\HasNoChildren \Junk) "/" "[Gmail]/Spam"
* LIST (\HasNoChildren \Flagged) "/" "[Gmail]/Starred"
* LIST (\HasNoChildren \Trash) "/" "[Gmail]/Trash"
IMAPClient parses this response into a list of
(flags, delimiter, name) tuples.
"""
return self.conn.list_folders()
def select_folder(self, folder, uidvalidity_cb):
""" Selects a given folder.
Makes sure to set the 'selected_folder' attribute to a
(folder_name, select_info) pair.
Selecting a folder indicates the start of an IMAP session. IMAP UIDs
are only guaranteed valid for sessions, so the caller must provide a
callback that checks UID validity.
Starts a new session even if `folder` is already selected, since
this does things like e.g. makes sure we're not getting
cached/out-of-date values for HIGHESTMODSEQ from the IMAP server.
"""
try:
select_info = self.conn.select_folder(
folder, readonly=self.readonly)
except imapclient.IMAPClient.Error as e:
# Specifically point out folders that come back as missing by
# checking for Yahoo / Gmail / Outlook (Hotmail) specific errors:
if '[NONEXISTENT] Unknown Mailbox:' in e.message or \
'does not exist' in e.message or \
"doesn't exist" in e.message:
raise FolderMissingError(folder)
# We can't assume that all errors here are caused by the folder
# being deleted, as other connection errors could occur - but we
# want to make sure we keep track of different providers'
# "nonexistent" messages, so log this event.
log.error("IMAPClient error selecting folder. May be deleted",
error=str(e))
raise
select_info['UIDVALIDITY'] = long(select_info['UIDVALIDITY'])
self.selected_folder = (folder, select_info)
# Don't propagate cached information from previous session
self._folder_names = None
return uidvalidity_cb(self.account_id, folder, select_info)
@property
def selected_folder_name(self):
return or_none(self.selected_folder, lambda f: f[0])
@property
def selected_folder_info(self):
return or_none(self.selected_folder, lambda f: f[1])
@property
def selected_uidvalidity(self):
return or_none(self.selected_folder_info, lambda i: i['UIDVALIDITY'])
@property
def selected_uidnext(self):
return or_none(self.selected_folder_info, lambda i: i.get('UIDNEXT'))
def sync_folders(self):
"""
List of folders to sync.
In generic IMAP, the 'INBOX' folder is required.
Returns
-------
list
Folders to sync (as strings).
"""
to_sync = []
have_folders = self.folder_names()
assert 'inbox' in have_folders, \
"Missing required 'inbox' folder for account_id: {}".\
format(self.account_id)
for names in have_folders.itervalues():
to_sync.extend(names)
return to_sync
def folder_names(self, force_resync=False):
"""
Return the folder names for the account as a mapping from
recognized role: list of folder names,
for example: 'sent': ['Sent Items', 'Sent'].
The list of recognized folder roles is in:
inbox/models/constants.py
Folders that do not belong to a recognized role are mapped to
None, for example: None: ['MyFolder', 'OtherFolder'].
The mapping is also cached in self._folder_names
Parameters:
-----------
force_resync: boolean
Return the cached mapping or return a refreshed mapping
(after refetching from the remote).
"""
if force_resync or self._folder_names is None:
self._folder_names = defaultdict(list)
raw_folders = self.folders()
for f in raw_folders:
self._folder_names[f.role].append(f.display_name)
return self._folder_names
def folders(self):
"""
Fetch the list of folders for the account from the remote, return as a
list of RawFolder objects.
NOTE:
Always fetches the list of folders from the remote.
"""
raw_folders = []
folders = self._fetch_folder_list()
for flags, delimiter, name in folders:
if u'\\Noselect' in flags or u'\\NoSelect' in flags \
or u'\\NonExistent' in flags:
# Special folders that can't contain messages
continue
raw_folder = self._process_folder(name, flags)
raw_folders.append(raw_folder)
return raw_folders
def _process_folder(self, display_name, flags):
"""
Determine the role for the remote folder from its `name` and `flags`.
Returns
-------
RawFolder representing the folder
"""
# TODO[[k]: Important/ Starred for generic IMAP?
# Different providers have different names for folders, here
# we have a default map for common name mapping, additional
# mappings can be provided via the provider configuration file
default_folder_map = {
'inbox': 'inbox',
'drafts': 'drafts',
'draft': 'drafts',
'junk': 'spam',
'spam': 'spam',
'archive': 'archive',
'sent': 'sent',
'trash': 'trash'}
# Additionally we provide a custom mapping for providers that
# don't fit into the defaults.
folder_map = self.provider_info.get('folder_map', {})
# Some providers also provide flags to determine common folders
# Here we read these flags and apply the mapping
flag_map = {'\\Trash': 'trash', '\\Sent': 'sent', '\\Drafts': 'drafts',
'\\Junk': 'spam', '\\Inbox': 'inbox', '\\Spam': 'spam'}
role = default_folder_map.get(display_name.lower())
if not role:
role = folder_map.get(display_name)
if not role:
for flag in flags:
role = flag_map.get(flag)
return RawFolder(display_name=display_name, role=role)
def create_folder(self, name):
self.conn.create_folder(name)
def condstore_supported(self):
# Technically QRESYNC implies CONDSTORE, although this is unlikely to
# matter in practice.
capabilities = self.conn.capabilities()
return 'CONDSTORE' in capabilities or 'QRESYNC' in capabilities
def idle_supported(self):
return 'IDLE' in self.conn.capabilities()
def search_uids(self, criteria):
"""
Find UIDs in this folder matching the criteria. See
http://tools.ietf.org/html/rfc3501.html#section-6.4.4 for valid
criteria.
"""
return sorted([long(uid) for uid in self.conn.search(criteria)])
def all_uids(self):
""" Fetch all UIDs associated with the currently selected folder.
Returns
-------
list
UIDs as integers sorted in ascending order.
"""
# Note that this list may include items which have been marked for
# deletion with the \Deleted flag, but not yet actually removed via
# an EXPUNGE command. I choose to include them here since most clients
# will still display them (sometimes with a strikethrough). If showing
# these is a problem, we can either switch back to searching for
# 'UNDELETED' or doing a fetch for ['UID', 'FLAGS'] and filtering.
try:
t = time.time()
fetch_result = self.conn.search(['ALL'])
except imaplib.IMAP4.error as e:
if e.message.find('UID SEARCH wrong arguments passed') >= 0:
# Mail2World servers fail for the otherwise valid command
# 'UID SEARCH ALL' but strangely pass for 'UID SEARCH ALL UID'
log.debug("Getting UIDs failed when using 'UID SEARCH "
"ALL'. Switching to alternative 'UID SEARCH "
"ALL UID", exception=e)
t = time.time()
fetch_result = self.conn.search(['ALL', 'UID'])
else:
raise
elapsed = time.time() - t
log.debug('Requested all UIDs',
selected_folder=self.selected_folder_name,
search_time=elapsed,
total_uids=len(fetch_result))
return sorted([long(uid) for uid in fetch_result])
def uids(self, uids):
uid_set = set(uids)
messages = []
raw_messages = {}
for uid in uid_set:
try:
raw_messages.update(self.conn.fetch(
uid, ['BODY.PEEK[]', 'INTERNALDATE', 'FLAGS']))
except imapclient.IMAPClient.Error as e:
if ('[UNAVAILABLE] UID FETCH Server error '
'while fetching messages') in str(e):
log.info('Got an exception while requesting an UID',
uid=uid, error=e,
logstash_tag='imap_download_exception')
continue
else:
log.info(('Got an unhandled exception while '
'requesting an UID'),
uid=uid, error=e,
logstash_tag='imap_download_exception')
raise
for uid in sorted(raw_messages.iterkeys(), key=long):
# Skip handling unsolicited FETCH responses
if uid not in uid_set:
continue
msg = raw_messages[uid]
if msg.keys() == ['SEQ']:
log.error('No data returned for UID, skipping', uid=uid)
continue
messages.append(RawMessage(uid=long(uid),
internaldate=msg['INTERNALDATE'],
flags=msg['FLAGS'],
body=msg['BODY[]'],
# TODO: use data structure that isn't
# Gmail-specific
g_thrid=None, g_msgid=None,
g_labels=None))
return messages
def flags(self, uids):
if len(uids) > 100:
# Some backends abort the connection if you give them a really
# long sequence set of individual UIDs, so instead fetch flags for
# all UIDs greater than or equal to min(uids).
seqset = '{}:*'.format(min(uids))
else:
seqset = uids
data = self.conn.fetch(seqset, ['FLAGS'])
uid_set = set(uids)
return {uid: Flags(ret['FLAGS'])
for uid, ret in data.items() if uid in uid_set}
def delete_uids(self, uids):
uids = [str(u) for u in uids]
self.conn.delete_messages(uids)
self.conn.expunge()
def set_starred(self, uids, starred):
if starred:
self.conn.add_flags(uids, ['\\Flagged'])
else:
self.conn.remove_flags(uids, ['\\Flagged'])
def set_unread(self, uids, unread):
uids = [str(u) for u in uids]
if unread:
self.conn.remove_flags(uids, ['\\Seen'])
else:
self.conn.add_flags(uids, ['\\Seen'])
def save_draft(self, message, date=None):
assert self.selected_folder_name in self.folder_names()['drafts'], \
'Must select a drafts folder first ({0})'.\
format(self.selected_folder_name)
self.conn.append(self.selected_folder_name, message, ['\\Draft',
'\\Seen'], date)
def create_message(self, message, date=None):
"""
Create a message on the server. Only used to fix server-side bugs,
like iCloud not saving Sent messages.
"""
assert self.selected_folder_name in self.folder_names()['sent'], \
'Must select sent folder first ({0})'.\
format(self.selected_folder_name)
return self.conn.append(self.selected_folder_name, message, [], date)
def fetch_headers(self, uids):
"""
Fetch headers for the given uids. Chunked because certain providers
fail with 'Command line too large' if you feed them too many uids at
once.
"""
headers = {}
for uid_chunk in chunk(uids, 100):
headers.update(self.conn.fetch(
uid_chunk, ['BODY.PEEK[HEADER]']))
return headers
def find_by_header(self, header_name, header_value):
"""Find all uids in the selected folder with the given header value."""
all_uids = self.all_uids()
# It would be nice to just search by header too, but some backends
# don't support that, at least not if you want to search by X-INBOX-ID
# header. So fetch the header for each draft and see if we
# can find one that matches.
# TODO(emfree): are there other ways we can narrow the result set a
# priori (by subject or date, etc.)
matching_draft_headers = self.fetch_headers(all_uids)
results = []
for uid, response in matching_draft_headers.iteritems():
headers = response['BODY[HEADER]']
parser = HeaderParser()
header = parser.parsestr(headers).get(header_name)
if header == header_value:
results.append(uid)
return results
def delete_draft(self, inbox_uid, message_id_header):
"""
Delete a draft, as identified either by its X-Inbox-Id or by its
Message-Id header. We first delete the message from the Drafts folder,
and then also delete it from the Trash folder if necessary.
"""
drafts_folder_name = self.folder_names()['drafts'][0]
self.conn.select_folder(drafts_folder_name)
self._delete_message(inbox_uid, message_id_header)
trash_folder_name = self.folder_names()['trash'][0]
self.conn.select_folder(trash_folder_name)
self._delete_message(inbox_uid, message_id_header)
def _delete_message(self, inbox_uid, message_id_header):
"""
Delete a message from the selected folder, using either the X-Inbox-Id
header or the Message-Id header to locate it. Does nothing if no
matching messages are found, or if more than one matching message is
found.
"""
assert inbox_uid or message_id_header, 'Need at least one header'
if inbox_uid:
matching_uids = self.find_by_header('X-Inbox-Id', inbox_uid)
else:
matching_uids = self.find_by_header('Message-Id',
message_id_header)
if not matching_uids:
log.error('No remote messages found to delete',
inbox_uid=inbox_uid,
message_id_header=message_id_header)
return
if len(matching_uids) > 1:
log.error('Multiple remote messages found to delete',
inbox_uid=inbox_uid,
message_id_header=message_id_header,
uids=matching_uids)
return
self.conn.delete_messages(matching_uids)
self.conn.expunge()
def logout(self):
self.conn.logout()
def idle(self, timeout):
"""Idle for up to `timeout` seconds. Make sure we take the connection
back out of idle mode so that we can reuse this connection in another
context."""
log.info('Idling', timeout=timeout)
self.conn.idle()
try:
with self._restore_timeout():
r = self.conn.idle_check(timeout)
except:
self.conn.idle_done()
raise
self.conn.idle_done()
return r
@contextlib.contextmanager
def _restore_timeout(self):
# IMAPClient.idle_check() calls setblocking(1) on the underlying
# socket, erasing any previously set timeout. So make sure to restore
# the timeout.
sock = getattr(self.conn._imap, 'sslobj', self.conn._imap.sock)
timeout = sock.gettimeout()
try:
yield
finally:
sock.settimeout(timeout)
def condstore_changed_flags(self, modseq):
data = self.conn.fetch('1:*', ['FLAGS'],
modifiers=['CHANGEDSINCE {}'.format(modseq)])
return {uid: Flags(ret['FLAGS']) for uid, ret in data.items()}
class GmailCrispinClient(CrispinClient):
PROVIDER = 'gmail'
def sync_folders(self):
"""
Gmail-specific list of folders to sync.
In Gmail, every message is in `All Mail`, with the exception of
messages in the Trash and Spam folders. So we only sync the `All Mail`,
Trash and Spam folders.
Returns
-------
list
Folders to sync (as strings).
"""
present_folders = self.folder_names()
if 'all' not in present_folders:
raise GmailSettingError(
"Account {} ({}) is missing the 'All Mail' folder. This is "
"probably due to 'Show in IMAP' being disabled. "
"Please enable at "
"https://mail.google.com/mail/#settings/labels"
.format(self.account_id, self.email_address))
# If the account has Trash, Spam folders, sync those too.
to_sync = []
for folder in ['all', 'trash', 'spam']:
if folder in present_folders:
to_sync.append(present_folders[folder][0])
return to_sync
def flags(self, uids):
"""
Gmail-specific flags.
Returns
-------
dict
Mapping of `uid` : GmailFlags.
"""
data = self.conn.fetch(uids, ['FLAGS', 'X-GM-LABELS'])
uid_set = set(uids)
return {uid: GmailFlags(ret['FLAGS'], ret['X-GM-LABELS'])
for uid, ret in data.items() if uid in uid_set}
def condstore_changed_flags(self, modseq):
data = self.conn.fetch('1:*', ['FLAGS', 'X-GM-LABELS'],
modifiers=['CHANGEDSINCE {}'.format(modseq)])
results = {}
for uid, ret in data.items():
if 'FLAGS' not in ret or 'X-GM-LABELS' not in ret:
# We might have gotten an unsolicited fetch response that
# doesn't have all the data we asked for -- if so, explicitly
# fetch flags and labels for that UID.
log.info('Got incomplete response in flags fetch', uid=uid,
ret=str(ret))
data_for_uid = self.conn.fetch(uid, ['FLAGS', 'X-GM-LABELS'])
if not data_for_uid:
continue
ret = data_for_uid[uid]
results[uid] = GmailFlags(ret['FLAGS'], ret['X-GM-LABELS'])
return results
def g_msgids(self, uids):
"""
X-GM-MSGIDs for the given UIDs.
Returns
-------
dict
Mapping of `uid` (long) : `g_msgid` (long)
"""
data = self.conn.fetch(uids, ['X-GM-MSGID'])
uid_set = set(uids)
return {uid: ret['X-GM-MSGID']
for uid, ret in data.items() if uid in uid_set}
def folder_names(self, force_resync=False):
"""
Return the folder names ( == label names for Gmail) for the account
as a mapping from recognized role: list of folder names in the
role, for example: 'sent': ['Sent Items', 'Sent'].
The list of recognized categories is in:
inbox/models/constants.py
Folders that do not belong to a recognized role are mapped to None, for
example: None: ['MyFolder', 'OtherFolder'].
The mapping is also cached in self._folder_names
Parameters:
-----------
force_resync: boolean
Return the cached mapping or return a refreshed mapping
(after refetching from the remote).
"""
if force_resync or self._folder_names is None:
self._folder_names = defaultdict(list)
raw_folders = self.folders()
for f in raw_folders:
self._folder_names[f.role].append(f.display_name)
return self._folder_names
def folders(self):
"""
Fetch the list of folders for the account from the remote, return as a
list of RawFolder objects.
NOTE:
Always fetches the list of folders from the remote.
"""
raw_folders = []
folders = self._fetch_folder_list()
for flags, delimiter, name in folders:
if u'\\Noselect' in flags or u'\\NoSelect' in flags \
or u'\\NonExistent' in flags:
# Special folders that can't contain messages, usually
# just '[Gmail]'
continue
raw_folder = self._process_folder(name, flags)
raw_folders.append(raw_folder)
return raw_folders
def _process_folder(self, display_name, flags):
"""
Determine the canonical_name for the remote folder from its `name` and
`flags`.
Returns
-------
RawFolder representing the folder
"""
flag_map = {'\\Drafts': 'drafts', '\\Important': 'important',
'\\Sent': 'sent', '\\Junk': 'spam', '\\Flagged': 'starred',
'\\Trash': 'trash'}
role = None
if '\\All' in flags:
role = 'all'
elif display_name.lower() == 'inbox':
# Special-case the display name here. In Gmail, the inbox
# folder shows up in the folder list as 'INBOX', and in sync as
# the label '\\Inbox'. We're just always going to give it the
# display name 'Inbox'.
role = 'inbox'
display_name = 'Inbox'
else:
for flag in flags:
if flag in flag_map:
role = flag_map[flag]
return RawFolder(display_name=display_name, role=role)
def uids(self, uids):
raw_messages = self.conn.fetch(uids, ['BODY.PEEK[]', 'INTERNALDATE',
'FLAGS', 'X-GM-THRID',
'X-GM-MSGID', 'X-GM-LABELS'])
messages = []
uid_set = set(uids)
for uid in sorted(raw_messages.iterkeys(), key=long):
# Skip handling unsolicited FETCH responses
if uid not in uid_set:
continue
msg = raw_messages[uid]
messages.append(RawMessage(uid=long(uid),
internaldate=msg['INTERNALDATE'],
flags=msg['FLAGS'],
body=msg['BODY[]'],
g_thrid=long(msg['X-GM-THRID']),
g_msgid=long(msg['X-GM-MSGID']),
g_labels=msg['X-GM-LABELS']))
return messages
def g_metadata(self, uids):
"""
Download Gmail MSGIDs, THRIDs, and message sizes for the given uids.
Parameters
----------
uids : list
UIDs to fetch data for. Must be from the selected folder.
Returns
-------
dict
uid: GMetadata(msgid, thrid, size)
"""
# Super long sets of uids may fail with BAD ['Could not parse command']
# In that case, just fetch metadata for /all/ uids.
seqset = uids if len(uids) < 1e6 else '1:*'
data = self.conn.fetch(seqset, ['X-GM-MSGID', 'X-GM-THRID',
'RFC822.SIZE'])
uid_set = set(uids)
return {uid: GMetadata(ret['X-GM-MSGID'], ret['X-GM-THRID'],
ret['RFC822.SIZE'])
for uid, ret in data.items() if uid in uid_set}
def expand_thread(self, g_thrid):
"""
Find all message UIDs in the selected folder with X-GM-THRID equal to
g_thrid.
Returns
-------
list
"""
uids = [long(uid) for uid in
self.conn.search('X-GM-THRID {}'.format(g_thrid))]
# UIDs ascend over time; return in order most-recent first
return sorted(uids, reverse=True)
def find_by_header(self, header_name, header_value):
criteria = ['HEADER {} {}'.format(header_name, header_value)]
return self.conn.search(criteria)
| gale320/sync-engine | inbox/crispin.py | Python | agpl-3.0 | 34,132 |
class TripPurpose < ApplicationRecord
acts_as_paranoid # soft delete
has_paper_trail
validates :name, presence: true, uniqueness: { :case_sensitive => false, conditions: -> { where(deleted_at: nil) } }
def self.by_provider(provider)
hidden_ids = HiddenLookupTableValue.hidden_ids self.table_name, provider.try(:id)
where.not(id: hidden_ids)
end
def as_api_json
{
name: name,
code: id
}
end
end
| camsys/ridepilot | app/models/trip_purpose.rb | Ruby | agpl-3.0 | 441 |
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
//
// Copyright (C) 2006-2022 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
using System;
using System.Xml;
using System.Collections.Generic;
using Kaltura.Enums;
using Kaltura.Request;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Kaltura.Types
{
public class AccessControlContextTypeHolder : ContextTypeHolder
{
#region Constants
#endregion
#region Private Fields
#endregion
#region Properties
#endregion
#region CTor
public AccessControlContextTypeHolder()
{
}
public AccessControlContextTypeHolder(JToken node) : base(node)
{
}
#endregion
#region Methods
public override Params ToParams(bool includeObjectType = true)
{
Params kparams = base.ToParams(includeObjectType);
if (includeObjectType)
kparams.AddReplace("objectType", "KalturaAccessControlContextTypeHolder");
return kparams;
}
protected override string getPropertyName(string apiName)
{
switch(apiName)
{
default:
return base.getPropertyName(apiName);
}
}
#endregion
}
}
| kaltura/KalturaGeneratedAPIClientsCsharp | KalturaClient/Types/AccessControlContextTypeHolder.cs | C# | agpl-3.0 | 2,292 |
define(function (require) {
'use strict';
var Vector2 = require('vector2-node');
/**
* Returns a new unit vector in the direction specified by the angle
*/
Vector2.fromAngle = function(angle) {
return new Vector2(1, 0).rotate(angle);
};
Vector2.prototype.toString = function(precision) {
if (precision === undefined)
precision = 4;
return '(' + this.x.toFixed(precision) + ', ' + this.y.toFixed(precision) + ')';
};
/**
* Rounds each component to the nearest integer.
*/
Vector2.prototype.round = function() {
this.x = Math.round(this.x);
this.y = Math.round(this.y);
return this;
};
return Vector2;
}); | Connexions/simulations | common/math/vector2.js | JavaScript | agpl-3.0 | 731 |
<?php
//
require('../config.php');
require('../db_lib.php');
$db = new db();
// If the user clicked one of the buttons
if ((isset($_GET['submit'])) || (isset($_GET['prev'])) || (isset($_GET['next']))) {
$where = '';
$start_date = htmlspecialchars($_GET['start_date'], ENT_QUOTES);
if ($start_date != '0000-00-00') {
$where .= ' AND dms.created_at >= "' . $db->date($start_date) . '"';
}
$end_date = htmlspecialchars($_GET['end_date'], ENT_QUOTES);
if ($end_date != '0000-00-00') {
$where .= ' AND dms.created_at <= "' . $db->date($end_date) . '"';
}
$query = htmlspecialchars($_GET['query'], ENT_QUOTES);
if ($query != '') {
$query_words = explode(' ',$query);
foreach($query_words as $word) {
$word = trim($word);
$where .= " AND dms.dm_text LIKE '%$word%' ";
}
}
if(isset($_GET['prev'])) {
$page = intval($_GET['page']) - 1;
if($page<0) {
$page=0;
}
} elseif ($_GET['next']) {
$page = intval($_GET['page']) + 1;
} else {
$page = 0;
}
} else {
$start_date = '0000-00-00';
$end_date = '0000-00-00';
$query = '';
$page = 0;
}
require('page_top.html');
print '<h2>Search DMs</h2>';
// Display the form with empty fields
// or the values entered before Run button was clicked
print "<form action='search_dms.php' method='get'>";
print "Start Date: <input type='text' name='start_date' value='$start_date'>";
print "End Date: <input type='text' name='end_date' value='$end_date'><br/>";
print "Search Terms: <input type='text' name='query' value='$query' size='50'>";
print "<input type='hidden' name='page' value=$page>";
print '<button type="submit" name="submit" value=1>Search</button>';
print '<button type="submit" name="prev" value=1>< Prev</button>';
print '<button type="submit" name="next" value=1>Next ></button>';
print '</form>';
if (!empty($where)) {
require('../get_all_dms.php');
$dms = get_all_dms($where,$page*$results_per_page, $results_per_page);
require('display_dms.php');
}
require('page_bottom.html');
?> | rolencea/org.civicrm.civisocial2 | twitterAPI/civisocialtwitter/report/search_dms.php | PHP | agpl-3.0 | 2,051 |
const ERR = require('async-stacktrace');
const _ = require('lodash');
const async = require('async');
const sqldb = require('../prairielib/lib/sql-db');
module.exports = {
pages(chosenPage, count, pageSize) {
let lastPage = Math.ceil(count / pageSize);
if (lastPage === 0) lastPage = 1;
let currPage = Number(chosenPage);
if (!_.isInteger(currPage)) currPage = 1;
let prevPage = currPage - 1;
let nextPage = currPage + 1;
currPage = Math.max(1, Math.min(lastPage, currPage));
prevPage = Math.max(1, Math.min(lastPage, prevPage));
nextPage = Math.max(1, Math.min(lastPage, nextPage));
return { currPage, prevPage, nextPage, lastPage };
},
/**
* Utility function to facilitate extremely large queries whose results
* cannot fit in memory all at once. The given query must accept an "offset"
* param that will be used to paginate the query. The "receiveRow" callback
* will be called once for each row in the result set. The "done" callback
* is called either if an error has occurred or when all rows have been
* delivered.
*/
paginateQuery(sql, params, receiveRow, done) {
const _params = Object.assign({}, params);
let offset = 0;
async.doWhilst(
(callback) => {
_params.offset = offset;
sqldb.query(sql, _params, (err, result) => {
if (ERR(err, callback)) return;
async.eachSeries(result.rows, receiveRow, (err) => {
if (ERR(err, callback)) return;
offset += result.rows.length;
callback(null, result.rows.length);
});
});
},
(count, callback) => {
callback(null, count > 0);
},
(err) => {
if (ERR(err, done)) return;
done(null);
}
);
},
};
| PrairieLearn/PrairieLearn | lib/paginate.js | JavaScript | agpl-3.0 | 1,786 |
# -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
from openerp import fields, models
class Tag(models.Model):
_inherit = 'myo.tag'
pharmacy_ids = fields.Many2many(
'myo.pharmacy',
'myo_pharmacy_tag_rel',
'tag_id',
'pharmacy_id',
'Pharmacies'
)
class Pharmacy(models.Model):
_inherit = 'myo.pharmacy'
tag_ids = fields.Many2many(
'myo.tag',
'myo_pharmacy_tag_rel',
'pharmacy_id',
'tag_id',
'Tags'
)
| MostlyOpen/odoo_addons | myo_pharmacy/models/tag.py | Python | agpl-3.0 | 1,365 |
<?php
namespace Plenty\Modules\ItemSet\Models;
/**
* The ItemSetConfig model.
*/
abstract class ItemSetConfig
{
const CREATED_AT = 'createdAt';
const UPDATED_AT = 'updatedAt';
public $setId;
public $rebate;
/**
* Returns this model as an array.
*/
public function toArray(
):array
{
return [];
}
} | plentymarkets/plugin-hack-api | Modules/ItemSet/Models/ItemSetConfig.php | PHP | agpl-3.0 | 326 |
<?php
# AST_LISTS_stats.php
#
# Copyright (C) 2014 Matt Florell <vicidial@gmail.com> LICENSE: AGPLv2
#
# This is a list inventory report, not a calling report. This report will show
# statistics for all of the lists in the selected campaigns
#
# CHANGES
# 130926-0721 - First build based upon LISTS campaign report
# 130927-2154 - Added summary and full download options
# 140108-0714 - Added webserver and hostname to report logging
# 140328-0005 - Converted division calculations to use MathZDC function
#
$startMS = microtime();
header ("Content-type: text/html; charset=utf-8");
require("dbconnect_mysqli.php");
require("functions.php");
$PHP_AUTH_USER=$_SERVER['PHP_AUTH_USER'];
$PHP_AUTH_PW=$_SERVER['PHP_AUTH_PW'];
$PHP_SELF=$_SERVER['PHP_SELF'];
if (isset($_GET["group"])) {$group=$_GET["group"];}
elseif (isset($_POST["group"])) {$group=$_POST["group"];}
if (isset($_GET["list"])) {$list=$_GET["list"];}
elseif (isset($_POST["list"])) {$list=$_POST["list"];}
if (isset($_GET["DB"])) {$DB=$_GET["DB"];}
elseif (isset($_POST["DB"])) {$DB=$_POST["DB"];}
if (isset($_GET["submit"])) {$submit=$_GET["submit"];}
elseif (isset($_POST["submit"])) {$submit=$_POST["submit"];}
if (isset($_GET["SUBMIT"])) {$SUBMIT=$_GET["SUBMIT"];}
elseif (isset($_POST["SUBMIT"])) {$SUBMIT=$_POST["SUBMIT"];}
if (isset($_GET["file_download"])) {$file_download=$_GET["file_download"];}
elseif (isset($_POST["file_download"])) {$file_download=$_POST["file_download"];}
if (isset($_GET["report_display_type"])) {$report_display_type=$_GET["report_display_type"];}
elseif (isset($_POST["report_display_type"])) {$report_display_type=$_POST["report_display_type"];}
if (isset($_GET["campaigns_or_lists_rpt"])) {$campaigns_or_lists_rpt=$_GET["campaigns_or_lists_rpt"];}
elseif (isset($_POST["campaigns_or_lists_rpt"])) {$campaigns_or_lists_rpt=$_POST["campaigns_or_lists_rpt"];}
$report_name = 'Lists Statuses Report';
$db_source = 'M';
$JS_text="<script language='Javascript'>\n";
$JS_onload="onload = function() {\n";
#############################################
##### START SYSTEM_SETTINGS LOOKUP #####
$stmt = "SELECT use_non_latin,outbound_autodial_active,slave_db_server,reports_use_slave_db FROM system_settings;";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$qm_conf_ct = mysqli_num_rows($rslt);
if ($qm_conf_ct > 0)
{
$row=mysqli_fetch_row($rslt);
$non_latin = $row[0];
$outbound_autodial_active = $row[1];
$slave_db_server = $row[2];
$reports_use_slave_db = $row[3];
}
##### END SETTINGS LOOKUP #####
###########################################
if ($non_latin < 1)
{
$PHP_AUTH_USER = preg_replace('/[^-_0-9a-zA-Z]/', '', $PHP_AUTH_USER);
$PHP_AUTH_PW = preg_replace('/[^-_0-9a-zA-Z]/', '', $PHP_AUTH_PW);
}
else
{
$PHP_AUTH_PW = preg_replace("/'|\"|\\\\|;/","",$PHP_AUTH_PW);
$PHP_AUTH_USER = preg_replace("/'|\"|\\\\|;/","",$PHP_AUTH_USER);
}
$auth=0;
$reports_auth=0;
$admin_auth=0;
$auth_message = user_authorization($PHP_AUTH_USER,$PHP_AUTH_PW,'REPORTS',1);
if ($auth_message == 'GOOD')
{$auth=1;}
if ($auth > 0)
{
$stmt="SELECT count(*) from vicidial_users where user='$PHP_AUTH_USER' and user_level > 7 and view_reports > 0;";
if ($DB) {echo "|$stmt|\n";}
$rslt=mysql_to_mysqli($stmt, $link);
$row=mysqli_fetch_row($rslt);
$admin_auth=$row[0];
$stmt="SELECT count(*) from vicidial_users where user='$PHP_AUTH_USER' and user_level > 6 and view_reports > 0;";
if ($DB) {echo "|$stmt|\n";}
$rslt=mysql_to_mysqli($stmt, $link);
$row=mysqli_fetch_row($rslt);
$reports_auth=$row[0];
if ($reports_auth < 1)
{
$VDdisplayMESSAGE = "You are not allowed to view reports";
Header ("Content-type: text/html; charset=utf-8");
echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$auth_message|\n";
exit;
}
if ( ($reports_auth > 0) and ($admin_auth < 1) )
{
$ADD=999999;
$reports_only_user=1;
}
}
else
{
$VDdisplayMESSAGE = "Login incorrect, please try again";
if ($auth_message == 'LOCK')
{
$VDdisplayMESSAGE = "Too many login attempts, try again in 15 minutes";
Header ("Content-type: text/html; charset=utf-8");
echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$auth_message|\n";
exit;
}
Header("WWW-Authenticate: Basic realm=\"CONTACT-CENTER-ADMIN\"");
Header("HTTP/1.0 401 Unauthorized");
echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$PHP_AUTH_PW|$auth_message|\n";
exit;
}
##### BEGIN log visit to the vicidial_report_log table #####
$LOGip = getenv("REMOTE_ADDR");
$LOGbrowser = getenv("HTTP_USER_AGENT");
$LOGscript_name = getenv("SCRIPT_NAME");
$LOGserver_name = getenv("SERVER_NAME");
$LOGserver_port = getenv("SERVER_PORT");
$LOGrequest_uri = getenv("REQUEST_URI");
$LOGhttp_referer = getenv("HTTP_REFERER");
if (preg_match("/443/i",$LOGserver_port)) {$HTTPprotocol = 'https://';}
else {$HTTPprotocol = 'http://';}
if (($LOGserver_port == '80') or ($LOGserver_port == '443') ) {$LOGserver_port='';}
else {$LOGserver_port = ":$LOGserver_port";}
$LOGfull_url = "$HTTPprotocol$LOGserver_name$LOGserver_port$LOGrequest_uri";
$LOGhostname = php_uname('n');
if (strlen($LOGhostname)<1) {$LOGhostname='X';}
if (strlen($LOGserver_name)<1) {$LOGserver_name='X';}
$stmt="SELECT webserver_id FROM vicidial_webservers where webserver='$LOGserver_name' and hostname='$LOGhostname' LIMIT 1;";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {echo "$stmt\n";}
$webserver_id_ct = mysqli_num_rows($rslt);
if ($webserver_id_ct > 0)
{
$row=mysqli_fetch_row($rslt);
$webserver_id = $row[0];
}
else
{
##### insert webserver entry
$stmt="INSERT INTO vicidial_webservers (webserver,hostname) values('$LOGserver_name','$LOGhostname');";
if ($DB) {echo "$stmt\n";}
$rslt=mysql_to_mysqli($stmt, $link);
$affected_rows = mysqli_affected_rows($link);
$webserver_id = mysqli_insert_id($link);
}
$stmt="INSERT INTO vicidial_report_log set event_date=NOW(), user='$PHP_AUTH_USER', ip_address='$LOGip', report_name='$report_name', browser='$LOGbrowser', referer='$LOGhttp_referer', notes='$LOGserver_name:$LOGserver_port $LOGscript_name |$group[0], $query_date, $end_date, $shift, $file_download, $report_display_type|', url='$LOGfull_url', webserver='$webserver_id';";
if ($DB) {echo "|$stmt|\n";}
$rslt=mysql_to_mysqli($stmt, $link);
$report_log_id = mysqli_insert_id($link);
##### END log visit to the vicidial_report_log table #####
if ( (strlen($slave_db_server)>5) and (preg_match("/$report_name/",$reports_use_slave_db)) )
{
mysqli_close($link);
$use_slave_server=1;
$db_source = 'S';
require("dbconnect.php");
$MAIN.="<!-- Using slave server $slave_db_server $db_source -->\n";
}
$stmt="SELECT user_group from vicidial_users where user='$PHP_AUTH_USER';";
if ($DB) {$MAIN.="|$stmt|\n";}
$rslt=mysql_to_mysqli($stmt, $link);
$row=mysqli_fetch_row($rslt);
$LOGuser_group = $row[0];
$stmt="SELECT allowed_campaigns,allowed_reports from vicidial_user_groups where user_group='$LOGuser_group';";
if ($DB) {$MAIN.="|$stmt|\n";}
$rslt=mysql_to_mysqli($stmt, $link);
$row=mysqli_fetch_row($rslt);
$LOGallowed_campaigns = $row[0];
$LOGallowed_reports = $row[1];
if ( (!preg_match("/$report_name/",$LOGallowed_reports)) and (!preg_match("/ALL REPORTS/",$LOGallowed_reports)) )
{
Header("WWW-Authenticate: Basic realm=\"CONTACT-CENTER-ADMIN\"");
Header("HTTP/1.0 401 Unauthorized");
echo "You are not allowed to view this report: |$PHP_AUTH_USER|$report_name|\n";
exit;
}
$NOW_DATE = date("Y-m-d");
$NOW_TIME = date("Y-m-d H:i:s");
$STARTtime = date("U");
$LOGallowed_campaignsSQL='';
$whereLOGallowed_campaignsSQL='';
if ( (!preg_match('/\-ALL/i', $LOGallowed_campaigns)) )
{
$rawLOGallowed_campaignsSQL = preg_replace("/ -/",'',$LOGallowed_campaigns);
$rawLOGallowed_campaignsSQL = preg_replace("/ /","','",$rawLOGallowed_campaignsSQL);
$LOGallowed_campaignsSQL = "and campaign_id IN('$rawLOGallowed_campaignsSQL')";
$whereLOGallowed_campaignsSQL = "where campaign_id IN('$rawLOGallowed_campaignsSQL')";
}
$regexLOGallowed_campaigns = " $LOGallowed_campaigns ";
###########
if (!isset($list)) {$list = '';}
$i=0;
$list_string='|';
$list_ct = count($list);
while($i < $list_ct)
{
$list_string .= "$list[$i]|";
$i++;
}
$stmt="select list_id, list_name, campaign_id from vicidial_lists $whereLOGallowed_campaignsSQL order by list_id;";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$lists_to_print = mysqli_num_rows($rslt);
$i=0;
while ($i < $lists_to_print)
{
$row=mysqli_fetch_row($rslt);
$lists[$i] = $row[0];
$list_names[$i] = $row[1];
$list_campaigns[$i] = $row[2];
if (preg_match('/\-ALL/',$list_string) )
{$list[$i] = $lists[$i];}
$i++;
}
$i=0;
$list_string='|';
$list_ct = count($list);
while($i < $list_ct)
{
$list_string .= "$list[$i]|";
$list_SQL .= "'$list[$i]',";
$listQS .= "&list[]=$list[$i]";
$i++;
}
$list_id_str=substr($list_SQL,0,-1);
$group_SQL = "$LOGallowed_campaignsSQL";
$group_SQLand = "$LOGallowed_campaignsSQL";
#######################
# Get lists to query to avoid using a nested query
$lists_id_str="";
$list_stmt="SELECT list_id from vicidial_lists where active IN('Y','N') $group_SQLand";
$list_rslt=mysql_to_mysqli($list_stmt, $link);
while ($lrow=mysqli_fetch_row($list_rslt)) {
$lists_id_str.="'$lrow[0]',";
}
$lists_id_str=substr($lists_id_str,0,-1);
$stmt="select vsc_id,vsc_name from vicidial_status_categories;";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {echo "$stmt\n";}
$statcats_to_print = mysqli_num_rows($rslt);
$i=0;
while ($i < $statcats_to_print)
{
$row=mysqli_fetch_row($rslt);
$vsc_id[$i] = $row[0];
$vsc_name[$i] = $row[1];
$category_statuses="";
$status_stmt="select distinct status from vicidial_statuses where category='$row[0]' UNION select distinct status from vicidial_campaign_statuses where category='$row[0]' $group_SQLand";
if ($DB) {echo "$status_stmt\n";}
$status_rslt=mysql_to_mysqli($status_stmt, $link);
while ($status_row=mysqli_fetch_row($status_rslt))
{
$category_statuses.="'$status_row[0]',";
}
$category_statuses=substr($category_statuses, 0, -1);
$category_stmt="select count(*) from vicidial_list where status in ($category_statuses) and list_id IN($lists_id_str)";
if ($DB) {echo "$category_stmt\n";}
$category_rslt=mysql_to_mysqli($category_stmt, $link);
$category_row=mysqli_fetch_row($category_rslt);
$vsc_count[$i] = $category_row[0];
$i++;
}
### BEGIN gather all statuses that are in status flags ###
$human_answered_statuses='';
$sale_statuses='';
$dnc_statuses='';
$customer_contact_statuses='';
$not_interested_statuses='';
$unworkable_statuses='';
$stmt="select status,human_answered,sale,dnc,customer_contact,not_interested,unworkable,scheduled_callback,completed,status_name from vicidial_statuses;";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$statha_to_print = mysqli_num_rows($rslt);
$i=0;
while ($i < $statha_to_print)
{
$row=mysqli_fetch_row($rslt);
$temp_status = $row[0];
$statname_list["$temp_status"] = "$row[9]";
if ($row[1]=='Y') {$human_answered_statuses .= "'$temp_status',";}
if ($row[2]=='Y') {$sale_statuses .= "'$temp_status',";}
if ($row[3]=='Y') {$dnc_statuses .= "'$temp_status',";}
if ($row[4]=='Y') {$customer_contact_statuses .= "'$temp_status',";}
if ($row[5]=='Y') {$not_interested_statuses .= "'$temp_status',";}
if ($row[6]=='Y') {$unworkable_statuses .= "'$temp_status',";}
if ($row[7]=='Y') {$scheduled_callback_statuses .= "'$temp_status',";}
if ($row[8]=='Y') {$completed_statuses .= "'$temp_status',";}
$i++;
}
$stmt="select status,human_answered,sale,dnc,customer_contact,not_interested,unworkable,scheduled_callback,completed,status_name from vicidial_campaign_statuses where selectable IN('Y','N') $group_SQLand;";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$statha_to_print = mysqli_num_rows($rslt);
$i=0;
while ($i < $statha_to_print)
{
$row=mysqli_fetch_row($rslt);
$temp_status = $row[0];
$statname_list["$temp_status"] = "$row[9]";
if ( ($row[1]=='Y') and (!preg_match("/'$temp_status'/",$human_answered_statuses)) ) {$human_answered_statuses .= "'$temp_status',";}
if ($row[2]=='Y') {$sale_statuses .= "'$temp_status',";}
if ($row[3]=='Y') {$dnc_statuses .= "'$temp_status',";}
if ($row[4]=='Y') {$customer_contact_statuses .= "'$temp_status',";}
if ($row[5]=='Y') {$not_interested_statuses .= "'$temp_status',";}
if ($row[6]=='Y') {$unworkable_statuses .= "'$temp_status',";}
if ($row[7]=='Y') {$scheduled_callback_statuses .= "'$temp_status',";}
if ($row[8]=='Y') {$completed_statuses .= "'$temp_status',";}
$i++;
}
if (strlen($human_answered_statuses)>2) {$human_answered_statuses = substr("$human_answered_statuses", 0, -1);}
else {$human_answered_statuses="''";}
if (strlen($sale_statuses)>2) {$sale_statuses = substr("$sale_statuses", 0, -1);}
else {$sale_statuses="''";}
if (strlen($dnc_statuses)>2) {$dnc_statuses = substr("$dnc_statuses", 0, -1);}
else {$dnc_statuses="''";}
if (strlen($customer_contact_statuses)>2) {$customer_contact_statuses = substr("$customer_contact_statuses", 0, -1);}
else {$customer_contact_statuses="''";}
if (strlen($not_interested_statuses)>2) {$not_interested_statuses = substr("$not_interested_statuses", 0, -1);}
else {$not_interested_statuses="''";}
if (strlen($unworkable_statuses)>2) {$unworkable_statuses = substr("$unworkable_statuses", 0, -1);}
else {$unworkable_statuses="''";}
if (strlen($scheduled_callback_statuses)>2) {$scheduled_callback_statuses = substr("$scheduled_callback_statuses", 0, -1);}
else {$scheduled_callback_statuses="''";}
if (strlen($completed_statuses)>2) {$completed_statuses = substr("$completed_statuses", 0, -1);}
else {$completed_statuses="''";}
$HEADER.="<HTML>\n";
$HEADER.="<HEAD>\n";
$HEADER.="<STYLE type=\"text/css\">\n";
$HEADER.="<!--\n";
$HEADER.=" .green {color: white; background-color: green}\n";
$HEADER.=" .red {color: white; background-color: red}\n";
$HEADER.=" .blue {color: white; background-color: blue}\n";
$HEADER.=" .purple {color: white; background-color: purple}\n";
$HEADER.="-->\n";
$HEADER.=" </STYLE>\n";
$HEADER.="<link rel=\"stylesheet\" href=\"horizontalbargraph.css\">\n";
$HEADER.="<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=utf-8\">\n";
$HEADER.="<TITLE>$report_name</TITLE></HEAD><BODY BGCOLOR=WHITE marginheight=0 marginwidth=0 leftmargin=0 topmargin=0>\n";
$short_header=1;
$MAIN.="<TABLE CELLPADDING=4 CELLSPACING=0><TR><TD>";
$MAIN.="<FORM ACTION=\"$PHP_SELF\" METHOD=GET name=vicidial_report id=vicidial_report>\n";
$MAIN.="<TABLE CELLSPACING=3><TR><TD VALIGN=TOP>";
$MAIN.="<INPUT TYPE=HIDDEN NAME=DB VALUE=\"$DB\">\n";
$MAIN.="</TD>";
$MAIN.="<TD VALIGN=TOP> Lists:<BR>";
$MAIN.="<SELECT SIZE=5 NAME=list[] multiple>\n";
if (preg_match('/\-\-ALL\-\-/',$list_string))
{$MAIN.="<option value=\"--ALL--\" selected>-- ALL LISTS --</option>\n";}
else
{$MAIN.="<option value=\"--ALL--\">-- ALL LISTS --</option>\n";}
$o=0;
while ($lists_to_print > $o)
{
if (preg_match("/$lists[$o]\|/i",$list_string)) {$MAIN.="<option selected value=\"$lists[$o]\">$lists[$o] - $list_names[$o]</option>\n";}
else {$MAIN.="<option value=\"$lists[$o]\">$lists[$o] - $list_names[$o]</option>\n";}
$o++;
}
$MAIN.="</SELECT><BR><a href=\"AST_LISTS_campaign_stats.php?DB=$DB\">SWITCH TO CAMPAIGNS</a>\n";
$MAIN.="</TD>";
$MAIN.="<TD VALIGN=TOP>";
#$MAIN.="Display as:<BR/>";
#$MAIN.="<select name='report_display_type'>";
#if ($report_display_type) {$MAIN.="<option value='$report_display_type' selected>$report_display_type</option>";}
#$MAIN.="<option value='TEXT'>TEXT</option><option value='HTML'>HTML</option></select> ";
$MAIN.="<BR><BR><BR>\n";
$MAIN.="<INPUT type=submit NAME=SUBMIT VALUE=SUBMIT>\n";
$MAIN.="</TD><TD VALIGN=TOP> ";
$MAIN.="<FONT FACE=\"ARIAL,HELVETICA\" COLOR=BLACK SIZE=2>";
if (strlen($group[0]) > 1)
{
$MAIN.=" <a href=\"./admin.php?ADD=34&campaign_id=$group[0]\">MODIFY</a> | \n";
$MAIN.=" <a href=\"./admin.php?ADD=999999\">REPORTS</a> </FONT>\n";
}
else
{
$MAIN.=" <a href=\"./admin.php?ADD=10\">CAMPAIGNS</a> | \n";
$MAIN.=" <a href=\"./admin.php?ADD=999999\">REPORTS</a> </FONT>\n";
}
$MAIN.="</TD></TR></TABLE>";
$MAIN.="</FORM>\n\n";
$MAIN.="<PRE><FONT SIZE=2>\n\n";
if (strlen($list[0]) < 1)
{
$MAIN.="\n\n";
$MAIN.="PLEASE SELECT A LIST OR LISTS ABOVE AND CLICK SUBMIT\n";
}
else
{
$totalOUToutput = '';
$totalOUToutput .= "List Status Stats $NOW_TIME <a href=\"$PHP_SELF?DB=$DB$listQS&SUBMIT=$SUBMIT&file_download=ALL\">DOWNLOAD FULL REPORT</a>\n";
$totalOUToutput .= "\n";
$list_stmt="select vicidial_list.list_id,list_name,active, count(*) from vicidial_list, vicidial_lists where vicidial_lists.list_id in ($list_id_str) and vicidial_lists.list_id=vicidial_list.list_id group by vicidial_list.list_id, list_name, active order by list_id, list_name asc;";
$list_rslt=mysql_to_mysqli($list_stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$listids_to_print = mysqli_num_rows($list_rslt);
$CSV_text1="\"\",\"LIST ID SUMMARY\"\n";
$CSV_text1.="\"LIST ID\",\"LIST NAME\",\"TOTAL LEADS\",\"ACTIVE/INACTIVE\"\n";
$CSV_text2="";
$CSV_text3="";
$CSV_textALL="";
$i=0;
$totalOUToutput .= "---------- TOTAL LIST ID SUMMARY <a href=\"$PHP_SELF?DB=$DB$listQS&SUBMIT=$SUBMIT&file_download=ALL\">DOWNLOAD FULL REPORT</a>\n";
$totalOUToutput .= "+------------------------------------------+------------+----------+\n";
$totalOUToutput .= "| LIST | LEADS | ACTIVE |\n";
$totalOUToutput .= "+------------------------------------------+------------+----------+\n";
$CSV_textSUMMARY.="\"LIST ID SUMMARY\"\n";
$CSV_textSUMMARY.="\"LIST\",\"LEADS\",\"ACTIVE\"\n";
$OUToutput='';
$OUToutput .= "\n";
$OUToutput .= "---------- INDIVIDUAL LIST ID SUMMARIES\n";
while ($i < $listids_to_print)
{
$list_row=mysqli_fetch_row($list_rslt);
$LISTIDlists[$i] = $list_row[0];
$LISTIDlist_names[$i] = $list_row[1];
if ($list_row[2]=="Y") {$active_txt="ACTIVE";} else {$active_txt="INACTIVE";}
$active_txt=sprintf("%-8s", $active_txt);
$LISTIDcalls[$i] = $list_row[3];
$TOTALleads =$list_row[3];
$totalTOTALleads+=$TOTALleads;
$LISTIDcount = sprintf("%10s", $LISTIDcalls[$i]);while(strlen($LISTIDcount)>10) {$LISTIDcount = substr("$LISTIDcount", 0, -1);}
$LISTIDname = sprintf("%-40s", "$LISTIDlists[$i] - $LISTIDlist_names[$i]");while(strlen($LISTIDname)>40) {$LISTIDname = substr("$LISTIDname", 0, -1);}
$totalOUToutput .= "| $LISTIDname | $LISTIDcount | $active_txt |\n";
$CSV_textSUMMARY.="\"$LISTIDname\",\"$LISTIDcount\",\"$active_txt\"\n";
$OUToutput .= "\n";
$OUToutput .= "---------- LIST ID SUMMARY <a href=\"$PHP_SELF?DB=$DB$listQS&SUBMIT=$SUBMIT&file_download=1\">DOWNLOAD LIST SUMMARIES</a>\n";
$OUToutput .= "+--------------------------------------------------------+\n";
$OUToutput .= "| LIST ID: ".sprintf("%-30s", $list_row[0])." ".sprintf("%-8s", $active_txt)." |\n";
$OUToutput .= "| LIST NAME: ".sprintf("%-30s", $list_row[1])." ".sprintf("%8s", "")." |\n";
$OUToutput .= "| TOTAL LEADS: ".sprintf("%-30s", $list_row[3])." ".sprintf("%8s", "")." |\n";
$OUToutput .= "+--------------------------------------------------------+\n";
$CSV_text1.="\"$list_row[0]\",\"$list_row[1]\",\"$list_row[3]\",\"$active_txt\"\n";
$CSV_textALL.="\"LIST ID #$list_row[0] SUMMARY\",\"\"\n";
$CSV_textALL.="\"LIST NAME\",\"TOTAL LEADS\",\"ACTIVE/INACTIVE\"\n";
$CSV_textALL.="\"$list_row[1]\",\"$list_row[3]\",\"$active_txt\"\n";
# $list_id_SQL .= "'$row[0]',";
# if ($row[0]>$max_calls) {$max_calls=$row[3];}
$i++;
$list_id=$list_row[0];
##############################
######### STATUS FLAGS STATS
$HA_count=0;
$HA_percent=0;
$SALE_count=0;
$SALE_percent=0;
$DNC_count=0;
$DNC_percent=0;
$CC_count=0;
$CC_percent=0;
$NI_count=0;
$NI_percent=0;
$UW_count=0;
$UW_percent=0;
$SC_count=0;
$SC_percent=0;
$COMP_count=0;
$COMP_percent=0;
$stmt="select count(*) from vicidial_list where status IN($human_answered_statuses) and list_id='$list_id';";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$HA_results = mysqli_num_rows($rslt);
if ($HA_results > 0)
{
$row=mysqli_fetch_row($rslt);
$HA_count = $row[0];
$flag_count+=$row[0];
$category_totals["HA"]+=$HA_count;
if ($HA_count>$max_calls) {$max_calls=$HA_count;}
$HA_percent = ( MathZDC($HA_count, $TOTALleads) * 100);
}
$stmt="select count(*) from vicidial_list where status IN($sale_statuses) and list_id='$list_id';";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$SALE_results = mysqli_num_rows($rslt);
if ($SALE_results > 0)
{
$row=mysqli_fetch_row($rslt);
$SALE_count = $row[0];
$flag_count+=$row[0];
$category_totals["SALE"]+=$SALE_count;
if ($SALE_count>$max_calls) {$max_calls=$SALE_count;}
$SALE_percent = ( MathZDC($SALE_count, $TOTALleads) * 100);
}
$stmt="select count(*) from vicidial_list where status IN($dnc_statuses) and list_id='$list_id';";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$DNC_results = mysqli_num_rows($rslt);
if ($DNC_results > 0)
{
$row=mysqli_fetch_row($rslt);
$DNC_count = $row[0];
$flag_count+=$row[0];
$category_totals["DNC"]+=$DNC_count;
if ($DNC_count>$max_calls) {$max_calls=$DNC_count;}
$DNC_percent = ( MathZDC($DNC_count, $TOTALleads) * 100);
}
$stmt="select count(*) from vicidial_list where status IN($customer_contact_statuses) and list_id='$list_id';";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$CC_results = mysqli_num_rows($rslt);
if ($CC_results > 0)
{
$row=mysqli_fetch_row($rslt);
$CC_count = $row[0];
$flag_count+=$row[0];
$category_totals["CC"]+=$CC_count;
if ($C_count>$max_calls) {$max_calls=$CC_count;}
$CC_percent = ( MathZDC($CC_count, $TOTALleads) * 100);
}
$stmt="select count(*) from vicidial_list where status IN($not_interested_statuses) and list_id='$list_id';";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$NI_results = mysqli_num_rows($rslt);
if ($NI_results > 0)
{
$row=mysqli_fetch_row($rslt);
$NI_count = $row[0];
$flag_count+=$row[0];
$category_totals["NI"]+=$NI_count;
if ($NI_count>$max_calls) {$max_calls=$NI_count;}
$NI_percent = ( MathZDC($NI_count, $TOTALleads) * 100);
}
$stmt="select count(*) from vicidial_list where status IN($unworkable_statuses) and list_id='$list_id';";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$UW_results = mysqli_num_rows($rslt);
if ($UW_results > 0)
{
$row=mysqli_fetch_row($rslt);
$UW_count = $row[0];
$flag_count+=$row[0];
$category_totals["UW"]+=$UW_count;
if ($UW_count>$max_calls) {$max_calls=$UW_count;}
$UW_percent = ( MathZDC($UW_count, $TOTALleads) * 100);
}
$stmt="select count(*) from vicidial_list where status IN($scheduled_callback_statuses) and list_id='$list_id';";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$SC_results = mysqli_num_rows($rslt);
if ($SC_results > 0)
{
$row=mysqli_fetch_row($rslt);
$SC_count = $row[0];
$flag_count+=$row[0];
$category_totals["SC"]+=$SC_count;
if ($SC_count>$max_calls) {$max_calls=$SC_count;}
$SC_percent = ( MathZDC($SC_count, $TOTALleads) * 100);
}
$stmt="select count(*) from vicidial_list where status IN($completed_statuses) and list_id='$list_id';";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$COMP_results = mysqli_num_rows($rslt);
if ($COMP_results > 0)
{
$row=mysqli_fetch_row($rslt);
$COMP_count = $row[0];
$flag_count+=$row[0];
$category_totals["COMP"]+=$COMP_count;
if ($COMP_count>$max_calls) {$max_calls=$COMP_count;}
$COMP_percent = ( MathZDC($COMP_count, $TOTALleads) * 100);
}
$HA_percent = sprintf("%6.2f", "$HA_percent"); while(strlen($HA_percent)>6) {$HA_percent = substr("$HA_percent", 0, -1);}
$SALE_percent = sprintf("%6.2f", "$SALE_percent"); while(strlen($SALE_percent)>6) {$SALE_percent = substr("$SALE_percent", 0, -1);}
$DNC_percent = sprintf("%6.2f", "$DNC_percent"); while(strlen($DNC_percent)>6) {$DNC_percent = substr("$DNC_percent", 0, -1);}
$CC_percent = sprintf("%6.2f", "$CC_percent"); while(strlen($CC_percent)>6) {$CC_percent = substr("$CC_percent", 0, -1);}
$NI_percent = sprintf("%6.2f", "$NI_percent"); while(strlen($NI_percent)>6) {$NI_percent = substr("$NI_percent", 0, -1);}
$UW_percent = sprintf("%6.2f", "$UW_percent"); while(strlen($UW_percent)>6) {$UW_percent = substr("$UW_percent", 0, -1);}
$SC_percent = sprintf("%6.2f", "$SC_percent"); while(strlen($SC_percent)>6) {$SC_percent = substr("$SC_percent", 0, -1);}
$COMP_percent = sprintf("%6.2f", "$COMP_percent"); while(strlen($COMP_percent)>6) {$COMP_percent = substr("$COMP_percent", 0, -1);}
$HA_count = sprintf("%10s", "$HA_count"); while(strlen($HA_count)>10) {$HA_count = substr("$HA_count", 0, -1);}
$SALE_count = sprintf("%10s", "$SALE_count"); while(strlen($SALE_count)>10) {$SALE_count = substr("$SALE_count", 0, -1);}
$DNC_count = sprintf("%10s", "$DNC_count"); while(strlen($DNC_count)>10) {$DNC_count = substr("$DNC_count", 0, -1);}
$CC_count = sprintf("%10s", "$CC_count"); while(strlen($CC_count)>10) {$CC_count = substr("$CC_count", 0, -1);}
$NI_count = sprintf("%10s", "$NI_count"); while(strlen($NI_count)>10) {$NI_count = substr("$NI_count", 0, -1);}
$UW_count = sprintf("%10s", "$UW_count"); while(strlen($UW_count)>10) {$UW_count = substr("$UW_count", 0, -1);}
$SC_count = sprintf("%10s", "$SC_count"); while(strlen($SC_count)>10) {$SC_count = substr("$SC_count", 0, -1);}
$COMP_count = sprintf("%10s", "$COMP_count"); while(strlen($COMP_count)>10) {$COMP_count = substr("$COMP_count", 0, -1);}
$OUToutput .= "\n";
$OUToutput .= "---------- STATUS FLAGS BREAKDOWN: (and % of total leads in list) <a href=\"$PHP_SELF?DB=$DB$listQS&SUBMIT=$SUBMIT&file_download=2\">DOWNLOAD FLAG BREAKDOWNS</a>\n";
$OUToutput .= "+------------------+------------+----------+\n";
$OUToutput .= "| Human Answer | $HA_count | $HA_percent% |\n";
$OUToutput .= "| Sale | $SALE_count | $SALE_percent% |\n";
$OUToutput .= "| DNC | $DNC_count | $DNC_percent% |\n";
$OUToutput .= "| Customer Contact | $CC_count | $CC_percent% |\n";
$OUToutput .= "| Not Interested | $NI_count | $NI_percent% |\n";
$OUToutput .= "| Unworkable | $UW_count | $UW_percent% |\n";
$OUToutput .= "| Sched Callbacks | $SC_count | $SC_percent% |\n";
$OUToutput .= "| Completed | $COMP_count | $COMP_percent% |\n";
$OUToutput .= "+------------------+------------+----------+\n";
$OUToutput .= "\n";
$CSV_text_block = "\"STATUS FLAGS SUMMARY FOR LIST ID #$list_id:\"\n";
$CSV_text_block .= "\"Human Answer\",\"$HA_count\",\"$HA_percent%\"\n";
$CSV_text_block .= "\"Sale\",\"$SALE_count\",\"$SALE_percent%\"\n";
$CSV_text_block .= "\"DNC\",\"$DNC_count\",\"$DNC_percent%\"\n";
$CSV_text_block .= "\"Customer Contact\",\"$CC_count\",\"$CC_percent%\"\n";
$CSV_text_block .= "\"Not Interested\",\"$NI_count\",\"$NI_percent%\"\n";
$CSV_text_block .= "\"Unworkable\",\"$UW_count\",\"$UW_percent%\"\n";
$CSV_text_block .= "\"Scheduled Callbacks\",\"$SC_count\",\"$SC_percent%\"\n";
$CSV_text_block .= "\"Completed\",\"$COMP_count\",\"$COMP_percent%\"\n\n";
$CSV_text2.=$CSV_text_block;
$CSV_textALL.="\n".$CSV_text_block;
$stmt="select status, count(*) From vicidial_list where list_id='$list_id' group by status order by status asc";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$OUToutput .= "---------- STATUS BREAKDOWN: (and % of total leads in list) <a href=\"$PHP_SELF?DB=$DB$listQS&SUBMIT=$SUBMIT&file_download=3\">DOWNLOAD STAT BREAKDOWNS</a>\n";
$OUToutput .= "+--------+--------------------------------+----------+---------+\n";
$OUToutput .= "| STATUS | STATUS NAME | COUNT | LEAD % |\n";
$OUToutput .= "+--------+--------------------------------+----------+---------+\n";
$CSV_text3.="\"\",\"STATUS BREAKDOWN FOR LIST ID #$list_id:\"\n";
$CSV_text3.="\"STATUS\",\"STATUS NAME\",\"COUNT\",\"LEAD %\"\n";
$CSV_textALL.="\"STATUS BREAKDOWN FOR LIST ID #$list_id:\",\"\"\n";
$CSV_textALL.="\"STATUS\",\"STATUS NAME\",\"COUNT\",\"LEAD %\"\n";
while ($row=mysqli_fetch_row($rslt))
{
$OUToutput .= "| ".sprintf("%6s", $row[0])." | ".sprintf("%30s", $statname_list["$row[0]"])." | ".sprintf("%8s", $row[1])." | ".sprintf("%6.2f", ( MathZDC($row[1], $TOTALleads) * 100))."% |\n";
$CSV_text3.="\"$row[0]\",\"".$statname_list["$row[0]"]."\",\"$row[1]\",\"".sprintf("%6.2f", ( MathZDC($row[1], $TOTALleads) * 100))."%\"\n";
$CSV_textALL.="\"$row[0]\",\"".$statname_list["$row[0]"]."\",\"$row[1]\",\"".sprintf("%6.2f", ( MathZDC($row[1], $TOTALleads) * 100))."%\"\n";
}
$OUToutput .= "+-----------------------------------------+----------+---------+\n";
$OUToutput .= "| | ".sprintf("%8s", $TOTALleads)." | 100.00% |\n";
$OUToutput .= "+-----------------------------------------+----------+---------+\n";
$CSV_text3.="\"\",\"\",\"$TOTALleads\",\"100.00%\"\n\n\n";
$CSV_textALL.="\"\",\"\",\"$TOTALleads\",\"100.00%\"\n\n\n";
$OUToutput .= "\n";
$OUToutput .= "\n";
$OUToutput .= "\n";
}
$total_HA_percent = sprintf("%6.2f", ( MathZDC($category_totals["HA"], $totalTOTALleads) * 100)); while(strlen($total_HA_percent)>6) {$total_HA_percent = substr("$total_HA_percent", 0, -1);}
$total_SALE_percent = sprintf("%6.2f", ( MathZDC($category_totals["SALE"], $totalTOTALleads) * 100)); while(strlen($total_SALE_percent)>6) {$total_SALE_percent = substr("$total_SALE_percent", 0, -1);}
$total_DNC_percent = sprintf("%6.2f", ( MathZDC($category_totals["DNC"], $totalTOTALleads) * 100)); while(strlen($total_DNC_percent)>6) {$total_DNC_percent = substr("$total_DNC_percent", 0, -1);}
$total_CC_percent = sprintf("%6.2f", ( MathZDC($category_totals["CC"], $totalTOTALleads) * 100)); while(strlen($total_CC_percent)>6) {$total_CC_percent = substr("$total_CC_percent", 0, -1);}
$total_NI_percent = sprintf("%6.2f", ( MathZDC($category_totals["NI"], $totalTOTALleads) * 100)); while(strlen($total_NI_percent)>6) {$total_NI_percent = substr("$total_NI_percent", 0, -1);}
$total_UW_percent = sprintf("%6.2f", ( MathZDC($category_totals["UW"], $totalTOTALleads) * 100)); while(strlen($total_UW_percent)>6) {$total_UW_percent = substr("$total_UW_percent", 0, -1);}
$total_SC_percent = sprintf("%6.2f", ( MathZDC($category_totals["SC"], $totalTOTALleads) * 100)); while(strlen($total_SC_percent)>6) {$total_SC_percent = substr("$total_SC_percent", 0, -1);}
$total_COMP_percent = sprintf("%6.2f", ( MathZDC($category_totals["COMP"], $totalTOTALleads) * 100)); while(strlen($total_COMP_percent)>6) {$total_COMP_percent = substr("$total_COMP_percent", 0, -1);}
$total_HA_count = sprintf("%10s", $category_totals["HA"]); while(strlen($total_HA_count)>10) {$total_HA_count = substr("$total_HA_count", 0, -1);}
$total_SALE_count = sprintf("%10s", $category_totals["SALE"]); while(strlen($total_SALE_count)>10) {$total_SALE_count = substr("$total_SALE_count", 0, -1);}
$total_DNC_count = sprintf("%10s", $category_totals["DNC"]); while(strlen($total_DNC_count)>10) {$total_DNC_count = substr("$total_DNC_count", 0, -1);}
$total_CC_count = sprintf("%10s", $category_totals["CC"]); while(strlen($total_CC_count)>10) {$total_CC_count = substr("$total_CC_count", 0, -1);}
$total_NI_count = sprintf("%10s", $category_totals["NI"]); while(strlen($total_NI_count)>10) {$total_NI_count = substr("$total_NI_count", 0, -1);}
$total_UW_count = sprintf("%10s", $category_totals["UW"]); while(strlen($total_UW_count)>10) {$total_UW_count = substr("$total_UW_count", 0, -1);}
$total_SC_count = sprintf("%10s", $category_totals["SC"]); while(strlen($total_SC_count)>10) {$total_SC_count = substr("$total_SC_count", 0, -1);}
$total_COMP_count = sprintf("%10s", $category_totals["COMP"]); while(strlen($total_COMP_count)>10) {$total_COMP_count = substr("$total_COMP_count", 0, -1);}
$totalOUToutput .= "+------------------------------------------+------------+----------+\n";
$totalOUToutput .= "| TOTAL | ".sprintf("%10s", $totalTOTALleads)." |\n";
$totalOUToutput .= "+------------------------------------------+------------+\n";
$CSV_textSUMMARY .= "\"TOTAL\",\"$totalTOTALleads\"\n";
$totalOUToutput .= "\n";
$totalOUToutput .= "\n";
$totalOUToutput .= "---------- TOTAL STATUS FLAGS SUMMARY: (and % of leads in selected lists) <a href=\"$PHP_SELF?DB=$DB$listQS&SUBMIT=$SUBMIT&file_download=ALL\">DOWNLOAD FULL REPORT</a>\n";
$totalOUToutput .= "+------------------+------------+----------+\n";
$totalOUToutput .= "| Human Answer | $total_HA_count | $total_HA_percent% |\n";
$totalOUToutput .= "| Sale | $total_SALE_count | $total_SALE_percent% |\n";
$totalOUToutput .= "| DNC | $total_DNC_count | $total_DNC_percent% |\n";
$totalOUToutput .= "| Customer Contact | $total_CC_count | $total_CC_percent% |\n";
$totalOUToutput .= "| Not Interested | $total_NI_count | $total_NI_percent% |\n";
$totalOUToutput .= "| Unworkable | $total_UW_count | $total_UW_percent% |\n";
$totalOUToutput .= "| Sched Callbacks | $total_SC_count | $total_SC_percent% |\n";
$totalOUToutput .= "| Completed | $total_COMP_count | $total_COMP_percent% |\n";
$totalOUToutput .= "+------------------+------------+----------+\n";
$totalOUToutput .= "\n\n\n";
$CSV_textSUMMARY .= "\n\"STATUS FLAGS SUMMARY:\"\n";
$CSV_textSUMMARY .= "\"Human Answer\",\"$total_HA_count\",\"$total_HA_percent%\"\n";
$CSV_textSUMMARY .= "\"Sale\",\"$total_SALE_count\",\"$total_SALE_percent%\"\n";
$CSV_textSUMMARY .= "\"DNC\",\"$total_DNC_count\",\"$total_DNC_percent%\"\n";
$CSV_textSUMMARY .= "\"Customer Contact\",\"$total_CC_count\",\"$total_CC_percent%\"\n";
$CSV_textSUMMARY .= "\"Not Interested\",\"$total_NI_count\",\"$total_NI_percent%\"\n";
$CSV_textSUMMARY .= "\"Unworkable\",\"$total_UW_count\",\"$total_UW_percent%\"\n";
$CSV_textSUMMARY .= "\"Scheduled Callbacks\",\"$total_SC_count\",\"$total_SC_percent%\"\n";
$CSV_textSUMMARY .= "\"Completed\",\"$total_COMP_count\",\"$total_COMP_percent%\"\n\n\n\n";
$CSV_textALL=$CSV_textSUMMARY.$CSV_textALL;
if ($report_display_type=="HTML")
{
$MAIN.=$GRAPH;
}
else
{
$MAIN.="$totalOUToutput$OUToutput";
}
$ENDtime = date("U");
$RUNtime = ($ENDtime - $STARTtime);
$MAIN.="\nRun Time: $RUNtime seconds|$db_source\n";
$MAIN.="</PRE>\n";
$MAIN.="</TD></TR></TABLE>\n";
$MAIN.="</BODY></HTML>\n";
}
if ($file_download>0 || $file_download=="ALL") {
$FILE_TIME = date("Ymd-His");
$CSVfilename = "AST_LISTS_stats_$US$FILE_TIME.csv";
$CSV_var="CSV_text".$file_download;
$CSV_text=preg_replace('/^ +/', '', $$CSV_var);
$CSV_text=preg_replace('/\n +,/', ',', $CSV_text);
$CSV_text=preg_replace('/ +\"/', '"', $CSV_text);
$CSV_text=preg_replace('/\" +/', '"', $CSV_text);
// We'll be outputting a TXT file
header('Content-type: application/octet-stream');
// It will be called LIST_101_20090209-121212.txt
header("Content-Disposition: attachment; filename=\"$CSVfilename\"");
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
ob_clean();
flush();
echo "$CSV_text";
} else {
$JS_onload.="}\n";
$JS_text.=$JS_onload;
$JS_text.="</script>\n";
echo $HEADER;
echo $JS_text;
require("admin_header.php");
echo $MAIN;
}
if ($db_source == 'S')
{
mysqli_close($link);
$use_slave_server=0;
$db_source = 'M';
require("dbconnect.php");
}
$endMS = microtime();
$startMSary = explode(" ",$startMS);
$endMSary = explode(" ",$endMS);
$runS = ($endMSary[0] - $startMSary[0]);
$runM = ($endMSary[1] - $startMSary[1]);
$TOTALrun = ($runS + $runM);
$stmt="UPDATE vicidial_report_log set run_time='$TOTALrun' where report_log_id='$report_log_id';";
if ($DB) {echo "|$stmt|\n";}
$rslt=mysql_to_mysqli($stmt, $link);
exit;
?>
| patrickcmartins/goautodialtraduzido | vicidial/AST_LISTS_stats.php | PHP | agpl-3.0 | 37,059 |
package org.cbioportal.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.cbioportal.model.AlterationCountByGene;
import org.cbioportal.model.AlterationEnrichment;
import org.cbioportal.model.CopyNumberCountByGene;
import org.cbioportal.model.MolecularProfileCaseIdentifier;
import org.cbioportal.service.CopyNumberEnrichmentService;
import org.cbioportal.service.DiscreteCopyNumberService;
import org.cbioportal.service.exception.MolecularProfileNotFoundException;
import org.cbioportal.service.util.AlterationEnrichmentUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CopyNumberEnrichmentServiceImpl implements CopyNumberEnrichmentService {
@Autowired
private DiscreteCopyNumberService discreteCopyNumberService;
@Autowired
private AlterationEnrichmentUtil alterationEnrichmentUtil;
@Override
public List<AlterationEnrichment> getCopyNumberEnrichments(
Map<String, List<MolecularProfileCaseIdentifier>> molecularProfileCaseSets,
List<Integer> alterationTypes,
String enrichmentType) throws MolecularProfileNotFoundException {
Map<String, List<? extends AlterationCountByGene>> copyNumberCountByGeneAndGroup = new HashMap<>();
if (enrichmentType.equals("SAMPLE")) {
copyNumberCountByGeneAndGroup = molecularProfileCaseSets
.entrySet()
.stream()
.collect(Collectors.toMap(
entry -> entry.getKey(),
entry -> { //set value of each group to list of CopyNumberCountByGene
List<String> molecularProfileIds = new ArrayList<>();
List<String> sampleIds = new ArrayList<>();
entry.getValue().forEach(molecularProfileCase -> {
molecularProfileIds.add(molecularProfileCase.getMolecularProfileId());
sampleIds.add(molecularProfileCase.getCaseId());
});
return discreteCopyNumberService
.getSampleCountInMultipleMolecularProfiles(
molecularProfileIds,
sampleIds,
null,
alterationTypes,
false);
}));
} else {
copyNumberCountByGeneAndGroup = molecularProfileCaseSets.entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey(),
entry -> { //set value of each group to list of CopyNumberCountByGene
Map<String, List<MolecularProfileCaseIdentifier>> molecularProfileCaseIdentifiersMap = entry
.getValue().stream()
.collect(Collectors.groupingBy(MolecularProfileCaseIdentifier::getMolecularProfileId));
return molecularProfileCaseIdentifiersMap
.entrySet()
.stream()
.flatMap(molecularProfileCaseIdentifiers -> {
String molecularProfileId = molecularProfileCaseIdentifiers.getKey();
List<String> caseIds = molecularProfileCaseIdentifiers
.getValue()
.stream()
.map(MolecularProfileCaseIdentifier::getCaseId)
.collect(Collectors.toList());
return discreteCopyNumberService
.getPatientCountByGeneAndAlterationAndPatientIds(
molecularProfileId,
caseIds,
null,
alterationTypes)
.stream();
})
.collect(Collectors.toList());
}));
}
return alterationEnrichmentUtil
.createAlterationEnrichments(
copyNumberCountByGeneAndGroup,
molecularProfileCaseSets,
enrichmentType);
}
}
| d3b-center/pedcbioportal | service/src/main/java/org/cbioportal/service/impl/CopyNumberEnrichmentServiceImpl.java | Java | agpl-3.0 | 5,177 |
# encoding: utf-8
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import logging
import os.path
import sys
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
from ckan.lib.plugins import DefaultTranslation
from . import get_config
log = logging.getLogger(__name__)
class DiscoveryPlugin(plugins.SingletonPlugin, DefaultTranslation):
plugins.implements(plugins.ITemplateHelpers)
plugins.implements(plugins.ITranslation)
#
# ITemplateHelpers
#
def get_helpers(self):
return {
'discovery_get_config': get_config,
'discovery_as_bool': toolkit.asbool,
}
#
# ITranslation
#
def i18n_directory(self):
module = sys.modules['ckanext.discovery']
module_dir = os.path.abspath(os.path.dirname(module.__file__))
return os.path.join(module_dir, 'i18n')
def i18n_domain(self):
return 'ckanext-discovery'
| stadt-karlsruhe/ckanext-discovery | ckanext/discovery/plugins/discovery.py | Python | agpl-3.0 | 999 |
# - coding: utf-8 -*-
##############################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import models
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| odoo-arg/odoo_l10n_ar | l10n_ar/wizard/__init__.py | Python | agpl-3.0 | 951 |
//package com.x.processplatform.assemble.designer.jaxrs.projection;
//
//import com.x.base.core.container.EntityManagerContainer;
//import com.x.base.core.container.factory.EntityManagerContainerFactory;
//import com.x.base.core.project.exception.ExceptionAccessDenied;
//import com.x.base.core.project.exception.ExceptionEntityNotExist;
//import com.x.base.core.project.http.ActionResult;
//import com.x.base.core.project.http.EffectivePerson;
//import com.x.base.core.project.jaxrs.WrapBoolean;
//import com.x.processplatform.assemble.designer.Business;
//import com.x.processplatform.core.entity.element.Application;
//import com.x.processplatform.core.entity.element.Projection;
//
//class ActionEnable extends BaseAction {
//
// ActionResult<Wo> execute(EffectivePerson effectivePerson, String flag) throws Exception {
// try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
// ActionResult<Wo> result = new ActionResult<>();
//
// Business business = new Business(emc);
//
// Projection projection = emc.flag(flag, Projection.class);
//
// if (null == projection) {
// throw new ExceptionEntityNotExist(flag, Projection.class);
// }
//
// Application application = emc.flag(projection.getApplication(), Application.class);
//
// if (null == application) {
// throw new ExceptionEntityNotExist(projection.getApplication(), Application.class);
// }
//
// if (!business.editable(effectivePerson, application)) {
// throw new ExceptionAccessDenied(effectivePerson.getDistinguishedName());
// }
//
// emc.beginTransaction(Projection.class);
// projection.setEnable(true);
// emc.commit();
// Wo wo = new Wo();
// wo.setValue(true);
// result.setData(wo);
// return result;
// }
// }
//
// public static class Wo extends WrapBoolean {
//
// }
//
//} | o2oa/o2oa | o2server/x_processplatform_assemble_designer/src/main/java/com/x/processplatform/assemble/designer/jaxrs/projection/ActionEnable.java | Java | agpl-3.0 | 1,828 |
define("imcms-templates-tab-builder",
[
"imcms-bem-builder", "imcms-components-builder", "imcms-templates-rest-api", "imcms-document-types",
"imcms-i18n-texts", "imcms-page-info-tab"
],
function (BEM, components, templatesRestApi, docTypes, texts, PageInfoTab) {
texts = texts.pageInfo.appearance;
const tabData = {};
const TemplatesTab = function (name, docType) {
PageInfoTab.apply(this, arguments);
};
TemplatesTab.prototype = Object.create(PageInfoTab.prototype);
TemplatesTab.prototype.tabElementsFactory = () => {
const $templateSelectContainer = components.selects.selectContainer("<div>", {
name: "template",
text: texts.template
}),
$templateSelect = $templateSelectContainer.getSelect(),
$defaultChildTemplateSelectContainer = components.selects.selectContainer("<div>", {
name: "childTemplate",
text: texts.defaultChildTemplate
}),
$defaultChildTemplateSelect = $defaultChildTemplateSelectContainer.getSelect();
tabData.$templateSelect = $templateSelect;
tabData.$defaultChildTemplateSelect = $defaultChildTemplateSelect;
templatesRestApi.read(null)
.done(templates => {
const templatesDataMapped = templates.map(template => ({
text: template.name,
"data-value": template.name
}));
components.selects.addOptionsToSelect(templatesDataMapped, $templateSelect);
components.selects.addOptionsToSelect(templatesDataMapped, $defaultChildTemplateSelect);
});
return [
$templateSelectContainer,
$defaultChildTemplateSelectContainer
];
};
TemplatesTab.prototype.fillTabDataFromDocument = document => {
if (document.template) {
tabData.$templateSelect.selectValue(document.template.templateName);
tabData.$defaultChildTemplateSelect.selectValue(document.template.childrenTemplateName);
}
};
TemplatesTab.prototype.saveData = function (documentDTO) {
if (!this.isDocumentTypeSupported(documentDTO.type)) {
return documentDTO;
}
documentDTO.template.templateName = tabData.$templateSelect.getSelectedValue();
documentDTO.template.childrenTemplateName = tabData.$defaultChildTemplateSelect.getSelectedValue();
return documentDTO;
};
TemplatesTab.prototype.clearTabData = () => {
tabData.$templateSelect.selectFirst();
tabData.$defaultChildTemplateSelect.selectFirst();
};
return new TemplatesTab(texts.name, docTypes.TEXT);
}
);
| imCodePartnerAB/imcms | src/main/webapp/imcms/js/builders/components/page_info_tabs/imcms-templates-tab-builder.js | JavaScript | agpl-3.0 | 2,976 |
# encoding: utf-8
# Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and open public transport:
# a non ending quest to the responsive locomotion way of traveling!
#
# LICENCE: 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/>.
#
# Stay tuned using
# twitter @navitia
# IRC #navitia on freenode
# https://groups.google.com/d/forum/navitia
# www.navitia.io
from __future__ import absolute_import, print_function, unicode_literals, division
from six.moves.urllib.parse import quote, quote_plus
from .check_utils import journey_basic_query
from .tests_mechanism import dataset, AbstractTestFixture
from .check_utils import *
from six.moves import range
@dataset({"main_ptref_test": {}})
class TestPtRef(AbstractTestFixture):
"""
Test the structure of the ptref response
"""
@staticmethod
def _test_links(response, pt_obj_name):
# Test the validity of links of 'previous', 'next', 'last', 'first'
wanted_links_type = ['previous', 'next', 'last', 'first']
for l in response['links']:
if l['type'] in wanted_links_type:
assert pt_obj_name in l['href']
# Test the consistency between links
wanted_links = [l['href'] for l in response['links'] if l['type'] in wanted_links_type]
if len(wanted_links) <= 1:
return
def _get_dict_to_compare(link):
url_dict = query_from_str(link)
url_dict.pop('start_page', None)
url_dict['url'] = link.split('?')[0]
return url_dict
url_dict = _get_dict_to_compare(wanted_links[0])
for l in wanted_links[1:]:
assert url_dict == _get_dict_to_compare(l)
def test_pagination_links_with_count(self):
response = self.query_region("stop_points?count=2&start_page=2", display=True)
for link in response['links']:
if link['type'] in ('previous', 'next', 'first', 'last'):
assert 'count=2' in link['href']
def test_vj_default_depth(self):
"""default depth is 1"""
response = self.query_region("vehicle_journeys")
vjs = get_not_null(response, 'vehicle_journeys')
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=1)
assert len(vjs) == 3
vj = vjs[0]
assert vj['id'] == 'vj1'
assert len(vj['stop_times']) == 2
assert vj['stop_times'][0]['arrival_time'] == '101500'
assert vj['stop_times'][0]['departure_time'] == '101500'
assert vj['stop_times'][1]['arrival_time'] == '111000'
assert vj['stop_times'][1]['departure_time'] == '111000'
#we added some comments on the vj, we should have them
com = get_not_null(vj, 'comments')
assert len(com) == 1
assert com[0]['type'] == 'standard'
assert com[0]['value'] == 'hello'
assert "feed_publishers" in response
feed_publishers = response["feed_publishers"]
for feed_publisher in feed_publishers:
is_valid_feed_publisher(feed_publisher)
feed_publisher = feed_publishers[1]
assert (feed_publisher["id"] == "c1")
assert (feed_publisher["name"] == "name-c1")
assert (feed_publisher["license"] == "ls-c1")
assert (feed_publisher["url"] == "ws-c1")
feed_publisher = feed_publishers[0]
assert (feed_publisher["id"] == "builder")
assert (feed_publisher["name"] == "canal tp")
assert (feed_publisher["license"] == "ODBL")
assert (feed_publisher["url"] == "www.canaltp.fr")
def test_vj_depth_0(self):
"""default depth is 1"""
response = self.query_region("vehicle_journeys?depth=0")
vjs = get_not_null(response, 'vehicle_journeys')
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=0)
def test_vj_depth_2(self):
"""default depth is 1"""
response = self.query_region("vehicle_journeys?depth=2")
vjs = get_not_null(response, 'vehicle_journeys')
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=2)
def test_vj_depth_3(self):
"""default depth is 1"""
response = self.query_region("vehicle_journeys?depth=3")
vjs = get_not_null(response, 'vehicle_journeys')
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=3)
def test_vj_show_codes_propagation(self):
"""stop_area:stop1 has a code, we should be able to find it when accessing it by the vj"""
response = self.query_region("stop_areas/stop_area:stop1/vehicle_journeys")
vjs = get_not_null(response, 'vehicle_journeys')
assert vjs
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=1)
stop_points = [get_not_null(st, 'stop_point') for vj in vjs for st in vj['stop_times']]
stops1 = [s for s in stop_points if s['id'] == 'stop_area:stop1']
assert stops1
for stop1 in stops1:
# all reference to stop1 must have it's codes
codes = get_not_null(stop1, 'codes')
code_uic = [c for c in codes if c['type'] == 'code_uic']
assert len(code_uic) == 1 and code_uic[0]['value'] == 'bobette'
def test_ptref_without_current_datetime(self):
"""
stop_area:stop1 without message because _current_datetime is NOW()
"""
response = self.query_region("stop_areas/stop_area:stop1")
assert len(response['disruptions']) == 0
def test_ptref_invalid_type(self):
response, code = self.query_region("AAAAAA/stop_areas", check=False)
assert code == 400
assert response['message'] == 'unknown type: AAAAAA'
coord = "{lon};{lat}".format(lon=1.2, lat=3.4)
response, code = self.query_region("{coord}/stop_areas".format(coord=coord), check=False)
assert code == 400
assert response['message'] == 'unknown type: {coord}'.format(coord=coord)
def test_ptref_with_current_datetime(self):
"""
stop_area:stop1 with _current_datetime
"""
response = self.query_region("stop_areas/stop_area:stop1?_current_datetime=20140115T235959")
disruptions = get_not_null(response, 'disruptions')
assert len(disruptions) == 1
messages = get_not_null(disruptions[0], 'messages')
assert(messages[0]['text']) == 'Disruption on StopArea stop_area:stop1'
def test_contributors(self):
"""test contributor formating"""
response = self.query_region("contributors")
contributors = get_not_null(response, 'contributors')
assert len(contributors) == 1
ctr = contributors[0]
assert(ctr["id"] == 'c1')
assert(ctr["website"] == 'ws-c1')
assert(ctr["license"] == 'ls-c1')
def test_datasets(self):
"""test dataset formating"""
response = self.query_region("datasets")
datasets = get_not_null(response, 'datasets')
assert len(datasets) == 1
ds = datasets[0]
assert(ds["id"] == 'd1')
assert(ds["description"] == 'desc-d1')
assert(ds["system"] == 'sys-d1')
def test_contributor_by_dataset(self):
"""test contributor by dataset formating"""
response = self.query_region("datasets/d1/contributors")
ctrs = get_not_null(response, 'contributors')
assert len(ctrs) == 1
ctr = ctrs[0]
assert(ctr["id"] == 'c1')
assert(ctr["website"] == 'ws-c1')
assert(ctr["license"] == 'ls-c1')
def test_dataset_by_contributor(self):
"""test dataset by contributor formating"""
response = self.query_region("contributors/c1/datasets")
frs = get_not_null(response, 'datasets')
assert len(frs) == 1
fr = frs[0]
assert(fr["id"] == 'd1')
def test_line(self):
"""test line formating"""
response = self.query_region("lines")
lines = get_not_null(response, 'lines')
assert len(lines) == 3
l = lines[0]
is_valid_line(l, depth_check=1)
assert l["text_color"] == 'FFD700'
#we know we have a geojson for this test so we can check it
geo = get_not_null(l, 'geojson')
shape(geo)
com = get_not_null(l, 'comments')
assert len(com) == 1
assert com[0]['type'] == 'standard'
assert com[0]['value'] == "I'm a happy comment"
physical_modes = get_not_null(l, 'physical_modes')
assert len(physical_modes) == 1
is_valid_physical_mode(physical_modes[0], depth_check=1)
assert physical_modes[0]['id'] == 'physical_mode:Car'
assert physical_modes[0]['name'] == 'name physical_mode:Car'
line_group = get_not_null(l, 'line_groups')
assert len(line_group) == 1
is_valid_line_group(line_group[0], depth_check=0)
assert line_group[0]['name'] == 'A group'
assert line_group[0]['id'] == 'group:A'
self._test_links(response, 'lines')
def test_line_without_shape(self):
"""test line formating with shape disabled"""
response = self.query_region("lines?disable_geojson=true")
lines = get_not_null(response, 'lines')
assert len(lines) == 3
l = lines[0]
is_valid_line(l, depth_check=1)
#we don't want a geojson since we have desactivate them
assert 'geojson' not in l
response = self.query_region("lines")
lines = get_not_null(response, 'lines')
assert len(lines) == 3
l = lines[0]
is_valid_line(l, depth_check=1)
#we check our geojson, just to be safe :)
assert 'geojson' in l
geo = get_not_null(l, 'geojson')
shape(geo)
def test_line_with_shape(self):
"""test line formating with shape explicitly enabled"""
response = self.query_region("lines?disable_geojson=false")
lines = get_not_null(response, 'lines')
assert len(lines) == 3
l = lines[0]
is_valid_line(l, depth_check=1)
# Test that the geojson is indeed there
geo = get_not_null(l, 'geojson')
shape(geo)
def test_line_groups(self):
"""test line group formating"""
# Test for each possible range to ensure main_line is always at a depth of 0
for depth in range(0,3):
response = self.query_region("line_groups?depth={0}".format(depth))
line_groups = get_not_null(response, 'line_groups')
assert len(line_groups) == 1
lg = line_groups[0]
is_valid_line_group(lg, depth_check=depth)
if depth > 0:
com = get_not_null(lg, 'comments')
assert len(com) == 1
assert com[0]['type'] == 'standard'
assert com[0]['value'] == "I'm a happy comment"
# test if line_groups are accessible through the ptref graph
response = self.query_region("routes/line:A:0/line_groups")
line_groups = get_not_null(response, 'line_groups')
assert len(line_groups) == 1
lg = line_groups[0]
is_valid_line_group(lg)
def test_line_with_active_disruption(self):
"""test disruption is active"""
response = self.query_region("lines/line:A?_current_datetime=20140115T235959")
disruptions = get_not_null(response, 'disruptions')
assert len(disruptions) == 1
d = disruptions[0]
# in pt_ref, the status is always active as the checked
# period is the validity period
assert d["status"] == "active"
messages = get_not_null(d, 'messages')
assert(messages[0]['text']) == 'Disruption on Line line:A'
def test_line_codes(self):
"""test line formating"""
response = self.query_region("lines/line:A?show_codes=true")
lines = get_not_null(response, 'lines')
assert len(lines) == 1
l = lines[0]
codes = get_not_null(l, 'codes')
assert len(codes) == 4
is_valid_codes(codes)
def test_route(self):
"""test line formating"""
response = self.query_region("routes")
routes = get_not_null(response, 'routes')
assert len(routes) == 3
r = [r for r in routes if r['id'] == 'line:A:0']
assert len(r) == 1
r = r[0]
is_valid_route(r, depth_check=1)
#we know we have a geojson for this test so we can check it
geo = get_not_null(r, 'geojson')
shape(geo)
com = get_not_null(r, 'comments')
assert len(com) == 1
assert com[0]['type'] == 'standard'
assert com[0]['value'] == "I'm a happy comment"
self._test_links(response, 'routes')
def test_stop_areas(self):
"""test stop_areas formating"""
response = self.query_region("stop_areas")
stops = get_not_null(response, 'stop_areas')
assert len(stops) == 3
s = next((s for s in stops if s['name'] == 'stop_area:stop1'))
is_valid_stop_area(s, depth_check=1)
com = get_not_null(s, 'comments')
assert len(com) == 2
assert com[0]['type'] == 'standard'
assert com[0]['value'] == "comment on stop A"
assert com[1]['type'] == 'standard'
assert com[1]['value'] == "the stop is sad"
self._test_links(response, 'stop_areas')
def test_stop_area(self):
"""test stop_areas formating"""
response = self.query_region("stop_areas/stop_area:stop1?depth=2")
stops = get_not_null(response, 'stop_areas')
assert len(stops) == 1
is_valid_stop_area(stops[0], depth_check=2)
modes = get_not_null(stops[0], 'physical_modes')
assert len(modes) == 1
modes = get_not_null(stops[0], 'commercial_modes')
assert len(modes) == 1
def test_stop_points(self):
"""test stop_points formating"""
response = self.query_region("stop_points?depth=2")
stops = get_not_null(response, 'stop_points')
assert len(stops) == 3
s = next((s for s in stops if s['name'] == 'stop_area:stop2'))# yes, that's a stop_point
is_valid_stop_point(s, depth_check=2)
com = get_not_null(s, 'comments')
assert len(com) == 1
assert com[0]['type'] == 'standard'
assert com[0]['value'] == "hello bob"
modes = get_not_null(s, 'physical_modes')
assert len(modes) == 1
is_valid_physical_mode(modes[0], depth_check=1)
modes = get_not_null(s, 'commercial_modes')
assert len(modes) == 1
is_valid_commercial_mode(modes[0], depth_check=1)
self._test_links(response, 'stop_points')
def test_company_default_depth(self):
"""default depth is 1"""
response = self.query_region("companies")
companies = get_not_null(response, 'companies')
for company in companies:
is_valid_company(company, depth_check=1)
#we check afterward that we have the right data
#we know there is only one vj in the dataset
assert len(companies) == 1
company = companies[0]
assert company['id'] == 'CMP1'
self._test_links(response, 'companies')
def test_simple_crow_fly(self):
journey_basic_query = "journeys?from=9;9.001&to=stop_area%3Astop2&datetime=20140105T000000"
response = self.query_region(journey_basic_query)
#the response must be still valid (this test the kraken data reloading)
self.is_valid_journey_response(response, journey_basic_query)
def test_forbidden_uris_on_line(self):
"""test forbidden uri for lines"""
response = self.query_region("lines")
lines = get_not_null(response, 'lines')
assert len(lines) == 3
assert len(lines[0]['physical_modes']) == 1
assert lines[0]['physical_modes'][0]['id'] == 'physical_mode:Car'
#there is only one line, so when we forbid it's physical mode, we find nothing
response, code = self.query_no_assert("v1/coverage/main_ptref_test/lines"
"?forbidden_uris[]=physical_mode:Car")
assert code == 404
# for retrocompatibility purpose forbidden_id[] is the same
response, code = self.query_no_assert("v1/coverage/main_ptref_test/lines"
"?forbidden_id[]=physical_mode:Car")
assert code == 404
# when we forbid another physical_mode, we find again our line
response, code = self.query_no_assert("v1/coverage/main_ptref_test/lines"
"?forbidden_uris[]=physical_mode:Bus")
assert code == 200
def test_simple_pt_objects(self):
response = self.query_region('pt_objects?q=stop2')
is_valid_pt_objects_response(response)
pt_objs = get_not_null(response, 'pt_objects')
assert len(pt_objs) == 1
assert get_not_null(pt_objs[0], 'id') == 'stop_area:stop2'
def test_line_label_pt_objects(self):
response = self.query_region('pt_objects?q=line:A&type[]=line')
is_valid_pt_objects_response(response)
pt_objs = get_not_null(response, 'pt_objects')
assert len(pt_objs) == 1
assert get_not_null(pt_objs[0], 'name') == 'base_network Car line:A'
response = self.query_region('pt_objects?q=line:Ca roule&type[]=line')
pt_objs = get_not_null(response, 'pt_objects')
assert len(pt_objs) == 1
# not valid as there is no commercial mode (which impact name)
assert get_not_null(pt_objs[0], 'name') == 'base_network line:Ça roule'
def test_query_with_strange_char(self):
q = b'stop_points/stop_point:stop_with name bob \" , é'
encoded_q = quote(q)
response = self.query_region(encoded_q)
stops = get_not_null(response, 'stop_points')
assert len(stops) == 1
is_valid_stop_point(stops[0], depth_check=1)
assert stops[0]["id"] == u'stop_point:stop_with name bob \" , é'
def test_filter_query_with_strange_char(self):
"""test that the ptref mechanism works an object with a weird id"""
response = self.query_region('stop_points/stop_point:stop_with name bob \" , é/lines')
lines = get_not_null(response, 'lines')
assert len(lines) == 1
for l in lines:
is_valid_line(l)
def test_filter_query_with_strange_char_in_filter(self):
"""test that the ptref mechanism works an object with a weird id passed in filter args"""
response = self.query_region('lines?filter=stop_point.uri="stop_point:stop_with name bob \\\" , é"')
lines = get_not_null(response, 'lines')
assert len(lines) == 1
for l in lines:
is_valid_line(l)
def test_journey_with_strange_char(self):
#we use an encoded url to be able to check the links
query = 'journeys?from={}&to={}&datetime=20140105T070000'.format(quote_plus(b'stop_with name bob \" , é'), quote_plus(b'stop_area:stop1'))
response = self.query_region(query, display=True)
self.is_valid_journey_response(response, query)
def test_vj_period_filter(self):
"""with just a since in the middle of the period, we find vj1"""
response = self.query_region("vehicle_journeys?since=20140105T070000")
vjs = get_not_null(response, 'vehicle_journeys')
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=1)
assert 'vj1' in (vj['id'] for vj in vjs)
# same with an until at the end of the day
response = self.query_region("vehicle_journeys?since=20140105T000000&until=20140106T0000")
vjs = get_not_null(response, 'vehicle_journeys')
assert 'vj1' in (vj['id'] for vj in vjs)
# there is no vj after the 8
response, code = self.query_no_assert("v1/coverage/main_ptref_test/vehicle_journeys?since=20140109T070000")
assert code == 404
assert get_not_null(response, 'error')['message'] == 'ptref : Filters: Unable to find object'
def test_line_by_code(self):
"""test the filter=type.has_code(key, value)"""
response = self.query_region("lines?filter=line.has_code(codeB, B)&show_codes=true")
lines = get_not_null(response, 'lines')
assert len(lines) == 1
assert 'B' in [code['value'] for code in lines[0]['codes'] if code['type'] == 'codeB']
response = self.query_region("lines?filter=line.has_code(codeB, Bise)&show_codes=true")
lines = get_not_null(response, 'lines')
assert len(lines) == 1
assert 'B' in [code['value'] for code in lines[0]['codes'] if code['type'] == 'codeB']
response = self.query_region("lines?filter=line.has_code(codeC, C)&show_codes=true")
lines = get_not_null(response, 'lines')
assert len(lines) == 1
assert 'B' in [code['value'] for code in lines[0]['codes'] if code['type'] == 'codeB']
response, code = self.query_no_assert("v1/coverage/main_ptref_test/lines?filter=line.has_code(codeB, rien)&show_codes=true")
assert code == 400
assert get_not_null(response, 'error')['message'] == 'ptref : Filters: Unable to find object'
response, code = self.query_no_assert("v1/coverage/main_ptref_test/lines?filter=line.has_code(codeC, rien)&show_codes=true")
assert code == 400
assert get_not_null(response, 'error')['message'] == 'ptref : Filters: Unable to find object'
def test_pt_ref_internal_method(self):
from jormungandr import i_manager
from navitiacommon import type_pb2
i = i_manager.instances['main_ptref_test']
assert len([r for r in i.ptref.get_objs(type_pb2.ROUTE)]) == 3
@dataset({"main_ptref_test": {}, "main_routing_test": {}})
class TestPtRefRoutingAndPtrefCov(AbstractTestFixture):
def test_external_code(self):
"""test the strange and ugly external code api"""
response = self.query("v1/lines?external_code=A&show_codes=true")
lines = get_not_null(response, 'lines')
assert len(lines) == 1
assert 'A' in [code['value'] for code in lines[0]['codes'] if code['type'] == 'external_code']
def test_external_code_no_code(self):
"""the external_code is a mandatory parameter for collection without coverage"""
r, status = self.query_no_assert("v1/lines")
assert status == 400
assert "parameter \"external_code\" invalid: " \
"Missing required parameter in the post body or the query string" \
"\nexternal_code description: An external code to query" == \
r.get('message')
def test_parameter_error_message(self):
"""test the parameter validation error message"""
r, status = self.query_no_assert("v1/coverage/lines?disable_geojson=12")
assert status == 400
assert "parameter \"disable_geojson\" invalid: Invalid literal for boolean(): 12\n" \
"disable_geojson description: hide the coverage geojson to reduce response size" == \
r.get('message')
def test_invalid_url(self):
"""the following bad url was causing internal errors, it should only be a 404"""
_, status = self.query_no_assert("v1/coverage/lines/bob")
assert status == 404
@dataset({"main_routing_test": {}})
class TestPtRefRoutingCov(AbstractTestFixture):
def test_with_coords(self):
"""test with a coord in the pt call, so a place nearby is actually called"""
response = self.query_region("coords/{coord}/stop_areas".format(coord=r_coord))
stops = get_not_null(response, 'stop_areas')
for s in stops:
is_valid_stop_area(s)
#the default is the search for all stops within 200m, so we should have A and C
assert len(stops) == 2
assert set(["stopA", "stopC"]) == set([s['name'] for s in stops])
def test_with_coord(self):
"""some but with coord and not coords"""
response = self.query_region("coord/{coord}/stop_areas".format(coord=r_coord))
stops = get_not_null(response, 'stop_areas')
for s in stops:
is_valid_stop_area(s)
#the default is the search for all stops within 200m, so we should have A and C
assert len(stops) == 2
assert set(["stopA", "stopC"]) == set([s['name'] for s in stops])
def test_with_coord_distance_different(self):
"""same as test_with_coord, but with 300m radius. so we find all stops"""
response = self.query_region("coords/{coord}/stop_areas?distance=300".format(coord=r_coord))
stops = get_not_null(response, 'stop_areas')
for s in stops:
is_valid_stop_area(s)
assert len(stops) == 3
assert set(["stopA", "stopB", "stopC"]) == set([s['name'] for s in stops])
def test_with_coord_and_filter(self):
"""
we now test with a more complex query, we want all stops with a metro within 300m of r
only A and C have a metro line
Note: the metro is physical_mode:0x1
"""
response = self.query_region("physical_modes/physical_mode:0x1/coords/{coord}/stop_areas"
"?distance=300".format(coord=r_coord), display=True)
stops = get_not_null(response, 'stop_areas')
for s in stops:
is_valid_stop_area(s)
#the default is the search for all stops within 200m, so we should have all 3 stops
#we should have 3 stops
assert len(stops) == 2
assert set(["stopA", "stopC"]) == set([s['name'] for s in stops])
def test_all_lines(self):
"""test with all lines in the pt call"""
response = self.query_region('lines')
assert 'error' not in response
lines = get_not_null(response, 'lines')
assert len(lines) == 4
assert {"1A", "1B", "1C", "1D"} == {l['code'] for l in lines}
def test_line_filter_line_code(self):
"""test filtering lines from line code 1A in the pt call"""
response = self.query_region('lines?filter=line.code=1A')
assert 'error' not in response
lines = get_not_null(response, 'lines')
assert len(lines) == 1
assert "1A" == lines[0]['code']
def test_line_filter_line_code_with_resource_uri(self):
"""test filtering lines from line code 1A in the pt call with a resource uri"""
response = self.query_region('physical_modes/physical_mode:0x1/lines?filter=line.code=1D')
assert 'error' not in response
lines = get_not_null(response, 'lines')
assert len(lines) == 1
assert "1D" == lines[0]['code']
def test_line_filter_line_code_empty_response(self):
"""test filtering lines from line code bob in the pt call
as no line has the code "bob" response returns no object"""
url = 'v1/coverage/main_routing_test/lines?filter=line.code=bob'
response, status = self.query_no_assert(url)
assert status == 400
assert 'error' in response
assert 'bad_filter' in response['error']['id']
def test_line_filter_route_code_ignored(self):
"""test filtering lines from route code bob in the pt call
as there is no attribute "code" for route, filter is invalid and ignored"""
response_all_lines = self.query_region('lines')
all_lines = get_not_null(response_all_lines, 'lines')
response = self.query_region('lines?filter=route.code=bob')
assert 'error' not in response
lines = get_not_null(response, 'lines')
assert len(lines) == 4
assert {l['code'] for l in all_lines} == {l['code'] for l in lines}
def test_route_filter_line_code(self):
"""test filtering routes from line code 1B in the pt call"""
response = self.query_region('routes?filter=line.code=1B')
assert 'error' not in response
routes = get_not_null(response, 'routes')
assert len(routes) == 1
assert "1B" == routes[0]['line']['code']
def test_headsign(self):
"""test basic usage of headsign"""
response = self.query_region('vehicle_journeys?headsign=vjA')
assert 'error' not in response
vjs = get_not_null(response, 'vehicle_journeys')
assert len(vjs) == 1
def test_headsign_with_resource_uri(self):
"""test usage of headsign with resource uri"""
response = self.query_region('physical_modes/physical_mode:0x0/vehicle_journeys'
'?headsign=vjA')
assert 'error' not in response
vjs = get_not_null(response, 'vehicle_journeys')
assert len(vjs) == 1
def test_headsign_with_code_filter_and_resource_uri(self):
"""test usage of headsign with code filter and resource uri"""
response = self.query_region('physical_modes/physical_mode:0x0/vehicle_journeys'
'?headsign=vjA&filter=line.code=1A')
assert 'error' not in response
vjs = get_not_null(response, 'vehicle_journeys')
assert len(vjs) == 1
def test_multiple_resource_uri_no_final_collection_uri(self):
"""test usage of multiple resource uris with line and physical mode giving result,
then with multiple resource uris giving no result as nothing matches"""
response = self.query_region('physical_modes/physical_mode:0x0/lines/A')
assert 'error' not in response
lines = get_not_null(response, 'lines')
assert len(lines) == 1
response = self.query_region('lines/D')
assert 'error' not in response
lines = get_not_null(response, 'lines')
assert len(lines) == 1
response = self.query_region('physical_modes/physical_mode:0x1/lines/D')
assert 'error' not in response
lines = get_not_null(response, 'lines')
assert len(lines) == 1
response, status = self.query_region('physical_modes/physical_mode:0x0/lines/D', False)
assert status == 404
assert 'error' in response
assert 'unknown_object' in response['error']['id']
def test_multiple_resource_uri_with_final_collection_uri(self):
"""test usage of multiple resource uris with line and physical mode giving result,
as we match it with a final collection, so the intersection is what we want"""
response = self.query_region('physical_modes/physical_mode:0x1/lines/D/stop_areas')
assert 'error' not in response
stop_areas = get_not_null(response, 'stop_areas')
assert len(stop_areas) == 2
response = self.query_region('physical_modes/physical_mode:0x0/lines/D/stop_areas')
assert 'error' not in response
stop_areas = get_not_null(response, 'stop_areas')
assert len(stop_areas) == 1
def test_headsign_stop_time_vj(self):
"""test basic print of headsign in stop_times for vj"""
response = self.query_region('vehicle_journeys?filter=vehicle_journey.name="vjA"')
assert 'error' not in response
vjs = get_not_null(response, 'vehicle_journeys')
assert len(vjs) == 1
assert len(vjs[0]['stop_times']) == 2
assert vjs[0]['stop_times'][0]['headsign'] == "A00"
assert vjs[0]['stop_times'][1]['headsign'] == "vjA"
def test_headsign_display_info_journeys(self):
"""test basic print of headsign in section for journeys"""
response = self.query_region('journeys?from=stop_point:stopB&to=stop_point:stopA&datetime=20120615T000000&max_duration_to_pt=0')
assert 'error' not in response
journeys = get_not_null(response, 'journeys')
assert len(journeys) == 1
assert len(journeys[0]['sections']) == 1
assert journeys[0]['sections'][0]['display_informations']['headsign'] == "A00"
def test_headsign_display_info_departures(self):
"""test basic print of headsign in display informations for departures"""
response = self.query_region('stop_points/stop_point:stopB/departures?from_datetime=20120615T000000')
assert 'error' not in response
departures = get_not_null(response, 'departures')
assert len(departures) == 2
assert {"A00", "vjB"} == {d['display_informations']['headsign'] for d in departures}
def test_headsign_display_info_arrivals(self):
"""test basic print of headsign in display informations for arrivals"""
response = self.query_region('stop_points/stop_point:stopB/arrivals?from_datetime=20120615T000000')
assert 'error' not in response
arrivals = get_not_null(response, 'arrivals')
assert len(arrivals) == 2
assert arrivals[0]['display_informations']['headsign'] == "vehicle_journey 2"
def test_headsign_display_info_route_schedules(self):
"""test basic print of headsign in display informations for route schedules"""
response = self.query_region('routes/A:0/route_schedules?from_datetime=20120615T000000')
assert 'error' not in response
route_schedules = get_not_null(response, 'route_schedules')
assert len(route_schedules) == 1
assert len(route_schedules[0]['table']['headers']) == 1
display_info = route_schedules[0]['table']['headers'][0]['display_informations']
assert display_info['headsign'] == "vjA"
assert {"A00", "vjA"} == set(display_info['headsigns'])
def test_trip_id_vj(self):
"""test basic print of trip and its id in vehicle_journeys"""
response = self.query_region('vehicle_journeys')
assert 'error' not in response
vjs = get_not_null(response, 'vehicle_journeys')
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=1)
assert any(vj['name'] == "vjB" and vj['trip']['id'] == "vjB" for vj in vjs)
def test_disruptions(self):
"""test the /disruptions api"""
response = self.query_region('disruptions')
disruptions = get_not_null(response, 'disruptions')
assert len(disruptions) == 9
for d in disruptions:
is_valid_disruption(d)
# we test that we can access a specific disruption
response = self.query_region('disruptions/too_bad_line_C')
disruptions = get_not_null(response, 'disruptions')
assert len(disruptions) == 1
# we can also display all disruptions of an object
response = self.query_region('lines/C/disruptions')
disruptions = get_not_null(response, 'disruptions')
assert len(disruptions) == 2
disruptions_uris = set([d['uri'] for d in disruptions])
assert {"too_bad_line_C", "too_bad_all_lines"} == disruptions_uris
# we can't access object from the disruption though (we don't think it to be useful for the moment)
response, status = self.query_region('disruptions/too_bad_line_C/lines', check=False)
assert status == 404
e = get_not_null(response, 'error')
assert e['id'] == 'unknown_object'
assert e['message'] == 'ptref : Filters: Unable to find object'
def test_trips(self):
"""test the /trips api"""
response = self.query_region('trips')
trips = get_not_null(response, 'trips')
assert len(trips) == 5
for t in trips:
is_valid_trip(t)
# we test that we can access a specific trip
response = self.query_region('trips/vjA')
trips = get_not_null(response, 'trips')
assert len(trips) == 1
assert get_not_null(trips[0], 'id') == "vjA"
# we can also display trip of a vj
response = self.query_region('vehicle_journeys/vjB/trips')
trips = get_not_null(response, 'trips')
assert len(trips) == 1
assert get_not_null(trips[0], 'id') == "vjB"
def test_attributs_in_display_info_journeys(self):
"""test some attributs in display_information of a section for journeys"""
response = self.query_region('journeys?from=stop_point:stopB&to=stop_point:stopA&datetime=20120615T000000&max_duration_to_pt=0')
assert 'error' not in response
journeys = get_not_null(response, 'journeys')
assert len(journeys) == 1
assert len(journeys[0]['sections']) == 1
assert journeys[0]['sections'][0]['display_informations']['headsign'] == "A00"
assert journeys[0]['sections'][0]['display_informations']['color'] == "289728"
assert journeys[0]['sections'][0]['display_informations']['text_color'] == "FFD700"
assert journeys[0]['sections'][0]['display_informations']['label'] == "1A"
assert journeys[0]['sections'][0]['display_informations']['code'] == "1A"
assert journeys[0]['sections'][0]['display_informations']['name'] == "A"
def test_stop_points_depth_3(self):
"""
test stop_points formating in depth 3
Note: done in main_routing_test because we need a routing graph to have all the attributes
"""
response = self.query_region("stop_points?depth=3")
for s in get_not_null(response, 'stop_points'):
is_valid_stop_point(s, depth_check=3)
def test_pois_uri_poi_types(self):
response = self.query_region("pois/poi:station_1/poi_types")
assert len(response["poi_types"]) == 1
assert response["poi_types"][0]["id"] == "poi_type:amenity:bicycle_rental"
| antoine-de/navitia | source/jormungandr/tests/ptref_tests.py | Python | agpl-3.0 | 38,313 |
/*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
import { CSS, React } from "smc-webapp/app-framework";
import { FOCUSED_COLOR } from "../util";
import {
SlateElement,
register,
useFocused,
useSelected,
useSlateStatic,
} from "./register";
export interface Hashtag extends SlateElement {
type: "hashtag";
content: string;
}
// Looks like antd tag but scales (and a lot simpler).
const STYLE = {
padding: "0 7px",
color: "#1b95e0",
borderRadius: "5px",
cursor: "pointer",
} as CSS;
register({
slateType: "hashtag",
fromSlate: ({ node }) => `#${node.content}`,
Element: ({ attributes, children, element }) => {
if (element.type != "hashtag") throw Error("bug");
const focused = useFocused();
const selected = useSelected();
const editor = useSlateStatic();
const border =
focused && selected ? `1px solid ${FOCUSED_COLOR}` : "1px solid #d9d9d9";
const backgroundColor = focused && selected ? "#1990ff" : "#fafafa";
const color = focused && selected ? "white" : undefined;
return (
<span {...attributes}>
<span
style={{ ...STYLE, border, backgroundColor, color }}
onClick={() => editor.search.focus("#" + element.content)}
>
#{element.content}
</span>
{children}
</span>
);
},
toSlate: ({ token }) => {
return {
type: "hashtag",
isVoid: true,
isInline: true,
content: token.content,
children: [{ text: " " }],
markup: token.markup,
};
},
});
| sagemathinc/smc | src/smc-webapp/editors/slate/elements/hashtag.tsx | TypeScript | agpl-3.0 | 1,639 |
<?php
App::uses('AppModel', 'Model');
class Galaxy extends AppModel
{
public $useTable = 'galaxies';
public $recursive = -1;
public $actsAs = array(
'Containable',
);
public $validate = array(
);
public $hasMany = array(
'GalaxyCluster' => array('dependent' => true)
);
public function beforeValidate($options = array())
{
parent::beforeValidate();
return true;
}
public function beforeDelete($cascade = true)
{
$this->GalaxyCluster->deleteAll(array('GalaxyCluster.galaxy_id' => $this->id));
}
private function __load_galaxies($force = false)
{
$dir = new Folder(APP . 'files' . DS . 'misp-galaxy' . DS . 'galaxies');
$files = $dir->find('.*\.json');
$galaxies = array();
foreach ($files as $file) {
$file = new File($dir->pwd() . DS . $file);
$galaxies[] = json_decode($file->read(), true);
$file->close();
}
$galaxyTypes = array();
foreach ($galaxies as $galaxy) {
$galaxyTypes[$galaxy['type']] = $galaxy['type'];
}
$temp = $this->find('all', array(
'fields' => array('uuid', 'version', 'id', 'icon'),
'recursive' => -1
));
$existingGalaxies = array();
foreach ($temp as $k => $v) {
$existingGalaxies[$v['Galaxy']['uuid']] = $v['Galaxy'];
}
foreach ($galaxies as $k => $galaxy) {
if (isset($existingGalaxies[$galaxy['uuid']])) {
if (
$force ||
$existingGalaxies[$galaxy['uuid']]['version'] < $galaxy['version'] ||
(!empty($galaxy['icon']) && ($existingGalaxies[$galaxy['uuid']]['icon'] != $galaxy['icon']))
) {
$galaxy['id'] = $existingGalaxies[$galaxy['uuid']]['id'];
$this->save($galaxy);
}
} else {
$this->create();
$this->save($galaxy);
}
}
return $this->find('list', array('recursive' => -1, 'fields' => array('type', 'id')));
}
public function update($force = false)
{
$galaxies = $this->__load_galaxies($force);
$dir = new Folder(APP . 'files' . DS . 'misp-galaxy' . DS . 'clusters');
$files = $dir->find('.*\.json');
$cluster_packages = array();
foreach ($files as $file) {
$file = new File($dir->pwd() . DS . $file);
$cluster_package = json_decode($file->read(), true);
$file->close();
if (!isset($galaxies[$cluster_package['type']])) {
continue;
}
$template = array(
'source' => isset($cluster_package['source']) ? $cluster_package['source'] : '',
'authors' => json_encode(isset($cluster_package['authors']) ? $cluster_package['authors'] : array(), true),
'collection_uuid' => isset($cluster_package['uuid']) ? $cluster_package['uuid'] : '',
'galaxy_id' => $galaxies[$cluster_package['type']],
'type' => $cluster_package['type'],
'tag_name' => 'misp-galaxy:' . $cluster_package['type'] . '="'
);
$elements = array();
$temp = $this->GalaxyCluster->find('all', array(
'conditions' => array(
'GalaxyCluster.galaxy_id' => $galaxies[$cluster_package['type']]
),
'recursive' => -1,
'fields' => array('version', 'id', 'value', 'uuid')
));
$existingClusters = array();
foreach ($temp as $k => $v) {
$existingClusters[$v['GalaxyCluster']['value']] = $v;
}
$clusters_to_delete = array();
// Delete all existing outdated clusters
foreach ($cluster_package['values'] as $k => $cluster) {
if (empty($cluster['value'])) {
continue;
}
if (isset($cluster['version'])) {
} elseif (!empty($cluster_package['version'])) {
$cluster_package['values'][$k]['version'] = $cluster_package['version'];
} else {
$cluster_package['values'][$k]['version'] = 0;
}
if (!empty($existingClusters[$cluster['value']])) {
if ($force || $existingClusters[$cluster['value']]['GalaxyCluster']['version'] < $cluster_package['values'][$k]['version']) {
$clusters_to_delete[] = $existingClusters[$cluster['value']]['GalaxyCluster']['id'];
} else {
unset($cluster_package['values'][$k]);
}
}
}
if (!empty($clusters_to_delete)) {
$this->GalaxyCluster->GalaxyElement->deleteAll(array('GalaxyElement.galaxy_cluster_id' => $clusters_to_delete), false, false);
$this->GalaxyCluster->delete($clusters_to_delete, false, false);
}
// create all clusters
foreach ($cluster_package['values'] as $cluster) {
if (empty($cluster['version'])) {
$cluster['version'] = 1;
}
$template['version'] = $cluster['version'];
$this->GalaxyCluster->create();
$cluster_to_save = $template;
if (isset($cluster['description'])) {
$cluster_to_save['description'] = $cluster['description'];
unset($cluster['description']);
}
$cluster_to_save['value'] = $cluster['value'];
$cluster_to_save['tag_name'] = $cluster_to_save['tag_name'] . $cluster['value'] . '"';
if (!empty($cluster['uuid'])) {
$cluster_to_save['uuid'] = $cluster['uuid'];
}
unset($cluster['value']);
if (empty($cluster_to_save['description'])) {
$cluster_to_save['description'] = '';
}
$result = $this->GalaxyCluster->save($cluster_to_save, false);
$galaxyClusterId = $this->GalaxyCluster->id;
if (isset($cluster['meta'])) {
foreach ($cluster['meta'] as $key => $value) {
if (is_array($value)) {
foreach ($value as $v) {
$elements[] = array(
$galaxyClusterId,
$key,
$v
);
}
} else {
$elements[] = array(
$this->GalaxyCluster->id,
$key,
$value
);
}
}
}
}
$db = $this->getDataSource();
$fields = array('galaxy_cluster_id', 'key', 'value');
if (!empty($elements)) {
$db->insertMulti('galaxy_elements', $fields, $elements);
}
}
return true;
}
private function __attachClusterToEvent($user, $target_id, $cluster_id) {
}
public function attachCluster($user, $target_type, $target_id, $cluster_id)
{
$connectorModel = Inflector::camelize($target_type) . 'Tag';
$cluster = $this->GalaxyCluster->find('first', array('recursive' => -1, 'conditions' => array('id' => $cluster_id), 'fields' => array('tag_name', 'id', 'value')));
$this->Tag = ClassRegistry::init('Tag');
if ($target_type === 'event') {
$target = $this->Tag->EventTag->Event->fetchEvent($user, array('eventid' => $target_id, 'metadata' => 1));
} elseif ($target_type === 'attribute') {
$target = $this->Tag->AttributeTag->Attribute->fetchAttributes($user, array('conditions' => array('Attribute.id' => $target_id), 'flatten' => 1));
} elseif ($target_type === 'tag_collection') {
$target = $this->Tag->TagCollectionTag->TagCollection->fetchTagCollection($user, array('conditions' => array('TagCollection.id' => $target_id)));
}
if (empty($target)) {
throw new NotFoundException(__('Invalid %s.', $target_type));
}
$target = $target[0];
$tag_id = $this->Tag->captureTag(array('name' => $cluster['GalaxyCluster']['tag_name'], 'colour' => '#0088cc', 'exportable' => 1), $user);
$existingTag = $this->Tag->$connectorModel->find('first', array('conditions' => array($target_type . '_id' => $target_id, 'tag_id' => $tag_id)));
if (!empty($existingTag)) {
return 'Cluster already attached.';
}
$this->Tag->$connectorModel->create();
$toSave = array($target_type . '_id' => $target_id, 'tag_id' => $tag_id);
if ($target_type === 'attribute') {
$event = $this->Tag->EventTag->Event->find('first', array(
'conditions' => array(
'Event.id' => $target['Attribute']['event_id']
),
'recursive' => -1
));
$toSave['event_id'] = $target['Attribute']['event_id'];
}
$result = $this->Tag->$connectorModel->save($toSave);
if ($result) {
if ($target_type !== 'tag_collection') {
if ($target_type === 'event') {
$event = $target;
}
$this->Tag->EventTag->Event->insertLock($user, $event['Event']['id']);
$event['Event']['published'] = 0;
$date = new DateTime();
$event['Event']['timestamp'] = $date->getTimestamp();
$this->Tag->EventTag->Event->save($event);
}
$this->Log = ClassRegistry::init('Log');
$this->Log->create();
$this->Log->save(array(
'org' => $user['Organisation']['name'],
'model' => ucfirst($target_type),
'model_id' => $target_id,
'email' => $user['email'],
'action' => 'galaxy',
'title' => 'Attached ' . $cluster['GalaxyCluster']['value'] . ' (' . $cluster['GalaxyCluster']['id'] . ') to ' . $target_type . ' (' . $target_id . ')',
'change' => ''
));
return 'Cluster attached.';
}
return 'Could not attach the cluster';
}
public function detachCluster($user, $target_type, $target_id, $cluster_id) {
$cluster = $this->GalaxyCluster->find('first', array(
'recursive' => -1,
'conditions' => array('id' => $cluster_id),
'fields' => array('tag_name', 'id', 'value')
));
$this->Tag = ClassRegistry::init('Tag');
if ($target_type === 'event') {
$target = $this->Tag->EventTag->Event->fetchEvent($user, array('eventid' => $target_id, 'metadata' => 1));
if (empty($target)) {
throw new NotFoundException(__('Invalid %s.', $target_type));
}
$target = $target[0];
$event = $target;
$event_id = $target['Event']['id'];
$org_id = $event['Event']['org_id'];
$orgc_id = $event['Event']['orgc_id'];
} elseif ($target_type === 'attribute') {
$target = $this->Tag->AttributeTag->Attribute->fetchAttributes($user, array('conditions' => array('Attribute.id' => $target_id), 'flatten' => 1));
if (empty($target)) {
throw new NotFoundException(__('Invalid %s.', $target_type));
}
$target = $target[0];
$event_id = $target['Attribute']['event_id'];
$event = $this->Tag->EventTag->Event->fetchEvent($user, array('eventid' => $event_id, 'metadata' => 1));
if (empty($event)) {
throw new NotFoundException(__('Invalid event'));
}
$event = $event[0];
$org_id = $event['Event']['org_id'];
$orgc_id = $event['Event']['org_id'];
} elseif ($target_type === 'tag_collection') {
$target = $this->Tag->TagCollectionTag->TagCollection->fetchTagCollection($user, array('conditions' => array('TagCollection.id' => $target_id)));
if (empty($target)) {
throw new NotFoundException(__('Invalid %s.', $target_type));
}
$target = $target[0];
$org_id = $target['org_id'];
$orgc_id = $org_id;
}
if (!$user['Role']['perm_site_admin'] && !$user['Role']['perm_sync']) {
if (
($scope === 'tag_collection' && !$user['Role']['perm_tag_editor']) ||
($scope !== 'tag_collection' && !$user['Role']['perm_tagger']) ||
($user['org_id'] !== $org_id && $user['org_id'] !== $orgc_id)
) {
throw new MethodNotAllowedException('Invalid ' . Inflector::humanize($targe_type) . '.');
}
}
$tag_id = $this->Tag->captureTag(array('name' => $cluster['GalaxyCluster']['tag_name'], 'colour' => '#0088cc', 'exportable' => 1), $user);
if ($target_type == 'attribute') {
$existingTargetTag = $this->Tag->AttributeTag->find('first', array(
'conditions' => array('AttributeTag.tag_id' => $tag_id, 'AttributeTag.attribute_id' => $target_id),
'recursive' => -1,
'contain' => array('Tag')
));
} elseif ($target_type == 'event') {
$existingTargetTag = $this->Tag->EventTag->find('first', array(
'conditions' => array('EventTag.tag_id' => $tag_id, 'EventTag.event_id' => $target_id),
'recursive' => -1,
'contain' => array('Tag')
));
} elseif ($target_type == 'tag_collection') {
$existingTargetTag = $this->Tag->TagCollectionTag->TagCollection->find('first', array(
'conditions' => array('tag_id' => $tag_id, 'tag_collection_id' => $target_id),
'recursive' => -1,
'contain' => array('Tag')
));
}
if (empty($existingTargetTag)) {
return 'Cluster not attached.';
} else {
if ($target_type == 'event') {
$result = $this->Tag->EventTag->delete($existingTargetTag['EventTag']['id']);
} elseif ($target_type == 'attribute') {
$result = $this->Tag->AttributeTag->delete($existingTargetTag['AttributeTag']['id']);
} elseif ($target_type == 'tag_collection') {
$result = $this->Tag->TagCollectionTag->delete($existingTargetTag['TagCollectionTag']['id']);
}
if ($result) {
if ($target_type !== 'tag_collection') {
$this->Tag->EventTag->Event->insertLock($user, $event['Event']['id']);
$event['Event']['published'] = 0;
$date = new DateTime();
$event['Event']['timestamp'] = $date->getTimestamp();
$this->Tag->EventTag->Event->save($event);
}
$this->Log = ClassRegistry::init('Log');
$this->Log->create();
$this->Log->save(array(
'org' => $user['Organisation']['name'],
'model' => ucfirst($target_type),
'model_id' => $target_id,
'email' => $user['email'],
'action' => 'galaxy',
'title' => 'Detached ' . $cluster['GalaxyCluster']['value'] . ' (' . $cluster['GalaxyCluster']['id'] . ') to ' . $target_type . ' (' . $target_id . ')',
'change' => ''
));
return 'Cluster detached';
} else {
return 'Could not detach cluster';
}
}
}
public function getMitreAttackGalaxyId($type="mitre-enterprise-attack-attack-pattern")
{
$galaxy = $this->find('first', array(
'recursive' => -1,
'fields' => 'id',
'conditions' => array('Galaxy.type' => $type),
));
return empty($galaxy) ? 0 : $galaxy['Galaxy']['id'];
}
public function getMitreAttackMatrix()
{
$killChainOrderEnterprise = array(
'initial-access',
'execution',
'persistence',
'privilege-escalation',
'defense-evasion',
'credential-access',
'discovery',
'lateral-movement',
'collection',
'exfiltration',
'command-and-control'
);
$killChainOrderMobile = array(
'persistence',
'privilege-escalation',
'defense-evasion',
'credential-access',
'discovery',
'lateral-movement',
'effects', 'collection',
'exfiltration',
'command-and-control',
'general-network-based',
'cellular-network-based',
'could-based'
);
$killChainOrderPre = array(
'priority-definition-planning',
'priority-definition-direction',
'target-selection',
'technical-information-gathering',
'people-information-gathering',
'organizational-information-gathering',
'technical-weakness-identification',
'people-weakness-identification',
'organizational-weakness-identification',
'adversary-opsec',
'establish-&-maintain-infrastructure',
'persona-development',
'build-capabilities',
'test-capabilities',
'stage-capabilities',
'app-delivery-via-authorized-app-store',
'app-delivery-via-other-means',
'exploit-via-cellular-network',
'exploit-via-internet',
);
$killChainOrders = array(
'mitre-enterprise-attack-attack-pattern' => $killChainOrderEnterprise,
'mitre-mobile-attack-attack-pattern' => $killChainOrderMobile,
'mitre-pre-attack-attack-pattern' => $killChainOrderPre,
);
$expectedDescription = 'ATT&CK Tactic';
$expectedNamespace = 'mitre-attack';
$conditions = array('Galaxy.description' => $expectedDescription, 'Galaxy.namespace' => $expectedNamespace);
$contains = array(
'GalaxyCluster' => array('GalaxyElement'),
);
$galaxies = $this->find('all', array(
'recursive' => -1,
'contain' => $contains,
'conditions' => $conditions,
));
$mispUUID = Configure::read('MISP')['uuid'];
$attackTactic = array(
'killChain' => $killChainOrders,
'attackTactic' => array(),
'attackTags' => array(),
'instance-uuid' => $mispUUID
);
foreach ($galaxies as $galaxy) {
$galaxyType = $galaxy['Galaxy']['type'];
$clusters = $galaxy['GalaxyCluster'];
$attackClusters = array();
// add cluster if kill_chain is present
foreach ($clusters as $cluster) {
if (empty($cluster['GalaxyElement'])) {
continue;
}
$toBeAdded = false;
$clusterType = $cluster['type'];
$galaxyElements = $cluster['GalaxyElement'];
foreach ($galaxyElements as $element) {
if ($element['key'] == 'kill_chain') {
$kc = explode(":", $element['value'])[2];
$attackClusters[$kc][] = $cluster;
$toBeAdded = true;
}
if ($element['key'] == 'external_id') {
$cluster['external_id'] = $element['value'];
}
}
if ($toBeAdded) {
array_push($attackTactic['attackTags'], $cluster['tag_name']);
}
}
$attackTactic['attackTactic'][$galaxyType] = array(
'clusters' => $attackClusters,
'galaxy' => $galaxy['Galaxy'],
);
}
return $attackTactic;
}
}
| Rafiot/MISP | app/Model/Galaxy.php | PHP | agpl-3.0 | 20,693 |
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.core.urlresolvers import reverse
from mitxmako.shortcuts import render_to_response
from courseware.access import has_access
from courseware.courses import get_course_with_access
from notes.utils import notes_enabled_for_course
from static_replace import replace_static_urls
@login_required
def index(request, course_id, book_index, page=None):
course = get_course_with_access(request.user, course_id, 'load')
staff_access = has_access(request.user, course, 'staff')
book_index = int(book_index)
if book_index < 0 or book_index >= len(course.textbooks):
raise Http404("Invalid book index value: {0}".format(book_index))
textbook = course.textbooks[book_index]
table_of_contents = textbook.table_of_contents
if page is None:
page = textbook.start_page
return render_to_response('staticbook.html',
{'book_index': book_index, 'page': int(page),
'course': course,
'book_url': textbook.book_url,
'table_of_contents': table_of_contents,
'start_page': textbook.start_page,
'end_page': textbook.end_page,
'staff_access': staff_access})
def index_shifted(request, course_id, page):
return index(request, course_id=course_id, page=int(page) + 24)
@login_required
def pdf_index(request, course_id, book_index, chapter=None, page=None):
"""
Display a PDF textbook.
course_id: course for which to display text. The course should have
"pdf_textbooks" property defined.
book index: zero-based index of which PDF textbook to display.
chapter: (optional) one-based index into the chapter array of textbook PDFs to display.
Defaults to first chapter. Specifying this assumes that there are separate PDFs for
each chapter in a textbook.
page: (optional) one-based page number to display within the PDF. Defaults to first page.
"""
course = get_course_with_access(request.user, course_id, 'load')
staff_access = has_access(request.user, course, 'staff')
book_index = int(book_index)
if book_index < 0 or book_index >= len(course.pdf_textbooks):
raise Http404("Invalid book index value: {0}".format(book_index))
textbook = course.pdf_textbooks[book_index]
def remap_static_url(original_url, course):
input_url = "'" + original_url + "'"
output_url = replace_static_urls(
input_url,
getattr(course, 'data_dir', None),
course_namespace=course.location
)
# strip off the quotes again...
return output_url[1:-1]
if 'url' in textbook:
textbook['url'] = remap_static_url(textbook['url'], course)
# then remap all the chapter URLs as well, if they are provided.
if 'chapters' in textbook:
for entry in textbook['chapters']:
entry['url'] = remap_static_url(entry['url'], course)
return render_to_response('static_pdfbook.html',
{'book_index': book_index,
'course': course,
'textbook': textbook,
'chapter': chapter,
'page': page,
'staff_access': staff_access})
@login_required
def html_index(request, course_id, book_index, chapter=None):
"""
Display an HTML textbook.
course_id: course for which to display text. The course should have
"html_textbooks" property defined.
book index: zero-based index of which HTML textbook to display.
chapter: (optional) one-based index into the chapter array of textbook HTML files to display.
Defaults to first chapter. Specifying this assumes that there are separate HTML files for
each chapter in a textbook.
"""
course = get_course_with_access(request.user, course_id, 'load')
staff_access = has_access(request.user, course, 'staff')
notes_enabled = notes_enabled_for_course(course)
book_index = int(book_index)
if book_index < 0 or book_index >= len(course.html_textbooks):
raise Http404("Invalid book index value: {0}".format(book_index))
textbook = course.html_textbooks[book_index]
def remap_static_url(original_url, course):
input_url = "'" + original_url + "'"
output_url = replace_static_urls(
input_url,
getattr(course, 'data_dir', None),
course_namespace=course.location
)
# strip off the quotes again...
return output_url[1:-1]
if 'url' in textbook:
textbook['url'] = remap_static_url(textbook['url'], course)
# then remap all the chapter URLs as well, if they are provided.
if 'chapters' in textbook:
for entry in textbook['chapters']:
entry['url'] = remap_static_url(entry['url'], course)
return render_to_response('static_htmlbook.html',
{'book_index': book_index,
'course': course,
'textbook': textbook,
'chapter': chapter,
'staff_access': staff_access,
'notes_enabled': notes_enabled})
| elimence/edx-platform | lms/djangoapps/staticbook/views.py | Python | agpl-3.0 | 5,555 |
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2015 CoNWeT Lab., Universidad Politécnica de Madrid
# This file is part of Wirecloud.
# Wirecloud 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.
# Wirecloud 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 Wirecloud. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
import locale
from optparse import make_option
from django.contrib.auth.models import User, Group
from django.core.management.base import BaseCommand, CommandError
from django.utils.translation import override, ugettext as _
from wirecloud.catalogue.views import add_packaged_resource
from wirecloud.commons.utils.template import TemplateParser
from wirecloud.commons.utils.wgt import WgtFile
from wirecloud.platform.localcatalogue.utils import install_resource_to_user, install_resource_to_group, install_resource_to_all_users
class Command(BaseCommand):
args = '<file.wgt>...'
help = 'Adds one or more packaged mashable application components into the catalogue'
option_list = BaseCommand.option_list + (
make_option('--redeploy',
action='store_true',
dest='redeploy',
help='Replace mashable application components files with the new ones.',
default=False),
make_option('-u', '--users',
action='store',
type='string',
dest='users',
help='Comma separated list of users that will obtain access to the uploaded mashable application components',
default=''),
make_option('-g', '--groups',
action='store',
type='string',
dest='groups',
help='Comma separated list of groups that will obtain access rights to the uploaded mashable application components',
default=''),
make_option('-p', '--public',
action='store_true',
dest='public',
help='Allow any user to access the mashable application components.',
default=False),
)
def _handle(self, *args, **options):
if len(args) < 1:
raise CommandError(_('Wrong number of arguments'))
self.verbosity = int(options.get('verbosity', 1))
users = []
groups = []
redeploy = options['redeploy']
public = options['public']
users_string = options['users'].strip()
groups_string = options['groups'].strip()
if redeploy is False and public is False and users_string == '' and groups_string == '':
raise CommandError(_('You must use at least one of the following flags: --redeploy, --users, --groups or --public '))
if not options['redeploy']:
if users_string != '':
for username in users_string.split(','):
users.append(User.objects.get(username=username))
if groups_string != '':
for groupname in groups_string.split(','):
groups.append(Group.objects.get(name=groupname))
for file_name in args:
try:
f = open(file_name, 'rb')
wgt_file = WgtFile(f)
except:
self.log(_('Failed to read from %(file_name)s') % {'file_name': file_name}, level=1)
continue
try:
template_contents = wgt_file.get_template()
template = TemplateParser(template_contents)
if options['redeploy']:
add_packaged_resource(f, None, wgt_file=wgt_file, template=template, deploy_only=True)
else:
for user in users:
install_resource_to_user(user, file_contents=wgt_file)
for group in groups:
install_resource_to_group(group, file_contents=wgt_file)
if public:
install_resource_to_all_users(file_contents=wgt_file)
wgt_file.close()
f.close()
self.log(_('Successfully imported \"%(name)s\" from \"%(file_name)s\"') % {'name': template.get_resource_processed_info()['title'], 'file_name': file_name}, level=1)
except:
self.log(_('Failed to import the mashable application component from %(file_name)s') % {'file_name': file_name}, level=1)
def handle(self, *args, **options):
try:
default_locale = locale.getdefaultlocale()[0][:2]
except TypeError:
default_locale = None
with override(default_locale):
return self._handle(*args, **options)
def log(self, msg, level=2):
"""
Small log helper
"""
if self.verbosity >= level:
self.stdout.write(msg)
| rockneurotiko/wirecloud | src/wirecloud/catalogue/management/commands/addtocatalogue.py | Python | agpl-3.0 | 5,256 |
from sst.actions import (
assert_title,
fails,
wait_for,
)
from u1testutils import mail
from u1testutils.sst import config
from acceptance import helpers
config.set_base_url_from_env()
PASSWORD = 'Admin007'
# 2) Create 2 accounts (A & B). In Account A add email address C and do not
# verify. In Account B add email address C and do not verify.
email_a_id = mail.make_unique_test_email_address()
email_b_id = mail.make_unique_test_email_address()
email_c_id = mail.make_unique_test_email_address()
helpers.register_account(email_a_id, password=PASSWORD)
vcode_x = helpers.add_email(email_c_id)
helpers.logout()
helpers.register_account(email_b_id, password=PASSWORD)
vcode_y = helpers.add_email(email_c_id)
# try x from a, should fail
helpers.logout()
helpers.login(email_a_id, PASSWORD)
# Trying and failing to use token X completely invalidates token X, even for
# account B (which now owns the token) later in this test.
# helpers.try_to_validate_email(email_c_id, vcode_x)
# fails(assert_title, 'Complete email address validation')
# try y from a, should fail
helpers.try_to_validate_email(email_c_id, vcode_y, finish_validation=False)
fails(assert_title, 'Complete email address validation')
# both x & y should work for b, but using one should kill the other.
# try x from b, should work
helpers.logout()
helpers.login(email_b_id, PASSWORD)
helpers.try_to_validate_email(email_c_id, vcode_x, finish_validation=False)
wait_for(assert_title, 'Complete email address validation')
# now, y from b should fail, because address C was already verified (but would
# normally work)
helpers.try_to_validate_email(email_c_id, vcode_y, finish_validation=False)
fails(assert_title, 'Complete email address validation')
| miing/mci_migo | acceptance/tests/emails/doubled_email.py | Python | agpl-3.0 | 1,736 |
<?php
if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
define("SERVER_NAME",$_SERVER['HTTP_X_FORWARDED_HOST']);
} else {
define("SERVER_NAME",$_SERVER['HTTP_HOST']);
//.(($_SERVER['SERVER_PORT']!="80")? ":".$_SERVER['SERVER_PORT']:""));
}
require_once(dirname(__FILE__)."/../../../../../../clases/class.i.php");
require_once(dirname(__FILE__)."/../../../../../../clases/class.i_image.php");
$ret = array();
$ret['error'] = false;
$cats = array();
$imgs = array();
//$cache = dirname(__FILE__)."/../../../../../../../cache/tinyCache/";
$legacyPath = '/../../../../../../../tinyCache/';
if (is_dir($legacyPath)) {
$cache = $legacyPath;
} else {
$cache = '/../../../../../../../cache/tinyCache/';
}
$cache = dirname(__FILE__).$cache;
$aPasa = array('.','..');
$imgok= array('image/jpg','image/gif','image/png');
$value = i::clean($_GET['val']);
switch($_GET['w']){
case "all":
if ($gestor = opendir($cache)) {
while (false !== ($a= readdir($gestor))) {
if(in_array($a,$aPasa)) continue;
if (!is_dir($cache.$a)) continue;
$cats[] = $a;
}
closedir($gestor);
if (sizeof($cats)<=0){
mkdir($cache."general", 0777);
chmod($cache."general", 0777);
$cats[] = "general";
}
}else{
$ret['error'] = "imposible abrir el directorio ".$cache;
}
case "images":
if (!isset($_GET['c'])) $c = $cats[0]; else $c = $_GET['c'];
if ($gestor = opendir($cache.$c)) {
while (false !== ($a= readdir($gestor))) {
if(in_array($a,$aPasa)) continue;
if (!is_file($cache.$c.'/'.$a)||!in_array(i::mime_content_type($cache.$c.'/'.$a),$imgok)) continue;
$imgs[] = $a;
}
closedir($gestor);
}
break;
case "newCat":
if (trim($value)!=""){
if ($gestor = opendir($cache)) {
while (false !== ($a= readdir($gestor))) {
if(in_array($a,$aPasa)) continue;
if (!is_dir($cache.$a)) continue;
$cats[] = $a;
}
closedir($gestor);
if (!in_array($value,$cats)){
mkdir($cache.$value, 0777);
chmod($cache.$value, 0777);
$ret['result'] = "Categoría insertada con éxito.";
}else{
$ret['error'] = "Entrada repetida";
}
}else{
$ret['error'] = "imposible abrir el directorio ".$cache;
}
}else{
$ret['error'] = 'Debes introducir un nombre';
}
break;
case "delCat":
if (is_dir($cache.$value)){
i::rmrf($cache . $value);
$ret['result'] = "Categoría borrada con éxito.";
}else{
$ret['error'] = 'Error';
}
break;
}
$ret['categories'] = $cats;
$ret['images'] = $imgs;
$ret['path'] = i::base_url()."../../../../../../../cache/tinyCache/".$c."/";
// $ret['svname'] = "http://".SERVER_NAME;
$ret['svname'] = "";
echo json_encode($ret);
exit();
?>
| irontec/Mintzatu | public/karma/modules/tablon/scripts/tiny_mce/plugins/advimage/ajax_gallery.php | PHP | agpl-3.0 | 2,902 |
/**
* Copyright (C) 2009-2013 FoundationDB, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.foundationdb.server.store.statistics;
import com.foundationdb.ais.model.Index;
import com.foundationdb.ais.model.IndexColumn;
import com.foundationdb.server.service.session.Session;
import com.foundationdb.server.service.tree.KeyCreator;
import com.foundationdb.server.store.IndexVisitor;
import com.foundationdb.server.store.Store;
import java.util.ArrayList;
import java.util.List;
public class IndexStatisticsVisitor<K extends Comparable<? super K>, V> extends IndexVisitor<K,V>
{
public interface VisitorCreator<K extends Comparable<? super K>, V> {
IndexStatisticsGenerator<K,V> multiColumnVisitor(Index index);
IndexStatisticsGenerator<K,V> singleColumnVisitor(Session session, IndexColumn indexColumn);
}
public IndexStatisticsVisitor(Session session,
Index index,
long indexRowCount,
long expectedSampleCount,
VisitorCreator<K,V> creator)
{
this.index = index;
this.indexRowCount = indexRowCount;
this.expectedSampleCount = expectedSampleCount;
this.multiColumnVisitor = creator.multiColumnVisitor(index);
this.nIndexColumns = index.getKeyColumns().size();
this.singleColumnVisitors = new ArrayList<>(nIndexColumns-1);
// Single column 0 is handled as leading column of multi-column.
for (int f = 1; f < nIndexColumns; f++) {
singleColumnVisitors.add(
creator.singleColumnVisitor(session, index.getKeyColumns().get(f))
);
}
}
public void init(int bucketCount)
{
multiColumnVisitor.init(bucketCount, expectedSampleCount);
for (int c = 1; c < nIndexColumns; c++) {
singleColumnVisitors.get(c-1).init(bucketCount, expectedSampleCount);
}
}
public void finish(int bucketCount)
{
multiColumnVisitor.finish(bucketCount);
for (int c = 1; c < nIndexColumns; c++) {
singleColumnVisitors.get(c-1).finish(bucketCount);
}
}
protected void visit(K key, V value)
{
multiColumnVisitor.visit(key, value);
for (int c = 1; c < nIndexColumns; c++) {
singleColumnVisitors.get(c-1).visit(key, value);
}
}
public IndexStatistics getIndexStatistics()
{
IndexStatistics indexStatistics = new IndexStatistics(index);
// The multi-column visitor has the sampled row count. The single-column visitors
// have the count of distinct sampled keys for that column.
int sampledCount = multiColumnVisitor.rowCount();
indexStatistics.setRowCount(indexRowCount);
indexStatistics.setSampledCount(sampledCount);
multiColumnVisitor.getIndexStatistics(indexStatistics);
for (int c = 1; c < nIndexColumns; c++) {
singleColumnVisitors.get(c-1).getIndexStatistics(indexStatistics);
}
return indexStatistics;
}
private final Index index;
private final long indexRowCount, expectedSampleCount;
private final IndexStatisticsGenerator<K,V> multiColumnVisitor;
private final List<IndexStatisticsGenerator<K,V>> singleColumnVisitors;
private final int nIndexColumns;
}
| AydinSakar/sql-layer | src/main/java/com/foundationdb/server/store/statistics/IndexStatisticsVisitor.java | Java | agpl-3.0 | 4,030 |
/* This file is part of VoltDB.
* Copyright (C) 2008-2013 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltcore.messaging;
import java.io.IOException;
import java.nio.ByteBuffer;
public class VoltMessageFactory {
// Identify each message
final public static byte AGREEMENT_TASK_ID = 1;
final public static byte BINARY_PAYLOAD_ID = 2;
final public static byte FAILURE_SITE_UPDATE_ID = 3;
final public static byte HEARTBEAT_ID = 4;
final public static byte HEARTBEAT_RESPONSE_ID = 5;
final public static byte RECOVERY_ID = 6;
// DON'T JUST ADD A MESSAGE TYPE WITHOUT READING THIS!
// VoltDbMessageFactory is going to use this to generate non-core message IDs.
// Update the max value if you add a new message type above, or you
// will be sad, and I will have no sympathy. --izzy
final public static byte VOLTCORE_MESSAGE_ID_MAX = 6;
public VoltMessage createMessageFromBuffer(ByteBuffer buffer, long sourceHSId)
throws IOException
{
byte type = buffer.get();
// instantiate a new message instance according to the id
VoltMessage message = instantiate_local(type);
if (message == null)
{
message = instantiate(type);
}
message.m_sourceHSId = sourceHSId;
message.initFromBuffer(buffer.slice().asReadOnlyBuffer());
return message;
}
/**
* Overridden by subclasses to create message types unknown by voltcore
* @param messageType
* @return
*/
protected VoltMessage instantiate_local(byte messageType)
{
return null;
}
private VoltMessage instantiate(byte messageType) {
// instantiate a new message instance according to the id
VoltMessage message = null;
switch (messageType) {
case HEARTBEAT_ID:
message = new HeartbeatMessage();
break;
case HEARTBEAT_RESPONSE_ID:
message = new HeartbeatResponseMessage();
break;
case FAILURE_SITE_UPDATE_ID:
message = new FailureSiteUpdateMessage();
break;
case RECOVERY_ID:
message = new RecoveryMessage();
break;
case AGREEMENT_TASK_ID:
message = new AgreementTaskMessage();
break;
case BINARY_PAYLOAD_ID:
message = new BinaryPayloadMessage();
break;
default:
org.voltdb.VoltDB.crashLocalVoltDB("Unrecognized message type " + messageType, true, null);
}
return message;
}
}
| kobronson/cs-voltdb | src/frontend/org/voltcore/messaging/VoltMessageFactory.java | Java | agpl-3.0 | 3,216 |
<?php
return array(
'plural' => function($n) { return (($n==1) ? 0 : (($n>=2 && $n<=4) ? 1 : 2)); },
'attachment' => 'příloha',
'When there is nothing to read, redirect me to this page' => 'Když není nic ke čtení, přesměruj mě na tuto stránku',
'There is nothing new to read, enjoy your favorites articles!' => 'Není tu nic nového ke čtení, užijte si vaše oblíbené články!',
'There is nothing new to read, enjoy your previous readings!' => 'Není tu nic nového ke čtení, užijte si vaše starší články!',
'Immediately' => 'Hned',
'(error occurred during the last check)' => '(během poslední kontroly nastala chyba)',
'The feed id is required' => 'Id zdroje je vyžadováno',
'The title is required' => 'Název je vyžadován',
'The site url is required' => 'URL stránky je vyžadováno',
'The feed url is required' => 'URL zdroje je vyžadováno',
'or' => 'nebo',
'edit' => 'upravit',
'cancel' => 'zrušit',
'Feed URL' => 'URL zdroje',
'Website URL' => 'URL stránky',
'Title' => 'Název',
'Edit subscription' => 'Upravit odběr',
'Unable to edit your subscription.' => 'Nelze upravit váš odběr.',
'Your subscription has been updated.' => 'Váš odběr byl aktualizován',
'Older items first' => 'Nejdřív starší články',
'Most recent first' => 'Nejdřív nejnovější',
'Default sorting order for items' => 'Výchozí pořadí článků',
'This subscription is empty, %sgo back to unread items%s' => 'Tento odběr je prázdný %svrátit se na nepřečtené články%s',
'sort by date %s(%s)%s' => 'řadit podle data %s(%s)%s',
'most recent first' => 'nejdříve nejnovější',
'older first' => 'nejdříve starší',
'Show only this subscription' => 'Zobrazovat pouze tento odběr',
'Go to unread' => 'Jít na nepřečtené',
'Go to bookmarks' => 'Jít na záložky',
'Go to history' => 'Jít na historii',
'Go to subscriptions' => 'Jít na odběry',
'Go to preferences' => 'Jít na nastavení',
'Bookmarklet' => 'Bookmarklet',
'Subscribe with Miniflux' => 'Odebírat Minifluxem',
'Drag and drop this link to your bookmarks' => 'Přetáhněte si tento odkaz mezi záložky',
'Download full content' => 'Stahovat celý obsah',
'Downloading full content is slower because Miniflux grab the content from the original website. You should use that for subscriptions that display only a summary. This feature doesn\'t work with all websites.' => 'Stahování celého obsahu je pomalejší, protože Miniflux získává obsah z původní webové stránky. Měli byste to používat jen pro odběry které zobrazují pouze shrnutí. Tato funkce nefunguje se všemi stránkami.',
'No message' => 'Žádné zprávy',
'flush messages' => 'smazat zprávy',
'API endpoint:' => 'Koncový bod:',
'API username:' => 'Uživatelské jméno:',
'API token:' => 'Heslo:',
'Generate new tokens' => 'Generovat nové heslo',
'Bookmark RSS Feed' => 'RSS záložek',
'updated just now' => 'aktualizováno právě teď',
'checked at' => 'zkontrolováno',
'never updated after creation' => 'nikdy neaktualizováno po vytvoření',
'Subscription disabled' => 'Odběr zakázán',
'content downloaded' => 'obsah stažen',
'in progress...' => 'probíhá…',
'unable to fetch content' => 'nelze stáhnout obsah',
'Download content' => 'Stáhnout obsah',
'download content' => 'stáhnout obsah',
'Help' => 'Nápověda',
'Theme' => 'Vzhled',
'Items per page' => 'Článků na stránku',
'Previous page' => 'Předchozí stránka',
'Next page' => 'Další stránka',
'Do not fetch the content of articles' => 'Nestahovat obsah článků',
'Remove automatically read items' => 'Automaticky odstraňovat přečtené články',
'Never' => 'Nikdy',
'After %d day' => array('Po %d dni', 'Po %d dnech', 'Po %d dnech'),
'unread' => 'nepřečtené',
'Unread' => 'Nepřečtené',
'bookmark' => 'přidat do záložek',
'remove bookmark' => 'odstranit záložku',
'bookmarks' => 'záložky',
'Bookmarks' => 'Záložky',
'Bookmark item' => 'Přidat článek do záložek',
'No bookmark' => 'Žádné záložky',
'history' => 'historie',
'subscriptions' => 'odběry',
'Subscriptions' => 'Odběry',
'preferences' => 'nastavení',
'Preferences' => 'Nastavení',
'logout' => 'odhlásit',
'Username' => 'Přihlašovací jméno',
'Password' => 'Heslo',
'Confirmation' => 'Potvrzení',
'Language' => 'Jazyk',
'Save' => 'Uložit',
'Database size:' => 'Velikost databáze:',
'Optimize the database' => 'Optimalizovat databázi',
'(VACUUM command)' => '(příkaz VACUUM)',
'Download the entire database' => 'Stáhnout celou databázi',
'(Gzip compressed Sqlite file)' => '(Gzipem komprimovaný SQLite soubor)',
'Keyboard shortcuts' => 'Klávesové zkratky',
'Previous item' => 'Předchozí článek',
'Next item' => 'Další článek',
'Mark as read or unread' => 'Označit jako (ne)přečtené',
'Open original link' => 'Otevřít původní odkaz',
'Open item' => 'Otevřít článek',
'About' => 'O aplikaci',
'Miniflux version:' => 'Verze Miniflux:',
'Nothing to read' => 'Nic ke čtení',
'mark all as read' => 'označit vše jako přečtené',
'original link' => 'původní odkaz',
'mark as read' => 'označit jako přečtené',
'No history' => 'Žádná historie',
'mark as unread' => 'označit jako nepřečtené',
'History' => 'Historie',
'flush all items' => 'zahodit všechny články',
'Item not found' => 'Článek nenalezen',
'Next' => 'Další',
'Previous' => 'Předchozí',
'Sign in' => 'Přihlásit',
'feeds' => 'zdroje',
'add' => 'přidat',
'import' => 'importovat',
'export' => 'exportovat',
'OPML Import' => 'Importovat OPML',
'OPML file' => 'OPML soubor',
'Import' => 'Importovat',
'refresh all' => 'aktualizovat vše',
'No subscription' => 'Žádné zdroje',
'remove' => 'odstranit',
'Remove' => 'Odstranit',
'refresh' => 'aktualizovat',
'New subscription' => 'Nový odběr',
'Website or Feed URL' => 'URL stránky nebo zdroje',
'Add' => 'Přidat',
'http://website/' => 'http://webova-stranka/',
'Official website:' => 'Oficiální stránka:',
'Bad username or password' => 'Špatné přihlašovací jméno nebo heslo',
'Unable to update your preferences.' => 'Nelze aktualizovat nastavení.',
'Your preferences are updated.' => 'Nastavení aktualizována.',
'Unable to import your OPML file.' => 'Nelze importovat OPML soubor.',
'Your feeds have been imported.' => 'Zdroje byly importovány.',
'Unable to find a subscription.' => 'Nelze nalézt odběry.',
'Subscription added successfully.' => 'Odběr úspěšně přidán.',
'Your subscriptions are updated' => 'Odběry aktualizovány',
'Unable to remove this subscription.' => 'Nelze odstranit tento odběr.',
'This subscription has been removed successfully.' => 'Tento odběr byl úspěšně odstraněn.',
'The user name is required' => 'Přihlašovací jméno je vyžadováno',
'The maximum length is 50 characters' => 'Maximální délka je 50 znaků',
'The password is required' => 'Heslo je vyžadováno',
'The minimum length is 6 characters' => 'Minimální délka je 6 znaků',
'The confirmation is required' => 'Potvrzení je vyžadováno',
'Passwords don\'t match' => 'Hesla se neshodují',
'Do you really want to remove these items from your history?' => 'Opravdu chcete odstranit tyto články z historie?',
'Do you really want to remove this subscription: "%s"?' => 'Opravdu chcete odstranit tento odběr: "%s"?',
'Nothing to read, do you want to %supdate your subscriptions%s?' => 'Nic ke čtení, chcete %saktualizovat vaše odběry%s?',
'Show help' => 'Zobrazit nápovědu',
'Close help' => 'Zavřít nápovědu',
'%d second ago' => array('před sekundou', 'před %d sekundami', 'před %d sekundami'),
'%d minute ago' => array('před minutou', 'před %d minutami', 'před %d minutami'),
'%d hour ago' => array('před hodinou', 'před %d hodinami', 'před %d hodinami'),
'%d day ago' => array('včera', 'před %d dny', 'před %d dny'),
'%d week ago' => array('minulý týden', 'před %d týdny', 'před %d týdny'),
'%d month ago' => array('před měsícem', 'před %d měsíci', 'před %d měsíci'),
'Timezone' => 'Časová zóna',
'Update all subscriptions' => 'Aktualizovat všechny odběry',
'Auto-Update URL' => 'URL automatické aktualizace',
'Update Miniflux' => 'Aktualizovat Miniflux',
'Miniflux is updated!' => 'Miniflux je aktualizovaný!',
'Unable to update Miniflux, check the console for errors.' => 'Nelze aktualizovat Miniflux, zkontrolujte konzoli na chyby.',
'Don\'t forget to backup your database' => 'Nezapomeňte zálohovat vaši databázi',
'The name must have only alpha-numeric characters' => 'Jméno smí obsahovat pouze písmena a číslice',
'New database' => 'Nová databáze',
'Database name' => 'Jméno databáze',
'Default database' => 'Výchozí databáze',
'Select another database' => 'Vyberte jinou databázi',
'The database name is required' => 'Jméno databáze je vyžadováno',
'Database created successfully.' => 'Databáze úspěšně vytvořena.',
'Unable to create the new database.' => 'Nelze vytvořit novou databázi.',
'Add a new database (new user)' => 'Přidat novou databázi (nového uživatele)',
'Create' => 'Vytvořit',
'Unknown' => 'Neznámý',
'Remember Me' => 'Zapamatovat si mě',
'Display items on lists' => 'Zobrazovat články na seznamech',
'Summaries' => 'Shrnutí',
'Full contents' => 'Celý obsah',
'Force RTL mode (Right-to-left language)' => 'Vynutit režim zprava doleva',
'Activated' => 'Aktivováno',
'Remove this feed' => 'Odstranit tento zdroj',
'Miniflux' => 'Miniflux',
'mini%sflux%s' => 'mini%sflux%s',
'All' => 'Vše',
'Advanced' => 'Pokročilé',
'Documentation' => 'dokumentace',
'Installation instructions' => 'Instalační instrukce',
'Upgrade to a new version' => 'Aktualizovat na novou verzi',
'Cronjob' => 'Cronjob',
'Advanced configuration' => 'Pokročilá nastavení',
'Full article download' => 'stahování celého článku',
'Multiple users' => 'Více uživatelů',
'Themes' => 'Témata',
'Json-RPC API' => 'Json-RPC API',
'Fever API' => 'Fever API',
'Translations' => 'Překlady',
'Run Miniflux with Docker' => 'Spouštět Miniflux s Dockerem',
'FAQ' => 'ČKD',
'settings' => 'nastavení',
'help' => 'nápověda',
'api' => 'api',
'about' => 'o',
'This action will update Miniflux with the last development version, are you sure?' => 'Tato akce aktualizuje Miniflux na poslední vývojovou verzi. Jste si jistí?',
'database' => 'databáze',
'Console' => 'konzole',
'Miniflux API' => 'Miniflux API',
'menu' => 'nabídka',
'Default' => 'Výchozí',
'Value required' => 'Hodnota vyžadována',
'Must be an integer' => 'Musí být celé číslo',
'Remove automatically unread items' => 'Automaticky odstraňovat nepřečtené články',
'Toggle RTL mode' => 'Přepnout režim zprava doleva',
'external services' => 'externí služby',
'Send bookmarks to Pinboard' => 'Posílat záložky na Pinboard',
'Pinboard API token' => 'Pinboard API token',
'Pinboard tags' => 'Pinboard štítky',
'Instapaper username' => 'Instapaper uživatelské jméno',
'Instapaper password' => 'Instapaper heslo',
'Instapaper' => 'Instapaper',
'Pinboard' => 'Pinboard',
'Send bookmarks to Instapaper' => 'Posílat záložky na Instapaper',
'Authentication' => 'Autentikace',
'Reading' => 'Čtení',
'Application' => 'Aplikace',
'Enable image proxy' => 'Povolit proxy obrázků',
'Avoid mixed content warnings with HTTPS' => 'Vyhne se varování o pomíchaném obsahu s HTTPS',
'Download favicons' => 'Stahovat favicony',
'general' => 'základní',
'An error occurred during the last check. Refresh the feed manually and check the %sconsole%s for errors afterwards!' => 'Nastala chyba při poslední kontrole. Obnovte zdroj ručně a poté zkontrolujte %skonzoli%s na chyby!',
'Refresh interval in minutes for unread counter' => 'Obnovovací interval v minutách pro počítadlo nepřečtených',
'Nothing to show. Enable the debug mode to see log messages.' => 'Není co ukázat. Povolte ladící režim pro zobrazení záznamů.',
'Enable debug mode' => 'Povolit ladící režim',
'Original link marks article as read' => 'Původní odkaz označí článek za přečtený',
'Cloak the image referrer' => 'Zamaskovat původce obrázků',
'This subscription already exists.' => 'Tento odběr již existuje.',
'Connection timeout.' => 'Vypršel časový limit spojení.',
'Error occured.' => 'Nastala chyba.',
'Feed is malformed.' => 'Odběr má špatný formát.',
'Invalid SSL certificate.' => 'Neplatný SSL certifikát.',
'Maximum number of HTTP redirections exceeded.' => 'Maximální počet HTTP přesměrování překročen.',
'The content size exceeds to maximum allowed size.' => 'Velikost obsahu překročila maximální povolenou velikost.',
'Unable to detect the feed format.' => 'Nelze detekovat formát odběru.',
'add a new group' => 'přidat novou skupinu',
'Groups' => 'Skupiny',
'Back to the group' => 'Zpět do skupiny',
'view' => 'zobrazit',
'Item title links to' => 'Titulek článku odkazuje na',
'Original' => 'Originál',
'Last login:' => 'Poslední přihlášení:',
'Search' => 'Hledat',
'There are no results for your search' => 'Žádné výsledky vašeho hledání',
);
| mkresin/miniflux | locales/cs_CZ/translations.php | PHP | agpl-3.0 | 14,023 |
<?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".
********************************************************************************/
class ApprovalProcessForMixedModelsSearchListView extends SecuredListView
{
public static function getDefaultMetadata()
{
$metadata = array(
'global' => array(
'panels' => array(
array(
'rows' => array(
array('cells' =>
array(
array(
'elements' => array(
array('attributeName' => 'name', 'type' => 'Text', 'isLink' => true),
),
),
)
),
array('cells' =>
array(
array(
'elements' => array(
array('attributeName' => 'opportunity', 'type' => 'Opportunity', 'isLink' => true),
),
),
)
),
array('cells' =>
array(
array(
'elements' => array(
array('attributeName' => 'assignedto', 'type' => 'User', 'isLink' => true ),
),
),
)
),
array('cells' =>
array(
array(
'elements' => array(
array('attributeName' => 'comments', 'type' => 'TextArea'),
),
),
)
),
),
),
),
),
);
return $metadata;
}
public static function getDesignerRulesType()
{
return 'ForMixedModelsSearchListView';
}
}
?>
| Ramkavanan/SHCRM | app/protected/modules/approvalProcess/views/ApprovalProcessForMixedModelsSearchListView.php | PHP | agpl-3.0 | 4,693 |
<?php /* Smarty version 2.6.11, created on 2014-09-27 03:20:43
compiled from include/EditView/header.tpl */ ?>
<?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php');
smarty_core_load_plugins(array('plugins' => array(array('function', 'sugar_button', 'include/EditView/header.tpl', 81, false),array('function', 'sugar_action_menu', 'include/EditView/header.tpl', 91, false),)), $this); ?>
{*
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
*}
<script>
{literal}
$(document).ready(function(){
$("ul.clickMenu").each(function(index, node){
$(node).sugarActionMenu();
});
});
{/literal}
</script>
<div class="clear"></div>
<form action="index.php" method="POST" name="{$form_name}" id="{$form_id}" {$enctype}>
<table width="100%" cellpadding="0" cellspacing="0" border="0" class="dcQuickEdit">
<tr>
<td class="buttons">
<input type="hidden" name="module" value="{$module}">
{if isset($smarty.request.isDuplicate) && $smarty.request.isDuplicate eq "true"}
<input type="hidden" name="record" value="">
<input type="hidden" name="duplicateSave" value="true">
<input type="hidden" name="duplicateId" value="{$fields.id.value}">
{else}
<input type="hidden" name="record" value="{$fields.id.value}">
{/if}
<input type="hidden" name="isDuplicate" value="false">
<input type="hidden" name="action">
<input type="hidden" name="return_module" value="{$smarty.request.return_module}">
<input type="hidden" name="return_action" value="{$smarty.request.return_action}">
<input type="hidden" name="return_id" value="{$smarty.request.return_id}">
<input type="hidden" name="module_tab">
<input type="hidden" name="contact_role">
{if (!empty($smarty.request.return_module) || !empty($smarty.request.relate_to)) && !(isset($smarty.request.isDuplicate) && $smarty.request.isDuplicate eq "true")}
<input type="hidden" name="relate_to" value="{if $smarty.request.return_relationship}{$smarty.request.return_relationship}{elseif $smarty.request.relate_to && empty($smarty.request.from_dcmenu)}{$smarty.request.relate_to}{elseif empty($isDCForm) && empty($smarty.request.from_dcmenu)}{$smarty.request.return_module}{/if}">
<input type="hidden" name="relate_id" value="{$smarty.request.return_id}">
{/if}
<input type="hidden" name="offset" value="{$offset}">
{assign var='place' value="_HEADER"} <!-- to be used for id for buttons with custom code in def files-->
<?php if (isset ( $this->_tpl_vars['form']['hidden'] )): $_from = $this->_tpl_vars['form']['hidden']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array'); }if (count($_from)):
foreach ($_from as $this->_tpl_vars['field']):
echo $this->_tpl_vars['field']; ?>
<?php endforeach; endif; unset($_from); endif; if (empty ( $this->_tpl_vars['form']['button_location'] ) || $this->_tpl_vars['form']['button_location'] == 'top'): if (! empty ( $this->_tpl_vars['form'] ) && ! empty ( $this->_tpl_vars['form']['buttons'] )): ?>
<?php $_from = $this->_tpl_vars['form']['buttons']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array'); }if (count($_from)):
foreach ($_from as $this->_tpl_vars['val'] => $this->_tpl_vars['button']):
?>
<?php echo smarty_function_sugar_button(array('module' => ($this->_tpl_vars['module']),'id' => ($this->_tpl_vars['button']),'form_id' => ($this->_tpl_vars['form_id']),'view' => ($this->_tpl_vars['view']),'appendTo' => 'header_buttons','location' => 'HEADER'), $this);?>
<?php endforeach; endif; unset($_from); else: echo smarty_function_sugar_button(array('module' => ($this->_tpl_vars['module']),'id' => 'SAVE','view' => ($this->_tpl_vars['view']),'form_id' => ($this->_tpl_vars['form_id']),'location' => 'HEADER','appendTo' => 'header_buttons'), $this);?>
<?php echo smarty_function_sugar_button(array('module' => ($this->_tpl_vars['module']),'id' => 'CANCEL','view' => ($this->_tpl_vars['view']),'form_id' => ($this->_tpl_vars['form_id']),'location' => 'HEADER','appendTo' => 'header_buttons'), $this);?>
<?php endif; if (empty ( $this->_tpl_vars['form']['hideAudit'] ) || ! $this->_tpl_vars['form']['hideAudit']): echo smarty_function_sugar_button(array('module' => ($this->_tpl_vars['module']),'id' => 'Audit','view' => ($this->_tpl_vars['view']),'form_id' => ($this->_tpl_vars['form_id']),'appendTo' => 'header_buttons'), $this);?>
<?php endif; endif; echo smarty_function_sugar_action_menu(array('buttons' => $this->_tpl_vars['header_buttons'],'class' => 'fancymenu','flat' => true), $this);?>
</td>
<td align='right'><?php echo $this->_tpl_vars['ADMIN_EDIT']; ?>
<?php if ($this->_tpl_vars['panelCount'] == 0): ?>
<?php if ($this->_tpl_vars['SHOW_VCR_CONTROL']): ?>
{$PAGINATION}
<?php endif; endif; ?>
</td>
</tr>
</table> | alishahpakneeds/akbarsugarcrm | cache/smarty/templates_c/%%95^955^955CF478%%header.tpl.php | PHP | agpl-3.0 | 6,701 |
<?php
/**
* HTTP Raw Header Field Validator Class | Validation\HTTP\Headers\Raw.php
*
* @author Bruno Augusto
*
* @copyright Copyright (c) 2017 Next Studios
* @license http://www.gnu.org/licenses/agpl-3.0.txt GNU Affero General Public License 3.0
*/
namespace Next\Validation\HTTP\Headers;
use Next\Components\Object; # Object Class
/**
* The Raw Header Validator checks if input string if valid to be used as
* unfiltered — thus "raw" — Header Field
*
* Because they must be manually — and carefully — set, the only concerns
* we take care of is for the value not to be NULL, otherwise this would
* result in an empty string when being used and for the string to not
* have a colon (:) which is what usually separates a Header Field name
* from its value
*
* If a Raw Header must be sent with a Name, then it's not Raw, it's Generic ;)
*
* @package Next\Validation
*
* @uses Next\Components\Object
* Next\Validation\HTTP\Headers\Header
*/
class Raw extends Object implements Header {
/**
* Parameter Options Definition
*
* @var array $parameters
*/
protected $parameters = [
'value' => [ 'required' => TRUE ]
];
/**
* Validates Generic Header Field
*
* @return boolean
* TRUE if valid and FALSE otherwise
*/
public function validate() : bool {
return ( $this -> options -> value !== NULL &&
strpos( $this -> options -> value, ':' ) === FALSE );
}
}
| nextframework/next | Validation/HTTP/Headers/Raw.php | PHP | agpl-3.0 | 1,530 |
<?php /* Smarty version 2.6.11, created on 2014-11-06 21:16:36
compiled from cache/modules/Leads/SearchFormHeader.tpl */ ?>
<?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php');
smarty_core_load_plugins(array('plugins' => array(array('function', 'sugar_getjspath', 'cache/modules/Leads/SearchFormHeader.tpl', 4, false),)), $this); ?>
<div class="clear"></div>
<div class='listViewBody'>
<script type="text/javascript" src="<?php echo smarty_function_sugar_getjspath(array('file' => 'include/javascript/popup_parent_helper.js'), $this);?>
"></script>
<?php echo $this->_tpl_vars['TABS']; ?>
<?php echo '
<script>
function submitOnEnter(e)
{
var characterCode = (e && e.which) ? e.which : event.keyCode;
if (characterCode == 13) {
document.getElementById(\'search_form\').submit();
return false;
} else {
return true;
}
}
</script>
'; ?>
<form name='search_form' id='search_form' class='search_form' method='post' action='index.php?module=<?php echo $this->_tpl_vars['module']; ?>
&action=<?php echo $this->_tpl_vars['action']; ?>
' onkeydown='submitOnEnter(event);'>
<input type='hidden' name='searchFormTab' value='<?php echo $this->_tpl_vars['displayView']; ?>
'/>
<input type='hidden' name='module' value='<?php echo $this->_tpl_vars['module']; ?>
'/>
<input type='hidden' name='action' value='<?php echo $this->_tpl_vars['action']; ?>
'/>
<input type='hidden' name='query' value='true'/>
<?php $_from = $this->_tpl_vars['TAB_ARRAY']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array'); }$this->_foreach['tabIteration'] = array('total' => count($_from), 'iteration' => 0);
if ($this->_foreach['tabIteration']['total'] > 0):
foreach ($_from as $this->_tpl_vars['tabkey'] => $this->_tpl_vars['tabData']):
$this->_foreach['tabIteration']['iteration']++;
?>
<div id='<?php echo $this->_tpl_vars['module']; echo $this->_tpl_vars['tabData']['name']; ?>
_searchSearchForm' style='<?php echo $this->_tpl_vars['tabData']['displayDiv']; ?>
' class="edit view search <?php echo $this->_tpl_vars['tabData']['name']; ?>
"><?php if ($this->_tpl_vars['tabData']['displayDiv']): else: echo $this->_tpl_vars['return_txt']; endif; ?></div>
<?php endforeach; endif; unset($_from); ?>
<div id='<?php echo $this->_tpl_vars['module']; ?>
saved_viewsSearchForm' style='display: none;'><?php echo $this->_tpl_vars['saved_views_txt']; ?>
</div> | SoftNext/secondp | cache/smarty/templates_c/%%E2^E2E^E2EE98C0%%SearchFormHeader.tpl.php | PHP | agpl-3.0 | 2,421 |
// This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/)
// Copyright (c) 2015 Gerhard Zehetbauer
// Copyright (c) 2015 Alexander Nimmervoll
//
// 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/>.
using System;
using System.Windows;
using System.Diagnostics;
using System.Windows.Navigation;
using CalDavSynchronizer.Ui.Options.ViewModels;
namespace CalDavSynchronizer.Ui.Options.Views
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class OXInfoDialog : Window
{
public OXInfoDialog()
{
InitializeComponent();
DataContextChanged += OptionsWindow_DataContextChanged;
}
private void OptionsWindow_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var viewModel = e.NewValue as OXInfoDialogViewModel;
if (viewModel != null)
{
viewModel.CloseRequested += ViewModel_CloseRequested;
}
}
private void ViewModel_CloseRequested(object sender, CloseEventArgs e)
{
DialogResult = e.IsAcceptedByUser;
}
}
} | aluxnimm/outlookcaldavsynchronizer | CalDavSynchronizer/Ui/Options/Views/OXInfoDialog.xaml.cs | C# | agpl-3.0 | 1,818 |
/**
*
*/
/**
* @author sergio
*
*/
package bluecrystal.domain.helper; | bluecrystalsign/signer-source | bluecrystal.deps.domain/src/main/java/bluecrystal/domain/helper/package-info.java | Java | agpl-3.0 | 82 |
/**
* Copyright (C) 2000 - 2012 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.stratelia.silverpeas.versioning;
import junit.framework.Test;
import junit.framework.TestSuite;
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite(
"Test for com.stratelia.silverpeas.versioning");
//$JUnit-BEGIN$
suite.addTestSuite(com.stratelia.silverpeas.versioning.model.TestDocumentVersion.class);
suite.addTest(com.stratelia.silverpeas.versioning.jcr.impl.AllTests.suite());
//$JUnit-END$
return suite;
}
}
| NicolasEYSSERIC/Silverpeas-Core | ejb-core/versioning/src/test/java/com/stratelia/silverpeas/versioning/AllTests.java | Java | agpl-3.0 | 1,643 |
require 'feed-normalizer'
require 'open-uri'
class FeedPost < ActiveRecord::Base
extend PreferencesHelper
class << self
def update_posts
posts = find(:all, :select => "feedid")
post_ids = posts.map {|p| p.feedid}
begin
feed = FeedNormalizer::FeedNormalizer.parse open(global_prefs.blog_feed_url)
feed_ids = feed.entries.map {|e| e.id}
new_ids = feed_ids - post_ids
feed.entries.each do |entry|
if new_ids.include? entry.id
post = FeedPost.new()
post.feedid = entry.id
post.title = entry.title
post.urls = entry.urls
post.categories = entry.categories
post.content = entry.content
post.authors = entry.authors
post.date_published = entry.date_published
#post.last_updated = entry.last_updated
post.save
end
end
new_ids.length
rescue
nil
end
end
end
end
| austintimeexchange/oscurrency | app/models/feed_post.rb | Ruby | agpl-3.0 | 998 |
package jcog.pri.bag;
import jcog.Util;
import jcog.data.list.FasterList;
import jcog.pri.*;
import jcog.pri.bag.impl.ArrayBag;
import jcog.pri.bag.impl.HijackBag;
import jcog.pri.bag.impl.PriReferenceArrayBag;
import jcog.pri.bag.impl.hijack.DefaultHijackBag;
import jcog.random.XoRoShiRo128PlusRandom;
import jcog.signal.Tensor;
import jcog.signal.tensor.ArrayTensor;
import org.apache.commons.math3.random.EmpiricalDistribution;
import org.apache.commons.math3.stat.Frequency;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
import org.eclipse.collections.api.block.function.primitive.FloatToFloatFunction;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.stream.Collectors;
import static jcog.Texts.n4;
import static jcog.pri.bag.ArrayBagTest.assertSorted;
import static org.junit.jupiter.api.Assertions.*;
/**
* @author me
*/
class BagTest {
public static void testBasicInsertionRemoval(Bag<String, PriReference<String>> c) {
assertEquals(1, c.capacity());
if (!(c instanceof DefaultHijackBag)) {
assertEquals(0, c.size());
assertTrue(c.isEmpty());
}
PLink x0 = new PLink("x", 2 * ScalarValue.EPSILON);
PriReference added = c.put(x0);
assertSame(added, x0);
c.commit();
assertEquals(1, c.size());
assertEquals(0, c.priMin(), ScalarValue.EPSILON * 2);
PriReference<String> x = c.get("x");
assertNotNull(x);
assertSame(x, x0);
assertTrue(Util.equals(Prioritized.Zero.priElseNeg1(), x.priElseNeg1(), 0.01f));
}
public static Random rng() {
return new XoRoShiRo128PlusRandom(1);
}
public static void printDist(@NotNull EmpiricalDistribution f) {
System.out.println(f.getSampleStats().toString().replace("\n", " "));
f.getBinStats().forEach(
s -> {
/*if (s.getN() > 0)*/
System.out.println(
n4(s.getMin()) + ".." + n4(s.getMax()) + ":\t" + s.getN());
}
);
}
private static Tensor samplingPriDist(@NotNull Bag<PLink<String>, PLink<String>> b, int batches, int batchSize, int bins) {
assert(bins > 1);
Set<String> hit = new TreeSet();
Frequency hits = new Frequency();
ArrayTensor f = new ArrayTensor(bins);
assertFalse(b.isEmpty());
Random rng = new XoRoShiRo128PlusRandom(1);
float min = b.priMin(), max = b.priMax(), range = max-min;
for (int i = 0; i < batches; i++) {
b.sample(rng, batchSize, x -> {
f.data[Util.bin(b.pri(x), bins)]++;
String s = x.get();
hits.addValue(s);
hit.add(s);
});
}
int total = batches * batchSize;
assertEquals(total, Util.sum(f.data), 0.001f);
if (hits.getUniqueCount() != b.size()) {
System.out.println(hits.getUniqueCount() + " != " + b.size());
Set<String> items = b.stream().map(NLink::get).collect(Collectors.toSet());
items.removeAll(hit);
System.out.println("not hit: " + items);
System.out.println(hits);
fail("all elements must have been sampled at least once");
}
return f.scaled(1f / total);
}
public static void testRemoveByKey(Bag<String, PriReference<String>> a) {
a.put(new PLink("x", 0.1f));
a.commit();
assertEquals(1, a.size());
a.remove("x");
a.commit();
assertEquals(0, a.size());
assertTrue(a.isEmpty());
if (a instanceof ArrayBag) {
assertTrue(((PriReferenceArrayBag) a).listCopy().isEmpty());
//assertTrue(((PLinkArrayBag) a).keySet().isEmpty());
}
}
static void testBagSamplingDistributionLinear(Bag<PLink<String>, PLink<String>> bag, float batchSizeProp) {
fillLinear(bag, bag.capacity());
testBagSamplingDistribution(bag, batchSizeProp);
}
static void testBagSamplingDistributionSquashed(Bag<PLink<String>, PLink<String>> bag, float batchSizeProp) {
fill(bag, bag.capacity(), (x)-> (x/2f) + 0.5f);
testBagSamplingDistribution(bag, batchSizeProp);
}
static void testBagSamplingDistributionCurved(Bag<PLink<String>, PLink<String>> bag, float batchSizeProp) {
fill(bag, bag.capacity(), (x)-> 1-(1-x)*(1-x));
testBagSamplingDistribution(bag, batchSizeProp);
}
static void testBagSamplingDistributionRandom(ArrayBag<PLink<String>, PLink<String>> bag, float batchSizeProp) {
fillRandom(bag);
testBagSamplingDistribution(bag, batchSizeProp);
}
static void testBagSamplingDistribution(Bag<PLink<String>, PLink<String>> bag, float batchSizeProp) {
int cap = bag.capacity();
int batchSize = (int)Math.ceil(batchSizeProp * cap);
int batches = cap * 1000 / batchSize;
if (bag.size() < 3)
return; //histogram tests wont apply
int bins = Math.min(8, Math.max(3, cap/2));
Tensor f1 = samplingPriDist(bag, batches, batchSize, bins);
String h = "cap=" + cap + " total=" + (batches * batchSize);
// System.out.println(h + ":\n\t" + f1.tsv2());
// System.out.println();
float[] ff = f1.snapshot();
float orderThresh = 0.1f;
int n = ff.length;
if (ff[n-1] == 0)
n--; //skip last empty histogram cell HACK
if (ff[n-1] == 0)
n--; //skip last empty histogram cell HACK
for (int j = 0; j < n; j++) {
// assertTrue(ff[j] > 0); //no zero bins
for (int i = j+1; i < n; i++) {
float diff = ff[j] - ff[i];
boolean unordered = diff > orderThresh;
if (unordered) {
fail("sampling distribution not ordered. contents=" + bag);
}
}
}
final float MIN_RATIO = 1.5f;
for (int lows : n > 4 ? new int[] { 0, 1} : new int[] { 0 } ) {
for (int highs : n > 4 ? new int[] { n -1, n -2} : new int[] { n -1 } ) {
if (lows!=highs) {
float maxMinRatio = ff[highs] / ff[lows];
assertTrue(
maxMinRatio > MIN_RATIO,
maxMinRatio + " ratio between max and min"
);
}
}
}
}
private float maxMinRatio(@NotNull EmpiricalDistribution d) {
List<SummaryStatistics> bins = d.getBinStats();
return ((float) bins.get(bins.size() - 1).getN() / (bins.get(0).getN()));
}
public static void testPutMinMaxAndUniqueness(Bag<Integer, PriReference<Integer>> a) {
float pri = 0.5f;
int n = a.capacity() * 16;
for (int i = 0; i < n; i++) {
a.put(new PLink((i), pri));
}
a.commit(null);
assertEquals(a.capacity(), a.size());
if (a instanceof ArrayBag) assertSorted((ArrayBag)a);
List<Integer> keys = new FasterList(a.capacity());
a.forEachKey(keys::add);
assertEquals(a.size(), keys.size());
assertEquals(new HashSet(keys).size(), keys.size());
assertEquals(pri, a.priMin(), 0.01f);
assertEquals(a.priMin(), a.priMax(), 0.08f);
if (a instanceof ArrayBag)
assertTrue(((HijackBag)a).density() > 0.75f);
}
public static void populate(Bag<String, PriReference<String>> b, Random rng, int count, int dimensionality, float minPri, float maxPri, float qua) {
populate(b, rng, count, dimensionality, minPri, maxPri, qua, qua);
}
private static void populate(Bag<String, PriReference<String>> a, Random rng, int count, int dimensionality, float minPri, float maxPri, float minQua, float maxQua) {
float dPri = maxPri - minPri;
for (int i = 0; i < count; i++) {
a.put(new PLink(
"x" + rng.nextInt(dimensionality),
rng.nextFloat() * dPri + minPri)
);
}
a.commit(null);
if (a instanceof ArrayBag) assertSorted((ArrayBag)a);
}
/**
* fill it exactly to capacity
*/
public static void fillLinear(Bag<PLink<String>, PLink<String>> bag, int c) {
fill(bag, c, (x)->x);
assertEquals(1f / (c+1), bag.priMin(), 0.03f);
assertEquals(1 - 1f/(c+1), bag.priMax(), 0.03f);
}
public static void fill(Bag<PLink<String>, PLink<String>> bag, int c, FloatToFloatFunction priCurve) {
assertTrue(bag.isEmpty());
for (int i = c-1; i >= 0; i--) {
float x = (i + 1) / (c+1f); //center of index
PLink inserted = bag.put(new PLink(i + "x", priCurve.valueOf(x)));
assert(inserted!=null);
}
bag.commit(null);
assertEquals(c, bag.size());
if (bag instanceof ArrayBag) assertSorted((ArrayBag)bag);
}
private static void fillRandom(ArrayBag<PLink<String>, PLink<String>> bag) {
assertTrue(bag.isEmpty());
int c = bag.capacity();
Random rng = new XoRoShiRo128PlusRandom(1);
for (int i = c-1; i >= 0; i--) {
PLink inserted = bag.put(new PLink(i + "x", rng.nextFloat()));
assertTrue(inserted!=null);
assertSorted(bag);
}
bag.commit(null);
assertEquals(c, bag.size());
assertSorted(bag);
}
}
| automenta/narchy | util/src/test/java/jcog/pri/bag/BagTest.java | Java | agpl-3.0 | 10,149 |
import { Component } from '@angular/core';
import { AuthService } from './login/auth.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
mostrarMenu: boolean = false;
constructor(private authService: AuthService){
}
ngOnInit(){
this.authService.mostrarProdutoEmmiter.subscribe(
mostrar => this.mostrarMenu = mostrar
);
}
}
| ricardoroberto/TesteGrpLTM | FrontEnd/Estoque.Front/src/app/app.component.ts | TypeScript | agpl-3.0 | 470 |
#include "variableswidget.h"
#include "ui_variableswidget.h"
#include "desktoputils.h"
#include "variablespage/variablestablemodel.h"
#include <QModelIndexList>
#include <boost/foreach.hpp>
#include <algorithm>
#include <QDebug>
VariablesWidget::VariablesWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::VariablesWidget)
{
ui->setupUi(this);
_dataSet = NULL;
_currentColumn = NULL;
_levelsTableModel = new LevelsTableModel(this);
ui->labelsView->setModel(_levelsTableModel);
ui->columnheader->setText("");
(ui->labelsView->verticalHeader())->hide();
setToolTip("Double-click on a label to change it");
connect(ui->moveUpButton, SIGNAL(clicked()), this, SLOT(moveUpClicked()));
connect(ui->moveDownButton, SIGNAL(clicked()), this, SLOT(moveDownClicked()));
connect(ui->reverseButton, SIGNAL(clicked()), this, SLOT(reverseClicked()));
connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(close()));
connect(_levelsTableModel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(labelDataChanged(QModelIndex, QModelIndex)));
}
VariablesWidget::~VariablesWidget()
{
delete ui;
}
void VariablesWidget::setDataSet(DataSet *dataSet)
{
_dataSet = dataSet;
_levelsTableModel->refresh();
}
void VariablesWidget::clearDataSet()
{
_dataSet = NULL;
_currentColumn = NULL;
}
void VariablesWidget::moveUpClicked()
{
QModelIndexList selection = ui->labelsView->selectionModel()->selectedIndexes();
if (selection.length() == 0)
return;
qSort(selection.begin(), selection.end(), qLess<QModelIndex>());
if (selection.at(0).row() == 0) return;
_levelsTableModel->moveUp(selection);
// Reset Selection
ui->labelsView->clearSelection();
ui->labelsView->setSelectionMode(QAbstractItemView::MultiSelection);
BOOST_FOREACH (QModelIndex &index, selection)
{
if (index.column() == 0) {
ui->labelsView->selectRow(index.row() - 1);
}
}
//ui->labelsView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->labelsView->setSelectionMode(QAbstractItemView::ExtendedSelection);
if (_currentColumn != NULL)
emit(columnChanged(toQStr(_currentColumn->name())));
}
void VariablesWidget::moveDownClicked()
{
QModelIndexList selection = ui->labelsView->selectionModel()->selectedIndexes();
if (selection.length() == 0)
return;
qSort(selection.begin(), selection.end(), qGreater<QModelIndex>());
QModelIndex dummy = QModelIndex();
if (selection.at(0).row() >= (_levelsTableModel->rowCount(dummy) - 1)) return;
_levelsTableModel->moveDown(selection);
// Reset Selection
ui->labelsView->clearSelection();
ui->labelsView->setSelectionMode(QAbstractItemView::MultiSelection);
BOOST_FOREACH (QModelIndex &index, selection)
{
if (index.column() == 0) {
ui->labelsView->selectRow(index.row() + 1);
}
}
//ui->labelsView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->labelsView->setSelectionMode(QAbstractItemView::ExtendedSelection);
if (_currentColumn != NULL)
emit(columnChanged(toQStr(_currentColumn->name())));
}
void VariablesWidget::reverseClicked()
{
_levelsTableModel->reverse();
ui->labelsView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->labelsView->setSelectionMode(QAbstractItemView::ExtendedSelection);
if (_currentColumn != NULL)
emit(columnChanged(toQStr(_currentColumn->name())));
}
void VariablesWidget::setCurrentColumn(int columnnumber)
{
_currentColumn = &_dataSet->columns().at(columnnumber);
QString columnheader(_currentColumn->name().c_str());
_levelsTableModel->setColumn(_currentColumn);
ui->columnheader->setText("<b>" + columnheader + "</b>");
}
void VariablesWidget::labelDataChanged(QModelIndex m1, QModelIndex m2)
{
if (_currentColumn != NULL)
emit(columnChanged(toQStr(_currentColumn->name())));
emit(resetTableView());
}
| aknight1-uva/jasp-desktop | JASP-Desktop/variableswidget.cpp | C++ | agpl-3.0 | 3,776 |
"""
Views related to course groups functionality.
"""
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.decorators.http import require_POST
from django.contrib.auth.models import User
from django.core.paginator import Paginator, EmptyPage
from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponseBadRequest
from django.views.decorators.http import require_http_methods
from util.json_request import expect_json, JsonResponse
from django.db import transaction
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext
import logging
import re
from opaque_keys.edx.keys import CourseKey
from opaque_keys.edx.locations import SlashSeparatedCourseKey
from courseware.courses import get_course_with_access
from edxmako.shortcuts import render_to_response
from . import cohorts
from lms.djangoapps.django_comment_client.utils import get_discussion_category_map, get_discussion_categories_ids
from lms.djangoapps.django_comment_client.constants import TYPE_ENTRY
from .models import CourseUserGroup, CourseUserGroupPartitionGroup, CohortMembership
log = logging.getLogger(__name__)
def json_http_response(data):
"""
Return an HttpResponse with the data json-serialized and the right content
type header.
"""
return JsonResponse(data)
def split_by_comma_and_whitespace(cstr):
"""
Split a string both by commas and whitespace. Returns a list.
"""
return re.split(r'[\s,]+', cstr)
def link_cohort_to_partition_group(cohort, partition_id, group_id):
"""
Create cohort to partition_id/group_id link.
"""
CourseUserGroupPartitionGroup(
course_user_group=cohort,
partition_id=partition_id,
group_id=group_id,
).save()
def unlink_cohort_partition_group(cohort):
"""
Remove any existing cohort to partition_id/group_id link.
"""
CourseUserGroupPartitionGroup.objects.filter(course_user_group=cohort).delete()
# pylint: disable=invalid-name
def _get_course_cohort_settings_representation(course, course_cohort_settings):
"""
Returns a JSON representation of a course cohort settings.
"""
cohorted_course_wide_discussions, cohorted_inline_discussions = get_cohorted_discussions(
course, course_cohort_settings
)
return {
'id': course_cohort_settings.id,
'is_cohorted': course_cohort_settings.is_cohorted,
'cohorted_inline_discussions': cohorted_inline_discussions,
'cohorted_course_wide_discussions': cohorted_course_wide_discussions,
'always_cohort_inline_discussions': course_cohort_settings.always_cohort_inline_discussions,
}
def _get_cohort_representation(cohort, course):
"""
Returns a JSON representation of a cohort.
"""
group_id, partition_id = cohorts.get_group_info_for_cohort(cohort)
assignment_type = cohorts.get_assignment_type(cohort)
return {
'name': cohort.name,
'id': cohort.id,
'user_count': cohort.users.filter(courseenrollment__course_id=course.location.course_key,
courseenrollment__is_active=1).count(),
'assignment_type': assignment_type,
'user_partition_id': partition_id,
'group_id': group_id,
}
def get_cohorted_discussions(course, course_settings):
"""
Returns the course-wide and inline cohorted discussion ids separately.
"""
cohorted_course_wide_discussions = []
cohorted_inline_discussions = []
course_wide_discussions = [topic['id'] for __, topic in course.discussion_topics.items()]
all_discussions = get_discussion_categories_ids(course, None, include_all=True)
for cohorted_discussion_id in course_settings.cohorted_discussions:
if cohorted_discussion_id in course_wide_discussions:
cohorted_course_wide_discussions.append(cohorted_discussion_id)
elif cohorted_discussion_id in all_discussions:
cohorted_inline_discussions.append(cohorted_discussion_id)
return cohorted_course_wide_discussions, cohorted_inline_discussions
@require_http_methods(("GET", "PATCH"))
@ensure_csrf_cookie
@expect_json
@login_required
def course_cohort_settings_handler(request, course_key_string):
"""
The restful handler for cohort setting requests. Requires JSON.
This will raise 404 if user is not staff.
GET
Returns the JSON representation of cohort settings for the course.
PATCH
Updates the cohort settings for the course. Returns the JSON representation of updated settings.
"""
course_key = CourseKey.from_string(course_key_string)
course = get_course_with_access(request.user, 'staff', course_key)
cohort_settings = cohorts.get_course_cohort_settings(course_key)
if request.method == 'PATCH':
cohorted_course_wide_discussions, cohorted_inline_discussions = get_cohorted_discussions(
course, cohort_settings
)
settings_to_change = {}
if 'is_cohorted' in request.json:
settings_to_change['is_cohorted'] = request.json.get('is_cohorted')
if 'cohorted_course_wide_discussions' in request.json or 'cohorted_inline_discussions' in request.json:
cohorted_course_wide_discussions = request.json.get(
'cohorted_course_wide_discussions', cohorted_course_wide_discussions
)
cohorted_inline_discussions = request.json.get(
'cohorted_inline_discussions', cohorted_inline_discussions
)
settings_to_change['cohorted_discussions'] = cohorted_course_wide_discussions + cohorted_inline_discussions
if 'always_cohort_inline_discussions' in request.json:
settings_to_change['always_cohort_inline_discussions'] = request.json.get(
'always_cohort_inline_discussions'
)
if not settings_to_change:
return JsonResponse({"error": unicode("Bad Request")}, 400)
try:
cohort_settings = cohorts.set_course_cohort_settings(
course_key, **settings_to_change
)
except ValueError as err:
# Note: error message not translated because it is not exposed to the user (UI prevents this state).
return JsonResponse({"error": unicode(err)}, 400)
return JsonResponse(_get_course_cohort_settings_representation(course, cohort_settings))
@require_http_methods(("GET", "PUT", "POST", "PATCH"))
@ensure_csrf_cookie
@expect_json
@login_required
def cohort_handler(request, course_key_string, cohort_id=None):
"""
The restful handler for cohort requests. Requires JSON.
GET
If a cohort ID is specified, returns a JSON representation of the cohort
(name, id, user_count, assignment_type, user_partition_id, group_id).
If no cohort ID is specified, returns the JSON representation of all cohorts.
This is returned as a dict with the list of cohort information stored under the
key `cohorts`.
PUT or POST or PATCH
If a cohort ID is specified, updates the cohort with the specified ID. Currently the only
properties that can be updated are `name`, `user_partition_id` and `group_id`.
Returns the JSON representation of the updated cohort.
If no cohort ID is specified, creates a new cohort and returns the JSON representation of the updated
cohort.
"""
course_key = SlashSeparatedCourseKey.from_deprecated_string(course_key_string)
course = get_course_with_access(request.user, 'staff', course_key)
if request.method == 'GET':
if not cohort_id:
all_cohorts = [
_get_cohort_representation(c, course)
for c in cohorts.get_course_cohorts(course)
]
return JsonResponse({'cohorts': all_cohorts})
else:
cohort = cohorts.get_cohort_by_id(course_key, cohort_id)
return JsonResponse(_get_cohort_representation(cohort, course))
else:
name = request.json.get('name')
assignment_type = request.json.get('assignment_type')
if not name:
# Note: error message not translated because it is not exposed to the user (UI prevents this state).
return JsonResponse({"error": "Cohort name must be specified."}, 400)
if not assignment_type:
# Note: error message not translated because it is not exposed to the user (UI prevents this state).
return JsonResponse({"error": "Assignment type must be specified."}, 400)
# If cohort_id is specified, update the existing cohort. Otherwise, create a new cohort.
if cohort_id:
cohort = cohorts.get_cohort_by_id(course_key, cohort_id)
if name != cohort.name:
if cohorts.is_cohort_exists(course_key, name):
err_msg = ugettext("A cohort with the same name already exists.")
return JsonResponse({"error": unicode(err_msg)}, 400)
cohort.name = name
cohort.save()
try:
cohorts.set_assignment_type(cohort, assignment_type)
except ValueError as err:
return JsonResponse({"error": unicode(err)}, 400)
else:
try:
cohort = cohorts.add_cohort(course_key, name, assignment_type)
except ValueError as err:
return JsonResponse({"error": unicode(err)}, 400)
group_id = request.json.get('group_id')
if group_id is not None:
user_partition_id = request.json.get('user_partition_id')
if user_partition_id is None:
# Note: error message not translated because it is not exposed to the user (UI prevents this state).
return JsonResponse(
{"error": "If group_id is specified, user_partition_id must also be specified."}, 400
)
existing_group_id, existing_partition_id = cohorts.get_group_info_for_cohort(cohort)
if group_id != existing_group_id or user_partition_id != existing_partition_id:
unlink_cohort_partition_group(cohort)
link_cohort_to_partition_group(cohort, user_partition_id, group_id)
else:
# If group_id was specified as None, unlink the cohort if it previously was associated with a group.
existing_group_id, _ = cohorts.get_group_info_for_cohort(cohort)
if existing_group_id is not None:
unlink_cohort_partition_group(cohort)
return JsonResponse(_get_cohort_representation(cohort, course))
@ensure_csrf_cookie
def users_in_cohort(request, course_key_string, cohort_id):
"""
Return users in the cohort. Show up to 100 per page, and page
using the 'page' GET attribute in the call. Format:
Returns:
Json dump of dictionary in the following format:
{'success': True,
'page': page,
'num_pages': paginator.num_pages,
'users': [{'username': ..., 'email': ..., 'name': ...}]
}
"""
# this is a string when we get it here
course_key = SlashSeparatedCourseKey.from_deprecated_string(course_key_string)
get_course_with_access(request.user, 'staff', course_key)
# this will error if called with a non-int cohort_id. That's ok--it
# shouldn't happen for valid clients.
cohort = cohorts.get_cohort_by_id(course_key, int(cohort_id))
paginator = Paginator(cohort.users.all(), 100)
try:
page = int(request.GET.get('page'))
except (TypeError, ValueError):
# These strings aren't user-facing so don't translate them
return HttpResponseBadRequest('Requested page must be numeric')
else:
if page < 0:
return HttpResponseBadRequest('Requested page must be greater than zero')
try:
users = paginator.page(page)
except EmptyPage:
users = [] # When page > number of pages, return a blank page
user_info = [{'username': u.username,
'email': u.email,
'name': '{0} {1}'.format(u.first_name, u.last_name)}
for u in users]
return json_http_response({'success': True,
'page': page,
'num_pages': paginator.num_pages,
'users': user_info})
@transaction.non_atomic_requests
@ensure_csrf_cookie
@require_POST
def add_users_to_cohort(request, course_key_string, cohort_id):
"""
Return json dict of:
{'success': True,
'added': [{'username': ...,
'name': ...,
'email': ...}, ...],
'changed': [{'username': ...,
'name': ...,
'email': ...,
'previous_cohort': ...}, ...],
'present': [str1, str2, ...], # already there
'unknown': [str1, str2, ...]}
Raises Http404 if the cohort cannot be found for the given course.
"""
# this is a string when we get it here
course_key = SlashSeparatedCourseKey.from_deprecated_string(course_key_string)
get_course_with_access(request.user, 'staff', course_key)
try:
cohort = cohorts.get_cohort_by_id(course_key, cohort_id)
except CourseUserGroup.DoesNotExist:
raise Http404("Cohort (ID {cohort_id}) not found for {course_key_string}".format(
cohort_id=cohort_id,
course_key_string=course_key_string
))
users = request.POST.get('users', '')
added = []
changed = []
present = []
unknown = []
for username_or_email in split_by_comma_and_whitespace(users):
if not username_or_email:
continue
try:
(user, previous_cohort) = cohorts.add_user_to_cohort(cohort, username_or_email)
info = {
'username': user.username,
'email': user.email,
}
if previous_cohort:
info['previous_cohort'] = previous_cohort
changed.append(info)
else:
added.append(info)
except ValueError:
present.append(username_or_email)
except User.DoesNotExist:
unknown.append(username_or_email)
return json_http_response({'success': True,
'added': added,
'changed': changed,
'present': present,
'unknown': unknown})
@ensure_csrf_cookie
@require_POST
def remove_user_from_cohort(request, course_key_string, cohort_id):
"""
Expects 'username': username in POST data.
Return json dict of:
{'success': True} or
{'success': False,
'msg': error_msg}
"""
# this is a string when we get it here
course_key = SlashSeparatedCourseKey.from_deprecated_string(course_key_string)
get_course_with_access(request.user, 'staff', course_key)
username = request.POST.get('username')
if username is None:
return json_http_response({'success': False,
'msg': 'No username specified'})
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
log.debug('no user')
return json_http_response({'success': False,
'msg': "No user '{0}'".format(username)})
try:
membership = CohortMembership.objects.get(user=user, course_id=course_key)
membership.delete()
except CohortMembership.DoesNotExist:
pass
return json_http_response({'success': True})
def debug_cohort_mgmt(request, course_key_string):
"""
Debugging view for dev.
"""
# this is a string when we get it here
course_key = SlashSeparatedCourseKey.from_deprecated_string(course_key_string)
# add staff check to make sure it's safe if it's accidentally deployed.
get_course_with_access(request.user, 'staff', course_key)
context = {'cohorts_url': reverse(
'cohorts',
kwargs={'course_key': course_key.to_deprecated_string()}
)}
return render_to_response('/course_groups/debug.html', context)
@expect_json
@login_required
def cohort_discussion_topics(request, course_key_string):
"""
The handler for cohort discussion categories requests.
This will raise 404 if user is not staff.
Returns the JSON representation of discussion topics w.r.t categories for the course.
Example:
>>> example = {
>>> "course_wide_discussions": {
>>> "entries": {
>>> "General": {
>>> "sort_key": "General",
>>> "is_cohorted": True,
>>> "id": "i4x-edx-eiorguegnru-course-foobarbaz"
>>> }
>>> }
>>> "children": ["General", "entry"]
>>> },
>>> "inline_discussions" : {
>>> "subcategories": {
>>> "Getting Started": {
>>> "subcategories": {},
>>> "children": [
>>> ["Working with Videos", "entry"],
>>> ["Videos on edX", "entry"]
>>> ],
>>> "entries": {
>>> "Working with Videos": {
>>> "sort_key": None,
>>> "is_cohorted": False,
>>> "id": "d9f970a42067413cbb633f81cfb12604"
>>> },
>>> "Videos on edX": {
>>> "sort_key": None,
>>> "is_cohorted": False,
>>> "id": "98d8feb5971041a085512ae22b398613"
>>> }
>>> }
>>> },
>>> "children": ["Getting Started", "subcategory"]
>>> },
>>> }
>>> }
"""
course_key = CourseKey.from_string(course_key_string)
course = get_course_with_access(request.user, 'staff', course_key)
discussion_topics = {}
discussion_category_map = get_discussion_category_map(
course, request.user, cohorted_if_in_list=True, exclude_unstarted=False
)
# We extract the data for the course wide discussions from the category map.
course_wide_entries = discussion_category_map.pop('entries')
course_wide_children = []
inline_children = []
for name, c_type in discussion_category_map['children']:
if name in course_wide_entries and c_type == TYPE_ENTRY:
course_wide_children.append([name, c_type])
else:
inline_children.append([name, c_type])
discussion_topics['course_wide_discussions'] = {
'entries': course_wide_entries,
'children': course_wide_children
}
discussion_category_map['children'] = inline_children
discussion_topics['inline_discussions'] = discussion_category_map
return JsonResponse(discussion_topics)
| romain-li/edx-platform | openedx/core/djangoapps/course_groups/views.py | Python | agpl-3.0 | 19,604 |
/*
* GCWBaseContainerComponent.cpp
*
* Created on: Jan 24, 2013
* Author: root
*/
#include "GCWBaseContainerComponent.h"
#include "templates/params/creature/CreatureFlag.h"
bool GCWBaseContainerComponent::checkContainerPermission(SceneObject* sceneObject, CreatureObject* creature, uint16 permission) const {
ManagedReference<BuildingObject*> building = cast<BuildingObject*>(sceneObject);
if (building == NULL)
return false;
return checkContainerPermission(building, creature, permission, false);
}
bool GCWBaseContainerComponent::checkContainerPermission(BuildingObject* building, CreatureObject* creature, uint16 permission, bool sendMessage) const {
if (permission == ContainerPermissions::WALKIN) {
if (building == NULL) {
return false;
}
if (creature->isPlayerCreature() && creature->getPlayerObject()->hasGodMode())
return true;
if (building->getPvpStatusBitmask() & CreatureFlag::OVERT) {
return checkPVPPermission( building, creature, permission, sendMessage);
} else {
return checkPVEPermission(building, creature, permission, sendMessage);
}
}
return StructureContainerComponent::checkContainerPermission(building, creature, permission);
}
bool GCWBaseContainerComponent::checkPVPPermission(BuildingObject* building, CreatureObject* creature, uint16 permission, bool sendMessage) const {
PlayerObject* player = creature->getPlayerObject();
if (player == NULL) {
return false;
}
if (creature->getFaction() == 0) {
if (sendMessage)
creature->sendSystemMessage("@faction/faction_hq/faction_hq_response:youre_neutral_excluded"); // This is a restricted access military structure, and you haven't aligned yourself with the military. You are not cleared to enter.
return false;
}
if (player->getFactionStatus() != FactionStatus::OVERT) {
if (sendMessage)
creature->sendSystemMessage("@faction/faction_hq/faction_hq_response:youre_covert_excluded"); // You must be a member of the Special Forces to enter this structure.
return false;
}
if (creature->getFaction() == building->getFaction()) {
return true;
}
DataObjectComponentReference* data = building->getDataObjectComponent();
DestructibleBuildingDataComponent* baseData = NULL;
if (data != NULL) {
baseData = cast<DestructibleBuildingDataComponent*>(data->get());
}
if (baseData == NULL)
return false;
if (!baseData->hasDefense()) {
return true;
} else {
if (sendMessage)
creature->sendSystemMessage("@faction_perk:destroy_turrets"); // You cannot enter this HQ until all Turrets have been destroyed.
return false;
}
}
bool GCWBaseContainerComponent::checkPVEPermission(BuildingObject* building, CreatureObject* creature, uint16 permission, bool sendMessage) const {
PlayerObject* player = creature->getPlayerObject();
if (player == NULL) {
return false;
}
if (creature->getFaction() == 0) {
if (sendMessage)
creature->sendSystemMessage("@faction/faction_hq/faction_hq_response:youre_neutral_excluded"); // This is a restricted access military structure, and you haven't aligned yourself with the military. You are not cleared to enter.
return false;
}
if ((player->getFactionStatus() != FactionStatus::COVERT && player->getFactionStatus() != FactionStatus::OVERT)) {
if (sendMessage)
creature->sendSystemMessage("You must be at least a combatant to enter");
return false;
}
if (creature->getFaction() == building->getFaction()) {
return true;
}
DataObjectComponentReference* data = building->getDataObjectComponent();
DestructibleBuildingDataComponent* baseData = NULL;
if (data != NULL) {
baseData = cast<DestructibleBuildingDataComponent*>(data->get());
}
if (baseData != NULL) {
if (!baseData->hasDefense()) {
return true;
} else {
if (sendMessage)
creature->sendSystemMessage("@faction_perk:destroy_turrets"); // You cannot enter this HQ until all Turrets have been destroyed.
return false;
}
} else {
if (creature->getFaction() != building->getFaction()) {
return false;
}
}
return true;
}
| Tatwi/legend-of-hondo | MMOCoreORB/src/server/zone/objects/building/components/GCWBaseContainerComponent.cpp | C++ | agpl-3.0 | 4,046 |
# Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013 The Collaborative Software Foundation
#
# This file is part of TriSano.
#
# TriSano 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.
#
# TriSano 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 TriSano. If not, see http://www.gnu.org/licenses/agpl-3.0.txt.
When(/^I navigate to the new morbidity event page and start a simple event$/) do
@browser.open "/trisano/cmrs/new"
add_demographic_info(@browser, { :last_name => get_unique_name })
@browser.type('morbidity_event_first_reported_PH_date', Date.today)
end
When(/^I navigate to the new assessment event page and start a simple event$/) do
@browser.open "/trisano/aes/new"
add_demographic_info(@browser, { :last_name => get_unique_name })
@browser.type('assessment_event_first_reported_PH_date', Date.today)
end
When /^I go to the new CMR page$/ do
@browser.open "/trisano/cmrs/new"
@browser.wait_for_page_to_load
end
When(/^I navigate to the morbidity event edit page$/) do
@browser.click "link=EVENTS"
@browser.wait_for_page_to_load $load_time
@browser.click "link=Edit"
@browser.wait_for_page_to_load $load_time
end
When(/^I navigate to the assessment event edit page$/) do
@browser.click "link=EVENTS"
@browser.wait_for_page_to_load $load_time
@browser.click "link=Edit"
@browser.wait_for_page_to_load $load_time
end
When(/^I am on the assessment event edit page$/) do
@browser.open "/trisano/aes/#{(@event).id}/edit"
@browser.wait_for_page_to_load
end
When(/^I am on the morbidity event edit page$/) do
@browser.open "/trisano/cmrs/#{(@event).id}/edit"
@browser.wait_for_page_to_load
end
When(/^I am on the morbidity event show page$/) do
@browser.open "/trisano/cmrs/#{(@event).id}"
@browser.wait_for_page_to_load
end
# Consider refactoring the name of this one -- it really isn't
# navigating, it's more like a "when I am on" -- doesn't 'I am on'
# imply a verification that you are already there?
When(/^I navigate to the morbidity event show page$/) do
@browser.open "/trisano/cmrs/#{(@event).id}"
@browser.wait_for_page_to_load
end
When(/^I navigate to the assessment event show page$/) do
@browser.open "/trisano/aes/#{(@event).id}"
@browser.wait_for_page_to_load
end
When /^I am on the events index page$/ do
@browser.open "/trisano/events"
@browser.wait_for_page_to_load
end
When(/^I am on the contact event edit page$/) do
@browser.open "/trisano/contact_events/#{@contact_event.id}/edit"
@browser.wait_for_page_to_load
end
When /^I navigate to the contact event edit page$/ do
When "I am on the contact event edit page"
end
When /^I navigate to the encounter event edit page$/ do
@browser.open "/trisano/encounter_events/#{(@encounter_event).id}/edit"
@browser.wait_for_page_to_load
end
When /^I am on the encounter event edit page$/ do
When "I navigate to the encounter event edit page"
end
When /^I navigate to the contact named "(.+)"$/ do |last_name|
@contact_event = ContactEvent.first(:include => { :interested_party => { :person_entity => :person } },
:conditions => ['people.last_name = ?', last_name])
@browser.open "/trisano/contact_events/#{@contact_event.id}/edit"
@browser.wait_for_page_to_load
end
When /^I select "([^\"]*)" from the sibling navigator$/ do |option_text|
@browser.select "css=.events_nav", option_text
@browser.wait_for_page_to_load
end
When /^I select "([^\"]*)" from the sibling navigator and Save$/ do |option_text|
@browser.select "css=.events_nav", option_text
@browser.wait_for_element_present "//button/span[contains(text(), 'Save')]"
@browser.click "//button/span[contains(text(), 'Save')]"
@browser.wait_for_page_to_load
end
When /^I select "([^\"]*)" from the sibling navigator and leave without saving$/ do |option_text|
@browser.select "css=.events_nav", option_text
@browser.wait_for_element_present "//button/span[contains(text(), 'Leave')]"
@browser.click "//button/span[contains(text(), 'Leave')]"
@browser.wait_for_page_to_load
end
When /^I select "([^\"]*)" from the sibling navigator but cancel the dialog$/ do |option_text|
@browser.select "css=.events_nav", option_text
@browser.wait_for_element_present "//a/span[contains(text(), 'close')]"
@browser.click "//a/span[contains(text(), 'close')]"
end
Then /^I should be on the contact named "([^\"]*)"$/ do |last_name|
@contact_event = ContactEvent.first(:include => { :interested_party => { :person_entity => :person } },
:conditions => ['people.last_name = ?', last_name])
@browser.get_location.should =~ /trisano\/contact_events\/#{@contact_event.id}\/edit/
end
When /^I enter "([^\"]*)" as the contact\'s first name$/ do |text|
@browser.type("css=#contact_event_interested_party_attributes_person_entity_attributes_person_attributes_first_name",
text)
end
Then /^no value should be selected in the sibling navigator$/ do
script = "selenium.browserbot.getCurrentWindow().$j('.events_nav').val();"
@browser.get_eval(script).should == ""
end
When(/^I am on the place event edit page$/) do
@browser.open "/trisano/place_events/#{(@place_event).id}/edit"
@browser.wait_for_page_to_load
end
When /^I save and continue$/ do
@browser.click("//*[@id='save_and_continue_btn']")
@browser.wait_for_page_to_load
end
When /^I save and exit$/ do
@browser.click("//*[@id='save_and_exit_btn']")
@browser.wait_for_page_to_load
end
Then /^events list should show (\d+) events$/ do |expected_count|
@browser.get_xpath_count("//div[@class='patientname']").should == expected_count
end
Given /^a clean events table$/ do
Address.destroy_all
ParticipationsRiskFactor.destroy_all
Participation.destroy_all
Task.destroy_all
Event.destroy_all
end
After('@clean_events') do
Address.all.each(&:delete)
ParticipationsRiskFactor.destroy_all
Participation.destroy_all
Task.destroy_all
Event.all.each(&:delete)
end
When /^I scroll down a bit$/ do
script = "selenium.browserbot.getCurrentWindow().$j(window).scrollTop(300);"
@browser.get_eval(script).should == "[object Window]" # Just making sure the script ran
end
Then /^I should have been scrolled back to the top of the page$/ do
script = "selenium.browserbot.getCurrentWindow().$j(window).scrollTop();"
@browser.get_eval(script).should == "0"
end
Then /^I should have a note that says "([^\"]*)"$/ do |text|
@browser.get_xpath_count("//div[@id='existing-notes']//p[contains(text(), '#{text}')]").to_i.should >= 1
end
When /^I enter a valid first reported to public health date$/ do
@browser.type('morbidity_event_first_reported_PH_date', Date.today)
end
When /^I enter basic CMR data$/ do
@browser.type 'morbidity_event_interested_party_attributes_person_entity_attributes_person_attributes_last_name', 'Smoker'
When %{I enter a valid first reported to public health date}
end
| csinitiative/trisano | webapp/features/enhanced_step_definitions/event_steps.rb | Ruby | agpl-3.0 | 7,381 |
/*
*/
/*
* Copyright (C) 2015-present ScyllaDB
*
* Modified by ScyllaDB
*/
/*
* SPDX-License-Identifier: (AGPL-3.0-or-later and Apache-2.0)
*/
#pragma once
#include <iostream>
namespace db {
enum class read_repair_decision {
NONE,
GLOBAL,
DC_LOCAL
};
inline std::ostream& operator<<(std::ostream& out, db::read_repair_decision d) {
switch (d) {
case db::read_repair_decision::NONE: out << "NONE"; break;
case db::read_repair_decision::GLOBAL: out << "GLOBAL"; break;
case db::read_repair_decision::DC_LOCAL: out << "DC_LOCAL"; break;
default: out << "ERR"; break;
}
return out;
}
}
| scylladb/scylla | db/read_repair_decision.hh | C++ | agpl-3.0 | 632 |
/* Copyright (C) 2007-2017 Patrick G. Durand
*
* 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.
*
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/agpl-3.0.txt
*
* 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.
*/
package bzh.plealog.dbmirror.lucenedico.go;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import bzh.plealog.dbmirror.indexer.ParserMonitor;
import bzh.plealog.dbmirror.lucenedico.DicoParsable;
import bzh.plealog.dbmirror.lucenedico.DicoParserException;
import bzh.plealog.dbmirror.lucenedico.DicoStorageSystem;
import bzh.plealog.dbmirror.lucenedico.DicoUtils;
import bzh.plealog.dbmirror.util.Utils;
import bzh.plealog.dbmirror.util.conf.DBMSAbstractConfig;
/**
* Class which parses obo file and create, for each of terms a GeneOntologyTerm
* containing the name, the GO id, the ontology and the parents of the term.
*
* @author Patrick G. Durand
*
*/
public class GeneOntologyOBONodeParser implements DicoParsable {
// terms of the obo file
private HashMap<String, GeneOntologyTerm> _nodes = new HashMap<String, GeneOntologyTerm>();
private ParserMonitor _pMonitor;
private boolean _verbose = true;
private int _entries;
private static final Log LOGGER = LogFactory
.getLog(DBMSAbstractConfig.KDMS_ROOTLOG_CATEGORY
+ ".GeneOntologyOBONodeParser");
private static final String ROOT_GO = "GO:0003673";
private static final String ROOT_NAME = "Gene_Ontology";
private static final String BIO_PRO_GO = "GO:0008150";
private static final String BIO_PRO_ONT = "biological_process";
private static final String MOL_FUNC_GO = "GO:0003674";
private static final String MOL_FUNC_ONT = "molecular_function";
private static final String CELL_COMP_GO = "GO:0005575";
private static final String CELL_COMP_ONT = "cellular_component";
private static final String OBSO_BIOPRO_GO = "obsolete_Bp";
private static final String OBSO_BIOPRO_NAME = "obsolete_biological_process";
private static final String OBSO_MOLFUNC_GO = "obsolete_Mf";
private static final String OBSO_MOLFUNC_NAME = "obsolete_molecular_function";
private static final String OBSO_CELLCOMP_GO = "obsolete_Cc";
private static final String OBSO_CELLCOMP_NAME = "obsolete_cellular_component";
private static final String TERM = "[Term]";
private static final String ID = "id:";
private static final String NAME = "name:";
private static final String IS_OBSOLETE = "is_obsolete:";
private static final String NAMESPACE = "namespace:";
private static final String IS_A = "is_a:";
private static final String RELATIONSHIP = "relationship:";
private static final String PART_OF = "part_of";
private static final String REGULATES = "regulates";
private static final String POSITIVELY_REGULATES = "positively_regulates";
private static final String NEGATIVELY_REGULATES = "negatively_regulates";
private static final String TYPE_DEF = "[Typedef]";
private static final String ALT_ID = "alt_id";
private static final int IS_A_LENGTH = IS_A
.length();
private static final int PART_OF_LENGTH = PART_OF
.length();
private static final int REGULATES_LENGTH = REGULATES
.length();
private static final int POSITIVELY_REGULATES_LENGTH = POSITIVELY_REGULATES
.length();
private static final int NEGATIVELY_REGULATES_LENGTH = NEGATIVELY_REGULATES
.length();
private static final int RELATIONSHIP_LENGTH = RELATIONSHIP
.length();
public GeneOntologyOBONodeParser() {
_nodes = new HashMap<String, GeneOntologyTerm>();
_verbose = false;
_entries = 0;
}
/**
* Implementation of DicoParsable interface.
*/
public void setParserMonitor(ParserMonitor pm) {
_pMonitor = pm;
}
/**
* Initialize the root of the gene Ontology graph. [R O O T] / | \ bio_pro
* mol_func cell_comp | | | obso_bp obso_mf obso_cc
*/
private void initStructure() {
GeneOntologyTerm root = new GeneOntologyTerm(ROOT_GO, ROOT_NAME, null);
_nodes.put(ROOT_GO, root);
GeneOntologyTerm bio_p = new GeneOntologyTerm(BIO_PRO_GO, BIO_PRO_ONT,
BIO_PRO_ONT);
bio_p.add_parent(root, GeneOntologyTermRelationship.TYPE_EDGE.K);
_nodes.put(BIO_PRO_GO, bio_p);
GeneOntologyTerm mol_fun = new GeneOntologyTerm(MOL_FUNC_GO, MOL_FUNC_ONT,
MOL_FUNC_ONT);
mol_fun.add_parent(root, GeneOntologyTermRelationship.TYPE_EDGE.K);
_nodes.put(MOL_FUNC_GO, mol_fun);
GeneOntologyTerm cell_comp = new GeneOntologyTerm(CELL_COMP_GO,
CELL_COMP_ONT, CELL_COMP_ONT);
cell_comp.add_parent(root, GeneOntologyTermRelationship.TYPE_EDGE.K);
_nodes.put(CELL_COMP_GO, cell_comp);
GeneOntologyTerm o_bp = new GeneOntologyTerm(OBSO_BIOPRO_GO,
OBSO_BIOPRO_NAME, BIO_PRO_ONT);
o_bp.add_parent(bio_p, GeneOntologyTermRelationship.TYPE_EDGE.K);
_nodes.put(OBSO_BIOPRO_GO, o_bp);
GeneOntologyTerm o_mf = new GeneOntologyTerm(OBSO_MOLFUNC_GO,
OBSO_MOLFUNC_NAME, MOL_FUNC_ONT);
o_mf.add_parent(mol_fun, GeneOntologyTermRelationship.TYPE_EDGE.K);
_nodes.put(OBSO_MOLFUNC_GO, o_mf);
GeneOntologyTerm o_cc = new GeneOntologyTerm(OBSO_CELLCOMP_GO,
OBSO_CELLCOMP_NAME, CELL_COMP_ONT);
o_cc.add_parent(cell_comp, GeneOntologyTermRelationship.TYPE_EDGE.K);
_nodes.put(OBSO_CELLCOMP_GO, o_cc);
_entries = 6;
}
/**
* Create and inquire the differents fields of the GeneOntologyTerm created
* from parsed term.
*
* @param file
* the file ro process
* @param goIdTerm
* GO id of the term obtained by the "id" field
* @param nameAndOntology
* of the term obtained by the "name" field
* @param id_parent
* fathers of the term obtained by the "is_a/part_of/regulate" field
* @param edge
* type of the link between a term's parent and the term. depends on
* "is_a/part_of/regulate" field
* @param alternative_id
* alternative GO id of the term obtained by the "alt_id" field
* @param curPos
* current position in the file (butes)
*/
private void handleData(String file, String goIdTerm, String nameAndOntology,
ArrayList<String> id_parent,
ArrayList<GeneOntologyTermRelationship.TYPE_EDGE> edge,
ArrayList<String> alternative_id, long curPos) {
GeneOntologyTerm son;
GeneOntologyTerm father;
// Ignore the root to avoid bugs
if (goIdTerm != null && !goIdTerm.equals(ROOT_GO)
&& nameAndOntology != null) {
if (!_nodes.containsKey(goIdTerm)) {
son = new GeneOntologyTerm(goIdTerm, nameAndOntology);
_nodes.put(goIdTerm, son);
} else if (_nodes.get(goIdTerm).get_node_name() == null) {
son = _nodes.get(goIdTerm);
son.set_node_ontology(nameAndOntology);
son.set_node_name(nameAndOntology);
son.set_node_nameAndOntology(nameAndOntology);
} else {
son = _nodes.get(goIdTerm);
}
if (_pMonitor != null) {
_pMonitor.seqFound(goIdTerm, nameAndOntology, file, curPos, curPos,
false);
}
// For each father of the term scanned
for (int i = 0; i < id_parent.size(); i++) {
if (!_nodes.containsKey(id_parent.get(i))) {
father = new GeneOntologyTerm(id_parent.get(i));
son.add_parent(father, edge.get(i));
_nodes.put(father.get_node_id(), father);
} else {
father = _nodes.get(id_parent.get(i));
// add the father to the fatherlist of the current term and add the
// current term as son in the sonlist of the father term
son.add_parent(father, edge.get(i));
}
}
if (!alternative_id.isEmpty()) {
for (String alt_id : alternative_id) {
_nodes.put(alt_id, son);
}
}
if (_verbose && (_entries % 5000) == 0) {
System.out.println("Nb term parsed: " + _entries);
}
}
}
public static String prepareTerm(String name, String ontology) {
StringBuffer buf = new StringBuffer();
buf.delete(0, buf.length());
buf.append(DicoUtils.GO_NAME_KEY);
buf.append(name);
buf.append("|");
buf.append(DicoUtils.GO_ONTO_KEY);
if (ontology != null)
buf.append(ontology);
else
buf.append("unknown");
return buf.toString();
}
/**
* Parse the obo file
*/
public void parse(String file, DicoStorageSystem ss)
throws DicoParserException {
BufferedReader reader = null;
String line;
String go_iD = null;
String go_name = null;
String type = null;
String termPrepared;
String alt_id_term;
String ontology = null;
ArrayList<String> go_parent = new ArrayList<String>();
ArrayList<GeneOntologyTermRelationship.TYPE_EDGE> typeEdge = new ArrayList<GeneOntologyTermRelationship.TYPE_EDGE>();
ArrayList<String> alt_id = new ArrayList<String>();
int endOfLineSize, termCounter = 0;
long curPos = 0;
boolean stop = false;
try {
_entries = 0;
initStructure();
endOfLineSize = Utils.getLineTerminatorSize(file);
reader = new BufferedReader(new InputStreamReader(new FileInputStream(
file), "UTF-8"));
if (_pMonitor != null) {
_pMonitor.startProcessingFile(file, new File(file).length());
}
while ((line = reader.readLine()) != null && !stop) {
if (line.startsWith(TERM)) {
termCounter++;
termPrepared = prepareTerm(go_name, ontology);
handleData(file, go_iD, termPrepared, go_parent, typeEdge, alt_id,
curPos);
go_iD = ontology = go_name = type = null;
go_parent.clear();
typeEdge.clear();
alt_id.clear();
} else if (line.startsWith(ID)) {
go_iD = line.substring(3).trim();
} else if (line.startsWith(NAME)) {
go_name = line.substring(5).trim();
} else if (line.startsWith(NAMESPACE)) {
ontology = line.substring(10).trim();
} else if (line.startsWith(IS_OBSOLETE)) {
typeEdge.add(GeneOntologyTermRelationship.TYPE_EDGE.O);
if (ontology.equals(BIO_PRO_ONT)) {
go_parent.add(OBSO_BIOPRO_GO);
} else if (ontology.equals(MOL_FUNC_ONT)) {
go_parent.add(OBSO_MOLFUNC_GO);
} else if (ontology.equals(CELL_COMP_GO)) {
go_parent.add(OBSO_CELLCOMP_GO);
}
} else if (line.startsWith(IS_A)) {
typeEdge.add(GeneOntologyTermRelationship.TYPE_EDGE.I);
type = line.substring(IS_A_LENGTH + 1).trim().split("!")[0].trim();
go_parent.add(type);
} else if (line.startsWith(RELATIONSHIP)) {
type = line.substring(RELATIONSHIP_LENGTH + 1).trim().split("!")[0]
.trim();
if (type.startsWith(PART_OF)) {
typeEdge.add(GeneOntologyTermRelationship.TYPE_EDGE.P);
go_parent.add(type.substring(PART_OF_LENGTH + 1));
} else if (type.startsWith(REGULATES)) {
typeEdge.add(GeneOntologyTermRelationship.TYPE_EDGE.R);
go_parent.add(type.substring(REGULATES_LENGTH + 1));
} else if (type.startsWith(POSITIVELY_REGULATES)) {
typeEdge.add(GeneOntologyTermRelationship.TYPE_EDGE.U);
go_parent.add(type.substring(POSITIVELY_REGULATES_LENGTH + 1));
} else if (type.startsWith(NEGATIVELY_REGULATES)) {
typeEdge.add(GeneOntologyTermRelationship.TYPE_EDGE.N);
go_parent.add(type.substring(NEGATIVELY_REGULATES_LENGTH + 1));
}
} else if (line.startsWith(TYPE_DEF)) {
stop = true;
} else if (line.startsWith(ALT_ID)) {
alt_id_term = line.substring(7).trim();
alt_id.add(alt_id_term);
}
curPos += (long) (line.length() + endOfLineSize);
}
// handle last term
termPrepared = prepareTerm(go_name, ontology);
handleData(file, go_iD, termPrepared, go_parent, typeEdge, alt_id, curPos);
// add Term in a Lucene index
indexingSequences(ss);
} catch (Exception e) {
String msg = "Error while parsing GeneOntology entry no. "
+ (termCounter + 1);
LOGGER.warn(msg + ": " + e);
throw new DicoParserException(msg + ": " + e.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
if (_pMonitor != null) {
_pMonitor.stopProcessingFile(file, _entries);
}
}
if (_entries == 0)
throw new DicoParserException("Data file does not contain any terms.");
}
public HashMap<String, GeneOntologyTerm> get_nodes() {
return _nodes;
}
/**
* For each term found, we add it in a Lucene index
*
* @param ss
* link to index
*/
private void indexingSequences(DicoStorageSystem ss) {
GeneOntologyTerm term;
Object[] keys = _nodes.keySet().toArray();
int size;
size = keys.length;
_entries += size;
for (int i = 0; i < size; i++) {
term = _nodes.get(keys[i]);
if (ss != null) {
ss.addBinaryEntry((String) keys[i], term);
}
}
}
/**
* Implementation of DicoParsable interface.
*/
public void setVerbose(boolean verbose) {
_verbose = verbose;
}
public int getTerms() {
return _entries;
}
}
| pgdurand/BeeDeeM | src/bzh/plealog/dbmirror/lucenedico/go/GeneOntologyOBONodeParser.java | Java | agpl-3.0 | 15,713 |
#coding:utf-8
from openerp.osv import osv,fields
class rainsoft_stock_return(osv.Model):
_inherit='stock.return.picking'
_defaults={
'invoice_state': '2binvoiced',
}
| kevin8909/xjerp | openerp/addons/Rainsoft_Xiangjie/rainsoft_stock_return.py | Python | agpl-3.0 | 185 |
<?php
/*
* Copyright 2007-2015 Abstrium <contact (at) pydio.com>
* This file is part of Pydio.
*
* Pydio 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.
*
* Pydio 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 Pydio. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
namespace Pydio\OCS;
use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Pydio\Cache\Core\CacheStreamLayer;
use Pydio\Core\Exception\PydioException;
use Pydio\Core\Model\Context;
use Pydio\Core\Model\ContextInterface;
use Pydio\Core\Services\ConfService;
use Pydio\Core\Utils\Vars\InputFilter;
use Pydio\Log\Core\Logger;
use Pydio\OCS\Client\OCSClient;
use Pydio\OCS\Model\SQLStore;
use Zend\Diactoros\Response\JsonResponse;
defined('AJXP_EXEC') or die('Access not allowed');
/**
* Class ActionsController
* @package Pydio\OCS
*/
class ActionsController
{
private $configs;
/**
* ActionsController constructor.
* @param $configs
*/
public function __construct($configs){
$this->configs = $configs;
}
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @return null
* @throws PydioException
* @throws \Exception
*/
public function switchAction(ServerRequestInterface &$request, ResponseInterface &$response) {
/** @var ContextInterface $ctx */
$ctx = $request->getAttribute("ctx");
$action = $request->getAttribute("action");
$httpVars = $request->getParsedBody();
switch($action){
case "user_list_authorized_users":
if(isSet($httpVars['trusted_server_id'])){
$this->forwardUsersListToRemote($request, $response);
}
break;
case "accept_invitation":
$remoteShareId = InputFilter::sanitize($httpVars["remote_share_id"], InputFilter::SANITIZE_ALPHANUM);
$store = new SQLStore();
$remoteShare = $store->remoteShareById($remoteShareId);
if($remoteShare === null){
throw new PydioException("Cannot find remote share with ID ".$remoteShareId);
}
$client = new OCSClient();
$client->acceptInvitation($remoteShare);
$remoteShare->setStatus(OCS_INVITATION_STATUS_ACCEPTED);
$store->storeRemoteShare($remoteShare);
$urlBase = $ctx->getUrlBase();
CacheStreamLayer::clearDirCache($urlBase);
CacheStreamLayer::clearStatCache($urlBase . "/" . $remoteShare->getDocumentName());
$remoteCtx = new Context($remoteShare->getUser(), "ocs_remote_share_" . $remoteShare->getId());
CacheStreamLayer::clearStatCache($remoteCtx->getUrlBase());
break;
case "reject_invitation":
$remoteShareId = InputFilter::sanitize($httpVars["remote_share_id"], InputFilter::SANITIZE_ALPHANUM);
$store = new SQLStore();
$remoteShare = $store->remoteShareById($remoteShareId);
if($remoteShare === null){
throw new PydioException("Cannot find remote share with ID ".$remoteShareId);
}
$client = new OCSClient();
try {
$client->declineInvitation($remoteShare);
} catch (\Exception $e) {
// If the reject fails, we still want the share to be removed from the db
Logger::error(__CLASS__,"Exception",$e->getMessage());
}
$store->deleteRemoteShare($remoteShare);
ConfService::getInstance()->invalidateLoadedRepositories();
$urlBase = $ctx->getUrlBase();
CacheStreamLayer::clearDirCache($urlBase);
CacheStreamLayer::clearStatCache($urlBase . "/" . $remoteShare->getDocumentName());
$remoteCtx = new Context($remoteShare->getUser(), "ocs_remote_share_" . $remoteShare->getId());
CacheStreamLayer::clearStatCache($remoteCtx->getUrlBase());
break;
default:
break;
}
return null;
}
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $responseInterface
* @throws PydioException
*/
protected function forwardUsersListToRemote(ServerRequestInterface &$request, ResponseInterface &$responseInterface){
$httpVars = $request->getParsedBody();
$searchQuery = InputFilter::sanitize($httpVars['value'], InputFilter::SANITIZE_HTML_STRICT);
$trustedServerId = InputFilter::sanitize($httpVars['trusted_server_id'], InputFilter::SANITIZE_ALPHANUM);
if(!isSet($this->configs["TRUSTED_SERVERS"]) || !isSet($this->configs["TRUSTED_SERVERS"][$trustedServerId])){
throw new PydioException("Cannot find trusted server with id " . $trustedServerId);
}
$serverData = $this->configs["TRUSTED_SERVERS"][$trustedServerId];
$url = $serverData['url'] . '/api/pydio/user_list_authorized_users/' . $searchQuery;
$params = [
'format' => 'json',
'users_only' => 'true',
'existing_only' => 'true',
'exclude_current' => 'false'
];
$client = new Client();
$postResponse = $client->post($url, [
'headers' => [
'Authorization' => 'Basic ' . base64_encode($serverData['user'] . ':' . $serverData['pass'])
],
'body' => $params
]);
$body = $postResponse->getBody()->getContents();
$jsonContent = json_decode($body);
foreach($jsonContent as $userEntry){
$userEntry->trusted_server_id = $trustedServerId;
$userEntry->trusted_server_label = $serverData['label'];
}
$httpVars['processed'] = true;
$request = $request->withParsedBody($httpVars);
$responseInterface = new JsonResponse($jsonContent);
}
} | ChuckDaniels87/pydio-core | core/src/plugins/core.ocs/src/ActionsController.php | PHP | agpl-3.0 | 6,752 |
using System;
using BricksDb.RedisInterface.BriksCommunication;
using BricksDb.RedisInterface.RedisOperations;
using Qoollo.Client.Configuration;
using Qoollo.Client.Support;
namespace BricksDb.RedisInterface.Server
{
class RedisToBriks : RedisToSmthSystem
{
private readonly RedisGate _redisGate;
public RedisToBriks()
{
_redisGate = new RedisGate(
new NetConfiguration(ConfigurationHelper.Instance.Localhost, 8000, Consts.WcfServiceName),
new ProxyConfiguration(Consts.ChangeDistributorTimeoutSec),
new CommonConfiguration(ConfigurationHelper.Instance.CountThreads));
}
protected override void InnerBuild(RedisMessageProcessor processor)
{
_redisGate.Build();
processor.AddOperation("SET", new RedisSet(new ProxyDataAdapter(_redisGate.RedisTable), "SET"));
processor.AddOperation("GET", new RedisGet(new ProxyDataAdapter(_redisGate.RedisTable), "GET"));
}
public override void Start()
{
_redisGate.Start();
var result = _redisGate.RedisTable.SayIAmHere(ConfigurationHelper.Instance.DistributorHost,
ConfigurationHelper.Instance.DistributorPort);
Console.WriteLine(result);
base.Start();
}
public override void Stop()
{
base.Stop();
_redisGate.Dispose();
}
}
}
| qoollo/bricksdb | src/BriksDb.RedisInterface/Server/RedisToBriks.cs | C# | agpl-3.0 | 1,543 |
/*
This file is part of ContentManager.
ContentManager 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.
ContentManager 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 ContentManager. If not, see <http://www.gnu.org/licenses/>.
*/
var messageHandler = {
displayInfoMessage : function (message) {
var messageJson = {messageClass : "alert-info", message : message}
$("#app-message").html(Mustache.render($('#message-template').html() ,messageJson));
setTimeout(function(){
$("#app-message").html('');
},1500)
},
displayLoadMessage : function (message) {
var messageJson = {message : message}
$("#app-message").html(Mustache.render($('#message-template').html() ,messageJson));
},
displayErrorMessage : function (message) {
var messageJson = {messageClass : "alert-danger", message : message}
$("#app-message").html(Mustache.render($('#message-template').html() ,messageJson));
setTimeout(function(){
$("#app-message").html('');
},3000)
},
resetMessage : function(){
$("#app-message").html(Mustache.render($('#message-template').html() ,{}));
},
showJiveErrorMessage : function(message){
osapi.jive.core.container.sendNotification( {'message':message, 'severity' : 'error'} );
},
getCurrentMessage : function(){
return $("#app-message").text()
},
displayTagErrorMessage : function (message) {
var messageJson = {messageClass : "alert-danger", message : message}
$("#tag-message").html(Mustache.render($('#message-template').html() ,messageJson));
setTimeout(function(){
$("#tag-message").html('');
},1500)
},
displayCategoryErrorMessage : function(message){
var messageJson = {messageClass : "alert-danger", message : message}
$("#category-message").html(Mustache.render($('#message-template').html() ,messageJson));
setTimeout(function(){
$("#category-message").html('');
},1500)
}
}
| siddharthadeshpande89/jive-content-manager | apps/content_manager/public/javascripts/helpers/messageViewHandler.js | JavaScript | agpl-3.0 | 2,511 |
var origShow = jQuery.fn.show, origHide = jQuery.fn.hide;
jQuery.fn.show = function() {
$(this).removeClass("hidden");
return origShow.apply(this, arguments);
};
jQuery.fn.hide = function() {
$(this).addClass("hidden");
return origHide.apply(this, arguments);
};
$.ajaxSetup({
cache: false
});
function onBlur() {
document.body.className = 'blurred';
}
function onFocus() {
document.body.className = 'focused';
}
function getNotification(type) {
sendRequest({type: type}, "notifications", "get", function(res) {
$("#notification-dropdown").html(function() {
var str = "";
if (type !== "messages") {
if (res.result !== null && typeof res.result !== "undefined" && res.result.length > 0) {
for (x in res.result)
str += tmpl("notification-" + type, res.result[x]);
} else
str = tmpl("notification-empty", {});
return str;
} else if (type === "messages") {
if (res.conversations !== null && typeof res.conversations !== "undefined" && res.conversations.length > 0) {
$.getJSON(siteurl + "style/" + design + "/img/emoticons/emoticons.json", function(data) {
smileys = new Array();
for (x in data)
smileys[data[x]] = '<img src="' + siteurl + 'style/' + design + '/img/emoticons/' + data[x] + '.png" class="message-smiley" data-key="' + data[x] + '">';
for (con in res.conversations) {
var c = res.conversations[con], i = 0, image = null;
if (c.users !== null && typeof c.users === "string") {
us = c.users.split(","), userstring = "";
for (user in us) {
if (i === 2) {
userstring += ", +" + (us.length - 2);
break;
}
var tmp = us[user].split("|");
userstring += ", " + tmp[0];
i++;
}
userstring = userstring.substr(2);
} else if (c.users !== null & typeof c.users === "object") { // there is only one user
userstring = c.users.name;
image = c.users.pimg;
} else
userstring = "None";
c.message = c.message.substr(0, 35);
for (x in smileys)
c.message = replaceAll('[:' + x + ':]', smileys[x], c.message);
str += tmpl("notification-messages", {name: userstring, message: c.message, conversation: c.conversation, sendername: c.sendername, time: c.time, image: checkImage(image, "users", "cr_")});
}
$("#notification-dropdown").html(str);
return;
});
} else
return tmpl("notification-empty", {});
}
}).removeClass("notification-messages notification-friends notification-general").addClass("notification-" + type).show();
});
}
function sendRequest(requestData, module, action, callback) {
if (typeof requestData !== "undefined") {
return $.ajax({
url: convertUrl({module: module, action: action}),
dataType: "json",
data: requestData,
type: 'POST',
success: function(data) {
if (typeof data.session !== "undefined" && data.session === 0) {
alert("Your session is timed out! Please login again!");
location.href = convertUrl({module: "start"});
} else if (data.status == false) {
if (typeof data.msg == "undefined")
data.msg = "Error";
bootbox.alert(data.msg);
} else if (typeof callback == 'function') {
callback(data);
refreshTime();
}
}
});
}
return null;
}
function convertUrl(data) {
if (modrewrite) {
var str = siteurl + data.module;
if (typeof data.action !== "undefined" && data.action !== null)
str += "/" + data.action;
if (typeof data.x !== "undefined" && data.x !== null)
str += "/" + data.x;
if (typeof data.y !== "undefined" && data.y !== null)
str += "/" + data.y;
return str;
} else {
var str = siteurl + "index.php?m=" + data.module;
if (typeof data.action !== "undefined" && data.x !== null)
str += "&action=" + data.action;
if (typeof data.x !== "undefined" && data.x !== null)
str += "&x=" + data.y;
if (typeof data.y !== "undefined" && data.x !== null)
str += "&y=" + data.y;
return str;
}
}
function checkImage(filename, type, prefix) {
prefix = (typeof prefix === "undefined") ? "" : prefix;
if (filename === null || typeof filename === "undefined" || filename.length === 0)
return siteurl + 'style/' + design + '/img/placeholders/noimg-' + type + '.png';
return prefix + filename;
}
function getErrorMessage(tplname) {
return tmpl(tplname, {});
}
function like(ref_name, ref_id, callback) {
sendRequest({"ref_name": ref_name, "ref_id": ref_id}, "likes", "like", callback);
}
function dislike(ref_name, ref_id, callback) {
sendRequest({"ref_name": ref_name, "ref_id": ref_id}, "likes", "dislike", callback);
}
function unlike(ref_name, ref_id, callback) {
sendRequest({"ref_name": ref_name, "ref_id": ref_id}, "likes", "unlike", callback);
}
function comment(ref_name, ref_id, content, callback) {
sendRequest({"ref_name": ref_name, "ref_id": ref_id, "content": content}, "comments", "add", callback);
}
function deleteComment(comment_id) {
bootbox.confirm("Are You sure you want to delete this comment?", function(r) {
if (r) {
sendRequest({"comment_id": comment_id}, "comments", "remove", function() {
$("#comment-" + comment_id).remove();
});
}
});
}
function getLikes(refname, refid, dislike, title) {
sendRequest({"ref_name": refname, "ref_id": refid, "dislike": dislike}, "likes", "get", function(res) {
if (typeof res.likes !== "undefined" && res.likes.length > 0) {
bootbox.dialog({
message: function() {
var msg = "";
for (x in res.likes)
msg += tmpl("like-list", res.likes[x]);
return '<div class="likesmodalbox">' + msg + '</div>';
},
title: title,
buttons: {
main: {
label: "Ok",
className: "btn-primary"
}
},
className: "likelistmodal"
});
}
});
}
function refreshTime() {
$(".timestring").each(function() {
var el = $(this);
el.replaceWith(function() {
return convertDate(el.data("source"));
});
});
$(".tooltip").remove();
$(".tooltip-trigger").tooltip({
container: 'body'
});
}
function convertDate(timestring) {
if (typeof timestring == "undefined" || timestring === "" || timestring === null)
return "NaN";
var now = new Date();
var then = new Date(timestring.replace(/-/g, '/'));
var r = "";
then.setMinutes(then.getMinutes() + now.getTimezoneOffset() * (-1));
var since = Math.round((now.getTime() - then.getTime()) / 1000);
var chunks = [
[22896000, 'year'],
[2592000, 'month'],
[604800, 'week'],
[86400, 'day'],
[3600, 'hour'],
[60, 'minute']
];
if (since < 60)
r = "just now";
else {
var count;
for (i = 0, j = chunks.length; i < j; i++) {
seconds = chunks[i][0];
name = chunks[i][1];
count = Math.floor(since / seconds);
if (count !== 0)
break;
}
r = ((count === 1) ? '1 ' + name : count + " " + name + "s") + " ago";
}
return '<span class="tooltip-trigger timestring" data-source="' + timestring + '" data-title="' + then.toLocaleString() + '">' + r + '</span>';
}
function escapeRegExp(string) {
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
function replaceAll(find, replace, str) {
return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
$(document).ready(function() {
if (/*@cc_on!@*/false) { // check for Internet Explorer
document.onfocusin = onFocus;
document.onfocusout = onBlur;
} else {
window.onfocus = onFocus;
window.onblur = onBlur;
}
$(".sidebar").css("minHeight", window.innerHeight - 101);
$('input.filefakeinput').change(function() {
$($(this).data("rel")).val($(this).val());
});
$('.dropdown-menu').on('click', function(e) {
if ($(this).hasClass('dropdown-checkbox-menu')) {
e.stopPropagation();
}
});
$('.btn[data-loading-text]').click(function() {
$(this).button('loading');
});
$("a[href=\"#\"],a[href=\"\"]").click(function(e) {
e.preventDefault();
});
$("#mobile-slide-nav > .mobile-menu").html($(".main-menu > .nav").html());
$(document).on("click", "#menu-trigger", function() {
if (login) {
if ($("body").hasClass("menu-active"))
$("body").removeClass("menu-active");
else
$("body").addClass("menu-active");
} else
location.href = convertUrl({module: "start"});
}).on("mouseenter", ".notification-general-item:not(.read)", function() {
var el = $(this);
sendRequest({id: el.data("id")}, "notifications", "markRead", function() {
el.addClass("read");
el.find(".label-new").fadeOut("slow");
});
});
if (login) {
//Load unread messages badge
sendRequest({type: "messages"}, "notifications", "get", function(res) {
if (typeof res.conversations !== "undefined" && res.conversations.length > 0) {
$(".main-menu-item-messages > a > .badge").html(res.conversations.length);
$(".notification-link-messages").addClass("active");
} else
$(".notification-link-messages").removeClass("active");
});
sendRequest({type: "friends"}, "notifications", "get", function(res) {
if (typeof res.result !== "undefined" && res.result !== null && res.result.length > 0) {
$(".main-menu-item-friends > a > .badge").html(res.result.length);
$(".notification-link-friends").addClass("active");
} else
$(".notification-link-friends").removeClass("active");
});
sendRequest({type: "general"}, "notifications", "get", function(res) {
if (res.new > 0)
$(".notification-link-general").addClass("active");
else
$(".notification-link-general").removeClass("active");
});
}
$(document).on("click", "a.close", function(e) {
e.stopPropagation();
});
$(document).on("submit", "form.ajaxform", function(e) {
e.preventDefault();
var form = $(this);
form.find("input[type='submit'],button[type='submit']").button('loading');
if (form.prop("ajaxform-send") === true)
return;
if (form.attr("enctype") === "multipart/form-data") {
var name = "ajaxformframe" + Math.random();
var frame = $("<iframe/>", {"name": name, class: "hidden"}).appendTo(form);
form.attr("target", name).prop("ajaxform-send", true).submit();
frame.on("load", function() {
form.find("input[type='submit'],button[type='submit']").button('reset');
if (form.find(".ajaxform-callback").length > 0) {
console.log(frame.contents().find('body').html());
var callback = window[form.find(".ajaxform-callback").val()];
if (typeof callback === "function")
callback(jQuery.parseJSON(frame.contents().find('body').html()));
}
});
} else {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
dataType: "json"
}).done(function(data) {
form.find("input[type='submit'],button[type='submit']").button('reset');
if (form.find(".ajaxform-callback").length > 0) {
var callback = window[form.find(".ajaxform-callback").val()];
if (data.status === false) {
bootbox.alert(data.msg);
} else if (typeof callback === "function")
callback(data);
}
});
}
}).on("click", function(e) {
if ($(e.target).attr("id") !== "notification-dropdown" && $("#notification-dropdown").length > 0)
$("#notification-dropdown").hide();
});
$("#infoModal").on('show.bs.modal', function(e) {
$("#infoModal").find(".modal-title").html($(e.relatedTarget).data("title"));
if (typeof $(e.relatedTarget).data("href") !== "undefined")
$("#infoModal").find(".modal-body").html('<iframe src="' + $(e.relatedTarget).data("href") + '" style="border:0;width:100%"></iframe>').css("padding", 10);
});
$("*[data-moveto]").each(function() {
$(this).appendTo($(this).data("moveto")).removeAttr("data-moveto");
});
}); | kolplex/cunity | style/CunityRefreshed/javascript/cunity-core.js | JavaScript | agpl-3.0 | 14,280 |
# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import logging
from eve.utils import config
from copy import deepcopy
from superdesk import get_resource_service
from superdesk.resource import Resource
from superdesk.services import BaseService
from apps.archive.common import ITEM_UPDATE, get_user, ITEM_CREATE
from superdesk.metadata.item import CONTENT_STATE, ITEM_STATE
from superdesk.utc import utcnow
log = logging.getLogger(__name__)
fields_to_remove = ['_id', '_etag', 'versioncreator', 'originalcreator', 'versioncreated',
'_current_version', 'version', '_updated', 'lock_session', 'lock_user', 'lock_time', 'lock_action',
'force_unlock', '_created', 'guid', 'family_id', 'firstcreated', 'original_creator']
class ArchiveHistoryResource(Resource):
endpoint_name = 'archive_history'
resource_methods = ['GET']
item_methods = ['GET']
schema = {
'item_id': {'type': 'string'},
'user_id': Resource.rel('users', True),
'operation': {'type': 'string'},
'update': {'type': 'dict', 'nullable': True},
'version': {'type': 'integer'},
'original_item_id': {'type': 'string'}
}
mongo_indexes = {'item_id': ([('item_id', 1)], {'background': True})}
class ArchiveHistoryService(BaseService):
def on_item_updated(self, updates, original, operation=None):
item = deepcopy(original)
if updates:
item.update(updates)
self._save_history(item, updates, operation or ITEM_UPDATE)
def on_item_deleted(self, doc):
lookup = {'item_id': doc[config.ID_FIELD]}
self.delete(lookup=lookup)
def get_user_id(self, item):
user = get_user()
if user:
return user.get(config.ID_FIELD)
def _save_history(self, item, update, operation):
# in case of auto-routing, if the original_creator exists in our database
# then create item create record in the archive history.
if item.get(ITEM_STATE) == CONTENT_STATE.ROUTED and item.get('original_creator') \
and not item.get('original_id'):
user = get_resource_service('users').find_one(req=None, _id=item.get('original_creator'))
firstcreated = item.get('firstcreated', utcnow())
if user:
history = {
'item_id': item[config.ID_FIELD],
'user_id': user.get(config.ID_FIELD),
'operation': ITEM_CREATE,
'update': self._remove_unwanted_fields(update, item),
'version': item.get(config.VERSION, 1),
'_created': firstcreated,
'_updated': firstcreated
}
self.post([history])
history = {
'item_id': item[config.ID_FIELD],
'user_id': self.get_user_id(item),
'operation': operation,
'update': self._remove_unwanted_fields(update, item),
'version': item.get(config.VERSION, 1)
}
self.post([history])
def _remove_unwanted_fields(self, update, original):
if update:
update_copy = deepcopy(update)
for field in fields_to_remove:
update_copy.pop(field, None)
if original.get('sms_message') == update_copy.get('sms_message'):
update_copy.pop('sms_message', None)
return update_copy
| hlmnrmr/superdesk-core | apps/archive_history/service.py | Python | agpl-3.0 | 3,708 |
# encoding: utf-8
require './test/test_helper'
describe ArtistasController do
let(:artista) { create(:artista) }
describe 'anónimamente' do
it 'accede al index' do
get :index
must_respond_with :success
assigns(:artistas).wont_be_nil
end
it 'muestra un artista' do
get :show, id: artista
must_respond_with :success
end
it 'no accede a edit' do
get :edit, id: artista
must_redirect_to :root
end
it 'no actualiza' do
put :update, id: artista, artista: attributes_for(:artista)
must_redirect_to :root
end
it 'no destruye' do
delete :destroy, id: artista
must_redirect_to :root
end
end
describe 'logueado' do
before { loguearse }
describe 'con permisos' do
it 'accede a edit' do
autorizar { get :edit, id: artista }
must_respond_with :success
end
it 'actualiza' do
autorizar { put :update, id: artista, artista: { nombre: 'Juan Salvo' } }
must_redirect_to assigns(:artista)
artista.reload.nombre.must_equal 'Juan Salvo'
end
it 'destruye' do
artista.must_be :persisted?
lambda do
autorizar { delete :destroy, id: artista }
end.must_change 'Artista.count', -1
must_redirect_to artistas_path
end
end
end
end
| mauriciopasquier/bibliotecadeleter | test/controllers/artistas_controller_test.rb | Ruby | agpl-3.0 | 1,366 |
/*
Code for Life
Copyright (C) 2015, Ocado Innovation Limited
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/>.
ADDITIONAL TERMS – Section 7 GNU General Public Licence
This licence does not grant any right, title or interest in any “Ocado” logos,
trade names or the trademark “Ocado” or any other trademarks or domain names
owned by Ocado Innovation Limited or the Ocado group of companies or any other
distinctive brand features of “Ocado” as may be secured from time to time. You
must not distribute any modification of this program using the trademark
“Ocado” or claim any affiliation or association with Ocado or its employees.
You are not authorised to use the name Ocado (or any of its trade names) or
the names of any author or contributor in advertising or for publicity purposes
pertaining to the distribution of this program, without the prior written
authorisation of Ocado.
Any propagation, distribution or conveyance of this program must include this
copyright notice and these terms. You must not misrepresent the origins of this
program; modified versions of the program must be marked as such and not
identified as the original program.
*/
'use strict';
var ocargo = ocargo || {};
var Blockly = Blockly || {};
function initCustomBlocks() {
initCustomBlocksDescription();
initCustomBlocksPython();
}
function initCustomBlocksDescription() {
Blockly.Blocks['start'] = {
// Beginning block - identifies the start of the program
init: function() {
ocargo.blocklyControl.numStartBlocks++;
this.setColour(50);
this.appendDummyInput()
.appendField('Start')
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + CHARACTER_EN_FACE_URL,
ocargo.BlocklyControl.BLOCK_CHARACTER_HEIGHT,
ocargo.BlocklyControl.BLOCK_CHARACTER_WIDTH));
this.setNextStatement(true, 'Action');
this.setTooltip('The beginning of the program');
this.setDeletable(false);
}
};
/*****************/
/* Action Blocks */
/*****************/
Blockly.Blocks['move_forwards'] = {
// Block for moving forward
init: function() {
this.setColour(160);
this.appendDummyInput()
.appendField('move forwards')
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'actions/forward.svg',
ocargo.BlocklyControl.IMAGE_WIDTH,
ocargo.BlocklyControl.BLOCK_HEIGHT));
this.setPreviousStatement(true, 'Action');
this.setNextStatement(true, 'Action');
this.setTooltip('Move the van forwards');
}
};
Blockly.Blocks['turn_left'] = {
// Block for turning left
init: function() {
this.setColour(160);
this.appendDummyInput()
.appendField('turn left')
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg',
38,
ocargo.BlocklyControl.BLOCK_HEIGHT))
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'actions/left.svg',
ocargo.BlocklyControl.IMAGE_WIDTH,
ocargo.BlocklyControl.BLOCK_HEIGHT));
this.setPreviousStatement(true, 'Action');
this.setNextStatement(true, 'Action');
this.setTooltip('Turn the van left');
}
};
Blockly.Blocks['turn_right'] = {
// Block for turning right
init: function() {
this.setColour(160);
this.appendDummyInput()
.appendField('turn right')
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg',
29,
ocargo.BlocklyControl.BLOCK_HEIGHT))
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'actions/right.svg',
ocargo.BlocklyControl.IMAGE_WIDTH,
ocargo.BlocklyControl.BLOCK_HEIGHT));
this.setPreviousStatement(true, 'Action');
this.setNextStatement(true, 'Action');
this.setTooltip('Turn the van right');
}
};
Blockly.Blocks['turn_around'] = {
// Block for turning around
init: function() {
this.setColour(160);
this.appendDummyInput()
.appendField('turn around')
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg',
12,
ocargo.BlocklyControl.BLOCK_HEIGHT))
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir +
'actions/turn_around.svg',
ocargo.BlocklyControl.IMAGE_WIDTH,
ocargo.BlocklyControl.BLOCK_HEIGHT));
this.setPreviousStatement(true, 'Action');
this.setNextStatement(true, 'Action');
this.setTooltip('Turn the van around');
}
};
Blockly.Blocks['wait'] = {
// Block for not moving the van for a time
init: function() {
this.setColour(160);
this.appendDummyInput()
.appendField('wait')
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg',
60,
ocargo.BlocklyControl.BLOCK_HEIGHT))
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'actions/wait.svg',
ocargo.BlocklyControl.IMAGE_WIDTH,
ocargo.BlocklyControl.BLOCK_HEIGHT));
this.setPreviousStatement(true, 'Action');
this.setNextStatement(true, 'Action');
this.setTooltip('Keep the van stationary');
}
};
Blockly.Blocks['deliver'] = {
// Block for delivering (only on levels with multiple destinations)
init: function() {
this.setColour(160);
this.appendDummyInput()
.appendField('deliver')
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg',
43,
ocargo.BlocklyControl.BLOCK_HEIGHT))
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'actions/deliver.svg',
ocargo.BlocklyControl.IMAGE_WIDTH,
ocargo.BlocklyControl.BLOCK_HEIGHT));
this.setPreviousStatement(true, 'Action');
this.setNextStatement(true, 'Action');
this.setTooltip('Deliver the goods from the van');
}
};
Blockly.Blocks['puff_up'] = {
// Block for puffing up the van
init: function() {
this.setColour(330);
this.appendDummyInput()
.appendField('puff up')
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg',
43,
ocargo.BlocklyControl.BLOCK_HEIGHT))
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg',
ocargo.BlocklyControl.IMAGE_WIDTH,
ocargo.BlocklyControl.BLOCK_HEIGHT));
this.setPreviousStatement(true, 'EventAction');
this.setNextStatement(false);
this.setTooltip('Puff up the van to scare away the cows');
}
};
Blockly.Blocks['sound_horn'] = {
// Block for puffing up the van
init: function() {
this.setColour(330);
this.appendDummyInput()
.appendField('sound horn')
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg',
43,
ocargo.BlocklyControl.BLOCK_HEIGHT))
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg',
ocargo.BlocklyControl.IMAGE_WIDTH,
ocargo.BlocklyControl.BLOCK_HEIGHT));
this.setPreviousStatement(true, 'EventAction');
this.setNextStatement(false);
this.setTooltip('Sound the horn to scare away the cows');
}
};
/*****************/
/* Conditions */
/*****************/
Blockly.Blocks['road_exists'] = {
init: function() {
var BOOLEANS =
[['road exists forward', 'FORWARD'],
['road exists left', 'LEFT'],
['road exists right', 'RIGHT']];
this.setColour(210);
this.setOutput(true, 'Boolean');
this.appendDummyInput()
.appendField(new Blockly.FieldDropdown(BOOLEANS), 'CHOICE')
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg',
ocargo.BlocklyControl.EXTRA_BLOCK_WIDTH,
ocargo.BlocklyControl.BLOCK_HEIGHT));
}
};
Blockly.Blocks['traffic_light'] = {
init: function() {
var BOOLEANS =
[['traffic light red', ocargo.TrafficLight.RED],
['traffic light green', ocargo.TrafficLight.GREEN]];
this.setColour(210);
this.setOutput(true, 'Boolean');
this.appendDummyInput()
.appendField(new Blockly.FieldDropdown(BOOLEANS), 'CHOICE')
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg',
ocargo.BlocklyControl.EXTRA_BLOCK_WIDTH,
ocargo.BlocklyControl.BLOCK_HEIGHT));
}
};
Blockly.Blocks['dead_end'] = {
init: function() {
this.setColour(210);
this.setOutput(true, 'Boolean');
this.appendDummyInput()
.appendField('is dead end')
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg',
ocargo.BlocklyControl.EXTRA_BLOCK_WIDTH,
ocargo.BlocklyControl.BLOCK_HEIGHT));
}
};
Blockly.Blocks['at_destination'] = {
init: function() {
this.setColour(210);
this.setOutput(true, 'Boolean');
this.appendDummyInput()
.appendField('at destination')
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg',
ocargo.BlocklyControl.EXTRA_BLOCK_WIDTH,
ocargo.BlocklyControl.BLOCK_HEIGHT));
}
};
/****************/
/* Procedures */
/****************/
Blockly.Blocks['call_proc'] = {
// Block for calling a defined procedure
init: function() {
var name = '';
this.setColour(260);
this.appendDummyInput()
.appendField('Call')
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', 7,
ocargo.BlocklyControl.BLOCK_HEIGHT))
.appendField(new Blockly.FieldTextInput(name),'NAME');
this.setPreviousStatement(true, 'Action');
this.setNextStatement(true, 'Action');
this.setTooltip('Call');
}
};
Blockly.Blocks['declare_proc'] = {
// Block for declaring a procedure
init: function() {
var name = '';
this.setColour(260);
this.appendDummyInput()
.appendField('Define')
.appendField(new Blockly.FieldTextInput(name),'NAME');
this.appendStatementInput('DO')
.setCheck('Action')
.appendField('Do');
this.setTooltip('Declares the procedure');
this.statementConnection_ = null;
}
};
/****************/
/* Events */
/****************/
Blockly.Blocks['declare_event'] = {
// Block for declaring an event handler
init: function() {
this.setColour(260);
var dropdown = new Blockly.FieldDropdown([['white', ocargo.Cow.WHITE], ['brown', ocargo.Cow.BROWN]], function(option) {
var imageUrl = ocargo.Drawing.imageDir + ocargo.Drawing.cowUrl(option);
this.sourceBlock_.getField('IMAGE').setValue(imageUrl);
});
this.appendDummyInput('Event')
.appendField('On ')
.appendField(dropdown, 'TYPE')
.appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + ocargo.Drawing.whiteCowUrl,
ocargo.BlocklyControl.COW_WIDTH,
ocargo.BlocklyControl.BLOCK_HEIGHT), 'IMAGE');
this.getField('IMAGE').EDITABLE = true; //saves the image path as well in the XML
this.appendStatementInput('DO')
.setCheck('EventAction')
.appendField('Do');
this.setTooltip('Declares the event handler');
this.statementConnection_ = null;
},
};
/*******************/
/* Control Flows */
/*******************/
Blockly.Blocks['controls_repeat_while'] = {
// Block for repeat while
init: function() {
this.setColour(120);
this.appendValueInput("condition")
.setCheck("Boolean")
.appendField("repeat while");
this.appendStatementInput("body")
.setCheck("Action")
.appendField("do");
this.setPreviousStatement(true, 'Action');
this.setNextStatement(true, 'Action');
this.setTooltip('While a value is true, do some statements');
}
};
Blockly.Blocks['controls_repeat_until'] = {
// Block for repeat until
init: function() {
this.setColour(120);
this.appendValueInput("condition")
.setCheck("Boolean")
.appendField("repeat until");
this.appendStatementInput("body")
.setCheck("Action")
.appendField("do");
this.setPreviousStatement(true, 'Action');
this.setNextStatement(true, 'Action');
this.setTooltip('Until a value is true, do some statements');
}
};
// Set text colour to red
var textBlock = Blockly.Blocks['text'];
var originalTextInit = textBlock.init;
textBlock.init = function() {
originalTextInit.call(this);
this.setColour(260);
};
//Customise controls_repeat block to not allow more than a sensible number of repetitions
var controlsRepeatBlock = Blockly.Blocks['controls_repeat'];
var originalInit = controlsRepeatBlock.init;
controlsRepeatBlock.init = function () {
originalInit.call(this);
this.setPreviousStatement(!0, 'Action');
this.setNextStatement(!0, 'Action');
this.inputList[1].setCheck('Action'); //Disallow event action blocks to be in body
var input = this.inputList[0];
var field = input.fieldRow[1];
field.changeHandler_ = function(text) {
var n = Blockly.FieldTextInput.numberValidator(text);
if (n) {
n = String(Math.min(Math.max(0, Math.floor(n)), 20));
}
return n;
};
};
// Make 'not' taller
var notBlock = Blockly.Blocks['logic_negate'];
var originalNotInit = notBlock.init;
notBlock.init = function () {
originalNotInit.call(this);
this.inputList[0].appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg',
ocargo.BlocklyControl.EXTRA_BLOCK_WIDTH,
ocargo.BlocklyControl.BLOCK_HEIGHT));
};
}
function initCustomBlocksPython() {
Blockly.Python['start'] = function(block) {
return '';
};
Blockly.Python['move_forwards'] = function(block) {
return 'v.move_forwards()\n';
};
Blockly.Python['turn_left'] = function(block) {
return 'v.turn_left()\n';
};
Blockly.Python['turn_right'] = function(block) {
return 'v.turn_right()\n';
};
Blockly.Python['turn_around'] = function(block) {
return 'v.turn_around()\n';
};
Blockly.Python['wait'] = function(block) {
return 'v.wait()\n';
};
Blockly.Python['deliver'] = function(block) {
return 'v.deliver()\n';
};
Blockly.Python['road_exists'] = function(block) {
if(block.inputList[0].fieldRow[1].value_ === 'FORWARD'){
var python = "v.is_road('FORWARD')";
}else if(block.inputList[0].fieldRow[1].value_ === 'LEFT'){
var python = "v.is_road('LEFT')";
}else{
var python = "v.is_road('RIGHT')";
}
return [python, Blockly.Python.ORDER_NONE];
// TODO: figure out what this ordering relates to
};
Blockly.Python['traffic_light'] = function(block) {
var python;
if(block.inputList[0].fieldRow[1].value_ === ocargo.TrafficLight.RED){
python = "v.at_traffic_light('RED')";
}else{
python = "v.at_traffic_light('GREEN')";
}
return [python, Blockly.Python.ORDER_NONE]; //TODO: figure out what this ordering relates to
};
Blockly.Python['dead_end'] = function(block) {
return ['v.at_dead_end()', Blockly.Python.ORDER_NONE];
// TODO: figure out what this ordering relates to
};
Blockly.Python['cow_crossing'] = function(block) {
return ['v.cow_crossing()', Blockly.Python.ORDER_NONE];
// TODO: figure out what this ordering relates to
};
Blockly.Python['at_destination'] = function(block) {
return ['v.at_destination()', Blockly.Python.ORDER_NONE];
// TODO: figure out what this ordering relates to;
};
Blockly.Python['call_proc'] = function(block) {
return block.inputList[0].fieldRow[2].text_ + '()\n';
};
Blockly.Python['declare_proc'] = function(block) {
var branch = Blockly.Python.statementToCode(block, 'DO');
return 'def ' + block.inputList[0].fieldRow[1].text_ + '():\n' + branch;
// TODO: get code out of sub-blocks (there's a Blockly function for it)
};
Blockly.Python['declare_event'] = function(block) {
// TODO support events in python
throw 'events not supported in python';
};
Blockly.Python['controls_repeat_while'] = function(block) {
var condition = Blockly.Python.valueToCode(block, 'condition', Blockly.Python.ORDER_ATOMIC);
var subBlock = Blockly.Python.statementToCode(block, 'body');
var code = 'while ' + condition + ':\n' + subBlock;
return code;
};
Blockly.Python['controls_repeat_until'] = function(block) {
var condition = Blockly.Python.valueToCode(block, 'condition', Blockly.Python.ORDER_ATOMIC);
var subBlock = Blockly.Python.statementToCode(block, 'body');
var code = 'while not ' + condition + ':\n' + subBlock;
return code;
};
}
| mikebryant/rapid-router | game/static/game/js/blocklyCustomBlocks.js | JavaScript | agpl-3.0 | 20,655 |
<?php
/**
* Copyright 2015-2018 ppy Pty. Ltd.
*
* This file is part of osu!web. osu!web is distributed with the hope of
* attracting more community contributions to the core ecosystem of osu!.
*
* osu!web is free software: you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License version 3
* as published by the Free Software Foundation.
*
* osu!web is distributed 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 osu!web. If not, see <http://www.gnu.org/licenses/>.
*/
return [
'not_negative' => ':attribute não pode ser negativo.',
'required' => ':attribute é necessário.',
'too_long' => ':attribute limite máximo excedido - só pode ser até :limit caracteres.',
'wrong_confirmation' => 'A confirmação não corresponde.',
'beatmap_discussion_post' => [
'discussion_locked' => 'A discussão está bloqueada.',
'first_post' => 'Não é possível eliminar uma publicação de começo.',
],
'beatmapset_discussion' => [
'beatmap_missing' => 'A marca de tempo está especificada mas o beatmap está em falta.',
'beatmapset_no_hype' => "O beatmap não pode ser hypeado.",
'hype_requires_null_beatmap' => 'O hype tem que ser feito na secção Geral (todas as dificuldades).',
'invalid_beatmap_id' => 'Dificuldade especificada inválida.',
'invalid_beatmapset_id' => 'Beatmap especificado inválido.',
'locked' => 'A discussão está bloqueada.',
'hype' => [
'guest' => 'Tens que estar com a sessão iniciada para hypear.',
'hyped' => 'Já hypeaste este beatmap.',
'limit_exceeded' => 'Usaste todo o teu hype.',
'not_hypeable' => 'Este beatmap não pode ser hypeado',
'owner' => 'Nada de hypear o teu próprio beatmap.',
],
'timestamp' => [
'exceeds_beatmapset_length' => 'A marca de tempo especificada ultrapassa a duração do beatmap.',
'negative' => "A marca de tempo não pode ser negativa.",
],
],
'forum' => [
'feature_vote' => [
'not_feature_topic' => 'Só se pode votar numa característica solicitada.',
'not_enough_feature_votes' => 'Votos insuficientes.',
],
'poll_vote' => [
'invalid' => 'Opção especificada inválida.',
],
'post' => [
'beatmapset_post_no_delete' => 'Não é permitido eliminar a publicação dos metadados do beatmap.',
'beatmapset_post_no_edit' => 'Não é permitido editar a publicação dos metadados do beatmap.',
],
'topic_poll' => [
'duplicate_options' => 'Uma opção duplicada não é permitida.',
'invalid_max_options' => 'As opções por cada utilizador não podem exceder o número de opções disponíveis.',
'minimum_one_selection' => 'Um mínimo de uma opção é necessária por utilizador.',
'minimum_two_options' => 'São necessárias pelo menos duas opções.',
'too_many_options' => 'Número máximo de opções permitidas excedido.',
],
'topic_vote' => [
'required' => 'Selecciona uma opção quando estiveres a votar.',
'too_many' => 'Foram seleccionadas opções a mais do que as permitidas.',
],
],
'user' => [
'contains_username' => 'A palavra-passe não pode conter o nome de utilizador.',
'email_already_used' => 'Endereço de email já usado.',
'invalid_country' => 'País inexistente na base de dados.',
'invalid_discord' => 'Nome de utilizador do Discord inválido.',
'invalid_email' => "Não parece que seja um endereço de email válido.",
'too_short' => 'A nova palavra-passe é demasiado curta.',
'unknown_duplicate' => 'Nome de utilizador e endereço de e-mail já usados.',
'username_available_in' => 'Este nome de utilizador irá estar disponível para uso em :duration.',
'username_available_soon' => 'Este nome de utilizador irá estar disponível para uso em qualquer momento!',
'username_invalid_characters' => 'O nome de utilizador solicitado contém caracteres inválidos.',
'username_in_use' => 'Este nome de utilizador já está a ser usado!',
'username_no_space_userscore_mix' => 'Por favor usa sublinhados ou espaços, não ambos!',
'username_no_spaces' => "O nome de utilizador não pode começar ou acabar com espaços!",
'username_not_allowed' => 'Esta escolha para nome de utilizador não é permitida.',
'username_too_short' => 'O nome de utilizador solicitado é demasiado curto.',
'username_too_long' => 'O nome de utilizador solicitado é demasiado longo.',
'weak' => 'Palavra-passe colocada na lista-negra.',
'wrong_current_password' => 'A palavra-passe actual está incorrecta.',
'wrong_email_confirmation' => 'A confirmação do email não corresponde.',
'wrong_password_confirmation' => 'A confirmação da palavra-passe não corresponde.',
'too_long' => 'Comprimento máximo excedido - só pode ser até :limit caracteres.',
'change_username' => [
'supporter_required' => [
'_' => 'Tu tens de ter :link para mudar o teu nome!',
'link_text' => 'ajudaste o osu!',
],
'username_is_same' => 'Este já é o teu nome de utilizador, tontinho!',
],
],
];
| kj415j45/osu-web | resources/lang/pt/model_validation.php | PHP | agpl-3.0 | 5,767 |
package org.rakam.report;
import com.facebook.presto.sql.tree.*;
import org.rakam.util.ValidationUtil;
import java.util.Optional;
import java.util.function.Function;
import static com.facebook.presto.sql.tree.LogicalBinaryExpression.Type.AND;
import static com.facebook.presto.sql.tree.LogicalBinaryExpression.Type.OR;
public class PreComputedTableSubQueryVisitor extends AstVisitor<String, Boolean> {
private final Function<String, Optional<String>> columnNameMapper;
public PreComputedTableSubQueryVisitor(Function<String, Optional<String>> columnNameMapper) {
this.columnNameMapper = columnNameMapper;
}
@Override
protected String visitLogicalBinaryExpression(LogicalBinaryExpression node, Boolean negate) {
LogicalBinaryExpression.Type type = node.getType();
if (type == AND) {
// TODO find a better way
// Optimization for the case when one hand or binary expression is IS NOT NULL predicate
if (node.getRight() instanceof IsNotNullPredicate && !(node.getLeft() instanceof IsNotNullPredicate) ||
node.getLeft() instanceof IsNotNullPredicate && !(node.getRight() instanceof IsNotNullPredicate)) {
Expression isNotNull = node.getRight() instanceof IsNotNullPredicate ? node.getRight() : node.getLeft();
Expression setExpression = isNotNull == node.getRight() ? node.getLeft() : node.getRight();
String excludeQuery = process(new IsNullPredicate(((IsNotNullPredicate) isNotNull).getValue()), negate);
return "SELECT l.date, l.dimension, l._user_set FROM (" + process(setExpression, negate) + ") l LEFT JOIN (" + excludeQuery + ") r ON (r.date = l.date AND l.dimension = r.dimension) WHERE r.date IS NULL";
}
String right = process(node.getRight(), negate);
String left = process(node.getLeft(), negate);
// TODO: use INTERSECT when it's implemented in Presto.
return "SELECT l.date, l.dimension, l._user_set FROM (" + left + ") l JOIN (" + right + ") r ON (r.date = l.date)";
} else if (type == OR) {
return "SELECT date, dimension, _user_set FROM (" + process(node.getLeft(), negate) +
" UNION ALL " + process(node.getRight(), negate) + ")";
} else {
throw new IllegalStateException();
}
}
@Override
protected String visitNotExpression(NotExpression node, Boolean negate) {
return process(node.getValue(), !negate);
}
@Override
protected String visitComparisonExpression(ComparisonExpression node, Boolean negate) {
String left = process(node.getLeft(), negate);
String right = process(node.getRight(), negate);
String predicate = node.getType().getValue() + " " + right;
if (negate) {
predicate = String.format("not(%s)", predicate);
}
return "SELECT date, dimension, _user_set FROM " + left + " WHERE dimension " + predicate;
}
@Override
protected String visitLongLiteral(LongLiteral node, Boolean negate) {
return Long.toString(node.getValue());
}
@Override
protected String visitLikePredicate(LikePredicate node, Boolean negate) {
return "SELECT date, dimension, _user_set FROM " + process(node.getValue(), negate) +
" WHERE dimension LIKE " + process(node.getPattern(), negate);
}
@Override
protected String visitIsNotNullPredicate(IsNotNullPredicate node, Boolean negate) {
if (negate) {
return visitIsNullPredicate(new IsNullPredicate(node.getValue()), !negate);
}
String column = process(node.getValue(), negate);
return "SELECT date, dimension, _user_set FROM " + column + " WHERE dimension is not null";
}
@Override
protected String visitIsNullPredicate(IsNullPredicate node, Boolean negate) {
if (negate) {
return visitIsNullPredicate(new IsNullPredicate(node.getValue()), !negate);
}
return "SELECT date, dimension, _user_set FROM " + process(node.getValue(), negate) + " WHERE dimension is null";
}
@Override
protected String visitInPredicate(InPredicate node, Boolean negate) {
String predicate = "IN " + process(node.getValue(), null) + " " + process(node, negate) + " ) ";
if (negate) {
predicate = String.format("NOT ", predicate);
}
return "SELECT date, dimension, _user_set FROM " + process(node.getValue(), negate) + " WHERE dimension " + predicate;
}
@Override
protected String visitBetweenPredicate(BetweenPredicate node, Boolean negate) {
String predicate = "BETWEEN " + process(node.getMin(), null) + " " + process(node, negate) + " ) ";
if (negate) {
predicate = String.format("not(%s)", predicate);
}
return "SELECT date, dimension, _user_set FROM " + process(node.getValue(), negate) + " WHERE dimension " + predicate;
}
@Override
protected String visitDoubleLiteral(DoubleLiteral node, Boolean negate) {
return Double.toString(node.getValue());
}
@Override
protected String visitGenericLiteral(GenericLiteral node, Boolean negate) {
return node.getType() + " '" + node.getValue() + "'";
}
@Override
protected String visitTimeLiteral(TimeLiteral node, Boolean negate) {
return "TIME '" + node.getValue() + "'";
}
@Override
protected String visitTimestampLiteral(TimestampLiteral node, Boolean negate) {
return "TIMESTAMP '" + node.getValue() + "'";
}
@Override
protected String visitNullLiteral(NullLiteral node, Boolean negate) {
return "null";
}
@Override
protected String visitIntervalLiteral(IntervalLiteral node, Boolean negate) {
String sign = (node.getSign() == IntervalLiteral.Sign.NEGATIVE) ? "- " : "";
StringBuilder builder = new StringBuilder()
.append("INTERVAL ")
.append(sign)
.append(" '").append(node.getValue()).append("' ")
.append(node.getStartField());
if (node.getEndField().isPresent()) {
builder.append(" TO ").append(node.getEndField().get());
}
return builder.toString();
}
@Override
protected String visitBooleanLiteral(BooleanLiteral node, Boolean negate) {
return String.valueOf(node.getValue());
}
@Override
protected String visitStringLiteral(StringLiteral node, Boolean negate) {
return "'" + node.getValue().replace("'", "''") + "'";
}
@Override
protected String visitIdentifier(Identifier node, Boolean context) {
String tableColumn = ValidationUtil
.checkTableColumn(node.getValue(), "reference in filter", '"');
Optional<String> preComputedTable = columnNameMapper.apply(tableColumn);
if (preComputedTable.isPresent()) {
return preComputedTable.get();
}
throw new UnsupportedOperationException();
}
@Override
protected String visitNode(Node node, Boolean negate) {
throw new UnsupportedOperationException();
}
}
| buremba/rakam | rakam-spi/src/main/java/org/rakam/report/PreComputedTableSubQueryVisitor.java | Java | agpl-3.0 | 7,236 |
# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import logging
from copy import copy
from eve.utils import config, ParsedRequest
from superdesk.utc import utcnow
from superdesk.services import BaseService
from superdesk.publish.formatters.ninjs_formatter import NINJSFormatter
from superdesk import get_resource_service
from superdesk.metadata.item import ITEM_TYPE, CONTENT_TYPE
logger = logging.getLogger('superdesk')
class PublishService(BaseService):
"""A service for publishing to the content api.
Serves mainly as a proxy to the data layer.
"""
formatter = NINJSFormatter()
subscriber = {'config': {}}
def publish(self, item, subscribers=[]):
"""Publish an item to content api.
This must be enabled via ``PUBLISH_TO_CONTENT_API`` setting.
:param item: item to publish
"""
if not self._filter_item(item):
doc = self.formatter._transform_to_ninjs(item, self.subscriber)
now = utcnow()
doc.setdefault('firstcreated', now)
doc.setdefault('versioncreated', now)
doc.setdefault(config.VERSION, item.get(config.VERSION, 1))
doc['subscribers'] = [str(sub['_id']) for sub in subscribers]
if 'evolvedfrom' in doc:
parent_item = self.find_one(req=None, _id=doc['evolvedfrom'])
if parent_item:
doc['ancestors'] = copy(parent_item.get('ancestors', []))
doc['ancestors'].append(doc['evolvedfrom'])
doc['bookmarks'] = parent_item.get('bookmarks', [])
else:
logger.warning("Failed to find evolvedfrom item '{}' for '{}'".format(
doc['evolvedfrom'], doc['guid'])
)
self._assign_associations(item, doc)
logger.info('publishing %s to %s' % (doc['guid'], subscribers))
_id = self._create_doc(doc)
if 'evolvedfrom' in doc and parent_item:
self.system_update(parent_item['_id'], {'nextversion': _id}, parent_item)
return _id
else:
return None
def create(self, docs, **kwargs):
ids = []
for doc in docs:
ids.append(self._create_doc(doc, **kwargs))
return ids
def _create_doc(self, doc, **kwargs):
"""Create a new item or update existing."""
item = copy(doc)
item.setdefault('_id', item.get('guid'))
_id = item[config.ID_FIELD] = item.pop('guid')
# merging the existing and new subscribers
original = self.find_one(req=None, _id=_id)
if original:
item['subscribers'] = list(set(original.get('subscribers', [])) | set(item.get('subscribers', [])))
self._process_associations(item, original)
self._create_version_doc(item)
if original:
self.update(_id, item, original)
return _id
else:
return super().create([item], **kwargs)[0]
def _create_version_doc(self, item):
"""
Store the item in the item version collection
:param item:
:return:
"""
version_item = copy(item)
version_item['_id_document'] = version_item.pop('_id')
get_resource_service('items_versions').create([version_item])
# if the update is a cancel we need to cancel all versions
if item.get('pubstatus', '') == 'canceled':
self._cancel_versions(item.get('_id'))
def _cancel_versions(self, doc_id):
"""
Given an id of a document set the pubstatus to canceled for all versions
:param doc_id:
:return:
"""
query = {'_id_document': doc_id}
update = {'pubstatus': 'canceled'}
for item in get_resource_service('items_versions').get_from_mongo(req=None, lookup=query):
if item.get('pubstatus') != 'canceled':
get_resource_service('items_versions').update(item['_id'], update, item)
def _filter_item(self, item):
"""
Filter the item out if it matches any API Block filter conditions
:param item:
:return: True of the item is blocked, False if it is OK to publish it on the API.
"""
# Get the API blocking Filters
req = ParsedRequest()
filter_conditions = list(get_resource_service('content_filters').get(req=req, lookup={'api_block': True}))
# No API blocking filters
if not filter_conditions:
return False
filter_service = get_resource_service('content_filters')
for fc in filter_conditions:
if filter_service.does_match(fc, item):
logger.info('API Filter block {} matched for item {}.'.format(fc, item.get(config.ID_FIELD)))
return True
return False
def _assign_associations(self, item, doc):
"""Assign Associations to published item
:param dict item: item being published
:param dit doc: ninjs documents
"""
if item[ITEM_TYPE] != CONTENT_TYPE.TEXT:
return
for assoc, assoc_item in (item.get('associations') or {}).items():
if not assoc_item:
continue
doc.get('associations', {}).get(assoc)['subscribers'] = list(map(str, assoc_item.get('subscribers') or []))
def _process_associations(self, updates, original):
"""Update associations using existing published item and ensure that associated item subscribers
are equal or subset of the parent subscribers.
:param updates:
:param original:
:return:
"""
if updates[ITEM_TYPE] != CONTENT_TYPE.TEXT:
return
subscribers = updates.get('subscribers') or []
for assoc, update_assoc in (updates.get('associations') or {}).items():
if not update_assoc:
continue
if original:
original_assoc = (original.get('associations') or {}).get(assoc)
if original_assoc and original_assoc.get(config.ID_FIELD) == update_assoc.get(config.ID_FIELD):
update_assoc['subscribers'] = list(set(original_assoc.get('subscribers') or []) |
set(update_assoc.get('subscribers') or []))
update_assoc['subscribers'] = list(set(update_assoc['subscribers']) & set(subscribers))
| marwoodandrew/superdesk-core | content_api/publish/service.py | Python | agpl-3.0 | 6,723 |
package android.support.design.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.design.c;
final class by {
private static final int[] a = new int[]{c.colorPrimary};
static void a(Context context) {
int i = 0;
TypedArray obtainStyledAttributes = context.obtainStyledAttributes(a);
if (!obtainStyledAttributes.hasValue(0)) {
i = 1;
}
if (obtainStyledAttributes != null) {
obtainStyledAttributes.recycle();
}
if (i != 0) {
throw new IllegalArgumentException("You need to use a Theme.AppCompat theme (or descendant) with the design library.");
}
}
}
| WenbinHou/PKUAutoGateway.Android | Reference/IPGWAndroid/android/support/design/widget/by.java | Java | agpl-3.0 | 714 |
module Puppetdb
class Nodes < Struct.new(:urls)
def all
filter = IDB.config.puppetdb.filter.blank? ? nil : Regexp.new(IDB.config.puppetdb.filter)
nodes = []
# Try to find machines in all puppetdb servers.
urls.each do |url|
api = Puppetdb::Api.new(url)
data = api.get('/v3/nodes').data || []
data.each do |node|
if filter.nil? || node['name'].match(filter)
nodes << node['name']
end
end
end
nodes
end
def facts(node)
Puppetdb::FactsV3.for_node(node, urls)
end
# returns either the puppetdb url or nil
def find_node(fqdn)
# Try to find machine in all puppetdb servers.
urls.each do |url|
api = Puppetdb::Api.new(url)
data = api.get("/v3/nodes/#{fqdn}").data
return url if data && data["name"]
end
nil
end
end
end
| fkr/the-idb | app/core/puppetdb/nodes.rb | Ruby | agpl-3.0 | 903 |
/*
* The Exomiser - A tool to annotate and prioritize genomic variants
*
* Copyright (c) 2016-2020 Queen Mary University of London.
* Copyright (c) 2012-2016 Charité Universitätsmedizin Berlin and Genome Research Ltd.
*
* 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/>.
*/
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.monarchinitiative.exomiser.core.genome;
import com.google.common.collect.Sets;
import de.charite.compbio.jannovar.data.JannovarData;
import org.junit.jupiter.api.Test;
import org.monarchinitiative.exomiser.core.model.Gene;
import org.monarchinitiative.exomiser.core.model.GeneIdentifier;
import java.util.Set;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
/**
*
* @author Jules Jacobsen <jules.jacobsen@sanger.ac.uk>
*/
public class GeneFactoryTest {
private static final JannovarData DEFAULT_JANNOVAR_DATA = TestFactory.buildDefaultJannovarData();
private final GeneFactory instance = new GeneFactory(DEFAULT_JANNOVAR_DATA);
@Test
public void testCreateKnownGeneIds() {
Set<GeneIdentifier> expected = Sets.newHashSet(TestFactory.buildGeneIdentifiers());
Set<GeneIdentifier> knownGeneIds = instance.getGeneIdentifiers();
assertThat(knownGeneIds, equalTo(expected));
}
@Test
public void testCreateKnownGenes() {
Set<Gene> expected = Sets.newHashSet(TestGeneFactory.buildGenes());
Set<Gene> knownGenes = Sets.newHashSet(instance.createKnownGenes());
assertThat(knownGenes, equalTo(expected));
}
}
| exomiser/Exomiser | exomiser-core/src/test/java/org/monarchinitiative/exomiser/core/genome/GeneFactoryTest.java | Java | agpl-3.0 | 2,339 |
<?php
class Search {
public static function matchTerm($term, $text) {
$reg = "/[ ]+/";
$text = self::normalize($text);
$term = self::normalize($term);
$words_text = preg_split($reg, $text);
$words_term = preg_split($reg, $term);
$text_final = "";
foreach($words_term as $key_term => $word_term) {
$matcher = "/".self::normalize($word_term)."/i";
$find = false;
foreach($words_text as $key_text => $word_text) {
if(preg_match($matcher, $word_text)) {
$find = true;
unset($words_text[$key_text]);
break;
}
unset($words_text[$key_text]);
}
if(!$find) {
return false;
}
}
return $find;
}
public static function matchTermLight($term, $text) {
$reg = "/[ ]+/";
$text = self::normalize($text);
$term = self::normalize($term);
$words_text = preg_split($reg, $text);
$words_term = preg_split($reg, $term);
$text_final = "";
foreach($words_term as $key_term => $word_term) {
$find = false;
foreach($words_text as $key_text => $word_text) {
if($word_term == $word_text) {
$find = true;
unset($words_text[$key_text]);
break;
}
unset($words_text[$key_text]);
}
if(!$find) {
return false;
}
}
return $find;
}
public static function normalize($text) {
return KeyInflector::unaccent($text);
}
public static function getWords($value) {
$words = array();
$expressions = preg_split('/([,; \|()])/', $value);
$words_mandatories = array("ac");
foreach($expressions as $exp) {
if(preg_match('/[\wû]{3,}/', $exp) || in_array(strtolower($exp), $words_mandatories)) {
$words[] = strtolower($exp);
}
}
return $words;
}
} | 24eme/vinsdeloire | project/plugins/acVinLibPlugin/lib/util/Search.class.php | PHP | agpl-3.0 | 1,975 |
/**
* Copyright (C) 2016 Jorge Campos Serrano.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects
* for all of the code used other than as permitted herein. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version. If you
* delete this exception statement from all source files in the program,
* then also delete it in the license file.
*/
Template.notificationsWidget.helpers({
notifications: function() {
return Notifications.find({userId: Meteor.userId(), read: false}, {limit: 4});
},
notificationCount: function(){
return Notifications.find({userId: Meteor.userId(), read: false}).count();
}
});
| jcamposs/coderoom | client/templates/notifications/notifications_widget.js | JavaScript | agpl-3.0 | 1,772 |
<?php
/*** COPYRIGHT NOTICE *********************************************************
*
* Copyright 2009-2016 ProjeQtOr - Pascal BERNARD - support@projeqtor.org
* Contributors : -
*
* This file is part of ProjeQtOr.
*
* ProjeQtOr 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.
*
* ProjeQtOr 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
* ProjeQtOr. If not, see <http://www.gnu.org/licenses/>.
*
* You can get complete code of ProjeQtOr, other resource, help and information
* about contributors at http://www.projeqtor.org
*
*** DO NOT REMOVE THIS NOTICE ************************************************/
/** ============================================================================
* Contact
*/
require_once('_securityCheck.php');
class Contact extends ContactMain {
/** ==========================================================================
* Constructor
* @param $id the id of the object in the database (null if not stored yet)
* @return void
*/
function __construct($id = NULL, $withoutDependentObjects=false) {
parent::__construct($id,$withoutDependentObjects);
}
/** ==========================================================================
* Destructor
* @return void
*/
function __destruct() {
parent::__destruct();
}
}
?> | papjul/projeqtor | model/Contact.php | PHP | agpl-3.0 | 1,800 |
##############################################################################
#
# ______ Releasing children from poverty _
# / ____/___ ____ ___ ____ ____ ___________(_)___ ____
# / / / __ \/ __ `__ \/ __ \/ __ `/ ___/ ___/ / __ \/ __ \
# / /___/ /_/ / / / / / / /_/ / /_/ (__ |__ ) / /_/ / / / /
# \____/\____/_/ /_/ /_/ .___/\__,_/____/____/_/\____/_/ /_/
# /_/
# in Jesus' name
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# @author: Nicolas Badoux <n.badoux@hotmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
# pylint: disable=C8101
{
"name": "Survey Phone",
"summary": "Make the filling of survey by internal users easier.",
"version": "12.0.1.0.0",
"category": "Other",
"sequence": 150,
"author": "Compassion CH",
"license": "AGPL-3",
"website": "http://www.compassion.ch",
"depends": [
"survey", # oca_addons/survey
"base_phone", # oca_addons/connector-telephony
"survey",
"partner_contact_birthdate", # oca_addons/partner_contact
"advanced_translation",
],
"data": [
"views/survey_user_input_view.xml",
"views/survey_phone.xml",
"report/survey_report.xml",
],
"demo": [],
"installable": True,
"auto_install": False,
}
| CompassionCH/compassion-modules | survey_phone/__manifest__.py | Python | agpl-3.0 | 2,093 |
//
// Copyright (C) 2013-2016 University of Amsterdam
//
// 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/>.
//
#include "tablemodelvariableslevels.h"
#include <QMimeData>
#include <QDebug>
#include "options/optionstring.h"
#include "options/optionlist.h"
#include "options/optionvariables.h"
#include "column.h"
using namespace std;
TableModelVariablesLevels::TableModelVariablesLevels(QWidget *parent) :
TableModel(parent)
{
_boundTo = NULL;
_source = NULL;
_variableTypesSuggested = 0;
_variableTypesAllowed = 0xff;
_nominalTextIcon = QIcon(":/icons/variable-nominal-text.svg");
_nominalIcon = QIcon(":/icons/variable-nominal.svg");
_ordinalIcon = QIcon(":/icons/variable-ordinal.svg");
_scaleIcon = QIcon(":/icons/variable-scale.svg");
_limitToOneLevel = false;
}
void TableModelVariablesLevels::bindTo(Option *option)
{
if (_source == NULL)
{
qDebug() << "source not set!";
return;
}
_boundTo = dynamic_cast<OptionsTable *>(option);
_levels = _boundTo->value();
Terms alreadyAssigned;
foreach (Options *level, _levels)
{
OptionVariables *levelVariablesOption = static_cast<OptionVariables*>(level->get("variables"));
Terms variablesInLevel = levelVariablesOption->variables();
alreadyAssigned.add(variablesInLevel);
}
if (alreadyAssigned.size() > 0)
_source->notifyAlreadyAssigned(alreadyAssigned);
refresh();
}
void TableModelVariablesLevels::mimeDataMoved(const QModelIndexList &indexes)
{
bool levelRemoved = false;
Terms toRemove;
foreach (const QModelIndex &index, indexes)
toRemove.add(_rows.at(index.row()).title());
for (int i = _levels.size() - 1; i >= 0; i--)
{
Options *levelOptions = _levels.at(i);
OptionVariables *variablesOption = dynamic_cast<OptionVariables *>(levelOptions->get("variables"));
Terms variables = variablesOption->variables();
variables.remove(toRemove);
if (variables.size() == 0)
{
Options *options = _levels.at(i);
_levels.erase(find(_levels.begin(), _levels.end(), options));
delete options;
levelRemoved = true;
}
else
{
variablesOption->setValue(variables.asVector());
}
}
if (levelRemoved)
{
OptionString *nameOption = static_cast<OptionString *>(_boundTo->rowTemplate()->get("name"));
QString nameTemplate = tq(nameOption->value());
for (uint i = 0; i < _levels.size(); i++)
{
nameOption = static_cast<OptionString *>(_levels.at(i)->get("name"));
nameOption->setValue(fq(nameTemplate.arg(i + 1)));
}
}
_boundTo->setValue(_levels);
refresh();
}
void TableModelVariablesLevels::setVariableTypesSuggested(int variableTypesSuggested)
{
_variableTypesSuggested = variableTypesSuggested;
}
int TableModelVariablesLevels::variableTypesSuggested() const
{
return _variableTypesSuggested;
}
void TableModelVariablesLevels::setVariableTypesAllowed(int variableTypesAllowed)
{
_variableTypesAllowed = variableTypesAllowed;
}
int TableModelVariablesLevels::variableTypesAllowed() const
{
return _variableTypesAllowed;
}
void TableModelVariablesLevels::setLimitToOneLevel(bool limitToOne)
{
_limitToOneLevel = limitToOne;
}
bool TableModelVariablesLevels::isSuggested(const Term &term) const
{
QVariant v = requestInfo(term, VariableInfo::VariableType);
int variableType = v.toInt();
return variableType & _variableTypesSuggested;
}
bool TableModelVariablesLevels::isAllowed(const Term &term) const
{
QVariant v = requestInfo(term, VariableInfo::VariableType);
int variableType = v.toInt();
return variableType == 0 || variableType & _variableTypesAllowed;
}
int TableModelVariablesLevels::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
if (_boundTo == NULL)
return 0;
return _rows.length();
}
int TableModelVariablesLevels::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
if (_boundTo == NULL)
return 0;
return 1;
}
QVariant TableModelVariablesLevels::data(const QModelIndex &index, int role) const
{
if (_boundTo == NULL)
return QVariant();
Row row = _rows.at(index.row());
if (role == Qt::DisplayRole || role == Qt::EditRole)
{
if ( ! row.isOption())
{
return row.title();
}
else
{
OptionList *list = row.option();
QString selected = tq(list->value());
if (role == Qt::DisplayRole)
return selected;
QStringList items = tql(list->options());
QList<QVariant> value;
value.append(selected);
value.append(items);
return value;
}
}
else if (role == Qt::DecorationRole)
{
if (row.isHeading() == false && row.isOption() == false)
{
int variableType = requestInfo(row.title(), VariableInfo::VariableType).toInt();
switch (variableType)
{
case Column::ColumnTypeNominalText:
return QVariant(_nominalTextIcon);
case Column::ColumnTypeNominal:
return QVariant(_nominalIcon);
case Column::ColumnTypeOrdinal:
return QVariant(_ordinalIcon);
case Column::ColumnTypeScale:
return QVariant(_scaleIcon);
default:
return QVariant();
}
}
}
else if (role == Qt::ForegroundRole)
{
if (_limitToOneLevel == false && index.row() == _rows.length() - 1)
return QBrush(QColor(0xAA, 0xAA, 0xAA));
}
else if (role == Qt::TextAlignmentRole)
{
if (row.isHeading())
return Qt::AlignCenter;
else if (row.isOption())
return Qt::AlignTop;
}
else if (role == Qt::SizeHintRole)
{
if (row.isHeading())
return QSize(-1, 24);
}
return QVariant();
}
Qt::ItemFlags TableModelVariablesLevels::flags(const QModelIndex &index) const
{
Qt::ItemFlags flags = Qt::ItemIsEnabled;
if (index.isValid() == false)
{
flags |= Qt::ItemIsDropEnabled;
}
else
{
Row row = _rows.at(index.row());
if (row.isOption())
flags |= Qt::ItemIsEditable;
else if (row.isHeading() == false)
flags |= Qt::ItemIsSelectable | Qt::ItemIsDragEnabled;
}
return flags;
}
bool TableModelVariablesLevels::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (role != Qt::DisplayRole && role != Qt::EditRole)
return false;
if (_boundTo == NULL)
return false;
OptionList *list = _rows.at(index.row()).option();
QString qsValue = value.toString();
QByteArray bytes = qsValue.toUtf8();
list->setValue(string(bytes.constData(), bytes.length()));
_boundTo->setValue(_levels);
emit dataChanged(index, index);
return true;
}
Qt::DropActions TableModelVariablesLevels::supportedDropActions() const
{
return Qt::MoveAction;
}
Qt::DropActions TableModelVariablesLevels::supportedDragActions() const
{
return Qt::MoveAction;
}
QStringList TableModelVariablesLevels::mimeTypes() const
{
QStringList m;
m << "application/vnd.list.variable";
return m;
}
QMimeData *TableModelVariablesLevels::mimeData(const QModelIndexList &indexes) const
{
QMimeData *mimeData = new QMimeData();
QByteArray encodedData;
QDataStream dataStream(&encodedData, QIODevice::WriteOnly);
dataStream << indexes.length();
for (int i = 0; i < indexes.length(); i++)
{
Row row = _rows.at(indexes.at(i).row());
dataStream << QStringList(row.title());
}
mimeData->setData("application/vnd.list.variable", encodedData);
return mimeData;
}
bool TableModelVariablesLevels::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
{
if (action == Qt::IgnoreAction)
return true;
if ( ! canDropMimeData(data, action, row, column, parent))
return false;
if (mimeTypes().contains("application/vnd.list.variable"))
{
QByteArray encodedData = data->data("application/vnd.list.variable");
Terms variables;
variables.set(encodedData);
if (variables.size() == 0)
return false;
if (parent.isValid() == false)
{
if (row == -1) // dropped at end
row = _rows.length();
else if (row == 0) // dropped at beginning
row = 1;
size_t level = 0;
int positionInLevel = 0;
for (int i = 1; i < row; i++)
{
if (_rows[i].isHeading())
{
level++;
positionInLevel = 0;
}
else if (_rows[i].isOption() == false)
{
positionInLevel++;
}
}
if (level == _levels.size())
{
// create new level
Options *options = dynamic_cast<Options*>(_boundTo->rowTemplate()->clone());
OptionString *nameOption = dynamic_cast<OptionString *>(options->get("name"));
string levelName = fq(tq(nameOption->value()).arg(level + 1));
nameOption->setValue(levelName);
_levels.push_back(options);
}
Options *levelDroppedOn = _levels.at(level);
OptionVariables *variablesOption = dynamic_cast<OptionVariables*>(levelDroppedOn->get("variables"));
Terms currentVariables = variablesOption->variables();
foreach (const Term &variable, variables)
{
if (currentVariables.contains(variable)) // prevent dropping to own level (because it introduces complications)
return false;
currentVariables.insert(positionInLevel, variable);
positionInLevel++;
}
variablesOption->setValue(currentVariables.asVector());
// remove the variables which were just dropped, from the other levels
// (to handle the case that a variable is dragged and dropped from another level)
bool levelRemoved = false;
vector<Options*>::iterator itr = _levels.begin();
while (itr != _levels.end())
{
Options *level = *itr;
if (level == levelDroppedOn)
{
itr++;
continue;
}
OptionVariables *variablesOption = dynamic_cast<OptionVariables*>(level->get("variables"));
Terms currentVariables = variablesOption->variables();
currentVariables.remove(variables);
if (currentVariables.size() == 0)
{
delete variablesOption;
itr = _levels.erase(itr);
levelRemoved = true;
}
else
{
variablesOption->setValue(currentVariables.asVector());
itr++;
}
}
if (levelRemoved)
{
// update the level names
OptionString *nameOption = static_cast<OptionString *>(_boundTo->rowTemplate()->get("name"));
QString nameTemplate = tq(nameOption->value());
for (uint i = 0; i < _levels.size(); i++)
{
nameOption = static_cast<OptionString *>(_levels.at(i)->get("name"));
nameOption->setValue(fq(nameTemplate.arg(i + 1)));
}
}
_boundTo->setValue(_levels);
refresh();
return true;
}
}
return false;
}
bool TableModelVariablesLevels::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(action);
Q_UNUSED(row);
Q_UNUSED(column);
Q_UNUSED(parent);
if (data->hasFormat("application/vnd.list.variable"))
{
QByteArray encodedData = data->data("application/vnd.list.variable");
Terms variables;
variables.set(encodedData);
foreach (const Term &variable, variables)
{
if ( ! isAllowed(variable))
return false;
}
return true;
}
else
{
return false;
}
return false;
}
void TableModelVariablesLevels::setSource(TableModelVariablesAvailable *source)
{
_source = source;
setInfoProvider(source);
}
void TableModelVariablesLevels::refresh()
{
_rows.clear();
if (_boundTo == NULL)
return;
beginResetModel();
uint i;
for (i = 0; i < _levels.size(); i++)
{
Options *level = _levels.at(i);
OptionVariables *variablesOption = dynamic_cast<OptionVariables *>(level->get("variables"));
OptionString *nameOption = dynamic_cast<OptionString *>(level->get("name"));
vector<string> variables = variablesOption->variables();
_rows.append(Row(tq(nameOption->value()), true));
for (uint j = 2; j < level->size(); j++)
{
OptionList *list = dynamic_cast<OptionList *>(level->get(j));
_rows.append(Row(list));
}
foreach (const string &variable, variables)
_rows.append(Row(tq(variable)));
}
if (_limitToOneLevel == false)
{
OptionString *nameTemplate = static_cast<OptionString *>(_boundTo->rowTemplate()->get("name"));
QString name = tq(nameTemplate->value()).arg(i + 1);
_rows.append(Row(name, true));
}
endResetModel();
}
| raviselker/jasp-desktop | JASP-Desktop/widgets/tablemodelvariableslevels.cpp | C++ | agpl-3.0 | 12,498 |
class ChangeBoardCompositionResolution < ResolutionWrapper
attr_accessor :max_user_directors, :max_employee_directors, :max_supporter_directors,
:max_producer_directors, :max_consumer_directors
def after_initialize
[
:max_user_directors, :max_employee_directors, :max_supporter_directors, :max_producer_directors, :max_consumer_directors
].each do |clause_name|
send("#{clause_name}=", organisation.constitution.send(clause_name)) unless send(clause_name)
end
end
def attributes_for_resolutions
result = []
[:user, :employee, :supporter, :producer, :consumer].each do |member_type|
method = "max_#{member_type}_directors"
if organisation.send(method) != send(method).to_i
result.push({
:relation => :change_integer_resolutions,
:name => method,
:value => send(method).to_i,
:title => "Allow a maximum of #{send(method)} #{member_type.to_s.titlecase} Members on the Board"
})
end
end
result
end
end
| oneclickorgs/one-click-orgs | app/models/change_board_composition_resolution.rb | Ruby | agpl-3.0 | 1,028 |
# frozen_string_literal: true
module Decidim
# This holds the decidim-surveys version.
module Surveys
def self.version
"0.22.0"
end
end
end
| codegram/decidim | decidim-surveys/lib/decidim/surveys/version.rb | Ruby | agpl-3.0 | 161 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.fluxtion.runtime.plugin.executor;
import com.fluxtion.runtime.event.Event;
import com.fluxtion.runtime.lifecycle.EventHandler;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
*
* @author Greg Higgins (greg.higgins@V12technology.com)
*/
public class SingleThreadedAsyncEventHandler implements AsyncEventHandler {
private final EventHandler handler;
public SingleThreadedAsyncEventHandler(EventHandler handler) {
this.handler = handler;
}
@Override
public Future submitTask(SepCallable task) {
return new Future() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return true;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public Object get() throws InterruptedException, ExecutionException {
try {
return task.call(handler);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@Override
public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return get();
}
};
}
@Override
public void onEvent(Event e) {
handler.onEvent(e);
}
@Override
public EventHandler delegate() {
return handler;
}
}
| v12technology/fluxtion-utils | runtime-plugins/src/main/java/com/fluxtion/runtime/plugin/executor/SingleThreadedAsyncEventHandler.java | Java | agpl-3.0 | 1,904 |
/**
* This file is part of RLO-Plan.
*
* Copyright 2009, 2010 Tillmann Karras, Josua Grawitter
*
* RLO-Plan 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.
*
* RLO-Plan 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 RLO-Plan. If not, see <http://www.gnu.org/licenses/>.
*/
var column_titles = ['Uhrzeit', 'Klasse', 'Fach', 'Dauer', 'Vertretung', 'Änderung', 'Alter Raum', 'Neuer Raum'];
var column_names = ['time', 'course', 'subject', 'duration', 'sub', 'change', 'oldroom', 'newroom'];
var column_widths = ['40px', '40px', '45px', '25px', '150px', '245px', '40px', '40px'];
var column_maxLengths = [ 5, 5, 6, 3, 30, 40, 5, 5];
var day_names = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];
var relative_day_names = ['heute', 'morgen', 'übermorgen']; // array index corresponds to distance from today
function modify_entry(button) {
hide_buttons(button);
show_buttons(button.nextSibling.nextSibling);
var row = button.parentNode.parentNode;
for (var i = 0; i < row.childNodes.length - 1; i++) {
var cell = row.childNodes[i];
make_textbox(cell, i);
make_backup(cell, cell.lastChild.value);
}
}
function remove_row(row) {
if (row.parentNode.childNodes.length == 2) {
var teacher = row.parentNode.parentNode;
var day = teacher.parentNode;
if (day.childNodes.length == 4) {
remove(day);
} else {
remove(teacher);
}
} else {
remove(row);
}
}
function delete_entry(button) {
hide_buttons(button.previousSibling);
var row = button.parentNode.parentNode;
var msg = 'action=delete&id=' + row.id.substr(5); // remove 'entry' from 'entry123'
var status = newStatus('Wird gelöscht...', row.lastChild);
send_msg(msg, function(xhr) {
if (xhr.status == 200) {
remove_row(row);
} else {
show_buttons(button.previousSibling);
remove_status(status, xhr);
}
});
}
function save_entry(button) {
var row = button.parentNode.parentNode;
var teacher = row.parentNode.parentNode;
var day = teacher.parentNode;
var date = parse_date(day.firstChild.textContent);
if (date === null) {
alert('Bitte berichtigen Sie erst das Datum.');
return;
}
date = format_date_server(date);
var msg = '&date=' + date + '&teacher=' + teacher.firstChild.textContent;
var contentHasChanged = false;
for (var i = 0; i < row.childNodes.length - 1; i++) {
var cell = row.childNodes[i];
var new_value = cell.firstChild.value;
if (i == 0) {
new_value = parse_time(new_value);
if (new_value === null) {
alert('Die Uhrzeit ist fehlerhaft.');
return;
}
hide_buttons(button);
}
if (new_value != cell.lastChild.textContent) {
cell.textContent = new_value;
msg += '&' + column_names[i] + '=' + new_value;
contentHasChanged = true;
} else {
cell.textContent = cell.lastChild.textContent;
}
}
if (contentHasChanged) {
msg = 'action=update&id=' + row.id.substr(5) + msg;
var status = newStatus('Wird gespeichert...', row.lastChild);
send_msg(msg, function(xhr) {
show_buttons(button.previousSibling.previousSibling);
if (xhr.status != 200) {
button.previousSibling.previousSibling.click();
}
remove_status(status, xhr);
});
} else {
show_buttons(button.previousSibling.previousSibling);
}
}
function save_new_entry(button) {
var row = button.parentNode.parentNode;
var teacher = row.parentNode.parentNode;
var day = teacher.parentNode;
var date = parse_date(day.firstChild.textContent);
if (date === null) {
alert('Bitte berichtigen Sie erst das Datum.');
return;
}
date = format_date_server(date);
var msg = '&date=' + date + '&teacher=' + teacher.firstChild.textContent;
for (var i = 0; i < row.childNodes.length - 1; i++) {
var cell = row.childNodes[i];
var new_value = cell.firstChild.value;
if (i == 0) {
new_value = parse_time(new_value);
if (new_value === null) {
alert('Die Uhrzeit ist fehlerhaft.');
return;
}
hide_buttons(button);
}
cell.textContent = new_value;
msg += '&' + column_names[i] + '=' + cell.textContent;
}
msg = 'action=add' + msg;
var status = newStatus('Wird hinzugefügt...', row.lastChild);
send_msg(msg, function(xhr) {
remove_status(status, xhr);
if (xhr.status == 200) {
row.id = 'entry' + xhr.responseText;
} else {
row.lastChild.firstChild.onclick();
}
// TODO: is this ok here?
show_buttons(button.previousSibling.previousSibling);
button.onclick = function() {
save_entry(button);
}
button.nextSibling.innerHTML = 'Abbrechen';
button.nextSibling.onclick = function() {
cancel_editing(button.nextSibling);
}
});
}
function delete_new_entry(button) {
remove_row(button.parentNode.parentNode);
}
function add_new_entry(button) {
var row = newElement('tr');
// data cells:
for (var i = 0; i < column_widths.length; i++) {
var cell = newCell('');
make_textbox(cell, i);
row.appendChild(cell);
}
// button cell:
var button_cell = newElement('td');
var mod_button = newButton('Bearbeiten', modify_entry);
mod_button.style.display = 'none';
button_cell.appendChild(mod_button);
var del_button = newButton('Löschen', delete_entry);
del_button.style.display = 'none';
button_cell.appendChild(del_button);
var save_button = newButton('Speichern', save_new_entry);
button_cell.appendChild(save_button);
var cancel_button = newButton('Löschen', delete_new_entry);
button_cell.appendChild(cancel_button);
row.appendChild(button_cell);
button.previousSibling.appendChild(row);
row.firstChild.firstChild.focus();
}
function add_teacher(button) {
var day = button.parentNode;
var teacher = newTeacher('Neuer Lehrer', []);
day.insertBefore(teacher, day.lastChild);
teacher.childNodes[1].value = '';
teacher.firstChild.onclick();
}
function parse_time(time) {
var matches = time.match(/^(\d\d?).(\d\d?)$/);
if (matches !== null) {
for (var i = 1; i <= 2; i++) {
if (matches[i].length == 1) {
matches[i] = '0' + matches[i];
}
}
return matches[1] + ':' + matches[2];
}
return null;
}
function parse_date(date) {
var matches = date.match(/(\d\d?).(\d\d?).((\d\d)?\d\d)$/);
if (matches !== null) {
var year = matches[3];
if (year.length == 2) {
year = '20' + year;
}
return new Date(year, matches[2] - 1, matches[1], 0, 0, 0, 0);
}
var lower_date = date.toLowerCase();
for (var i = 0; i < relative_day_names.length; i++) {
if (lower_date == relative_day_names[i]) {
var result = new Date();
result.setDate(result.getDate() + i);
return result;
}
}
if (date.length <= 10) { // length of 'Donnerstag'
for (var i = 0; i < day_names.length; i++) {
if (lower_date == day_names[i].substr(0, lower_date.length).toLowerCase()) {
var result = new Date();
var today = result.getDay();
if (i < today) {
i += 7;
}
result.setDate(result.getDate() + i - today);
return result;
}
}
}
return null;
}
// DayOfWeek, DD.MM.YYYY
function format_date_client(d) {
var day = d.getDate() + '';
if (day.length == 1) {
day = '0' + day;
}
var month = (d.getMonth() + 1) + '';
if (month.length == 1) {
month = '0' + month;
}
return day_names[d.getDay()] + ', ' + day + '.' + month + '.' + d.getFullYear();
}
// YYYY-MM-DD
function format_date_server(d) {
return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
}
function get_default_date() {
var d = new Date();
var last_day = document.getElementById('ovp').lastChild.previousSibling;
if (last_day) {
var last_date = parse_date(last_day.firstChild.textContent);
if (last_date && last_date.getDate() >= d.getDate()) {
d = last_date;
d.setDate(d.getDate() + 1);
}
}
if (d.getDay() == 0) { // skip Sunday
d.setDate(d.getDate() + 1);
} else if (d.getDay() == 6) { // skip Saturday
d.setDate(d.getDate() + 2);
}
return format_date_client(d);
}
function add_day(button) {
var ovp = button.parentNode;
var date = get_default_date();
var day = newDay(date, []);
ovp.insertBefore(day, ovp.lastChild);
day.firstChild.onclick();
}
// 'id' is from the database
function newEntry(id, cols) {
var row = newElement('tr');
row.id = 'entry' + id;
// data cells:
for (i in cols) {
row.appendChild(newCell(cols[i]));
}
// button cell:
var button_cell = newElement('td');
var mod_button = newButton('Bearbeiten', modify_entry);
button_cell.appendChild(mod_button);
var del_button = newButton('Löschen', delete_entry);
button_cell.appendChild(del_button);
var save_button = newButton('Speichern', save_entry);
save_button.style.display = 'none';
button_cell.appendChild(save_button);
var cancel_button = newButton('Abbrechen', cancel_editing);
cancel_button.style.display = 'none';
button_cell.appendChild(cancel_button);
row.appendChild(button_cell);
return row;
}
function save_teacher(teacher) {
// subfunction needed since otherwise "status" would reference one variable only
function update_entry(msg, parent) {
var status = newStatus('Wird aktualisiert...', parent);
send_msg(msg, function(xhr) {
remove_status(status, xhr);
});
}
var date = parse_date(teacher.parentNode.firstChild.textContent);
if (date === null) {
alert('Bitte berichtigen Sie erst das Datum.');
return;
}
date = format_date_server(date);
var rows = teacher.childNodes[2].childNodes;
for (var i = 1; i < rows.length; i++) {
var row = rows[i];
if (row.id) {
var cells = row.childNodes;
var msg = 'action=update&id=' + row.id.substr(5) + '&date=' + date + '&teacher=' + teacher.firstChild.textContent;
for (var j = 0; j < cells.length - 1; j++) {
msg += '&' + column_names[j] + '=' + cells[j].textContent;
}
update_entry(msg, row.lastChild);
}
}
}
function newTeacher(name, entries) {
var teacher = newElement('section');
var header = newElement('h3');
header.style.display = 'table';
header.innerHTML = name;
header.onclick = function() {
header.style.display = 'none';
var textbox = header.nextSibling;
textbox.style.display = 'block';
textbox.focus();
textbox.select();
}
teacher.appendChild(header);
var textbox = newElement('input');
textbox.type = 'text';
textbox.style.display = 'none';
textbox.value = name;
textbox['last_key'] = 0;
textbox.onkeydown = function(e) {
var key;
if (window.event) {
key = event.keyCode;
} else if (e) {
key = e.which;
}
if (key == 9 && textbox['last_key'] == 0) {
textbox['create_entry_on_first_blur'] = true;
}
textbox['last_key'] = key - 9;
return true;
}
textbox.onkeyup = function() {
textbox['last_key'] = 0;
}
textbox.onblur = function() {
textbox.style.display = 'none';
var header = textbox.previousSibling;
var table = textbox.nextSibling;
if (textbox.value != header.textContent && textbox.value != '') {
header.textContent = textbox.value;
if (table.childNodes.length > 1) {
save_teacher(textbox.parentNode);
}
}
if (table.childNodes.length == 1 && textbox['create_entry_on_first_blur']) {
textbox.parentNode.lastChild.onclick();
}
header.style.display = 'table';
}
teacher.appendChild(textbox);
var table = newElement('table');
table.setAttribute('class', 'ovp_table');
var header_row = newElement('tr');
for (var i = 0; i < column_titles.length; i++) {
header_row.appendChild(newCell(column_titles[i]));
}
header_row.appendChild(newCell('Aktion'));
table.appendChild(header_row);
for (i in entries) {
table.appendChild(entries[i]);
}
teacher.appendChild(table);
var entry_button = newButton('+ Eintrag', add_new_entry);
teacher.appendChild(entry_button);
return teacher;
}
function newDay(title, teachers) {
var day = newElement('section');
var header = newElement('h2');
header.style.display = 'table';
header.innerHTML = title;
header.onclick = function() {
header.style.display = 'none';
var textbox = header.nextSibling;
textbox.style.display = 'block';
textbox.focus();
textbox.select();
}
day.appendChild(header);
var textbox = newElement('input');
textbox.type = 'text';
textbox.style.display = 'none';
textbox.value = title;
textbox['last_key'] = 0;
textbox.onkeydown = function(e) {
var key;
if (window.event) {
key = event.keyCode;
} else if (e) {
key = e.which;
}
if (key == 9 && textbox['last_key'] == 0) {
textbox['create_teacher_on_first_blur'] = true;
}
textbox['last_key'] = key - 9;
return true;
}
textbox.onkeyup = function() {
textbox['last_key'] = 0;
}
textbox.onblur = function() {
var header = textbox.previousSibling;
if (textbox.value != '') {
var new_date = parse_date(textbox.value);
if (new_date) {
var new_header = format_date_client(new_date);
if (header.textContent != new_header) {
header.textContent = new_header;
var teachers = textbox.parentNode.getElementsByTagName('section');
for (var i = 0; i < teachers.length; i++) {
save_teacher(teachers[i]);
}
}
} else {
header.innerHTML = '<span class="ovp_error">' + textbox.value + '</span>';
}
}
textbox.style.display = 'none';
header.style.display = 'table';
if (textbox.parentNode.childNodes.length == 3 && textbox['create_teacher_on_first_blur']) {
textbox.parentNode.lastChild.onclick();
}
}
day.appendChild(textbox);
for (i in teachers) {
day.appendChild(teachers[i]);
}
day.appendChild(newButton('+ Lehrer', add_teacher));
return day;
}
function insert_days(days) {
var ovp = document.getElementById('ovp');
for (i in days) {
ovp.insertBefore(days[i], ovp.lastChild);
}
}
function init_entry() {
document.getElementById('ovp').appendChild(newButton('+ Tag', add_day));
fill_in_data();
}
document.addEventListener("DOMContentLoaded", init_entry, false);
| gwater/rlo-plan | entry.js | JavaScript | agpl-3.0 | 16,345 |
///////////////////////////////////////////////////////////////////////////////
//Copyright (C) 2014 Joliciel Informatique
//
//This file is part of Talismane.
//
//Talismane is free software: you can redistribute it and/or modify
//it under the terms of the GNU Affero General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//Talismane is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Affero General Public License for more details.
//
//You should have received a copy of the GNU Affero General Public License
//along with Talismane. If not, see <http://www.gnu.org/licenses/>.
//////////////////////////////////////////////////////////////////////////////
package com.joliciel.talismane.machineLearning.features;
/**
* Mimics an in-then-else structure - if condition is true return thenFeature result, else return elseFeature result.
* @author Assaf Urieli
*
*/
public class IfThenElseGenericFeature<T,Y> extends AbstractCachableFeature<T,Y> {
private BooleanFeature<T> condition;
private Feature<T,Y> thenFeature;
private Feature<T,Y> elseFeature;
public IfThenElseGenericFeature(BooleanFeature<T> condition, Feature<T,Y> thenFeature, Feature<T,Y> elseFeature) {
super();
this.condition = condition;
this.thenFeature = thenFeature;
this.elseFeature = elseFeature;
this.setName("IfThenElse(" + condition.getName() + "," + thenFeature.getName() + "," + elseFeature.getName() + ")");
}
@Override
protected FeatureResult<Y> checkInternal(T context, RuntimeEnvironment env) {
FeatureResult<Y> featureResult = null;
FeatureResult<Boolean> conditionResult = condition.check(context, env);
if (conditionResult!=null) {
boolean conditionOutcome = conditionResult.getOutcome();
if (conditionOutcome) {
FeatureResult<Y> thenFeatureResult = thenFeature.check(context, env);
if (thenFeatureResult!=null) {
Y result = thenFeatureResult.getOutcome();
featureResult = this.generateResult(result);
}
} else {
FeatureResult<Y> elseFeatureResult = elseFeature.check(context, env);
if (elseFeatureResult!=null) {
Y result = elseFeatureResult.getOutcome();
featureResult = this.generateResult(result);
}
}
}
return featureResult;
}
public BooleanFeature<T> getCondition() {
return condition;
}
public Feature<T,Y> getThenFeature() {
return thenFeature;
}
public Feature<T,Y> getElseFeature() {
return elseFeature;
}
public void setCondition(BooleanFeature<T> condition) {
this.condition = condition;
}
public void setThenFeature(Feature<T,Y> thenFeature) {
this.thenFeature = thenFeature;
}
public void setElseFeature(Feature<T,Y> elseFeature) {
this.elseFeature = elseFeature;
}
@SuppressWarnings("rawtypes")
@Override
public Class<? extends Feature> getFeatureType() {
return thenFeature.getFeatureType();
}
}
| safety-data/talismane | talismane_machine_learning/src/main/java/com/joliciel/talismane/machineLearning/features/IfThenElseGenericFeature.java | Java | agpl-3.0 | 3,068 |
class SDGManagement::CardsController < SDGManagement::BaseController
include Admin::Widget::CardsActions
helper_method :index_path
load_and_authorize_resource :phase, class: "SDG::Phase", id_param: "sdg_phase_id"
load_and_authorize_resource :card, through: :phase, class: "Widget::Card"
private
def index_path
sdg_management_homepage_path
end
end
| consul/consul | app/controllers/sdg_management/cards_controller.rb | Ruby | agpl-3.0 | 374 |
<!-- Piwik -->
<script type="text/javascript">
var _paq = _paq || [];
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="//arrakiz.org/analytics/";
_paq.push(['setTrackerUrl', u+'piwik.php']);
_paq.push(['setSiteId', 1]);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
})();
</script>
<noscript><p><img src="//arrakiz.org/analytics/piwik.php?idsite=1" style="border:0;" alt="" /></p></noscript>
<!-- End Piwik Code -->
| Scindix/ArrakizPHP | tracking.php | PHP | agpl-3.0 | 612 |
/*****************************************************************************
* Stefans Poker Game *
* *
* Copyright (C) 2016 Stefan Oltmann *
* *
* Contact : pokergame@stefan-oltmann.de *
* Homepage: http://www.stefan-oltmann.de/ *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*****************************************************************************/
package de.stefan_oltmann.poker.server;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import de.stefan_oltmann.poker.model.Account;
import de.stefan_oltmann.poker.model.BlindHoehe;
import de.stefan_oltmann.poker.model.SpielEventListener;
import de.stefan_oltmann.poker.model.SpielImpl;
import de.stefan_oltmann.poker.model.Spieler;
import de.stefan_oltmann.poker.model.SpielerStatus;
import de.stefan_oltmann.poker.model.hand.Karte;
public class SpielControllerTest extends TestCase {
public static final Account ALICE = new Account("TEST1", "Alice", 1500);
public static final Account BOB = new Account("TEST2", "Bob", 1500);
public static final Account EVE = new Account("TEST3", "Eve", 1500);
/*
* TODO FIXME Unfertig
*/
public void testSpielMitDreiSpielern() {
SpielImpl spiel = new SpielImpl("123");
SpielLog spielLog = new SpielLog();
spiel.addListener(spielLog);
SpielController spielController = new SpielController(spiel);
Spieler spielerAlice = new Spieler("1", ALICE.getId(), spiel.getId());
Spieler spielerBob = new Spieler("2", BOB.getId(), spiel.getId());
Spieler spielerEve = new Spieler("3", EVE.getId(), spiel.getId());
/*
* Status-Prüfung vor Start
*/
assertEquals(0, spiel.getAnzahlAktiverSpieler());
assertFalse(spielController.isSpielLaueft());
assertNull(spiel.getDealer());
assertNull(spiel.getAktiverSpieler());
/* Drei Spieler treten bei uns warten auf die nächste Runde. */
spiel.sitIn(spielerAlice, 1, 1500);
assertEquals(1, spiel.getAnzahlAktiverSpieler());
assertFalse(spielController.isSpielLaueft());
assertEquals("sitIn Spieler[Account[TEST1:Alice]@Spiel[123]] platz=1 chips=1500", spielLog.getNextMessage());
assertEquals(SpielerStatus.WARTET_AUF_NAECHSTE_RUNDE, spielerAlice.getStatus());
spiel.sitIn(spielerBob, 2, 1500);
assertEquals(2, spiel.getAnzahlAktiverSpieler());
assertTrue(spielController.isSpielLaueft());
assertEquals("sitIn Spieler[Account[TEST2:Bob]@Spiel[123]] platz=2 chips=1500", spielLog.getNextMessage());
assertEquals(SpielerStatus.WARTET_AUF_NAECHSTE_RUNDE, spielerBob.getStatus());
spiel.sitIn(spielerEve, 3, 1500);
assertEquals(3, spiel.getAnzahlAktiverSpieler());
assertTrue(spielController.isSpielLaueft());
assertEquals("sitIn Spieler[Account[TEST3:Eve]@Spiel[123]] platz=3 chips=1500", spielLog.getNextMessage());
assertEquals(SpielerStatus.WARTET_AUF_NAECHSTE_RUNDE, spielerEve.getStatus());
/*
* Das Spiel startet
*/
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
}
/* Alice wird als Button ausgewählt */
assertEquals("setzeButton Spieler[Account[TEST1:Alice]@Spiel[123]]", spielLog.getNextMessage());
try {
Thread.sleep(9999);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class SpielLog implements SpielEventListener {
private List<String> messages = new ArrayList<String>();
// public List<String> getMessages() {
// return messages;
// }
public int counter = -1;
public String getNextMessage() {
this.counter++;
if (counter >= messages.size())
return null;
return messages.get(counter);
}
private void addMessage(String message) {
this.messages.add(message);
System.out.println("addMessage(): " + message);
}
@Override
public void onPlayerSatIn(Spieler spieler, int platzNummer, int chips) {
addMessage("sitIn " + spieler + " platz=" + platzNummer + " chips=" + chips);
}
@Override
public void onPlayerSatOut(Spieler spieler) {
addMessage("sitOut " + spieler);
}
@Override
public void onPlayerLeft(Spieler spieler) {
addMessage("leave " + spieler);
}
@Override
public void onHoleCardsDealt() {
addMessage("dealHoleCards");
}
@Override
public void onFlopDealt(Karte flop1, Karte flop2, Karte flop3) {
addMessage("dealFlop " + flop1 + " " + flop2 + " " + flop3);
}
@Override
public void onTurnDealt(Karte turn) {
addMessage("dealTurn " + turn);
}
@Override
public void onRiverDealt(Karte river) {
addMessage("dealRiver " + river);
}
@Override
public void onHandEnded() {
addMessage("endHand");
}
@Override
public void onButtonGesetzt(Spieler spieler) {
addMessage("setzeButton " + spieler);
}
@Override
public void onAktiverSpielerGesetzt(Spieler spieler, int sekunden) {
addMessage("setzeAktivenSpieler " + spieler);
}
@Override
public void onLetztenSpielerGesetzt(Spieler spieler) {
addMessage("setzeLetztenSpieler " + spieler);
}
@Override
public void onBlindLevelChanged(BlindHoehe blindHoehe) {
addMessage("changeBlindLevel " + blindHoehe);
}
@Override
public void onPlayerFold(Spieler spieler) {
addMessage("fold " + spieler);
}
@Override
public void onPlayerCheck(Spieler spieler) {
addMessage("check " + spieler);
}
@Override
public void onPlayerBet(Spieler spieler, int chips) {
addMessage("bet " + spieler + " chips=" + chips);
}
@Override
public void onPlayerRaise(Spieler spieler, int chips) {
addMessage("raise " + spieler + " chips=" + chips);
}
@Override
public void onHoleCardsShown(Spieler spieler, Karte holeCard1, Karte holeCard2) {
addMessage("showHoleCards " + holeCard1 + " " + holeCard2);
}
}
}
| StefanOltmann/PokerGame | server/src/test/java/de/stefan_oltmann/poker/server/SpielControllerTest.java | Java | agpl-3.0 | 8,108 |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'kmol'
SITENAME = 'CDW11 網頁 (虎尾科大MDE)'
SITEURL = 'http://cdw11-40323200.rhcloud.com/static/'
# 不要用文章所在目錄作為類別
USE_FOLDER_AS_CATEGORY = False
#PATH = 'content'
#OUTPUT_PATH = 'output'
TIMEZONE = 'Asia/Taipei'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Blogroll
LINKS = (('Pelican', 'http://getpelican.com/'),
('pelican-bootstrap3', 'https://github.com/DandyDev/pelican-bootstrap3/'),
('pelican-plugins', 'https://github.com/getpelican/pelican-plugins'),
('Tipue search', 'https://github.com/Tipue/Tipue-Search'),)
# Social widget
#SOCIAL = (('You can add links in your config file', '#'),('Another social link', '#'),)
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
# 必須絕對目錄或相對於設定檔案所在目錄
PLUGIN_PATHS = ['plugin']
PLUGINS = ['liquid_tags.notebook', 'summary', 'tipue_search', 'sitemap', 'render_math']
# for sitemap plugin
SITEMAP = {
'format': 'xml',
'priorities': {
'articles': 0.5,
'indexes': 0.5,
'pages': 0.5
},
'changefreqs': {
'articles': 'monthly',
'indexes': 'daily',
'pages': 'monthly'
}
}
# search is for Tipue search
DIRECT_TEMPLATES = (('index', 'tags', 'categories', 'authors', 'archives', 'search'))
# for pelican-bootstrap3 theme settings
#TAG_CLOUD_MAX_ITEMS = 50
DISPLAY_CATEGORIES_ON_SIDEBAR = True
DISPLAY_RECENT_POSTS_ON_SIDEBAR = True
DISPLAY_TAGS_ON_SIDEBAR = True
DISPLAY_TAGS_INLINE = True
TAGS_URL = "tags.html"
CATEGORIES_URL = "categories.html"
#SHOW_ARTICLE_AUTHOR = True
#MENUITEMS = [('Home', '/'), ('Archives', '/archives.html'), ('Search', '/search.html')]
# 希望將部份常用的 Javascript 最新版程式庫放到這裡, 可以透過 http://cadlab.mde.tw/post/js/ 呼叫
STATIC_PATHS = ['js'] | tsrnnash/bg8-cdw11 | static/pelicanconf.py | Python | agpl-3.0 | 2,146 |
import * as React from 'react';
export interface DeleteButtonProps {
questionId: string,
onChange(questionId: string): void
}
export interface NameInputProps {
name: string,
onChange(value: string, e: object): void
}
export const DeleteButton = ({ questionId, onChange }: DeleteButtonProps) => {
function handleClick() { onChange(questionId) }
return <button onClick={handleClick} type="button">Delete</button>;
}
export const NameInput = ({ name, onChange }: NameInputProps) => {
function handleChange(e: object) { onChange('name', e) };
return(
<label className="label" htmlFor="activity-name-input">
Name
<input
aria-label="activity-name-input"
className="input"
id="activity-name-input"
onChange={handleChange}
placeholder="Text input"
type="text"
value={name}
/>
</label>
);
}
| empirical-org/Empirical-Core | services/QuillLMS/client/app/bundles/Diagnostic/components/lessons/lessonFormComponents.tsx | TypeScript | agpl-3.0 | 887 |
import os
from flask import current_app
def get_absolute_file_path(relative_path: str) -> str:
return os.path.join(current_app.config['UPLOAD_FOLDER'], relative_path)
| SamR1/FitTrackee | fittrackee/workouts/utils_files.py | Python | agpl-3.0 | 174 |
/*
* SourceCppStartedEvent.java
*
* Copyright (C) 2020 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.workbench.views.output.sourcecpp.events;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
public class SourceCppStartedEvent extends GwtEvent<SourceCppStartedEvent.Handler>
{
public interface Handler extends EventHandler
{
void onSourceCppStarted(SourceCppStartedEvent event);
}
public SourceCppStartedEvent()
{
}
@Override
public Type<Handler> getAssociatedType()
{
return TYPE;
}
@Override
protected void dispatch(Handler handler)
{
handler.onSourceCppStarted(this);
}
public static final Type<Handler> TYPE = new Type<>();
}
| JanMarvin/rstudio | src/gwt/src/org/rstudio/studio/client/workbench/views/output/sourcecpp/events/SourceCppStartedEvent.java | Java | agpl-3.0 | 1,265 |
'use strict';
define(function(require) {
var Backbone = require('backbone'),
routes = require('routes'),
GroupModel = require('model/groups/group-model');
var GroupsList = Backbone.Collection.extend({
model: GroupModel,
url: routes.absoluteUrl(routes.GROUPS_DATA),
fetch: function(options){
if (this.search) {
(options || (options = {})).data = {
search: this.search
};
}
return Backbone.Collection.prototype.fetch.call(this, options);
}
});
return GroupsList;
}) | hflabs/perecoder | rcd-web/src/main/javascript/app/model/groups/groups-list.js | JavaScript | agpl-3.0 | 619 |
/** @jsx React.DOM */
'use strict';
var Lazy = require('lazy.js'),
React = require('react'),
ReactIntlMixin = require('react-intl');
var EnumerationControl = React.createClass({
mixins: [ReactIntlMixin],
propTypes: {
default: React.PropTypes.string,
error: React.PropTypes.string,
label: React.PropTypes.element.isRequired,
labels: React.PropTypes.object.isRequired,
name: React.PropTypes.string.isRequired,
onChange: React.PropTypes.func.isRequired,
suggestion: React.PropTypes.string,
value: React.PropTypes.oneOfType([
React.PropTypes.number,
React.PropTypes.string,
]),
},
handleChange(event) {
this.props.onChange(event.target.value);
},
render() {
var firstOptionLabel = `${this.getIntlMessage('notIndicated')} (${
this.props.suggestion ?
this.formatMessage(this.getIntlMessage('suggestedValue'), {value: this.props.labels[this.props.suggestion]}) :
this.formatMessage(this.getIntlMessage('defaultValue'), {value: this.props.labels[this.props.default]})
})`;
return (
<div>
{this.props.label}
<select
className="form-control"
id={this.props.name}
onChange={this.handleChange}
value={this.props.value}
>
<option value="">{firstOptionLabel}</option>
{
Lazy(this.props.labels).map((label, labelId) =>
<option key={labelId} value={labelId}>{label}</option>
).toArray()
}
</select>
</div>
);
},
});
module.exports = EnumerationControl;
| openfisca/openfisca-web-ui | openfisca_web_ui/static/js/components/test-case/form/enumeration-control.js | JavaScript | agpl-3.0 | 1,605 |
# -*- coding: utf-8 -*-
"""
This is the common settings file, intended to set sane defaults. If you have a
piece of configuration that's dependent on a set of feature flags being set,
then create a function that returns the calculated value based on the value of
FEATURES[...]. Modules that extend this one can change the feature
configuration in an environment specific config file and re-calculate those
values.
We should make a method that calls all these config methods so that you just
make one call at the end of your site-specific dev file to reset all the
dependent variables (like INSTALLED_APPS) for you.
Longer TODO:
1. Right now our treatment of static content in general and in particular
course-specific static content is haphazard.
2. We should have a more disciplined approach to feature flagging, even if it
just means that we stick them in a dict called FEATURES.
3. We need to handle configuration for multiple courses. This could be as
multiple sites, but we do need a way to map their data assets.
"""
# We intentionally define lots of variables that aren't used, and
# want to import all variables from base settings files
# pylint: disable=W0401, W0611, W0614
import sys
import json
import lms.envs.common
from lms.envs.common import (
USE_TZ, TECH_SUPPORT_EMAIL, PLATFORM_NAME, BUGS_EMAIL, DOC_STORE_CONFIG, ALL_LANGUAGES
)
from path import path
from lms.lib.xblock.mixin import LmsBlockMixin
from cms.lib.xblock.mixin import CmsBlockMixin
from xmodule.modulestore.inheritance import InheritanceMixin
from xmodule.x_module import XModuleMixin, prefer_xmodules
from dealer.git import git
############################ FEATURE CONFIGURATION #############################
FEATURES = {
'USE_DJANGO_PIPELINE': True,
'GITHUB_PUSH': False,
'ENABLE_DISCUSSION_SERVICE': False,
'AUTH_USE_CERTIFICATES': False,
# email address for studio staff (eg to request course creation)
'STUDIO_REQUEST_EMAIL': '',
'STUDIO_NPS_SURVEY': True,
# Segment.io - must explicitly turn it on for production
'SEGMENT_IO': False,
# Enable URL that shows information about the status of various services
'ENABLE_SERVICE_STATUS': False,
# Don't autoplay videos for course authors
'AUTOPLAY_VIDEOS': False,
# If set to True, new Studio users won't be able to author courses unless
# edX has explicitly added them to the course creator group.
'ENABLE_CREATOR_GROUP': False,
# whether to use password policy enforcement or not
'ENFORCE_PASSWORD_POLICY': False,
# If set to True, Studio won't restrict the set of advanced components
# to just those pre-approved by edX
'ALLOW_ALL_ADVANCED_COMPONENTS': False,
# Turn off account locking if failed login attempts exceeds a limit
'ENABLE_MAX_FAILED_LOGIN_ATTEMPTS': False,
# Allow editing of short description in course settings in cms
'EDITABLE_SHORT_DESCRIPTION': True,
# Hide any Personally Identifiable Information from application logs
'SQUELCH_PII_IN_LOGS': False,
# Toggles embargo functionality
'EMBARGO': False,
# Turn on/off Microsites feature
'USE_MICROSITES': False,
}
ENABLE_JASMINE = False
########### course fields #############
# COURSE_EXTEND_FIELDS = lms.envs.common.COURSE_EXTEND_FIELDS
############################# SET PATH INFORMATION #############################
PROJECT_ROOT = path(__file__).abspath().dirname().dirname() # /edx-platform/cms
REPO_ROOT = PROJECT_ROOT.dirname()
COMMON_ROOT = REPO_ROOT / "common"
LMS_ROOT = REPO_ROOT / "lms"
ENV_ROOT = REPO_ROOT.dirname() # virtualenv dir /edx-platform is in
GITHUB_REPO_ROOT = ENV_ROOT / "data"
sys.path.append(REPO_ROOT)
sys.path.append(PROJECT_ROOT / 'djangoapps')
sys.path.append(COMMON_ROOT / 'djangoapps')
sys.path.append(COMMON_ROOT / 'lib')
# For geolocation ip database
GEOIP_PATH = REPO_ROOT / "common/static/data/geoip/GeoIP.dat"
############################# WEB CONFIGURATION #############################
# This is where we stick our compiled template files.
from tempdir import mkdtemp_clean
MAKO_MODULE_DIR = mkdtemp_clean('mako')
MAKO_TEMPLATES = {}
MAKO_TEMPLATES['main'] = [
PROJECT_ROOT / 'templates',
COMMON_ROOT / 'templates',
COMMON_ROOT / 'djangoapps' / 'pipeline_mako' / 'templates',
COMMON_ROOT / 'djangoapps' / 'pipeline_js' / 'templates',
]
for namespace, template_dirs in lms.envs.common.MAKO_TEMPLATES.iteritems():
MAKO_TEMPLATES['lms.' + namespace] = template_dirs
TEMPLATE_DIRS = MAKO_TEMPLATES['main']
EDX_ROOT_URL = ''
LOGIN_REDIRECT_URL = EDX_ROOT_URL + '/signin'
LOGIN_URL = EDX_ROOT_URL + '/signin'
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.core.context_processors.static',
'django.contrib.messages.context_processors.messages',
'django.core.context_processors.i18n',
'django.contrib.auth.context_processors.auth', # this is required for admin
'django.core.context_processors.csrf',
'dealer.contrib.django.staff.context_processor', # access git revision
'contentstore.context_processors.doc_url',
)
# use the ratelimit backend to prevent brute force attacks
AUTHENTICATION_BACKENDS = (
'ratelimitbackend.backends.RateLimitModelBackend',
)
LMS_BASE = None
#################### CAPA External Code Evaluation #############################
XQUEUE_INTERFACE = {
'url': 'http://localhost:8888',
'django_auth': {'username': 'local',
'password': 'local'},
'basic_auth': None,
}
################################# Middleware ###################################
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'staticfiles.finders.FileSystemFinder',
'staticfiles.finders.AppDirectoriesFinder',
'pipeline.finders.PipelineFinder',
)
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
MIDDLEWARE_CLASSES = (
'request_cache.middleware.RequestCache',
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'method_override.middleware.MethodOverrideMiddleware',
# Instead of AuthenticationMiddleware, we use a cache-backed version
'cache_toolbox.middleware.CacheBackedAuthenticationMiddleware',
'student.middleware.UserStandingMiddleware',
'contentserver.middleware.StaticContentServer',
'crum.CurrentRequestUserMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'track.middleware.TrackMiddleware',
# Allows us to dark-launch particular languages
'dark_lang.middleware.DarkLangMiddleware',
'embargo.middleware.EmbargoMiddleware',
# Detects user-requested locale from 'accept-language' header in http request
'django.middleware.locale.LocaleMiddleware',
'django.middleware.transaction.TransactionMiddleware',
# needs to run after locale middleware (or anything that modifies the request context)
'edxmako.middleware.MakoMiddleware',
# catches any uncaught RateLimitExceptions and returns a 403 instead of a 500
'ratelimitbackend.middleware.RateLimitMiddleware',
# for expiring inactive sessions
'session_inactivity_timeout.middleware.SessionInactivityTimeout',
# use Django built in clickjacking protection
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
# Clickjacking protection can be enabled by setting this to 'DENY'
X_FRAME_OPTIONS = 'ALLOW'
############# XBlock Configuration ##########
# This should be moved into an XBlock Runtime/Application object
# once the responsibility of XBlock creation is moved out of modulestore - cpennington
XBLOCK_MIXINS = (LmsBlockMixin, CmsBlockMixin, InheritanceMixin, XModuleMixin)
# Allow any XBlock in Studio
# You should also enable the ALLOW_ALL_ADVANCED_COMPONENTS feature flag, so that
# xblocks can be added via advanced settings
XBLOCK_SELECT_FUNCTION = prefer_xmodules
############################ SIGNAL HANDLERS ################################
# This is imported to register the exception signal handling that logs exceptions
import monitoring.exceptions # noqa
############################ DJANGO_BUILTINS ################################
# Change DEBUG/TEMPLATE_DEBUG in your environment settings files, not here
DEBUG = False
TEMPLATE_DEBUG = False
# Site info
SITE_ID = 1
SITE_NAME = "0.0.0.0:8001"
HTTPS = 'on'
ROOT_URLCONF = 'cms.urls'
IGNORABLE_404_ENDS = ('favicon.ico')
# Email
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.126.com'
EMAIL_PORT = 25
EMAIL_USE_TLS = False
EMAIL_HOST_USER = 'xiaodunxin'
EMAIL_HOST_PASSWORD = '123456qr'
DEFAULT_FROM_EMAIL = 'xiaodunxin@126.com'
DEFAULT_FEEDBACK_EMAIL = 'xiaodunxin@126.com'
SERVER_EMAIL = 'xiaodunxin@126.com'
ADMINS = ()
MANAGERS = ADMINS
# Static content
STATIC_URL = '/static/' + git.revision + "/"
ADMIN_MEDIA_PREFIX = '/static/admin/'
STATIC_ROOT = ENV_ROOT / "staticfiles" / git.revision
STATICFILES_DIRS = [
COMMON_ROOT / "static",
PROJECT_ROOT / "static",
LMS_ROOT / "static",
# This is how you would use the textbook images locally
# ("book", ENV_ROOT / "book_images"),
]
# Locale/Internationalization
TIME_ZONE = 'Asia/Shanghai' # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
LANGUAGE_CODE = 'zh-cn' # http://www.i18nguy.com/unicode/language-identifiers.html
SITE_NAME = 'mooc.diandiyun.com:18010'
LANGUAGES = lms.envs.common.LANGUAGES
USE_I18N = True
USE_L10N = True
# Localization strings (e.g. django.po) are under this directory
LOCALE_PATHS = (REPO_ROOT + '/conf/locale',) # edx-platform/conf/locale/
# Messages
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
# If this is true, random scores will be generated for the purpose of debugging the profile graphs
GENERATE_PROFILE_SCORES = False
############################### Pipeline #######################################
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
from rooted_paths import rooted_glob
PIPELINE_CSS = {
'style-vendor': {
'source_filenames': [
'css/vendor/normalize.css',
'css/vendor/font-awesome.css',
'css/vendor/html5-input-polyfills/number-polyfill.css',
'js/vendor/CodeMirror/codemirror.css',
'css/vendor/ui-lightness/jquery-ui-1.8.22.custom.css',
'css/vendor/jquery.qtip.min.css',
'js/vendor/markitup/skins/simple/style.css',
'js/vendor/markitup/sets/wiki/style.css',
],
'output_filename': 'css/cms-style-vendor.css',
},
'style-app': {
'source_filenames': [
'sass/style-app.css',
],
'output_filename': 'css/cms-style-app.css',
},
'style-app-extend1': {
'source_filenames': [
'sass/style-app-extend1.css',
],
'output_filename': 'css/cms-style-app-extend1.css',
},
'style-xmodule': {
'source_filenames': [
'sass/style-xmodule.css',
],
'output_filename': 'css/cms-style-xmodule.css',
},
'style-calendar-vendor': {
'source_filenames': [
'css/vendor/fullcalendar/fullcalendar.css',
'css/vendor/fullcalendar/fullcalendar_s.css',
'css/vendor/fullcalendar/fullcalendar.print.css',
],
'output_filename': 'css/lms-style-fullcalendar-vendor.css',
}
}
fullcalendar_vendor_js = [
'js/vendor/fullcalendar/moment.min.js',
'js/vendor/fullcalendar/fullcalendar.min.js',
'js/vendor/fullcalendar/jquery-ui.custom.min.js',
'js/vendor/fullcalendar/lang-all.js',
]
# test_order: Determines the position of this chunk of javascript on
# the jasmine test page
PIPELINE_JS = {
'module-js': {
'source_filenames': (
rooted_glob(COMMON_ROOT / 'static/', 'xmodule/descriptors/js/*.js') +
rooted_glob(COMMON_ROOT / 'static/', 'xmodule/modules/js/*.js') +
rooted_glob(COMMON_ROOT / 'static/', 'coffee/src/discussion/*.js')
),
'output_filename': 'js/cms-modules.js',
'test_order': 1
},
'calendar_vendor': {
'source_filenames': fullcalendar_vendor_js,
'output_filename': 'js/lms-fullcalendar_vendor.js',
'test_order': 0,
},
}
PIPELINE_COMPILERS = (
'pipeline.compilers.coffee.CoffeeScriptCompiler',
)
PIPELINE_CSS_COMPRESSOR = None
PIPELINE_JS_COMPRESSOR = None
STATICFILES_IGNORE_PATTERNS = (
"*.py",
"*.pyc"
# it would be nice if we could do, for example, "**/*.scss",
# but these strings get passed down to the `fnmatch` module,
# which doesn't support that. :(
# http://docs.python.org/2/library/fnmatch.html
"sass/*.scss",
"sass/*/*.scss",
"sass/*/*/*.scss",
"sass/*/*/*/*.scss",
"coffee/*.coffee",
"coffee/*/*.coffee",
"coffee/*/*/*.coffee",
"coffee/*/*/*/*.coffee",
# Symlinks used by js-test-tool
"xmodule_js",
"common_static",
)
PIPELINE_YUI_BINARY = 'yui-compressor'
################################# CELERY ######################################
# Message configuration
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_MESSAGE_COMPRESSION = 'gzip'
# Results configuration
CELERY_IGNORE_RESULT = False
CELERY_STORE_ERRORS_EVEN_IF_IGNORED = True
# Events configuration
CELERY_TRACK_STARTED = True
CELERY_SEND_EVENTS = True
CELERY_SEND_TASK_SENT_EVENT = True
# Exchange configuration
CELERY_DEFAULT_EXCHANGE = 'edx.core'
CELERY_DEFAULT_EXCHANGE_TYPE = 'direct'
# Queues configuration
HIGH_PRIORITY_QUEUE = 'edx.core.high'
DEFAULT_PRIORITY_QUEUE = 'edx.core.default'
LOW_PRIORITY_QUEUE = 'edx.core.low'
CELERY_QUEUE_HA_POLICY = 'all'
CELERY_CREATE_MISSING_QUEUES = True
CELERY_DEFAULT_QUEUE = DEFAULT_PRIORITY_QUEUE
CELERY_DEFAULT_ROUTING_KEY = DEFAULT_PRIORITY_QUEUE
CELERY_QUEUES = {
HIGH_PRIORITY_QUEUE: {},
LOW_PRIORITY_QUEUE: {},
DEFAULT_PRIORITY_QUEUE: {}
}
############################## Video ##########################################
# URL to test YouTube availability
YOUTUBE_TEST_URL = 'https://gdata.youtube.com/feeds/api/videos/'
############################ APPS #####################################
INSTALLED_APPS = (
# Standard apps
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'djcelery',
'south',
'method_override',
# Database-backed configuration
'config_models',
# Monitor the status of services
'service_status',
# Testing
'django_nose',
# For CMS
'contentstore',
'course_creators',
'student', # misleading name due to sharing with lms
'course_groups', # not used in cms (yet), but tests run
# Tracking
'track',
'eventtracking.django',
# Monitoring
'datadog',
# For asset pipelining
'edxmako',
'pipeline',
'staticfiles',
'static_replace',
# comment common
'django_comment_common',
# for course creator table
'django.contrib.admin',
# XBlocks containing migrations
'mentoring',
# for managing course modes
'course_modes',
# Dark-launching languages
'dark_lang',
# Student identity reverification
'reverification',
# User preferences
'user_api',
'django_openid_auth',
'embargo',
)
################# EDX MARKETING SITE ##################################
EDXMKTG_COOKIE_NAME = 'edxloggedin'
MKTG_URLS = {}
MKTG_URL_LINK_MAP = {
}
COURSES_WITH_UNSAFE_CODE = []
############################## EVENT TRACKING #################################
TRACK_MAX_EVENT = 10000
TRACKING_BACKENDS = {
'logger': {
'ENGINE': 'track.backends.logger.LoggerBackend',
'OPTIONS': {
'name': 'tracking'
}
}
}
#### PASSWORD POLICY SETTINGS #####
PASSWORD_MIN_LENGTH = None
PASSWORD_MAX_LENGTH = None
PASSWORD_COMPLEXITY = {}
PASSWORD_DICTIONARY_EDIT_DISTANCE_THRESHOLD = None
PASSWORD_DICTIONARY = []
# We're already logging events, and we don't want to capture user
# names/passwords. Heartbeat events are likely not interesting.
TRACKING_IGNORE_URL_PATTERNS = [r'^/event', r'^/login', r'^/heartbeat']
TRACKING_ENABLED = True
# Current youtube api for requesting transcripts.
# for example: http://video.google.com/timedtext?lang=en&v=j_jEn79vS3g.
YOUTUBE_API = {
'url': "http://video.google.com/timedtext",
'params': {'lang': 'en', 'v': 'set_youtube_id_of_11_symbols_here'}
}
##### ACCOUNT LOCKOUT DEFAULT PARAMETERS #####
MAX_FAILED_LOGIN_ATTEMPTS_ALLOWED = 5
MAX_FAILED_LOGIN_ATTEMPTS_LOCKOUT_PERIOD_SECS = 15 * 60
### JSdraw (only installed in some instances)
try:
import edx_jsdraw
except ImportError:
pass
else:
INSTALLED_APPS += ('edx_jsdraw',)
############## SSO KEY ################
SSO_KEY = "SSOFOUNDER"
############## user auth ##############
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
'django.contrib.auth.hashers.SHA1PasswordHasher',
'django.contrib.auth.hashers.MD5PasswordHasher',
'django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher',
'django.contrib.auth.hashers.CryptPasswordHasher'
)
############## SSO KEY ################
SSO_KEY = "SSOFOUNDER"
############## BUSINESS SYSTEM #################
XIAODUN_BACK_HOST = 'http://busi.xiaodun.cn/app'
############## video mettings ##################
VEDIO_MEETING_DOMAIN = "http://passport.guoshi.com/mp"
############## wenjuan domain ##################
WENJUAN_DOMAIN = "http://apitest.wenjuan.com:8000"
####### wenjuan secret_key #######
WENJUAN_SECKEY = "9d15a674a6e621058f1ea9171413b7c0"
| XiaodunServerGroup/ddyedx | cms/envs/common.py | Python | agpl-3.0 | 18,114 |
/*
* Copyright (c) 2015. Philip DeCamp
* Released under the BSD 2-Clause License
* http://opensource.org/licenses/BSD-2-Clause
*/
package bits.photosort;
import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;
import java.text.*;
public class TimestampReader {
public static void main(String[] args) {
try{
test1();
}catch(Exception ex) {
ex.printStackTrace();
}
}
private static void test1() throws Exception {
//String path = "/Volumes/DATA2/hsp_data/forgeorge/living_pics/039.jpg";
String path = "/Users/decamp/Photos/FILE0001.JPG";
ByteBuffer buf = bufferFile(new File(path));
long timestamp = readJpegTimestampMicros(buf);
System.out.println(timestamp);
if(timestamp != Long.MIN_VALUE) {
System.out.println(new java.util.Date(timestamp / 1000L));
}
}
private static ByteBuffer bufferFile(File file) throws IOException {
long size = file.length();
ByteBuffer buf = ByteBuffer.allocate((int)(size & 0x7FFFFFFF));
FileChannel chan = new FileInputStream(file).getChannel();
while(buf.remaining() > 0) {
int n = chan.read(buf);
if(n <= 0)
throw new IOException("Read operation failed.");
}
chan.close();
buf.flip();
return buf;
}
/**
*
* Once we have the ExifMarker data, we need to delve into the where the timestamp
* should be kept. This is a fairly grueling process because we have to go three layers
* deep.
*
* JPEG Marker
* |
* -- TIFF Header
* |
* -- IFD0
* |
* -- SubIFD
* |
* -- MakerNote IFD
* |
* -- Timestamp
*/
public static long readJpegTimestampMicros(ByteBuffer buf) throws IOException {
buf = readExifSegment(buf);
if(buf == null)
return Long.MIN_VALUE;
buf = readTiffHeader(buf);
if(buf == null)
return Long.MIN_VALUE;
int offset = findIfdTagOffset(buf, 0x8769);
if(offset < 0)
return Long.MIN_VALUE;
int off2 = findIfdTagOffset(buf, 0x9003, offset);
if(off2 >= 0) {
if(buf.position() + off2 + 20 > buf.limit())
return -1;
DateFormat format = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
buf.position(buf.position() + off2);
byte[] bytes = new byte[20];
buf.get(bytes);
String dateString = new String(bytes);
try{
return format.parse(dateString).getTime() * 1000L;
}catch(ParseException ex) {
return Long.MIN_VALUE;
}
}
offset = findIfdTagOffset(buf, 0x927C, offset);
if(offset < 0)
return Long.MIN_VALUE;
offset = findIfdTagOffset(buf, 0xFDE8, offset);
if(offset < 0)
return Long.MIN_VALUE;
if(offset + 8 > buf.remaining())
return Long.MIN_VALUE;
buf.position(buf.position() + offset);
int sec = buf.getInt();
int usec = buf.getInt();
return sec * 1000000L + usec;
}
/**
* @param buf Buffer containing JPEG.
* @return buffer containing EXIF segment.
*/
private static ByteBuffer readExifSegment(ByteBuffer buf) {
buf = buf.duplicate();
//Loop through each byte in JPEG and find markers.
while(buf.remaining() >= 4) {
int b = (buf.get() & 0xFF);
//Markers always start with 0xFF. However, they may start with multiple 0xFFs.
while(b == 0xFF) {
if(buf.remaining() < 3)
return null;
b = (buf.get() & 0xFF);
//Another 0xFF means the marker is still starting.
//0x00 means the previous 0xFF was not a marker.
//0xD8 and 0xD9 indicate SOE and EOF (StartOfImage or EndOfImage), which are not segments.
if(b == 0xFF || b == 0x00 || b == 0xD8 || b == 0xD9)
continue;
//After the marker (0xFF + one-byte ID), the next two bytes indicate the segment length.
//The segment length includes itself (two bytes), but not the two-byte marker.
int length = (buf.getShort() & 0xFFFF) - 2;
//Check if we have all the data.
if(length > buf.remaining())
return null;
//Check if this is the exif segment.
if(b == 0xE1) {
buf.limit(buf.position() + length);
return buf;
}
buf.position(buf.position() + length);
}
}
return null;
}
/**
* @param buf Buffer containing EXIF segment.
* @return ByteBuffer containing IFD0.
*/
private static ByteBuffer readTiffHeader(ByteBuffer buf) {
if(buf.remaining() < 6)
return null;
buf = buf.duplicate();
if(buf.get() == 'E' && buf.get() == 'x' && buf.get() == 'i' && buf.get() == 'f' &&
buf.get() == 0 && buf.get() == 0)
{
return buf;
}
return null;
}
/**
* @param buf Buffer containing IFD0
* @return timestamp micros, or Long.MIN_VALUE if not found.
*/
private static long findTimestampMicros(ByteBuffer buf) {
int offset = findIfdTagOffset(buf, 0x8769);
if(offset < 0)
return Long.MIN_VALUE;
offset = findIfdTagOffset(buf, 0x927C, offset);
if(offset < 0)
return Long.MIN_VALUE;
offset = findIfdTagOffset(buf, 0xFDE8, offset);
if(offset < 0)
return Long.MIN_VALUE;
if(offset + 8 > buf.remaining())
return Long.MIN_VALUE;
buf = buf.duplicate();
buf.position(buf.position() + offset);
int sec = buf.getInt();
int usec = buf.getInt();
return sec * 1000000L + usec;
}
/**
* @param buf Buffer containing IFD0
* @param tag Tag of entry to locate.
* @return offset of entry, or -1 if not found.
*/
private static int findIfdTagOffset(ByteBuffer buf, int tag) {
return findIfdTagOffset(buf, tag, -1);
}
/**
* @param buf Buffer containing IFD0
* @param tag Tag of entry to locate.
* @param offset Offset of index to use, or -1 if first index should be used.
* @return offset to entry, or -1 if not found.
*/
private static int findIfdTagOffset(ByteBuffer buf, int tag, int offset) {
if(buf.remaining() < 8)
return -1;
buf = buf.duplicate();
int start = buf.position();
int length = buf.remaining();
//2-byte indicator of byte alignment indicator.
//MM means Motoral (Big-Endian).
//II means Intel (Little-Endian).
{
byte order = buf.get();
if(order != buf.get())
return -1;
if(order == (byte)0x4D) {
buf.order(ByteOrder.BIG_ENDIAN);
}else if(order == (byte)0x49) {
buf.order(ByteOrder.LITTLE_ENDIAN);
}else{
return -1;
}
}
//2-byte constant.
if((buf.getShort() & 0xFFFF) != 0x002A)
return -1;
//If no offset is given, use 4-byte offset to SubIFD tag.
if(offset < 0)
offset = buf.getInt();
//Check offset validity.
if(offset < 0 || length < offset + 2)
return -1;
//Get number of entries.
buf.position(start + offset);
int entryCount = (buf.getShort() & 0xFFFF);
//Check length validity.
if(length < offset + 2 + 12 * entryCount)
return -1;
//Find the entry.
for(int i = 0; i < entryCount; i++) {
buf.position(start + offset + 2 + i * 12);
if((buf.getShort() & 0xFFFF) == tag) {
buf.position(start + offset + 2 + i * 12 + 8);
return buf.getInt();
}
}
return -1;
}
} | decamp/photosort | src/main/java/bits/photosort/TimestampReader.java | Java | agpl-3.0 | 8,819 |
var searchData=
[
['unknown',['UNKNOWN',['../classtetgenmesh.xhtml#a1d02bed7b59566d57b896776d78a6b25a51233a7db87ef44baab2026b0ebdf22f',1,'tetgenmesh']]],
['unusedvertex',['UNUSEDVERTEX',['../classtetgenmesh.xhtml#ad0458f823a5eef2de89c7fae067aa2aca1d0b671fcad449d30b826305df861a52',1,'tetgenmesh']]]
];
| vroland/SimpleAnalyzer | doc/html/search/enumvalues_75.js | JavaScript | agpl-3.0 | 306 |
<?php /* Smarty version 2.6.11, created on 2015-06-17 13:35:10
compiled from cache/modules/AOW_WorkFlow/CasesDetailViewpriority.tpl */ ?>
<?php if (is_string ( $this->_tpl_vars['fields']['priority']['options'] )): ?>
<input type="hidden" class="sugar_field" id="<?php echo $this->_tpl_vars['fields']['priority']['name']; ?>
" value="<?php echo $this->_tpl_vars['fields']['priority']['options']; ?>
">
<?php echo $this->_tpl_vars['fields']['priority']['options']; ?>
<?php else: ?>
<input type="hidden" class="sugar_field" id="<?php echo $this->_tpl_vars['fields']['priority']['name']; ?>
" value="<?php echo $this->_tpl_vars['fields']['priority']['value']; ?>
">
<?php echo $this->_tpl_vars['fields']['priority']['options'][$this->_tpl_vars['fields']['priority']['value']]; ?>
<?php endif; ?> | caleboau2012/edusupport | test/cache/smarty/templates_c/%%19^19B^19BA849F%%CasesDetailViewpriority.tpl.php | PHP | agpl-3.0 | 805 |
package acquire
import (
"archive/zip"
"bytes"
"compress/gzip"
"fmt"
"io/ioutil"
"strings"
)
func unpackReport(filename string, data []byte) ([]byte, error) {
dataBuffer := bytes.NewBuffer(data)
if strings.HasSuffix(filename, ".gz") {
file, err := gzip.NewReader(dataBuffer)
if err != nil {
return nil, err
}
return ioutil.ReadAll(file)
}
if strings.HasSuffix(filename, ".zip") {
bt, err := ioutil.ReadAll(dataBuffer)
if err != nil {
return nil, err
}
r, err := zip.NewReader(bytes.NewReader(bt), int64(len(bt)))
if err != nil {
return nil, err
}
if len(r.File) != 1 {
return nil, fmt.Errorf("Not exactly one file in zip %s", filename)
}
f := r.File[0]
if !strings.HasSuffix(f.Name, ".xml") {
return nil, fmt.Errorf("Not an xml file in zip %s", filename)
}
file, err3 := f.Open()
if err3 != nil {
return nil, err3
}
return ioutil.ReadAll(file)
}
return nil, fmt.Errorf("Unknown extension of file %s", filename)
}
| martinhoefling/go-dmarc-report | acquire/unpack.go | GO | agpl-3.0 | 983 |
"""TOSEC models"""
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=256)
description = models.CharField(max_length=256)
category = models.CharField(max_length=256)
version = models.CharField(max_length=32)
author = models.CharField(max_length=128)
section = models.CharField(max_length=12, default='TOSEC')
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'Categories'
ordering = ('name', )
class Game(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
name = models.CharField(max_length=255)
description = models.CharField(max_length=255)
def __str__(self):
return self.name
class Meta:
ordering = ('category', 'name')
class Rom(models.Model):
game = models.ForeignKey(Game, related_name='roms', on_delete=models.CASCADE)
name = models.CharField(max_length=255)
size = models.IntegerField()
crc = models.CharField(max_length=16)
md5 = models.CharField(max_length=32)
sha1 = models.CharField(max_length=64)
def __str__(self):
return self.name
| lutris/website | tosec/models.py | Python | agpl-3.0 | 1,177 |
<?php
use Civi\Test\HeadlessInterface;
use Civi\Test\HookInterface;
use Civi\Test\TransactionalInterface;
/**
* RaiselyTest - Unit tests for the CiviCRM-Raisely web callback extension
*
* Tips:
* - With HookInterface, you may implement CiviCRM hooks directly in the test class.
* Simply create corresponding functions (e.g. "hook_civicrm_post(...)" or similar).
* - With TransactionalInterface, any data changes made by setUp() or test****() functions will
* rollback automatically -- as long as you don't manipulate schema or truncate tables.
* If this test needs to manipulate schema or truncate tables, then either:
* a. Do all that using setupHeadless() and Civi\Test.
* b. Disable TransactionalInterface, and handle all setup/teardown yourself.
*
* @group headless
*/
class CRM_Raisely_RaiselyTest extends \PHPUnit_Framework_TestCase implements HeadlessInterface, HookInterface, TransactionalInterface {
public function setUpHeadless() {
// Civi\Test has many helpers, like install(), uninstall(), sql(), and sqlFile().
// See: https://github.com/civicrm/org.civicrm.testapalooza/blob/master/civi-test.md
return \Civi\Test::headless()
->installMe(__DIR__)
->apply();
}
public function setUp() {
parent::setUp();
}
public function tearDown() {
parent::tearDown();
}
// Define our test data for several tests
private $test_data = [
'data' => [
'result' => [
'metadata' => [
'first_name' => 'Wonder',
'last_name' => 'Woman',
'email' => 'wonderwoman@justice.league',
'street_address' => '1 Temple Way',
'postal_code' => '2000',
'city' => 'Themyscira',
'state_province' => 'Paradise Islands',
'country' => 'GR',
'contact_type' => 'Individual',
'profile_url' => 'https://themyscira.raisely.com/justiceleague',
'public.donation_amount' => '50.00',
],
'id' => 'ch_1ARxTvH4f1FCRwDmBcQn0iPC',
'status' => 'succeeded',
'description' => 'Donation (79082) of AUD50 from Wonder Woman (153242) to Dummy Person (80298) for Dummy Campaign (1364)',
'currency' => 'aud',
'created' => 1496816247,
'amount' => '5000',
],
],
/**
* Test: _parseDonor returns a well-formed donor array
*/
public function testSuccessfulParseDonor() {
$expected = $test_data['data']['result']['metadata'];
unset($expected['profile_url']);
unset($expected['public.donation_amount']);
$donor = CRM_Raisely_Page_Raisely::_parseDonor($test_data);
$this->assertEquals($expected, $donor);
}
/**
* Test: _parseDonor returns NULL when required fields are missing
*/
public function testParseDonorMissingFields() {
unset($test_data['data']['result']['metadata']['first_name'];
$donor = CRM_Raisely_Page_Raisely::_parseDonor($test_data);
$this->assertNull($donor);
}
/**
* Test: _parseContribution returns a well-formed donor array
*/
public function testSuccessfulParseContribution() {
$expected = $test_data['data']['result'];
unset($expected['metadata']);
$contribution = CRM_Raisely_Page_Raisely::_parseContribution($test_data);
$this->assertEquals($expected, $contribution);
}
/**
* Test: _parseContribution returns NULL when required fields are missing
*/
public function testParseContributionMissingFields() {
$expected = $test_data['data']['result'];
unset($expected['amount']);
$contribution = CRM_Raisely_Page_Raisely::_parseContribution($test_data);
$this->assertNull($contribution);
}
}
| australiangreens/au.org.greens.raisely | tests/phpunit/CRM/Raisely/RaiselyTest.php | PHP | agpl-3.0 | 3,652 |
<?php
/**
* Routes configuration
*
* In this file, you set up routes to your controllers and their actions.
* Routes are very important mechanism that allows you to freely connect
* different URLs to chosen controllers and their actions (functions).
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
use Cake\Core\Plugin;
use Cake\Routing\Router;
/**
* The default class to use for all routes
*
* The following route classes are supplied with CakePHP and are appropriate
* to set as the default:
*
* - Route
* - InflectedRoute
* - DashedRoute
*
* If no call is made to `Router::defaultRouteClass()`, the class used is
* `Route` (`Cake\Routing\Route\Route`)
*
* Note that `Route` does not do any inflections on URLs which will result in
* inconsistently cased URLs when used with `:plugin`, `:controller` and
* `:action` markers.
*
*/
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function ($routes) {
$routes->connect('/', ['controller' => 'Migrations', 'action' => 'index']);
/**
* ...and connect the rest of 'Pages' controller's URLs.
*/
$routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
/**
* Connect catchall routes for all controllers.
*
* Using the argument `DashedRoute`, the `fallbacks` method is a shortcut for
* `$routes->connect('/:controller', ['action' => 'index'], ['routeClass' => 'DashedRoute']);`
* `$routes->connect('/:controller/:action/*', [], ['routeClass' => 'DashedRoute']);`
*
* Any route class can be used with this method, such as:
* - DashedRoute
* - InflectedRoute
* - Route
* - Or your own route class
*
* You can remove these routes once you've connected the
* routes you want in your application.
*/
$routes->fallbacks('DashedRoute');
});
/**
* Load all plugin routes. See the Plugin documentation on
* how to customize the loading of plugin routes.
*/
Plugin::routes();
| Oblady/web-task-runner-for-pentaho | config/routes.php | PHP | agpl-3.0 | 2,500 |
<?php
namespace wcf\data\user\online;
use wcf\data\option\OptionAction;
use wcf\data\session\SessionList;
use wcf\data\user\group\UserGroup;
use wcf\data\user\User;
use wcf\system\event\EventHandler;
use wcf\system\WCF;
use wcf\util\StringUtil;
/**
* Represents a list of currently online users.
*
* @author Marcel Werk
* @copyright 2001-2018 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\Data\User\Online
*
* @method UserOnline current()
* @method UserOnline[] getObjects()
* @method UserOnline|null search($objectID)
* @property UserOnline[] $objects
*/
class UsersOnlineList extends SessionList {
/**
* @inheritDoc
*/
public $sqlOrderBy = 'user_table.username';
/**
* users online stats
* @var array
*/
public $stats = [
'total' => 0,
'invisible' => 0,
'members' => 0,
'guests' => 0
];
/**
* users online markings
* @var array
*/
public $usersOnlineMarkings = null;
/**
* @inheritDoc
*/
public function __construct() {
parent::__construct();
$this->sqlSelects .= "user_avatar.*, user_option_value.*, user_group.userOnlineMarking, user_table.*";
$this->sqlConditionJoins .= " LEFT JOIN wcf".WCF_N."_user user_table ON (user_table.userID = session.userID)";
$this->sqlJoins .= " LEFT JOIN wcf".WCF_N."_user user_table ON (user_table.userID = session.userID)";
$this->sqlJoins .= " LEFT JOIN wcf".WCF_N."_user_option_value user_option_value ON (user_option_value.userID = user_table.userID)";
$this->sqlJoins .= " LEFT JOIN wcf".WCF_N."_user_avatar user_avatar ON (user_avatar.avatarID = user_table.avatarID)";
$this->sqlJoins .= " LEFT JOIN wcf".WCF_N."_user_group user_group ON (user_group.groupID = user_table.userOnlineGroupID)";
$this->getConditionBuilder()->add('session.lastActivityTime > ?', [TIME_NOW - USER_ONLINE_TIMEOUT]);
}
/**
* @inheritDoc
*/
public function readObjects() {
parent::readObjects();
$objects = $this->objects;
$this->indexToObject = $this->objects = [];
foreach ($objects as $object) {
$object = new UserOnline(new User(null, null, $object));
if (!$object->userID || self::isVisible($object->userID, $object->canViewOnlineStatus)) {
$this->objects[$object->sessionID] = $object;
$this->indexToObject[] = $object->sessionID;
}
}
$this->objectIDs = $this->indexToObject;
$this->rewind();
}
/**
* Fetches users online stats.
*/
public function readStats() {
$conditionBuilder = clone $this->getConditionBuilder();
$conditionBuilder->add('session.spiderID IS NULL');
$sql = "SELECT user_option_value.userOption".User::getUserOptionID('canViewOnlineStatus')." AS canViewOnlineStatus, session.userID
FROM wcf".WCF_N."_session session
LEFT JOIN wcf".WCF_N."_user_option_value user_option_value
ON (user_option_value.userID = session.userID)
".$conditionBuilder;
$statement = WCF::getDB()->prepareStatement($sql);
$statement->execute($conditionBuilder->getParameters());
while ($row = $statement->fetchArray()) {
$this->stats['total']++;
if ($row['userID']) {
$this->stats['members']++;
if ($row['canViewOnlineStatus'] && !self::isVisible($row['userID'], $row['canViewOnlineStatus'])) {
$this->stats['invisible']++;
}
}
else {
$this->stats['guests']++;
}
}
}
/**
* Returns a list of the users online markings.
*
* @return array
*/
public function getUsersOnlineMarkings() {
if ($this->usersOnlineMarkings === null) {
$this->usersOnlineMarkings = $priorities = [];
// get groups
foreach (UserGroup::getGroupsByType() as $group) {
if ($group->userOnlineMarking != '%s') {
$priorities[] = $group->priority;
$this->usersOnlineMarkings[] = str_replace('%s', StringUtil::encodeHTML(WCF::getLanguage()->get($group->groupName)), $group->userOnlineMarking);
}
}
// sort list
array_multisort($priorities, SORT_DESC, $this->usersOnlineMarkings);
}
return $this->usersOnlineMarkings;
}
/**
* Checks the users online record.
*/
public function checkRecord() {
$usersOnlineTotal = (USERS_ONLINE_RECORD_NO_GUESTS ? $this->stats['members'] : $this->stats['total']);
if ($usersOnlineTotal > USERS_ONLINE_RECORD) {
// save new record
$optionAction = new OptionAction([], 'import', ['data' => [
'users_online_record' => $usersOnlineTotal,
'users_online_record_time' => TIME_NOW
]]);
$optionAction->executeAction();
}
}
/**
* Checks the 'canViewOnlineStatus' setting.
*
* @param integer $userID
* @param integer $canViewOnlineStatus
* @return boolean
*/
public static function isVisible($userID, $canViewOnlineStatus) {
if (WCF::getSession()->getPermission('admin.user.canViewInvisible') || $userID == WCF::getUser()->userID) return true;
$data = ['result' => false, 'userID' => $userID, 'canViewOnlineStatus' => $canViewOnlineStatus];
switch ($canViewOnlineStatus) {
case 0: // everyone
$data['result'] = true;
break;
case 1: // registered
if (WCF::getUser()->userID) $data['result'] = true;
break;
case 2: // following
/** @noinspection PhpUndefinedMethodInspection */
if (WCF::getUserProfileHandler()->isFollower($userID)) $data['result'] = true;
break;
}
EventHandler::getInstance()->fireAction(get_called_class(), 'isVisible', $data);
return $data['result'];
}
}
| Morik/WCF | wcfsetup/install/files/lib/data/user/online/UsersOnlineList.class.php | PHP | lgpl-2.1 | 5,464 |
package org.cytoscape.task.internal.network;
import java.util.ArrayList;
import java.util.Collection;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.service.util.CyServiceRegistrar;
import org.cytoscape.task.AbstractNetworkCollectionTaskFactory;
import org.cytoscape.task.destroy.DestroyNetworkTaskFactory;
import org.cytoscape.work.TaskFactory;
import org.cytoscape.work.TaskIterator;
/*
* #%L
* Cytoscape Core Task Impl (core-task-impl)
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2006 - 2021 The Cytoscape Consortium
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
public class DestroyNetworkTaskFactoryImpl extends AbstractNetworkCollectionTaskFactory
implements DestroyNetworkTaskFactory, TaskFactory {
private final CyServiceRegistrar serviceRegistrar;
public DestroyNetworkTaskFactoryImpl(CyServiceRegistrar serviceRegistrar) {
this.serviceRegistrar = serviceRegistrar;
}
@Override
public TaskIterator createTaskIterator(Collection<CyNetwork> networks) {
return new TaskIterator(new DestroyNetworkTask(networks, serviceRegistrar));
}
@Override
public TaskIterator createTaskIterator() {
return new TaskIterator(new DestroyNetworkTask(new ArrayList<>(), serviceRegistrar));
}
@Override
public boolean isReady() {
return true;
}
}
| cytoscape/cytoscape-impl | core-task-impl/src/main/java/org/cytoscape/task/internal/network/DestroyNetworkTaskFactoryImpl.java | Java | lgpl-2.1 | 1,942 |
<?php
/*"******************************************************************************************************
* (c) 2004-2006 by MulchProductions, www.mulchprod.de *
* (c) 2007-2015 by Kajona, www.kajona.de *
* Published under the GNU LGPL v2.1, see /system/licence_lgpl.txt *
*-------------------------------------------------------------------------------------------------------*
* $Id$ *
********************************************************************************************************/
/**
* The top-level class for models, installers and top-level files
* An instance of this class is used by the admin & portal object to invoke common database based methods.
* Change with care!
*
* @package module_system
* @author sidler@mulchprod.de
*/
abstract class class_root {
const STR_MODULE_ANNOTATION = "@module";
const STR_MODULEID_ANNOTATION = "@moduleId";
/**
* Instance of class_config
*
* @var class_config
*/
protected $objConfig = null; //Object containing config-data
/**
* Instance of class_db
*
* @var class_db
*/
protected $objDB = null; //Object to the database
/**
* Instance of class_session
*
* @var class_session
*/
protected $objSession = null; //Object containing the session-management
/**
* Instance of class_lang
*
* @var class_lang
*/
private $objLang = null; //Object managing the langfiles
/**
* @var interface_sortmanager
*/
protected $objSortManager = null;
private $strAction; //current action to perform (GET/POST)
protected $arrModule = array(); //Array containing information about the current module
private $arrInitRow = null; //array to be used when loading details from the database. could reduce the amount of queries if populated.
//--- fields to be synchronized with the database ---
/**
* The records current systemid
* @var string
* @templateExport
*
* @tableColumn system.system_id
*/
private $strSystemid = "";
/**
* The records internal parent-id
* @var string
* @versionable
*
* @tableColumn system.system_prev_id
*/
private $strPrevId = -1;
/**
* The old prev-id, used to track hierarchical changes -> requires a rebuild of the rights-table
* @var string
*/
private $strOldPrevId = -1;
/**
* The records module-number
* @var int
* @tableColumn system.system_module_nr
*/
private $intModuleNr = 0;
/**
* The records sort-position relative to the parent record
* @var int
* @tableColumn system.system_sort
*/
private $intSort = -1;
/**
* The id of the user who created the record initially
* @var string
* @versionable
* @templateExport
* @templateMapper user
* @tableColumn system.system_owner
*/
private $strOwner = "";
/**
* The id of the user last who did the last changes to the current record
* @var string
* @tableColumn system.system_lm_user
*/
private $strLmUser = "";
/**
* Timestamp of the last modification
* ATTENTION: time() based, so 32 bit integer
* @todo migrate to long-timestamp
* @var int
* @templateExport
* @templateMapper datetime
* @tableColumn system.system_lm_time
*/
private $intLmTime = 0;
/**
* The id of the user locking the current record, empty otherwise
* @var string
* @tableColumn system.system_lock_id
*/
private $strLockId = "";
/**
* Time the current locking was triggered
* ATTENTION: time() based, so 32 bit integer
* @todo migrate to long-timestamp
* @var int
* @tableColumn system.system_lock_time
*/
private $intLockTime = 0;
/**
* The records status
* @var int
* @versionable
* @tableColumn system.system_status
*/
private $intRecordStatus = 1;
/**
* The records previous status, used to trigger status changed events
* @var int
*/
private $intOldRecordStatus = 1;
/**
* Indicates whether the object is deleted, or not
* @var int
* @versionable
* @tableColumn system.system_deleted
*/
private $intRecordDeleted = 0;
/**
* Human readable comment describing the current record
* @var string
* @tableColumn system.system_comment
*/
private $strRecordComment = "";
/**
* Holds the current objects' class
* @var string
* @tableColumn system.system_class
*/
private $strRecordClass = "";
/**
* Long-based representation of the timestamp the record was created initially
* @var int
* @templateExport
* @templateMapper datetime
* @tableColumn system.system_create_date
*/
private $longCreateDate = 0;
/**
* The start-date of the date-table
* @var class_date
* @versionable
* @templateExport
* @templateMapper datetime
*
* @tableColumn system_date.system_date_start
*/
private $objStartDate = null;
/**
* The end date of the date-table
* @var class_date
* @versionable
* @templateExport
* @templateMapper datetime
*
* @tableColumn system_date.system_date_end
*/
private $objEndDate = null;
/**
* The special-date of the date-table
* @var class_date
* @versionable
* @templateExport
* @templateMapper datetime
*
* @tableColumn system_date.system_date_special
*/
private $objSpecialDate = null;
private $bitDatesChanges = false;
/**
* Constructor
*
* @param string $strSystemid
*
* @return class_root
*/
public function __construct($strSystemid = "") {
//Generating all the needed objects. For this we use our cool cool carrier-object
//take care of loading just the necessary objects
$objCarrier = class_carrier::getInstance();
$this->objConfig = $objCarrier->getObjConfig();
$this->objDB = $objCarrier->getObjDB();
$this->objSession = $objCarrier->getObjSession();
$this->objLang = $objCarrier->getObjLang();
$this->objSortManager = new class_common_sortmanager($this);
//And keep the action
$this->strAction = $this->getParam("action");
$this->strSystemid = $strSystemid;
$this->setStrRecordClass(get_class($this));
//try to load the current module-name and the moduleId by reflection
$objReflection = new class_reflection($this);
if(!isset($this->arrModule["modul"])) {
$arrAnnotationValues = $objReflection->getAnnotationValuesFromClass(self::STR_MODULE_ANNOTATION);
if(count($arrAnnotationValues) > 0) {
$this->setArrModuleEntry("modul", trim($arrAnnotationValues[0]));
$this->setArrModuleEntry("module", trim($arrAnnotationValues[0]));
}
}
if(!isset($this->arrModule["moduleId"])) {
$arrAnnotationValues = $objReflection->getAnnotationValuesFromClass(self::STR_MODULEID_ANNOTATION);
if(count($arrAnnotationValues) > 0) {
$this->setArrModuleEntry("moduleId", constant(trim($arrAnnotationValues[0])));
$this->setIntModuleNr(constant(trim($arrAnnotationValues[0])));
}
}
if($strSystemid != "") {
$this->initObject();
}
}
/**
* Method to invoke object initialization.
* In nearly all cases, this is triggered by the framework itself.
* @return void
*/
public final function initObject() {
$this->initObjectInternal();
$this->internalInit();
//if given, read versioning information
if($this instanceof interface_versionable) {
$objChangelog = new class_module_system_changelog();
$objChangelog->readOldValues($this);
}
}
/**
* InitObjectInternal is called during an objects instantiation.
* The default implementation tries to map all database-fields to the objects fields
* and sets the values automatically.
*
* If you have a different column-property mapping or additional
* setters to call, overwrite this method.
* The row loaded from the database is available by calling $this->getArrInitRow().
* @return void
*/
protected function initObjectInternal() {
$objORM = new class_orm_objectinit($this);
$objORM->initObjectFromDb();
}
/**
* Init the current record with the system-fields
* @return void
*/
private final function internalInit() {
if(validateSystemid($this->getSystemid())) {
if(is_array($this->arrInitRow)) {
$arrRow = $this->arrInitRow;
}
else {
$strQuery = "SELECT *
FROM "._dbprefix_."system
LEFT JOIN "._dbprefix_."system_date
ON system_id = system_date_id
WHERE system_id = ? ";
$arrRow = $this->objDB->getPRow($strQuery, array($this->getSystemid()));
}
if(count($arrRow) > 3) {
//$this->setStrSystemid($arrRow["system_id"]);
$this->strPrevId =$arrRow["system_prev_id"];
$this->intModuleNr = $arrRow["system_module_nr"];
$this->intSort = $arrRow["system_sort"];
$this->strOwner = $arrRow["system_owner"];
$this->strLmUser = $arrRow["system_lm_user"];
$this->intLmTime = $arrRow["system_lm_time"];
$this->strLockId = $arrRow["system_lock_id"];
$this->intLockTime = $arrRow["system_lock_time"];
$this->intRecordStatus = $arrRow["system_status"];
$this->strRecordComment = $arrRow["system_comment"];
$this->longCreateDate = $arrRow["system_create_date"];
if(isset($arrRow["system_class"]))
$this->strRecordClass = $arrRow["system_class"];
if(isset($arrRow["system_deleted"]))
$this->intRecordDeleted = $arrRow["system_deleted"];
$this->strOldPrevId = $this->strPrevId;
$this->intOldRecordStatus = $this->intRecordStatus;
if($arrRow["system_date_start"] > 0)
$this->objStartDate = new class_date($arrRow["system_date_start"]);
if($arrRow["system_date_end"] > 0)
$this->objEndDate = new class_date($arrRow["system_date_end"]);
if($arrRow["system_date_special"] > 0)
$this->objSpecialDate = new class_date($arrRow["system_date_special"]);
}
$this->bitDatesChanges = false;
}
}
/**
* A generic approach to count the number of object currently available.
* This method is only a simple approach to determine the number of instances in the
* database, if you need more specific counts, overwrite this method or add your own
* implementation to the derived class.
*
* @param string $strPrevid
*
* @return int
*/
public static function getObjectCount($strPrevid = "") {
$objORM = new class_orm_objectlist();
return $objORM->getObjectCount(get_called_class(), $strPrevid);
}
/**
* A generic approach to load a list of objects currently available.
* This method is only a simple approach to determine the instances in the
* database, if you need more specific loaders, overwrite this method or add your own
* implementation to the derived class.
*
* @param string $strPrevid
* @param null|int $intStart
* @param null|int $intEnd
*
* @return self[]
*/
public static function getObjectList($strPrevid = "", $intStart = null, $intEnd = null) {
$objORM = new class_orm_objectlist();
return $objORM->getObjectList(get_called_class(), $strPrevid, $intStart, $intEnd);
}
/**
* Validates if the current record may be restored
* @return bool
*/
public function isRestorable() {
//validate the parent nodes' id
$objParent = class_objectfactory::getInstance()->getObject($this->getStrPrevId());
return $objParent != null && $objParent->getIntRecordDeleted() == 0;
}
public function restoreObject() {
/** @var $this class_root|interface_model */
$this->objDB->transactionBegin();
$this->intRecordDeleted = 0;
$this->intSort = $this->getNextSortValue($this->getStrPrevId());
$bitReturn = $this->updateObjectToDb();
class_objectfactory::getInstance()->removeFromCache($this->getSystemid());
class_orm_rowcache::removeSingleRow($this->getSystemid());
$this->objDB->flushQueryCache();
$this->objSortManager->fixSortOnPrevIdChange($this->strPrevId, $this->strPrevId);
$bitReturn = $bitReturn && class_core_eventdispatcher::getInstance()->notifyGenericListeners(class_system_eventidentifier::EVENT_SYSTEM_RECORDRESTORED_LOGICALLY, array($this->getSystemid(), get_class($this), $this));
if($bitReturn) {
class_logger::getInstance()->addLogRow("successfully restored record ".$this->getSystemid()." / ".$this->getStrDisplayName(), class_logger::$levelInfo);
$this->objDB->transactionCommit();
return true;
}
else {
class_logger::getInstance()->addLogRow("error restoring record ".$this->getSystemid()." / ".$this->getStrDisplayName(), class_logger::$levelInfo);
$this->objDB->transactionRollback();
return false;
}
}
/**
* Triggers the logical delete of the current object.
* This means the object itself is not deleted, but marked as deleted. Restoring the object is
* possible.
*
* @throws class_exception
* @return bool
*/
public function deleteObject() {
if(!$this->getLockManager()->isAccessibleForCurrentUser())
return false;
/** @var $this class_root|interface_model */
$this->objDB->transactionBegin();
//validate, if there are subrecords, so child nodes to be deleted
$arrChilds = $this->objDB->getPArray("SELECT system_id FROM "._dbprefix_."system where system_prev_id = ?", array($this->getSystemid()));
foreach($arrChilds as $arrOneChild) {
if(validateSystemid($arrOneChild["system_id"])) {
$objInstance = class_objectfactory::getInstance()->getObject($arrOneChild["system_id"]);
if($objInstance !== null)
$objInstance->deleteObject();
}
}
$this->intRecordDeleted = 1;
$this->intSort = -1;
$bitReturn = $this->updateObjectToDb();
class_objectfactory::getInstance()->removeFromCache($this->getSystemid());
class_orm_rowcache::removeSingleRow($this->getSystemid());
$this->objDB->flushQueryCache();
$this->objSortManager->fixSortOnDelete();
$bitReturn = $bitReturn && class_core_eventdispatcher::getInstance()->notifyGenericListeners(class_system_eventidentifier::EVENT_SYSTEM_RECORDDELETED_LOGICALLY, array($this->getSystemid(), get_class($this)));
if($bitReturn) {
class_logger::getInstance()->addLogRow("successfully deleted record ".$this->getSystemid()." / ".$this->getStrDisplayName(), class_logger::$levelInfo);
$this->objDB->transactionCommit();
return true;
}
else {
class_logger::getInstance()->addLogRow("error deleting record ".$this->getSystemid()." / ".$this->getStrDisplayName(), class_logger::$levelInfo);
$this->objDB->transactionRollback();
return false;
}
}
/**
* Deletes the object from the database. The record is removed in total, so no restoring will be possible.
*
* @return bool
* @throws class_exception
*/
public function deleteObjectFromDatabase() {
if(!$this->getLockManager()->isAccessibleForCurrentUser())
return false;
if($this instanceof interface_versionable) {
$objChanges = new class_module_system_changelog();
$objChanges->createLogEntry($this, class_module_system_changelog::$STR_ACTION_DELETE);
}
/** @var $this class_root|interface_model */
$this->objDB->transactionBegin();
//validate, if there are subrecords, so child nodes to be deleted
$arrChilds = $this->objDB->getPArray("SELECT system_id FROM "._dbprefix_."system where system_prev_id = ?", array($this->getSystemid()));
foreach($arrChilds as $arrOneChild) {
if(validateSystemid($arrOneChild["system_id"])) {
$objInstance = class_objectfactory::getInstance()->getObject($arrOneChild["system_id"]);
if($objInstance !== null)
$objInstance->deleteObjectFromDatabase();
}
}
$objORM = new class_orm_objectdelete($this);
$bitReturn = $objORM->deleteObject();
$this->objSortManager->fixSortOnDelete();
$bitReturn = $bitReturn && $this->deleteSystemRecord($this->getSystemid());
class_objectfactory::getInstance()->removeFromCache($this->getSystemid());
class_orm_rowcache::removeSingleRow($this->getSystemid());
//try to call other modules, maybe wanting to delete anything in addition, if the current record
//is going to be deleted
$bitReturn = $bitReturn && class_core_eventdispatcher::getInstance()->notifyGenericListeners(class_system_eventidentifier::EVENT_SYSTEM_RECORDDELETED, array($this->getSystemid(), get_class($this)));
if($bitReturn) {
class_logger::getInstance()->addLogRow("successfully deleted record ".$this->getSystemid()." / ".$this->getStrDisplayName(), class_logger::$levelInfo);
$this->objDB->transactionCommit();
$this->objDB->flushQueryCache();
return true;
}
else {
class_logger::getInstance()->addLogRow("error deleting record ".$this->getSystemid()." / ".$this->getStrDisplayName(), class_logger::$levelInfo);
$this->objDB->transactionRollback();
$this->objDB->flushQueryCache();
return false;
}
}
// --- DATABASE-SYNCHRONIZATION -------------------------------------------------------------------------
/**
* Saves the current object to the database. Determines, whether the current object has to be inserted
* or updated to the database.
* In case of an update, the objects' updateStateToDb() method is being called (as required by class_model).
* In the case of a new object, a blank record is being created. Therefore, all tables returned by class' doc comment
* will be filled with a new record (using the same new systemid as the primary key).
* The newly created systemid is being set as the current objects' one and can be used in the afterwards
* called updateStateToDb() method to reference the correct rows.
*
* @param string|bool $strPrevId The prev-id of the records, either to be used for the insert or to be used during the update of the record
* @return bool
* @since 3.3.0
* @throws class_exception
* @see interface_model
*
* @todo move to class_orm_objectupdate completely
*/
public function updateObjectToDb($strPrevId = false) {
$bitCommit = true;
/** @var $this class_root|interface_model */
if(!$this instanceof interface_model)
throw new class_exception("current object must implemented interface_model", class_exception::$level_FATALERROR);
if(!$this->getLockManager()->isAccessibleForCurrentUser()) {
$objUser = new class_module_user_user($this->getLockManager()->getLockId());
throw new class_exception("current object is locked by user ".$objUser->getStrDisplayName(), class_exception::$level_ERROR);
}
if(is_object($strPrevId) && $strPrevId instanceof class_root)
$strPrevId = $strPrevId->getSystemid();
$this->objDB->transactionBegin();
//current systemid given? if not, create a new record.
$bitRecordCreated = false;
if(!validateSystemid($this->getSystemid())) {
$bitRecordCreated = true;
if($strPrevId === false || $strPrevId === "" || $strPrevId === null) {
//try to find the current modules-one
if(isset($this->arrModule["modul"])) {
$strPrevId = class_module_system_module::getModuleByName($this->getArrModule("modul"), true)->getSystemid();
if(!validateSystemid($strPrevId))
throw new class_exception("automatic determination of module-id failed ", class_exception::$level_FATALERROR);
}
else
throw new class_exception("insert with no previd ", class_exception::$level_FATALERROR);
}
if(!validateSystemid($strPrevId) && $strPrevId !== "0") {
throw new class_exception("insert with erroneous prev-id ", class_exception::$level_FATALERROR);
}
//create the new systemrecord
//store date-bit temporary
$bitDates = $this->bitDatesChanges;
$this->createSystemRecord($strPrevId, $this->getStrDisplayName());
$this->bitDatesChanges = $bitDates;
if(validateSystemid($this->getStrSystemid())) {
//Create the foreign records
$objAnnotations = new class_reflection($this);
$arrTargetTables = $objAnnotations->getAnnotationValuesFromClass("@targetTable");
if(count($arrTargetTables) > 0) {
foreach($arrTargetTables as $strOneConfig) {
$arrSingleTable = explode(".", $strOneConfig);
$strQuery = "INSERT INTO ".$this->objDB->encloseTableName(_dbprefix_.$arrSingleTable[0])."
(".$this->objDB->encloseColumnName($arrSingleTable[1]).") VALUES
(?) ";
if(!$this->objDB->_pQuery($strQuery, array($this->getStrSystemid())))
$bitCommit = false;
}
}
if(!$this->onInsertToDb())
$bitCommit = false;
}
else
throw new class_exception("creation of systemrecord failed", class_exception::$level_FATALERROR);
//all updates are done, start the "real" update
class_carrier::getInstance()->flushCache(class_carrier::INT_CACHE_TYPE_DBQUERIES);
}
//new prev-id?
if($strPrevId !== false && $this->getSystemid() != $strPrevId && (validateSystemid($strPrevId) || $strPrevId == "0")) {
//validate the new prev id - it is not allowed to set a parent-node as a sub-node of its own child
if(!$this->isSystemidChildNode($this->getSystemid(), $strPrevId))
$this->setStrPrevId($strPrevId);
}
//new comment?
$this->setStrRecordComment($this->getStrDisplayName());
//Keep old and new status here, status changed event is being fired after record is completely updated (so after updateStateToDb())
$intOldStatus = $this->intOldRecordStatus;
$intNewStatus = $this->intRecordStatus;
//save back to the database
$bitCommit = $bitCommit && $this->updateSystemrecord();
//update ourselves to the database
if($bitCommit && !$this->updateStateToDb())
$bitCommit = false;
//now fire the status changed event
if($intOldStatus != $intNewStatus && $intOldStatus != -1) {
class_core_eventdispatcher::getInstance()->notifyGenericListeners(class_system_eventidentifier::EVENT_SYSTEM_STATUSCHANGED, array($this->getSystemid(), $this, $intOldStatus, $intNewStatus));
}
if($bitCommit) {
$this->objDB->transactionCommit();
//unlock the record
$this->getLockManager()->unlockRecord();
class_logger::getInstance()->addLogRow("updateObjectToDb() succeeded for systemid ".$this->getSystemid()." (".$this->getRecordComment().")", class_logger::$levelInfo);
}
else {
$this->objDB->transactionRollback();
class_logger::getInstance()->addLogRow("updateObjectToDb() failed for systemid ".$this->getSystemid()." (".$this->getRecordComment().")", class_logger::$levelWarning);
}
//call the recordUpdated-Listeners
class_core_eventdispatcher::getInstance()->notifyGenericListeners(class_system_eventidentifier::EVENT_SYSTEM_RECORDUPDATED, array($this, $bitRecordCreated));
class_carrier::getInstance()->flushCache(class_carrier::INT_CACHE_TYPE_DBQUERIES);
return $bitCommit;
}
/**
* A default implementation for copy-operations.
* Overwrite this method if you want to execute additional statements.
* Please be aware that you are working on the new object afterwards!
*
* @param string $strNewPrevid
* @param bool $bitChangeTitle
* @param bool $bitCopyChilds
*
* @throws class_exception
* @return bool
*/
public function copyObject($strNewPrevid = "", $bitChangeTitle = true, $bitCopyChilds = true) {
$this->objDB->transactionBegin();
$strOldSysid = $this->getSystemid();
if($strNewPrevid == "")
$strNewPrevid = $this->strPrevId;
//any date-objects to copy?
if($this->objStartDate != null || $this->objEndDate != null || $this->objSpecialDate != null)
$this->bitDatesChanges = true;
//check if there's a title field, in most cases that could be used to change the title
if($bitChangeTitle) {
$objReflection = new class_reflection($this);
$strGetter = $objReflection->getGetter("strTitle");
$strSetter = $objReflection->getSetter("strTitle");
if($strGetter != null && $strSetter != null) {
$strTitle = call_user_func(array($this, $strGetter));
if($strTitle != "") {
call_user_func(array($this, $strSetter), $strTitle."_copy");
}
}
}
//prepare the current object
$this->unsetSystemid();
$this->arrInitRow = null;
$bitReturn = $this->updateObjectToDb($strNewPrevid);
//call event listeners
$bitReturn = $bitReturn && class_core_eventdispatcher::getInstance()->notifyGenericListeners(class_system_eventidentifier::EVENT_SYSTEM_RECORDCOPIED, array($strOldSysid, $this->getSystemid(), $this));
if($bitCopyChilds) {
//process subrecords
//validate, if there are subrecords, so child nodes to be copied to the current record
$arrChilds = $this->objDB->getPArray("SELECT system_id FROM "._dbprefix_."system where system_prev_id = ? ORDER BY system_sort ASC", array($strOldSysid));
foreach($arrChilds as $arrOneChild) {
if(validateSystemid($arrOneChild["system_id"])) {
$objInstance = class_objectfactory::getInstance()->getObject($arrOneChild["system_id"]);
if($objInstance !== null)
$objInstance->copyObject($this->getSystemid(), false);
}
}
}
if($bitReturn)
$this->objDB->transactionCommit();
else
$this->objDB->transactionRollback();
$this->objDB->flushQueryCache();
$bitReturn = $bitReturn && class_core_eventdispatcher::getInstance()->notifyGenericListeners(class_system_eventidentifier::EVENT_SYSTEM_RECORDCOPYFINISHED, array($strOldSysid, $this->getSystemid(), $this));
return $bitReturn;
}
/**
* Internal helper, checks if a child-node is the descendant of a given base-node
*
* @param string $strBaseId
* @param string $strChildId
*
* @return bool
*/
private function isSystemidChildNode($strBaseId, $strChildId) {
while(validateSystemid($strChildId)) {
$objCommon = new class_module_system_common($strChildId);
if($objCommon->getSystemid() == $strBaseId)
return true;
else
return $this->isSystemidChildNode($strBaseId, $objCommon->getPrevId());
}
return false;
}
/**
* Called whenever a update-request was fired.
* Use this method to synchronize the current object with the database.
* Use only updates, inserts are not required to be implemented.
* Provides a default implementation based on the current objects column mappings.
* Override this method whenever you want to perform additional actions or escaping.
*
* @throws class_exception
* @return bool
*/
protected function updateStateToDb() {
$objORMMapper = new class_orm_objectupdate($this);
return $objORMMapper->updateStateToDb();
}
/**
* Overwrite this method if you want to trigger additional commands during the insert
* of an object, e.g. to create additional objects / relations
*
* @return bool
*/
protected function onInsertToDb() {
return true;
}
/**
* Updates the current record to the database and saves all relevant fields.
* Please note that this method is triggered internally.
*
* @return bool
* @final
* @since 3.4.1
*
* @todo find ussages and make private
*/
protected final function updateSystemrecord() {
if(!validateSystemid($this->getSystemid()))
return true;
class_logger::getInstance()->addLogRow("updated systemrecord ".$this->getStrSystemid()." data", class_logger::$levelInfo);
if(class_module_system_module::getModuleByName("system") != null && version_compare(class_module_system_module::getModuleByName("system")->getStrVersion(), 4.5, "lt")) {
$strQuery = "UPDATE "._dbprefix_."system
SET system_prev_id = ?,
system_module_nr = ?,
system_sort = ?,
system_owner = ?,
system_lm_user = ?,
system_lm_time = ?,
system_lock_id = ?,
system_lock_time = ?,
system_status = ?,
system_comment = ?,
system_class = ?,
system_create_date = ?
WHERE system_id = ? ";
$bitReturn = $this->objDB->_pQuery(
$strQuery,
array(
$this->getStrPrevId(),
(int)$this->getIntModuleNr(),
(int)$this->getIntSort(),
$this->getStrOwner(),
$this->objSession->getUserID(),
time(),
$this->getStrLockId(),
(int)$this->getIntLockTime(),
(int)$this->getIntRecordStatus(),
uniStrTrim($this->getStrRecordComment(), 245),
$this->getStrRecordClass(),
$this->getLongCreateDate(),
$this->getSystemid()
)
);
}
else {
$strQuery = "UPDATE "._dbprefix_."system
SET system_prev_id = ?,
system_module_nr = ?,
system_sort = ?,
system_owner = ?,
system_lm_user = ?,
system_lm_time = ?,
system_lock_id = ?,
system_lock_time = ?,
system_status = ?,
system_comment = ?,
system_class = ?,
system_create_date = ?,
system_deleted = ?
WHERE system_id = ? ";
$bitReturn = $this->objDB->_pQuery(
$strQuery,
array(
$this->getStrPrevId(),
(int)$this->getIntModuleNr(),
(int)$this->getIntSort(),
$this->getStrOwner(),
$this->objSession->getUserID(),
time(),
$this->getStrLockId(),
(int)$this->getIntLockTime(),
(int)$this->getIntRecordStatus(),
uniStrTrim($this->getStrRecordComment(), 245),
$this->getStrRecordClass(),
$this->getLongCreateDate(),
$this->getIntRecordDeleted(),
$this->getSystemid()
)
);
}
if($this->bitDatesChanges) {
$this->processDateChanges();
}
class_carrier::getInstance()->flushCache(class_carrier::INT_CACHE_TYPE_DBQUERIES | class_carrier::INT_CACHE_TYPE_ORMCACHE);
if($this->strOldPrevId != $this->strPrevId && $this->strOldPrevId != -1) {
class_carrier::getInstance()->getObjRights()->rebuildRightsStructure($this->getSystemid());
class_core_eventdispatcher::getInstance()->notifyGenericListeners(class_system_eventidentifier::EVENT_SYSTEM_PREVIDCHANGED, array($this->getSystemid(), $this->strOldPrevId, $this->strPrevId));
}
if($this->strOldPrevId != $this->strPrevId) {
$this->objSortManager->fixSortOnPrevIdChange($this->strOldPrevId, $this->strPrevId);
}
$this->strOldPrevId = $this->strPrevId;
$this->intOldRecordStatus = $this->intRecordStatus;
return $bitReturn;
}
/**
* Internal helper to fetch the next sort-id
* @param string $strPrevId
*
* @return int
*/
private function getNextSortValue($strPrevId) {
//determine the correct new sort-id - append by default
if(class_module_system_module::getModuleByName("system") != null && version_compare(class_module_system_module::getModuleByName("system")->getStrVersion(), "4.7.5", "lt")) {
$strQuery = "SELECT COUNT(*) FROM "._dbprefix_."system WHERE system_prev_id = ? AND system_id != '0'";
}
else {
$strQuery = "SELECT COUNT(*) FROM "._dbprefix_."system WHERE system_prev_id = ? AND system_id != '0' AND system_deleted = 0";
}
$arrRow = $this->objDB->getPRow($strQuery, array($strPrevId), 0, false);
$intSiblings = $arrRow["COUNT(*)"];
return (int)($intSiblings+1);
}
/**
* Generates a new SystemRecord and, if needed, the corresponding record in the rights-table (here inheritance is default)
* Returns the systemID used for this record
*
* @param string $strPrevId Previous ID in the tree-structure
* @param string $strComment Comment to identify the record
* @return string The ID used/generated
*
* * @todo find ussages and make private
*/
private function createSystemRecord($strPrevId, $strComment) {
$strSystemId = generateSystemid();
$this->setStrSystemid($strSystemId);
//Correct prevID
if($strPrevId == "")
$strPrevId = 0;
$this->setStrPrevId($strPrevId);
//determine the correct new sort-id - append by default
if(class_module_system_module::getModuleByName("system") != null && version_compare(class_module_system_module::getModuleByName("system")->getStrVersion(), "4.7.5", "lt")) {
$strQuery = "SELECT COUNT(*) FROM "._dbprefix_."system WHERE system_prev_id = ? AND system_id != '0'";
}
else {
$strQuery = "SELECT COUNT(*) FROM "._dbprefix_."system WHERE system_prev_id = ? AND system_id != '0' AND system_deleted = 0";
}
$arrRow = $this->objDB->getPRow($strQuery, array($strPrevId), 0, false);
$intSiblings = $arrRow["COUNT(*)"];
$strComment = uniStrTrim(strip_tags($strComment), 240);
if(class_module_system_module::getModuleByName("system") != null && version_compare(class_module_system_module::getModuleByName("system")->getStrVersion(), "4.7.5", "lt")) {
//So, lets generate the record
$strQuery = "INSERT INTO "._dbprefix_."system
( system_id, system_prev_id, system_module_nr, system_owner, system_create_date, system_lm_user,
system_lm_time, system_status, system_comment, system_sort, system_class) VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
//Send the query to the db
$this->objDB->_pQuery(
$strQuery,
array(
$strSystemId,
$strPrevId,
$this->getIntModuleNr(),
$this->objSession->getUserID(),
class_date::getCurrentTimestamp(),
$this->objSession->getUserID(),
time(),
(int)$this->getIntRecordStatus(),
$strComment,
$this->getNextSortValue($strPrevId),
$this->getStrRecordClass()
)
);
}
else {
//So, lets generate the record
$strQuery = "INSERT INTO "._dbprefix_."system
( system_id, system_prev_id, system_module_nr, system_owner, system_create_date, system_lm_user,
system_lm_time, system_status, system_comment, system_sort, system_class, system_deleted) VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
//Send the query to the db
$this->objDB->_pQuery(
$strQuery,
array(
$strSystemId,
$strPrevId,
$this->getIntModuleNr(),
$this->objSession->getUserID(),
class_date::getCurrentTimestamp(),
$this->objSession->getUserID(),
time(),
(int)$this->getIntRecordStatus(),
$strComment,
(int)($intSiblings + 1),
$this->getStrRecordClass(),
$this->getIntRecordDeleted()
)
);
}
//we need a Rights-Record
$this->objDB->_pQuery("INSERT INTO "._dbprefix_."system_right (right_id, right_inherit) VALUES (?, 1)", array($strSystemId));
//update rights to inherit
class_carrier::getInstance()->getObjRights()->setInherited(true, $strSystemId);
class_logger::getInstance()->addLogRow("new system-record created: ".$strSystemId ." (".$strComment.")", class_logger::$levelInfo);
$this->objDB->flushQueryCache();
$this->internalInit();
//reset the old values since we're having a new record
$this->strOldPrevId = -1;
$this->intOldRecordStatus = -1;
return $strSystemId;
}
/**
* Process date changes handles the insert and update of date-objects.
* It replaces the old createDate and updateDate methods
* @return bool
*/
private function processDateChanges() {
$intStart = 0;
$intEnd = 0;
$intSpecial = 0;
if($this->objStartDate != null && $this->objStartDate instanceof class_date)
$intStart = $this->objStartDate->getLongTimestamp();
if($this->objEndDate != null && $this->objEndDate instanceof class_date)
$intEnd = $this->objEndDate->getLongTimestamp();
if($this->objSpecialDate != null && $this->objSpecialDate instanceof class_date)
$intSpecial = $this->objSpecialDate->getLongTimestamp();
$arrRow = $this->objDB->getPRow("SELECT COUNT(*) FROM "._dbprefix_."system_date WHERE system_date_id = ?", array($this->getSystemid()));
if($arrRow["COUNT(*)"] == 0) {
//insert
$strQuery = "INSERT INTO "._dbprefix_."system_date
(system_date_id, system_date_start, system_date_end, system_date_special) VALUES
(?, ?, ?, ?)";
return $this->objDB->_pQuery($strQuery, array($this->getSystemid(), $intStart, $intEnd, $intSpecial));
}
else {
$strQuery = "UPDATE "._dbprefix_."system_date
SET system_date_start = ?,
system_date_end = ?,
system_date_special = ?
WHERE system_date_id = ?";
return $this->objDB->_pQuery($strQuery, array($intStart, $intEnd, $intSpecial, $this->getSystemid()));
}
}
/**
* Creates a record in the date table. Make sure to use a proper system-id!
* Up from Kajona V3.3, the signature changed. Pass instances of class_date instead of
* int-values.
*
* @param string $strSystemid
* @param class_date $objStartDate
* @param class_date $objEndDate
* @param class_date $objSpecialDate
* @deprecated use the internal date-objects to have all dates handled automatically
* @return bool
*/
public function createDateRecord($strSystemid, class_date $objStartDate = null, class_date $objEndDate = null, class_date $objSpecialDate = null) {
$intStart = 0;
$intEnd = 0;
$intSpecial = 0;
if($objStartDate != null && $objStartDate instanceof class_date)
$intStart = $objStartDate->getLongTimestamp();
if($objEndDate != null && $objEndDate instanceof class_date)
$intEnd = $objEndDate->getLongTimestamp();
if($objSpecialDate != null && $objSpecialDate instanceof class_date)
$intSpecial = $objSpecialDate->getLongTimestamp();
$strQuery = "INSERT INTO "._dbprefix_."system_date
(system_date_id, system_date_start, system_date_end, system_date_special) VALUES
(?, ?, ?, ?)";
return $this->objDB->_pQuery($strQuery, array($strSystemid, $intStart, $intEnd, $intSpecial));
}
/**
* Updates a record in the date table. Make sure to use a proper system-id!
* Up from Kajona V3.3, the signature changed. Pass instances of class_date instead of
* int-values.
*
* @param string $strSystemid
* @param class_date $objStartDate
* @param class_date $objEndDate
* @param class_date $objSpecialDate
* @deprecated use the internal date-objects to have all dates handled automatically
* @return bool
*/
public function updateDateRecord($strSystemid, class_date $objStartDate = null, class_date $objEndDate = null, class_date $objSpecialDate = null) {
$intStart = 0;
$intEnd = 0;
$intSpecial = 0;
if($objStartDate != null && $objStartDate instanceof class_date)
$intStart = $objStartDate->getLongTimestamp();
if($objEndDate != null && $objEndDate instanceof class_date)
$intEnd = $objEndDate->getLongTimestamp();
if($objSpecialDate != null && $objSpecialDate instanceof class_date)
$intSpecial = $objSpecialDate->getLongTimestamp();
$strQuery = "UPDATE "._dbprefix_."system_date
SET system_date_start = ?,
system_date_end = ?,
system_date_special = ?
WHERE system_date_id = ?";
return $this->objDB->_pQuery($strQuery, array($intStart, $intEnd, $intSpecial, $strSystemid));
}
/**
* Returns the bool-value for the right to view this record,
* Systemid MUST be given, otherwise false
*
* @return bool
*/
public function rightView() {
return class_carrier::getInstance()->getObjRights()->rightView($this->getSystemid());
}
/**
* Returns the bool-value for the right to edit this record,
* Systemid MUST be given, otherwise false
*
* @return bool
*/
public function rightEdit() {
return class_carrier::getInstance()->getObjRights()->rightEdit($this->getSystemid());
}
/**
* Returns the bool-value for the right to delete this record,
* Systemid MUST be given, otherwise false
*
* @return bool
*/
public function rightDelete() {
return class_carrier::getInstance()->getObjRights()->rightDelete($this->getSystemid());
}
/**
* Returns the bool-value for the right to change rights of this record,
* Systemid MUST be given, otherwise false
*
* @return bool
*/
public function rightRight() {
return class_carrier::getInstance()->getObjRights()->rightRight($this->getSystemid());
}
/**
* Returns the bool-value for the right1 of this record,
* Systemid MUST be given, otherwise false
*
* @return bool
*/
public function rightRight1() {
return class_carrier::getInstance()->getObjRights()->rightRight1($this->getSystemid());
}
/**
* Returns the bool-value for the right2 of this record,
* Systemid MUST be given, otherwise false
*
* @return bool
*/
public function rightRight2() {
return class_carrier::getInstance()->getObjRights()->rightRight2($this->getSystemid());
}
/**
* Returns the bool-value for the right3 of this record,
* Systemid MUST be given, otherwise false
*
* @return bool
*/
public function rightRight3() {
return class_carrier::getInstance()->getObjRights()->rightRight3($this->getSystemid());
}
/**
* Returns the bool-value for the right4 of this record,
* Systemid MUST be given, otherwise false
*
* @return bool
*/
public function rightRight4() {
return class_carrier::getInstance()->getObjRights()->rightRight4($this->getSystemid());
}
/**
* Returns the bool-value for the right5 of this record,
* Systemid MUST be given, otherwise false
*
* @return bool
*/
public function rightRight5() {
return class_carrier::getInstance()->getObjRights()->rightRight5($this->getSystemid());
}
/**
* Returns the bool-value for the changelog permissions of this record,
* Systemid MUST be given, otherwise false
*
* @return bool
*/
public function rightChangelog() {
return class_carrier::getInstance()->getObjRights()->rightChangelog($this->getSystemid());
}
// --- SystemID & System-Table Methods ------------------------------------------------------------------
/**
* Fetches the number of siblings belonging to the passed systemid
*
* @param string $strSystemid
* @param bool $bitUseCache
* @return int
* @deprecated
*/
public function getNumberOfSiblings($strSystemid = "", $bitUseCache = true) {
if($strSystemid == "")
$strSystemid = $this->getSystemid();
$strQuery = "SELECT COUNT(*)
FROM "._dbprefix_."system as sys1,
"._dbprefix_."system as sys2
WHERE sys1.system_id=?
AND sys2.system_prev_id = sys1.system_prev_id";
$arrRow = $this->objDB->getPRow($strQuery, array($strSystemid), 0, $bitUseCache);
return $arrRow["COUNT(*)"];
}
/**
* Fetches the records placed as child nodes of the current / passed id.
* <b> Only the IDs are fetched since the current object-context is not available!!! </b>
*
* @param string $strSystemid
* @return string[]
* @deprecated
*/
public function getChildNodesAsIdArray($strSystemid = "") {
if($strSystemid == "")
$strSystemid = $this->getSystemid();
$objORM = new class_orm_objectlist();
$strQuery = "SELECT system_id
FROM "._dbprefix_."system
WHERE system_prev_id=?
AND system_id != '0'
".$objORM->getDeletedWhereRestriction()."
ORDER BY system_sort ASC";
$arrReturn = array();
$arrTemp = $this->objDB->getPArray($strQuery, array($strSystemid));
if(count($arrTemp) > 0)
foreach($arrTemp as $arrOneRow)
$arrReturn[] = $arrOneRow["system_id"];
return $arrReturn;
}
/**
* Fetches all child nodes recusrsively of the current / passed id.
* <b> Only the IDs are fetched since the current object-context is not available!!! </b>
*
* @param string $strSystemid
* @return string[]
* @deprecated
*/
public function getAllSubChildNodesAsIdArray($strSystemid = "") {
$arrReturn = $this->getChildNodesAsIdArray($strSystemid);
if(count($arrReturn) > 0) {
foreach($arrReturn as $strId) {
$arrReturn = array_merge($arrReturn, $this->getAllSubChildNodesAsIdArray($strId));
}
}
return $arrReturn;
}
/**
* Sets the Position of a SystemRecord in the currect level one position upwards or downwards
*
* @param string $strDirection upwards || downwards
* @return void
* @deprecated
*/
public function setPosition($strDirection = "upwards") {
$this->objSortManager->setPosition($strDirection);
}
/**
* Sets the position of systemid using a given value.
*
* @param int $intNewPosition
* @param array|bool $arrRestrictionModules If an array of module-ids is passed, the determination of siblings will be limited to the module-records matching one of the module-ids
*
* @return void
*/
public function setAbsolutePosition($intNewPosition, $arrRestrictionModules = false) {
$this->objSortManager->setAbsolutePosition($intNewPosition, $arrRestrictionModules);
}
/**
* Return a complete SystemRecord
*
* @param string $strSystemid
* @return mixed
*/
public function getSystemRecord($strSystemid = "") {
if($strSystemid == "")
$strSystemid = $this->getSystemid();
$strQuery = "SELECT * FROM "._dbprefix_."system
LEFT JOIN "._dbprefix_."system_right
ON system_id = right_id
LEFT JOIN "._dbprefix_."system_date
ON system_id = system_date_id
WHERE system_id = ?";
return $this->objDB->getPRow($strQuery, array($strSystemid));
}
/**
* Returns the data for a registered module
*
* @param string $strName
* @param bool $bitCache
* @return mixed
* @deprecated
* @see class_module_system_module::getPlainModuleData($strName, $bitCache)
*/
public function getModuleData($strName, $bitCache = true) {
return class_module_system_module::getPlainModuleData($strName, $bitCache);
}
/**
* Deletes a record from the SystemTable
*
* @param string $strSystemid
* @param bool $bitRight
* @param bool $bitDate
* @return bool
* @todo: remove first params, is always the current systemid. maybe mark as protected, currently only called by the test-classes
*
* * @todo find ussages and make private
*
*/
public final function deleteSystemRecord($strSystemid, $bitRight = true, $bitDate = true) {
$bitResult = true;
//Start a tx before deleting anything
$this->objDB->transactionBegin();
$strQuery = "DELETE FROM "._dbprefix_."system WHERE system_id = ?";
$bitResult = $bitResult && $this->objDB->_pQuery($strQuery, array($strSystemid));
if($bitRight) {
$strQuery = "DELETE FROM "._dbprefix_."system_right WHERE right_id = ?";
$bitResult = $bitResult && $this->objDB->_pQuery($strQuery, array($strSystemid));
}
if($bitDate) {
$strQuery = "DELETE FROM "._dbprefix_."system_date WHERE system_date_id = ?";
$bitResult = $bitResult && $this->objDB->_pQuery($strQuery, array($strSystemid));
}
//end tx
if($bitResult) {
$this->objDB->transactionCommit();
class_logger::getInstance()->addLogRow("deleted system-record with id ".$strSystemid, class_logger::$levelInfo);
}
else {
$this->objDB->transactionRollback();;
class_logger::getInstance()->addLogRow("deletion of system-record with id ".$strSystemid." failed", class_logger::$levelWarning);
}
//flush the cache
$this->flushCompletePagesCache();
return $bitResult;
}
/**
* Deletes a record from the rights-table
*
* @param string $strSystemid
* @return bool
*/
public function deleteRight($strSystemid) {
$strQuery = "DELETE FROM "._dbprefix_."system_right WHERE right_id = ?";
return $this->objDB->_pQuery($strQuery, array($strSystemid));
}
/**
* Generates a sorted array of systemids, reaching from the passed systemid up
* until the assigned module-id
*
* @param string $strSystemid
* @param string $strStopSystemid
* @return mixed
*/
public function getPathArray($strSystemid = "", $strStopSystemid = "0") {
$arrReturn = array();
if($strSystemid == "") {
$strSystemid = $this->getSystemid();
}
//loop over all parent-records
$strTempId = $strSystemid;
while($strTempId != "0" && $strTempId != "" && $strTempId != -1 && $strTempId != $strStopSystemid) {
$arrReturn[] = $strTempId;
$objCommon = class_objectfactory::getInstance()->getObject($strTempId);
if($objCommon === null) {
break;
}
$strTempId = $objCommon->getPrevId();
}
$arrReturn = array_reverse($arrReturn);
return $arrReturn;
}
/**
* Returns a value from the $arrModule array.
* If the requested key not exists, returns ""
*
* @param string $strKey
* @return string
*/
public function getArrModule($strKey) {
if(isset($this->arrModule[$strKey]))
return $this->arrModule[$strKey];
else
return "";
}
// --- TextMethods --------------------------------------------------------------------------------------
/**
* Used to load a property.
* If you want to provide a list of parameters but no module (automatic loading), pass
* the parameters array as the second argument (an array). In this case the module is resolved
* internally.
*
* @param string $strName
* @param string|array $strModule Either the module name (if required) or an array of parameters
* @param array $arrParameters
*
* @return string
*/
public function getLang($strName, $strModule = "", $arrParameters = array()) {
if(is_array($strModule))
$arrParameters = $strModule;
if($strModule == "" || is_array($strModule)) {
$strModule = $this->getArrModule("modul");
}
//Now we have to ask the Text-Object to return the text
return $this->objLang->getLang($strName, $strModule, $arrParameters);
}
/**
* Returns the current Text-Object Instance
*
* @return class_lang
*/
protected function getObjLang() {
return $this->objLang;
}
// --- PageCache Features -------------------------------------------------------------------------------
/**
* Deletes the complete Pages-Cache
*
* @return bool
*/
public function flushCompletePagesCache() {
return class_cache::flushCache("class_element_portal");
}
/**
* Removes one page from the cache
*
* @param string $strPagename
* @return bool
*/
public function flushPageFromPagesCache($strPagename) {
return class_cache::flushCache("class_element_portal", $strPagename);
}
// --- Portal-Language ----------------------------------------------------------------------------------
/**
* Returns the language to display contents on the portal
*
* @return string
*/
public final function getStrPortalLanguage() {
$objLanguage = new class_module_languages_language();
return $objLanguage->getPortalLanguage();
}
// --- Admin-Language ----------------------------------------------------------------------------------
/**
* Returns the language to display contents or to edit contents on adminside
* NOTE: THIS ARE THE CONTENTS, NOT THE TEXTS
*
* @return string
*/
public final function getStrAdminLanguageToWorkOn() {
$objLanguage = new class_module_languages_language();
return $objLanguage->getAdminLanguage();
}
// --- GETTERS / SETTERS ----------------------------------------------------------------------------
/**
* Sets the current SystemID
*
* @param string $strID
* @return bool
*/
public function setSystemid($strID) {
if(validateSystemid($strID)) {
$this->strSystemid = $strID;
return true;
}
else
return false;
}
/**
* Resets the current systemid
* @return void
*/
public function unsetSystemid() {
$this->strSystemid = "";
}
/**
* Returns the current SystemID
*
* @return string
*/
public function getSystemid() {
return $this->strSystemid;
}
/**
* @return string
*/
public function getStrSystemid() {
return $this->strSystemid;
}
/**
* @param string $strSystemid
* @return void
*/
public function setStrSystemid($strSystemid) {
if(validateSystemid($strSystemid)) {
$this->strSystemid = $strSystemid;
}
}
/**
* Gets the Prev-ID of a record
*
* @param string $strSystemid
*
* @throws class_exception
* @return string
*/
public function getPrevId($strSystemid = "") {
if($strSystemid != "")
throw new class_exception("unsupported param @ ".__METHOD__, class_exception::$level_FATALERROR);
return $this->getStrPrevId();
}
/**
* @return string
*/
public function getStrPrevId() {
return $this->strPrevId;
}
/**
* @param string $strPrevId
* @return void
*/
public function setStrPrevId($strPrevId) {
if(validateSystemid($strPrevId) || $strPrevId === "0") {
$this->strPrevId = $strPrevId;
}
}
/**
* Gets the module id / module nr of a systemRecord
*
* @param string $strSystemid
*
* @throws class_exception
* @return int
*/
public function getRecordModuleNr($strSystemid = "") {
if($strSystemid != "")
throw new class_exception("unsupported param @ ".__METHOD__, class_exception::$level_FATALERROR);
return $this->getIntModuleNr();
}
/**
* @return int
*/
public function getIntModuleNr() {
return $this->intModuleNr;
}
/**
* @param int $intModuleNr
* @return void
*/
public function setIntModuleNr($intModuleNr) {
$this->intModuleNr = $intModuleNr;
}
/**
* @return int
*/
public function getIntSort() {
return $this->intSort;
}
/**
* @param int $intSort
* @return void
*/
public function setIntSort($intSort) {
$this->intSort = $intSort;
}
/**
* Returns the name of the user who last edited the record
*
* @param string $strSystemid
*
* @throws class_exception
* @return string
*/
public function getLastEditUser($strSystemid = "") {
if($strSystemid != "")
throw new class_exception("unsupported param @ ".__METHOD__, class_exception::$level_FATALERROR);
if(validateSystemid($this->getStrLmUser())) {
$objUser = new class_module_user_user($this->getStrLmUser());
return $objUser->getStrDisplayName();
}
else
return "System";
}
/**
* @return string string
*/
public function getStrLmUser() {
return $this->strLmUser;
}
/**
* Returns the id of the user who last edited the record
*
* @return string
*/
public function getLastEditUserId() {
return $this->getStrLmUser();
}
/**
* @param string $strLmUser
* @return void
*/
public function setStrLmUser($strLmUser) {
$this->strLmUser = $strLmUser;
}
/**
* @return int
*/
public function getIntLmTime() {
return $this->intLmTime;
}
/**
* @param int $strLmTime
* @return void
*/
public function setIntLmTime($strLmTime) {
$this->intLmTime = $strLmTime;
}
/**
* @return string
*/
public function getStrLockId() {
return $this->strLockId;
}
/**
* @param string $strLockId
* @return void
*/
public function setStrLockId($strLockId) {
$this->strLockId = $strLockId;
}
/**
* @return int
*/
public function getIntLockTime() {
return $this->intLockTime;
}
/**
* @param int $intLockTime
* @return void
*/
public function setIntLockTime($intLockTime) {
$this->intLockTime = $intLockTime;
}
/**
* @return int
*/
public function getLongCreateDate() {
return $this->longCreateDate;
}
/**
* Returns the creation-date of the current record
*
* @param string $strSystemid
*
* @throws class_exception
* @return class_date
*/
public function getObjCreateDate($strSystemid = "") {
if($strSystemid != "")
throw new class_exception("unsupported param @ ".__METHOD__, class_exception::$level_FATALERROR);
return new class_date($this->getLongCreateDate());
}
/**
* @param int $longCreateDate
* @return void
*/
public function setLongCreateDate($longCreateDate) {
$this->longCreateDate = $longCreateDate;
}
/**
* @return string
*/
public function getStrOwner() {
return $this->strOwner;
}
/**
* @param string $strOwner
* @return void
*/
public function setStrOwner($strOwner) {
$this->strOwner = $strOwner;
}
/**
* Gets the id of the user currently being the owner of the record
*
* @param string $strSystemid
*
* @throws class_exception
* @return string
*/
public final function getOwnerId($strSystemid = "") {
if($strSystemid != "")
throw new class_exception("unsupported param @ ".__METHOD__, class_exception::$level_FATALERROR);
return $this->getStrOwner();
}
/**
* Sets the id of the user who owns this record.
* Please note that since 4.4, setting an owner-id no longer fires an updateObjectToDb()!
*
* @param string $strOwner
* @param string $strSystemid
* @deprecated
*
* @throws class_exception
* @return bool
*/
public final function setOwnerId($strOwner, $strSystemid = "") {
if($strSystemid != "")
throw new class_exception("unsupported param @ ".__METHOD__, class_exception::$level_FATALERROR);
$this->setStrOwner($strOwner);
return true;
}
/**
* @return int
*/
public function getIntRecordStatus() {
return $this->intRecordStatus;
}
/**
* @return int
*/
public function getIntRecordDeleted() {
return $this->intRecordDeleted;
}
/**
* Gets the status of a systemRecord
*
* @param string $strSystemid
*
* @throws class_exception
* @return int
* @deprecated use class_root::getIntRecordStatus() instead
* @see class_root::getIntRecordStatus()
*/
public function getStatus($strSystemid = "") {
if($strSystemid != "")
throw new class_exception("unsupported param @ ".__METHOD__, class_exception::$level_FATALERROR);
return $this->getIntRecordStatus();
}
/**
* Sets the internal status. Fires a status-changed event.
*
* @param int $intRecordStatus
*/
public function setIntRecordStatus($intRecordStatus) {
$this->intRecordStatus = $intRecordStatus;
}
/**
* Gets comment saved with the record
*
* @param string $strSystemid
*
* @throws class_exception
* @return string
*/
public function getRecordComment($strSystemid = "") {
if($strSystemid != "")
throw new class_exception("unsupported param @ ".__METHOD__, class_exception::$level_FATALERROR);
return $this->getStrRecordComment();
}
/**
* @return string
*/
public function getStrRecordComment() {
return $this->strRecordComment;
}
/**
* @param string $strRecordComment
* @return void
*/
public function setStrRecordComment($strRecordComment) {
if(uniStrlen($strRecordComment) > 254)
$strRecordComment = uniStrTrim($strRecordComment, 250);
$this->strRecordComment = $strRecordComment;
}
/**
* @param string $strRecordClass
* @return void
*/
public function setStrRecordClass($strRecordClass) {
$this->strRecordClass = $strRecordClass;
}
/**
* @return string
* @return void
*/
public function getStrRecordClass() {
return $this->strRecordClass;
}
/**
* Writes a value to the params-array
*
* @param string $strKey
* @param mixed $mixedValue Value
* @return void
*/
public function setParam($strKey, $mixedValue) {
class_carrier::getInstance()->setParam($strKey, $mixedValue);
}
/**
* Returns a value from the params-Array
*
* @param string $strKey
* @return string else ""
*/
public function getParam($strKey) {
return class_carrier::getInstance()->getParam($strKey);
}
/**
* Returns the complete Params-Array
*
* @return mixed
*/
public final function getAllParams() {
return class_carrier::getAllParams();
}
/**
* returns the action used for the current request
*
* @return string
*/
public final function getAction() {
return (string)$this->strAction;
}
/**
* Returns an instance of the lockmanager, initialized
* with the current systemid.
*
* @return class_lockmanager
*/
public function getLockManager() {
return new class_lockmanager($this->getSystemid(), $this);
}
/**
* Writes a key-value-pair to the arrModule
*
* @param string $strKey
* @param mixed $strValue
* @return void
*/
public function setArrModuleEntry($strKey, $strValue) {
$this->arrModule[$strKey] = $strValue;
}
/**
* Use this method to set an array of values, e.g. fetched by your own init-method.
* If given, the root-class uses this array to set the internal fields instead of
* triggering another query to the database.
* On high-performance systems or large object-nets, this could reduce the amount of database-queries
* fired drastically.
* For best performance, include the matching row of the tables system, system_date and system_rights
*
* @param array $arrInitRow
* @return void
*/
public function setArrInitRow($arrInitRow) {
if(isset($arrInitRow["system_id"])) {
$this->arrInitRow = $arrInitRow;
}
}
/**
* Returns the set of internal values marked as init-values
* @return null|array
*/
public function getArrInitRow() {
return $this->arrInitRow;
}
/**
* @param \class_date $objEndDate
* @return void
*/
public function setObjEndDate($objEndDate = null) {
if($objEndDate === 0)
$objEndDate = null;
if(!$objEndDate instanceof class_date && $objEndDate != "" && $objEndDate != null)
$objEndDate = new class_date($objEndDate);
$this->objEndDate = $objEndDate;
$this->bitDatesChanges = true;
}
/**
* @return class_date
*/
public function getObjEndDate() {
return $this->objEndDate;
}
/**
* @param \class_date $objSpecialDate
* @return void
*/
public function setObjSpecialDate($objSpecialDate = null) {
if($objSpecialDate === 0)
$objSpecialDate = null;
if(!$objSpecialDate instanceof class_date && $objSpecialDate != "" && $objSpecialDate != null)
$objSpecialDate = new class_date($objSpecialDate);
$this->objSpecialDate = $objSpecialDate;
$this->bitDatesChanges = true;
}
/**
* @return class_date
*/
public function getObjSpecialDate() {
return $this->objSpecialDate;
}
/**
* @param class_date $objStartDate
* @return void
*/
public function setObjStartDate($objStartDate = null) {
if($objStartDate === 0)
$objStartDate = null;
if(!$objStartDate instanceof class_date && $objStartDate != "" && $objStartDate != null)
$objStartDate = new class_date($objStartDate);
$this->bitDatesChanges = true;
$this->objStartDate = $objStartDate;
}
/**
* @return class_date
*/
public function getObjStartDate() {
return $this->objStartDate;
}
}
| jinshana/kajonacms | module_system/system/class_root.php | PHP | lgpl-2.1 | 70,858 |
package net.time4j.range;
import net.time4j.CalendarUnit;
import net.time4j.Duration;
import net.time4j.PlainDate;
import net.time4j.PlainTimestamp;
import net.time4j.Weekcycle;
import net.time4j.engine.TimeSpan;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.text.ParseException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
@RunWith(JUnit4.class)
public class YearsTest {
@Test
public void integer_MIN_VALUE() {
assertThat(
Years.ofGregorian(Integer.MIN_VALUE).getPartialAmount(CalendarUnit.YEARS),
is(-2147483648L));
assertThat(
Years.ofGregorian(Integer.MIN_VALUE).getAmount(),
is(-2147483648));
assertThat(
Years.ofGregorian(Integer.MIN_VALUE).getTotalLength().size(),
is(1));
assertThat(
Years.ofGregorian(Integer.MIN_VALUE).getTotalLength().get(0),
is(TimeSpan.Item.of(-((long) Integer.MIN_VALUE), CalendarUnit.YEARS)));
assertThat(
Years.ofGregorian(Integer.MIN_VALUE).isNegative(),
is(true));
assertThat(
Years.ofGregorian(Integer.MIN_VALUE).toString(),
is("-P2147483648Y"));
}
@Test
public void zero() {
assertThat(
Years.ZERO == Years.ofGregorian(0),
is(true));
assertThat(
Years.ZERO.getPartialAmount(CalendarUnit.YEARS),
is(0L));
assertThat(
Years.ZERO.getAmount(),
is(0));
assertThat(
Years.ZERO.getTotalLength().size(),
is(0));
assertThat(
Years.ZERO.isEmpty(),
is(true));
assertThat(
Years.ZERO.toString(),
is("P0Y"));
}
@Test
public void one() {
assertThat(
Years.ONE == Years.ofGregorian(1),
is(true));
assertThat(
Years.ONE.getPartialAmount(CalendarUnit.YEARS),
is(1L));
assertThat(
Years.ONE.getAmount(),
is(1));
assertThat(
Years.ONE.getTotalLength().size(),
is(1));
assertThat(
Years.ONE.isPositive(),
is(true));
assertThat(
Years.ONE.toString(),
is("P1Y"));
}
@Test
public void signQuery() {
assertThat(
Years.ofGregorian(2).isPositive(),
is(true));
assertThat(
Years.ofGregorian(2).isEmpty(),
is(false));
assertThat(
Years.ofGregorian(2).isNegative(),
is(false));
assertThat(
Years.ofGregorian(-2).isNegative(),
is(true));
assertThat(
Years.ofGregorian(-2).isEmpty(),
is(false));
assertThat(
Years.ofGregorian(-2).isPositive(),
is(false));
}
@Test
public void contains() {
assertThat(Years.ZERO.contains(CalendarUnit.YEARS), is(false));
assertThat(Years.ONE.contains(CalendarUnit.YEARS), is(true));
}
@Test
public void addToPlainDate() {
assertThat(
PlainDate.of(1984, 2, 29).plus(Years.ofGregorian(5)),
is(PlainDate.of(1989, 2, 28)));
assertThat(
Years.ofGregorian(5).addTo(PlainDate.of(1984, 2, 29)),
is(PlainDate.of(1989, 2, 28)));
}
@Test
public void subtractFromPlainDate() {
assertThat(
PlainDate.of(1984, 2, 29).minus(Years.ofGregorian(5)),
is(PlainDate.of(1979, 2, 28)));
assertThat(
Years.ofGregorian(5).subtractFrom(PlainDate.of(1984, 2, 29)),
is(PlainDate.of(1979, 2, 28)));
}
@Test
public void betweenPlainDatesOrTimestamps() {
assertThat(
Years.between(PlainDate.of(1979, 2, 28), PlainDate.of(1985, 2, 27)),
is(Years.ofGregorian(5)));
assertThat(
Years.between(PlainTimestamp.of(1979, 2, 28, 9, 15), PlainTimestamp.of(1985, 2, 28, 9, 15)),
is(Years.ofGregorian(6)));
}
@Test
public void betweenCalendarYears() {
CalendarYear y1 = CalendarYear.of(2013);
CalendarYear y2 = CalendarYear.of(2017);
assertThat(Years.between(y1, y2), is(Years.ofGregorian(4)));
}
@Test
public void abs() {
assertThat(
Years.ofGregorian(-24).abs(),
is(Years.ofGregorian(24)));
assertThat(
Years.ofGregorian(24).abs(),
is(Years.ofGregorian(24)));
assertThat(
Years.ZERO.abs(),
is(Years.ofGregorian(0)));
}
@Test(expected=ArithmeticException.class)
public void absOverflow() {
Years.ofGregorian(Integer.MIN_VALUE).abs();
}
@Test
public void inverse() {
assertThat(
Years.ofGregorian(-24).inverse(),
is(Years.ofGregorian(24)));
assertThat(
Years.ofGregorian(24).inverse(),
is(Years.ofGregorian(-24)));
assertThat(
Years.ZERO.inverse(),
is(Years.ofGregorian(0)));
}
@Test(expected=ArithmeticException.class)
public void inverseOverflow() {
Years.ofGregorian(Integer.MIN_VALUE).inverse();
}
@Test
public void plus() {
assertThat(
Years.ofGregorian(-24).plus(Years.ofGregorian(3)),
is(Years.ofGregorian(-21)));
assertThat(
Years.ofGregorian(24).plus(3),
is(Years.ofGregorian(27)));
assertThat(
Years.ZERO.plus(0),
is(Years.ofGregorian(0)));
}
@Test(expected=ArithmeticException.class)
public void plusOverflow() {
Years.ofGregorian(2).plus(Integer.MAX_VALUE);
}
@Test
public void minus() {
assertThat(
Years.ofGregorian(-24).minus(Years.ofGregorian(3)),
is(Years.ofGregorian(-27)));
assertThat(
Years.ofGregorian(24).minus(3),
is(Years.ofGregorian(21)));
assertThat(
Years.ZERO.minus(0),
is(Years.ofGregorian(0)));
}
@Test(expected=ArithmeticException.class)
public void minusOverflow() {
Years.ofGregorian(-2).minus(Integer.MAX_VALUE);
}
@Test
public void multipliedBy() {
assertThat(
Years.ofGregorian(-24).multipliedBy(-3),
is(Years.ofGregorian(72)));
assertThat(
Years.ZERO.multipliedBy(10),
is(Years.ofGregorian(0)));
}
@Test(expected=ArithmeticException.class)
public void multipliedByOverflow() {
Years.ofGregorian(-2).multipliedBy(Integer.MAX_VALUE);
}
@Test
public void parse() throws ParseException {
assertThat(
Years.parseGregorian("-P35Y"),
is(Years.ofGregorian(-35)));
assertThat(
Years.parseGregorian("P35Y"),
is(Years.ofGregorian(35)));
assertThat(
Years.parseGregorian("P0Y"),
is(Years.ZERO));
}
@Test(expected=ParseException.class)
public void parseNoLiteralP() throws ParseException {
Years.parseGregorian("-35Y");
}
@Test(expected=ParseException.class)
public void parseNoUnitY() throws ParseException {
Years.parseGregorian("P35");
}
@Test(expected=ParseException.class)
public void parseNoDigits() throws ParseException {
Years.parseGregorian("PY");
}
@Test(expected=ParseException.class)
public void parseTrailingChars() throws ParseException {
Years.parseGregorian("P2Yx");
}
@Test
public void parseWeekBased() throws ParseException {
assertThat(
Years.parseWeekBased("-P35Y"),
is(Years.ofWeekBased(-35)));
assertThat(
Years.parseWeekBased("P35Y"),
is(Years.ofWeekBased(35)));
}
@Test
public void compareTo() throws ParseException {
assertThat(
Years.parseWeekBased("-P35Y").compareTo(Years.parseWeekBased("-P35Y")),
is(0));
assertThat(
Years.parseWeekBased("-P35Y").compareTo(Years.parseWeekBased("-P34Y")),
is(-1));
assertThat(
Years.parseWeekBased("-P35Y").compareTo(Years.parseWeekBased("-P36Y")),
is(1));
}
@Test(expected=ClassCastException.class)
@SuppressWarnings("unchecked")
public void compareToGregorianWeekBased() throws ParseException {
Years y1 = Years.parseGregorian("-P35Y");
Years y2 = Years.parseWeekBased("-P35Y");
y1.compareTo(y2);
}
@Test
public void getUnit() {
assertThat(Years.ofGregorian(15).getUnit(), is(CalendarUnit.YEARS));
assertThat(Years.ofWeekBased(15).getUnit(), is(CalendarUnit.weekBasedYears()));
}
@Test
public void toDuration() {
assertThat(Years.ofGregorian(15).toStdDuration(), is(Duration.ofCalendarUnits(15, 0, 0)));
assertThat(Years.ofWeekBased(-15).toStdDuration(), is(Duration.of(-15, Weekcycle.YEARS)));
}
} | MenoData/Time4J | base/src/test/java/net/time4j/range/YearsTest.java | Java | lgpl-2.1 | 9,209 |