code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
<!DOCTYPE html>
<html lang="en"
>
<head>
<title>第14課 - forRange with Lists forRange與列表 - 2017Spring 協同產品設計實習 (虎尾科大MDE)</title>
<!-- Using the latest rendering mode for IE -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="canonical" href="./Lesson 14.html">
<meta name="author" content="40423222" />
<meta name="keywords" content="notes,Lesson 14" />
<meta name="description" content="關於for的range( )配合列表的介紹 參考資訊: 網站: https://automatetheboringstuff.com/chapter4/ 影片: https://www.youtube.com/watch?v=umTnflPbYww" />
<meta property="og:site_name" content="2017Spring 協同產品設計實習 (虎尾科大MDE)" />
<meta property="og:type" content="article"/>
<meta property="og:title" content="第14課 - forRange with Lists forRange與列表"/>
<meta property="og:url" content="./Lesson 14.html"/>
<meta property="og:description" content="關於for的range( )配合列表的介紹 參考資訊: 網站: https://automatetheboringstuff.com/chapter4/ 影片: https://www.youtube.com/watch?v=umTnflPbYww"/>
<meta property="article:published_time" content="2017-09-10" />
<meta property="article:section" content="Python" />
<meta property="article:tag" content="notes" />
<meta property="article:tag" content="Lesson 14" />
<meta property="article:author" content="40423222" />
<!-- Bootstrap -->
<link rel="stylesheet" href="./theme/css/bootstrap.united.min.css" type="text/css"/>
<link href="./theme/css/font-awesome.min.css" rel="stylesheet">
<link href="./theme/css/pygments/monokai.css" rel="stylesheet">
<link href="./theme/tipuesearch/tipuesearch.css" rel="stylesheet">
<link rel="stylesheet" href="./theme/css/style.css" type="text/css"/>
<link href="./feeds/all.atom.xml" type="application/atom+xml" rel="alternate"
title="2017Spring 協同產品設計實習 (虎尾科大MDE) ATOM Feed"/>
<script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shCore.js"></script>
<script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushJScript.js"></script>
<script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushJava.js"></script>
<script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushPython.js"></script>
<script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushSql.js"></script>
<script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushXml.js"></script>
<script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushPhp.js"></script>
<script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushCpp.js"></script>
<script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushCss.js"></script>
<script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushCSharp.js"></script>
<script type="text/javascript" src="https://coursemdetw.github.io/project_site_files/files/syntaxhighlighter/shBrushBash.js"></script>
<script type='text/javascript'>
(function(){
var corecss = document.createElement('link');
var themecss = document.createElement('link');
var corecssurl = "https://chiamingyen.github.io/kmolab_data/files/syntaxhighlighter/css/shCore.css";
if ( corecss.setAttribute ) {
corecss.setAttribute( "rel", "stylesheet" );
corecss.setAttribute( "type", "text/css" );
corecss.setAttribute( "href", corecssurl );
} else {
corecss.rel = "stylesheet";
corecss.href = corecssurl;
}
document.getElementsByTagName("head")[0].insertBefore( corecss, document.getElementById("syntaxhighlighteranchor") );
var themecssurl = "https://chiamingyen.github.io/kmolab_data/files/syntaxhighlighter/css/shThemeDefault.css?ver=3.0.9b";
if ( themecss.setAttribute ) {
themecss.setAttribute( "rel", "stylesheet" );
themecss.setAttribute( "type", "text/css" );
themecss.setAttribute( "href", themecssurl );
} else {
themecss.rel = "stylesheet";
themecss.href = themecssurl;
}
//document.getElementById("syntaxhighlighteranchor").appendChild(themecss);
document.getElementsByTagName("head")[0].insertBefore( themecss, document.getElementById("syntaxhighlighteranchor") );
})();
SyntaxHighlighter.config.strings.expandSource = '+ expand source';
SyntaxHighlighter.config.strings.help = '?';
SyntaxHighlighter.config.strings.alert = 'SyntaxHighlighter\n\n';
SyntaxHighlighter.config.strings.noBrush = 'Can\'t find brush for: ';
SyntaxHighlighter.config.strings.brushNotHtmlScript = 'Brush wasn\'t configured for html-script option: ';
SyntaxHighlighter.defaults['pad-line-numbers'] = false;
SyntaxHighlighter.defaults['toolbar'] = false;
SyntaxHighlighter.all();
</script>
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="./" class="navbar-brand">
2017Spring 協同產品設計實習 (虎尾科大MDE) </a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li><a href="./pages/about/">
About
</a></li>
<li class="active">
<a href="./category/python.html">Python</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span>
<form class="navbar-search" action="./search.html">
<input type="text" class="search-query" placeholder="Search" name="q" id="tipue_search_input" required>
</form></span>
</li>
<li><a href="./archives.html"><i class="fa fa-th-list"></i><span class="icon-label">Archives</span></a></li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
</div> <!-- /.navbar -->
<!-- Banner -->
<!-- End Banner -->
<div class="container">
<div class="row">
<div class="col-sm-9">
<section id="content">
<article>
<header class="page-header">
<h1>
<a href="./Lesson 14.html"
rel="bookmark"
title="Permalink to 第14課 - forRange with Lists forRange與列表">
第14課 - forRange with Lists forRange與列表
</a>
</h1>
</header>
<div class="entry-content">
<div class="panel">
<div class="panel-body">
<footer class="post-info">
<span class="label label-default">Date</span>
<span class="published">
<i class="fa fa-calendar"></i><time datetime="2017-09-10T18:44:00+08:00"> Sun 10 September 2017</time>
</span>
<span class="label label-default">By</span>
<a href="./author/40423222.html"><i class="fa fa-user"></i> 40423222</a>
<span class="label label-default">Tags</span>
<a href="./tag/notes.html">notes</a>
/
<a href="./tag/lesson-14.html">Lesson 14</a>
</footer><!-- /.post-info --> </div>
</div>
<p>關於for的range( )配合列表的介紹<br>
參考資訊:
網站: <a href="https://automatetheboringstuff.com/chapter4/">https://automatetheboringstuff.com/chapter4/</a>
影片: <a href="https://www.youtube.com/watch?v=umTnflPbYww">https://www.youtube.com/watch?v=umTnflPbYww</a></p>
<hr>
<!-- 關於for的range與列表功用的介紹 -->
<h3>說明:</h3>
<p>forRange with Lists forRange與列表
<ul>
<li>for i in range(4) 等於 for i in [0, 1, 2, 3],所以在L-13的Lists能使用for i in ListsName
<li>常見的Python所使用的range範圍為 range(len(someList)),也就是看列表長度
<li>可利用List來建立operators(運算符號),利用值in列表得出True or False
<li>更多功能在下方圖片介紹
</ul></p>
<hr>
<!-- 因為圖片字太小所以要更改平時的圖片格式,需要改回來 可以去參考第11課 -->
<h3>forRange跟Lists的用法:</h3>
<p><img src="./../data/L-14/img/forRange with Lists.png" width="850"></p>
</div>
<!-- /.entry-content -->
</article>
</section>
</div>
<div class="col-sm-3" id="sidebar">
<aside>
<section class="well well-sm">
<ul class="list-group list-group-flush">
<li class="list-group-item"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Recent Posts</span></h4>
<ul class="list-group" id="recentposts">
<li class="list-group-item">
<a href="./Lesson 16.html">
第16課 - type( ), mutable and Immutable, copy( ) 列表更多應用
</a>
</li>
<li class="list-group-item">
<a href="./Lesson 15.html">
第15課 - index( ), append( ), insert( ), remove( ), sort( ) 用於列表的指令
</a>
</li>
<li class="list-group-item">
<a href="./Lesson 14.html">
第14課 - forRange with Lists forRange與列表
</a>
</li>
<li class="list-group-item">
<a href="./Lesson 13.html">
第13課 - Lists 列表
</a>
</li>
<li class="list-group-item">
<a href="./Flowchart.html">
Python flowchart 目錄
</a>
</li>
</ul>
</li>
<li class="list-group-item"><a href="./categories.html"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Categories</span></h4></a>
<ul class="list-group" id="categories">
<li class="list-group-item">
<a href="./category/python.html">
<i class="fa fa-folder-open fa-lg"></i> Python
</a>
</li>
</ul>
</li>
<li class="list-group-item"><a href="./tags.html"><h4><i class="fa fa-tags fa-lg"></i><span class="icon-label">Tags</span></h4></a>
<ul class="list-group list-inline tagcloud" id="tags">
</ul>
</li>
<li class="list-group-item"><h4><i class="fa fa-external-link-square fa-lg"></i><span class="icon-label">Links</span></h4>
<ul class="list-group" id="links">
<li class="list-group-item">
<a href="http://getpelican.com/" target="_blank">
Pelican
</a>
</li>
<li class="list-group-item">
<a href="https://github.com/DandyDev/pelican-bootstrap3/" target="_blank">
pelican-bootstrap3
</a>
</li>
<li class="list-group-item">
<a href="https://github.com/getpelican/pelican-plugins" target="_blank">
pelican-plugins
</a>
</li>
<li class="list-group-item">
<a href="https://github.com/Tipue/Tipue-Search" target="_blank">
Tipue search
</a>
</li>
</ul>
</li>
</ul>
</section>
</aside>
</div>
</div>
</div>
<footer>
<div class="container">
<hr>
<div class="row">
<div class="col-xs-10">© 2017 KMOL
· Powered by <a href="https://github.com/DandyDev/pelican-bootstrap3" target="_blank">pelican-bootstrap3</a>,
<a href="http://docs.getpelican.com/" target="_blank">Pelican</a>,
<a href="http://getbootstrap.com" target="_blank">Bootstrap</a> </div>
<div class="col-xs-2"><p class="pull-right"><i class="fa fa-arrow-up"></i> <a href="#">Back to top</a></p></div>
</div>
</div>
</footer>
<script src="./theme/js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="./theme/js/bootstrap.min.js"></script>
<!-- for https://github.com/jsor/lity lightbox video popup -->
<link href="./theme/css/lity.css" rel="stylesheet">
<script src="./theme/js/lity.js"></script>
<!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) -->
<script src="./theme/js/respond.min.js"></script>
</body>
</html> | 40423222/Python | blog/Lesson 14.html | HTML | agpl-3.0 | 13,619 |
# frozen_string_literal: true
require 'spec_helper'
describe 'SharedStrings' do
it 'custom_shared_strings_name.xlsx' do
xlsx = OoxmlParser::Parser.parse('spec/workbook/shared_strings/custom_shared_strings_name.xlsx')
expect(xlsx.shared_strings_table.count).to eq(1)
end
end
| ONLYOFFICE/ooxml_parser | spec/workbook/shared_strings_spec.rb | Ruby | agpl-3.0 | 288 |
exports.main = function(env){
var capsule = env.capsule;
var mtests = capsule.tests.modules;
var thsocket = capsule.tests.modules.transport.http.socket_srv;
// mtests.http_responder.test(capsule);
// thsocket.test({ 'url' : 'http://localhost:8810/sockethh.js'}, capsule);
var thttp = capsule.tests.modules.transport.http.server;
thttp.test({ 'url' : 'http://localhost:8810/krevetk/o'}, capsule);
}
| ixdu/capsule | tests/deployer/nodejs_srv/capsulated.js | JavaScript | agpl-3.0 | 445 |
/*******************************************************************************
* This file is part of Termitaria, a project management tool
* Copyright (C) 2008-2013 CodeSphere S.R.L., www.codesphere.ro
*
* Termitaria 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 Termitaria. If not, see <http://www.gnu.org/licenses/> .
******************************************************************************/
package ro.cs.logaudit.entity;
/**
* @author matti_joona
*
*/
public class Role {
private int roleId;
private String name;
private String description;
private String observation;
private Module module;
/**
* @return the module
*/
public Module getModule() {
return module;
}
/**
* @param module the module to set
*/
public void setModule(Module module) {
this.module = module;
}
/**
* @return the roleId
*/
public int getRoleId() {
return roleId;
}
/**
* @param roleId the roleId to set
*/
public void setRoleId(int roleId) {
this.roleId = roleId;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return the observation
*/
public String getObservation() {
return observation;
}
/**
* @param observation the observation to set
*/
public void setObservation(String observation) {
this.observation = observation;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuffer sb = new StringBuffer("[");
sb.append(this.getClass().getSimpleName());
sb.append(": ");
sb.append("roleId = ") .append(roleId) .append(", ");
sb.append("name = ") .append(name) .append(", ");
sb.append("description = ") .append(description).append(", ");
sb.append("observation = ") .append(observation).append(", ");
sb.append("module = ") .append(module) .append("]");
return sb.toString();
}
}
| CodeSphere/termitaria | TermitariaAudit/JavaSource/ro/cs/logaudit/entity/Role.java | Java | agpl-3.0 | 2,881 |
--[[
catfact.lua
Returns cat facts.
Based on a plugin by matthewhesketh.
Copyright 2016 topkecleon <[email protected]>
This code is licensed under the GNU AGPLv3. See /LICENSE for details.
]]--
local JSON = require('dkjson')
local HTTP = require('socket.http')
local utilities = require('otouto.utilities')
local catfact = {name = 'catfact'}
function catfact:init()
catfact.triggers = utilities.triggers(self.info.username, self.config.cmd_pat)
:t('catfact', true).table
catfact.command = 'catfact'
catfact.doc = 'Returns a cat fact.'
catfact.url = 'http://catfacts-api.appspot.com/api/facts'
end
function catfact:action(msg)
local jstr, code = HTTP.request(catfact.url)
if code ~= 200 then
utilities.send_reply(msg, self.config.errors.connection)
return
end
local data = JSON.decode(jstr)
local output = '*Cat Fact*\n_' .. data.facts[1] .. '_'
utilities.send_message(msg.chat.id, output, true, nil, true)
end
return catfact
| bb010g/otouto | otouto/plugins/catfact.lua | Lua | agpl-3.0 | 1,011 |
<?php
include_once '../../../../../../lib/defaults.php';
include_once '../fns/place_point_method_page.php';
include_once '../../../../../fns/ApiDoc/trueResult.php';
place_point_method_page('delete', [
[
'name' => 'id',
'description' => 'The ID of the point to delete.',
],
], ApiDoc\trueResult(), [
'POINT_NOT_FOUND' => "A point with the ID doesn't exist.",
]);
| zvini/website | www/help/api-doc/place/point/delete/index.php | PHP | agpl-3.0 | 392 |
package de.dvdb.domain.model.social;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "dvdb2_fbsession")
public class FacebookSession implements Serializable {
private static final long serialVersionUID = -8753714944734959457L;
private Long id;
private String sessionKey;
private Long user;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "user_id")
public Long getUser() {
return user;
}
public void setUser(Long user) {
this.user = user;
}
@Column(name = "sessionkey")
public String getSessionKey() {
return sessionKey;
}
public void setSessionKey(String sessionKey) {
this.sessionKey = sessionKey;
}
}
| chris-dvdb/dvdb.de | dvdb-ejb/src/main/java/de/dvdb/domain/model/social/FacebookSession.java | Java | agpl-3.0 | 961 |
/* Copyright (c) 2006-2012 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the 2-clause BSD license.
* See license.txt in the OpenLayers distribution or repository for the
* full text of the license. */
/**
* @requires OpenLayers/Format/SLD/v1.js
* @requires OpenLayers/Format/Filter/v1_0_0.js
*/
/**
* Class: OpenLayers.Format.SLD.v1_0_0
* Write SLD version 1.0.0.
*
* Inherits from:
* - <OpenLayers.Format.SLD.v1>
*/
OpenLayers.Format.SLD.v1_0_0 = OpenLayers.Class(
OpenLayers.Format.SLD.v1, {
/**
* Constant: VERSION
* {String} 1.0.0
*/
VERSION: "1.0.0",
/**
* Property: schemaLocation
* {String} http://www.opengis.net/sld
* http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd
*/
schemaLocation: "http://www.opengis.net/sld http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd",
/**
* Constructor: OpenLayers.Format.SLD.v1_0_0
* Instances of this class are not created directly. Use the
* <OpenLayers.Format.SLD> constructor instead.
*
* Parameters:
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
CLASS_NAME: "OpenLayers.Format.SLD.v1_0_0"
});
| B3Partners/geo-ov | src/main/webapp/openlayers/lib/OpenLayers/Format/SLD/v1_0_0.js | JavaScript | agpl-3.0 | 1,351 |
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2015 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
// ===================================================================================================
package com.kaltura.client.types;
import org.w3c.dom.Element;
import com.kaltura.client.KalturaParams;
import com.kaltura.client.KalturaApiException;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class KalturaUiConfAdminFilter extends KalturaUiConfAdminBaseFilter {
public KalturaUiConfAdminFilter() {
}
public KalturaUiConfAdminFilter(Element node) throws KalturaApiException {
super(node);
}
public KalturaParams toParams() throws KalturaApiException {
KalturaParams kparams = super.toParams();
kparams.add("objectType", "KalturaUiConfAdminFilter");
return kparams;
}
}
| moskiteau/KalturaGeneratedAPIClientsJava | src/main/java/com/kaltura/client/types/KalturaUiConfAdminFilter.java | Java | agpl-3.0 | 2,117 |
# -*- coding: utf-8 -*-
import os
import shutil
import sys
import datetime
from invoke import task
from invoke.util import cd
from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer
CONFIG = {
# Local path configuration (can be absolute or relative to tasks.py)
'deploy_path': '..',
# Github Pages configuration
'github_pages_branch': 'gh-pages',
'commit_message': "'Publish site on {}'".format(datetime.date.today().isoformat()),
# Port for `serve`
'port': 8000,
}
@task
def clean(c):
"""Remove generated files"""
if os.path.isdir(CONFIG['deploy_path']):
shutil.rmtree(CONFIG['deploy_path'])
os.makedirs(CONFIG['deploy_path'])
@task
def build(c):
"""Build local version of site"""
c.run('pelican -s pelicanconf.py')
@task
def rebuild(c):
"""`build` with the delete switch"""
c.run('pelican -d -s pelicanconf.py')
@task
def regenerate(c):
"""Automatically regenerate site upon file modification"""
c.run('pelican -r -s pelicanconf.py')
@task
def serve(c):
"""Serve site at http://localhost:8000/"""
class AddressReuseTCPServer(RootedHTTPServer):
allow_reuse_address = True
server = AddressReuseTCPServer(
CONFIG['deploy_path'],
('', CONFIG['port']),
ComplexHTTPRequestHandler)
sys.stderr.write('Serving on port {port} ...\n'.format(**CONFIG))
server.serve_forever()
@task
def reserve(c):
"""`build`, then `serve`"""
build(c)
serve(c)
@task
def preview(c):
"""Build production version of site"""
c.run('pelican -s publishconf.py')
@task
def publish(c):
"""Publish to production via rsync"""
c.run('pelican -s publishconf.py')
c.run(
'rsync --delete --exclude ".DS_Store" -pthrvz -c '
'{} {production}:{dest_path}'.format(
CONFIG['deploy_path'].rstrip('/') + '/',
**CONFIG))
@task
def gh_pages(c):
"""Publish to GitHub Pages"""
preview(c)
c.run('ghp-import -b {github_pages_branch} '
'-m {commit_message} '
'{deploy_path} -p'.format(**CONFIG))
| webcamoid/webcamoid.github.io | internal/tasks.py | Python | agpl-3.0 | 2,105 |
<?php
/**
* This file is part of the Checkbook NYC financial transparency software.
*
* Copyright (C) 2012, 2013 New York City
*
* 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/>.
*/
?>
<?php
echo eval($node->widgetConfig->header);
?>
<a class="trends-export" href="/export/download/trends_pledged_rev_cov_nyc_trans_csv?dataUrl=/node/<?php echo $node->nid ?>">Export</a>
<h5>(in thousands)<br/>New York City Transitional Finance Authority</h5>
<table id="table_<?php echo widget_unique_identifier($node) ?>" style='display:none' class="trendsShowOnLoad <?php echo $node->widgetConfig->html_class ?>">
<?php
if (isset($node->widgetConfig->caption_column)) {
echo '<caption>' . $node->data[0][$node->widgetConfig->caption_column] . '</caption>';
}
else if (isset($node->widgetConfig->caption)) {
echo '<caption>' . $node->widgetConfig->caption . '</caption>';
}
?>
<thead>
<tr>
<th class="number rowspan2Top"><div class="trendCen" >Fiscal</div></th>
<th rowspan="2" class="number"><div class="trendCen">PIT<br>Revenue<sup>(1)</sup></div></th>
<th rowspan="2" class="number"><div class="trendCen">Sales Tax<br>Revenue<sup>(2)</sup></div></th>
<th rowspan="2" class="number"><div class="trendCen">Total<br>Receipt</div></th>
<th rowspan="2" class="number"><div class="trendCen">Other<sup>(3)</sup></div></th>
<th rowspan="2" class="number"><div class="trendCen">Investment<br>Earnings</div></th>
<th rowspan="2" class="number"><div class="trendCen">Total<br>Revenue</div></th>
<th colspan="3" class="centrig"><div class="trendCen">Future Tax Secured<br>Bonds Debt Service</div></th>
<th rowspan="2" class="number"><div class="trendCen">Operating<br>Expenses</div></th>
<th rowspan="2" class="number"><div class="trendCen">Total to be<br>Covered</div></th>
<th rowspan="2"> </th>
</tr>
<tr>
<th class="number rowspan2Bot"><div class="trendCen">Year</div></th>
<th class="number"><div class="trendCen">Interest</div></th>
<th class="number"><div class="trendCen">Principal</div></th>
<th class="number"><div class="trendCen">Total</div></th>
</tr>
</thead>
<tbody>
<?php
$count = 1;
foreach( $node->data as $row){
$dollar_sign = ($count == 1)? '<div class="dollarItem" >$</div>':'';
$count++;
echo "<tr><td class='number'><div class='tdCen'>" . $row['fiscal_year'] . "</div></td>";
echo "<td class='number'>" . $dollar_sign . "<div class='tdCen'>" . (($row['pit_revenue']>0)?number_format($row['pit_revenue']):'-') . "</div></td>";
echo "<td class='number'>" . $dollar_sign . "<div class='tdCen'>" . (($row['sales_tax_revenue']>0)?number_format($row['sales_tax_revenue']):'-') . "</div></td>";
echo "<td class='number'>" . $dollar_sign . "<div class='tdCen'>" . (($row['total_receipt']>0)?number_format($row['total_receipt']):'-') . "</div></td>";
echo "<td class='number'>" . $dollar_sign . "<div class='tdCen'>" . (($row['other']>0)?number_format($row['other']):'-') . "</div></td>";
echo "<td class='number'>" . $dollar_sign . "<div class='tdCen'>" . (($row['investment_earnings']>0)?number_format($row['investment_earnings']):'-') . "</div></td>";
echo "<td class='number'>" . $dollar_sign . "<div class='tdCen'>" . (($row['total_revenue']>0)?number_format($row['total_revenue']):'-') . "</div></td>";
echo "<td class='number'>" . $dollar_sign . "<div class='tdCen'>" . (($row['interest']>0)?number_format($row['interest']):'-') . "</div></td>";
echo "<td class='number'>" . $dollar_sign . "<div class='tdCen'>" . (($row['pricipal']>0)?number_format($row['pricipal']):'-') . "</div></td>";
echo "<td class='number'>" . $dollar_sign . "<div class='tdCen'>" . (($row['total']>0)?number_format($row['total']):'-') . "</div></td>";
echo "<td class='number'>" . $dollar_sign . "<div class='tdCen'>" . (($row['operating_expenses']>0)?number_format($row['operating_expenses']):'-') . "</div></td>";
echo "<td class='number'>" . $dollar_sign . "<div class='tdCen'>" . (($row['total_to_be_covered']>0)?number_format($row['total_to_be_covered']):'-') . "</div></td>";
echo "<td> </td>";
echo "</tr>";
}
?>
</tbody>
</table>
<div class="footnote">
<p>(1) Personal income tax (PIT).</p>
<p>(2) Sales tax revenue has not been required by the TFA. This amount is available to cover debt service if required.</p>
<p>(3) Grant from City and Federal Subsidy.</p></div>
<?php
widget_data_tables_add_js($node);
?>
| MomixSolutions/MyGovCenter | source/webapp/sites/all/modules/custom/checkbook_trends/templates/debt_capacity_trends/pledged_rev_cov_nyc_trans.tpl.php | PHP | agpl-3.0 | 5,320 |
/*
* _Bullseye.cpp
*
* Created on: Aug 21, 2015
* Author: yankai
*/
#include "_Bullseye.h"
#ifdef USE_OPENCV
#ifdef USE_CUDA
namespace kai
{
_Bullseye::_Bullseye()
{
m_abs = 90;
m_scale1 = 0.25;
m_scale2 = 0.0625;
m_thr1 = 200;
m_thr2 = 255;
}
_Bullseye::~_Bullseye()
{
}
bool _Bullseye::init(void* pKiss)
{
IF_F(!this->_DetectorBase::init(pKiss));
Kiss* pK = (Kiss*)pKiss;
pK->v("abs", &m_abs);
pK->v("scale1", &m_scale1);
pK->v("scale2", &m_scale2);
pK->v("thr1", &m_thr1);
pK->v("thr2", &m_thr2);
m_nClass = 1;
return true;
}
bool _Bullseye::start(void)
{
NULL_F(m_pT);
return m_pT->start(getUpdate, this);
}
void _Bullseye::update(void)
{
while(m_pT->bRun())
{
m_pT->autoFPSfrom();
if(check() >= 0)
{
detect();
if(m_bGoSleep)
m_pU->clear();
}
m_pT->autoFPSto();
}
}
int _Bullseye::check(void)
{
NULL__(m_pU,-1);
NULL__(m_pV,-1);
IF__(m_pV->BGR()->bEmpty(),-1);
return this->_DetectorBase::check();
}
void _Bullseye::detect(void)
{
GpuMat mBGR = *(m_pV->BGR()->gm());
GpuMat mHSV;
cuda::cvtColor(mBGR, mHSV, COLOR_BGR2HSV);
vector<GpuMat> vmHSV(3);
split(mHSV, vmHSV);
GpuMat mH = vmHSV[0];
GpuMat mS = vmHSV[1];
GpuMat mV = vmHSV[2];
GpuMat gHred;
GpuMat gScaleHred;
GpuMat gScaleS;
GpuMat gBulleye;
GpuMat gThr;
cuda::absdiff(mH, Scalar(m_abs), gHred);
cuda::multiply(gHred, Scalar(m_scale1), gScaleHred);
cuda::multiply(mS, Scalar(m_scale2), gScaleS);
cuda::multiply(gScaleHred, gScaleS, gBulleye);
cuda::threshold(gBulleye, gThr, m_thr1, m_thr2, THRESH_BINARY); //THRESH_BINARY_INV);
Mat mThr;
gThr.download(mThr);
vector< vector< Point > > vvContours;
findContours(mThr, vvContours, RETR_EXTERNAL, CHAIN_APPROX_NONE);
float kx = 1.0/mBGR.cols;
float ky = 1.0/mBGR.rows;
_Object o;
vector<Point> vPoly;
for (unsigned int i=0; i<vvContours.size(); i++)
{
vPoly.clear();
approxPolyDP( vvContours[i], vPoly, 3, true );
Rect r = boundingRect(vPoly);
o.init();
o.setTstamp(m_pT->getTfrom());
o.setBB2D(rect2BB<vFloat4>(r));
o.scale(kx,ky);
o.setTopClass(0, o.area());
m_pU->add(o);
LOG_I("ID: "+ i2str(o.getTopClass()));
}
m_pU->swap();
}
}
#endif
#endif
| yankailab/OpenKAI | src/Detector/_Bullseye.cpp | C++ | agpl-3.0 | 2,195 |
DELETE FROM `weenie` WHERE `class_Id` = 35548;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (35548, 'ace35548-assassinsdagger', 6, '2019-02-10 00:00:00') /* MeleeWeapon */;
INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`)
VALUES (35548, 1, 1) /* ItemType - MeleeWeapon */
, (35548, 5, 100) /* EncumbranceVal */
, (35548, 9, 1048576) /* ValidLocations - MeleeWeapon */
, (35548, 10, 1048576) /* CurrentWieldedLocation - MeleeWeapon */
, (35548, 16, 1) /* ItemUseable - No */
, (35548, 51, 1) /* CombatUse - Melee */
, (35548, 93, 1044) /* PhysicsState - Ethereal, IgnoreCollisions, Gravity */
, (35548, 8041, 1) /* PCAPRecordedPlacement - RightHandCombat */;
INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`)
VALUES (35548, 22, True ) /* Inscribable */;
INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`)
VALUES (35548, 1, 'Assassin''s Dagger') /* Name */;
INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`)
VALUES (35548, 1, 33558325) /* Setup */
, (35548, 3, 536870932) /* SoundTable */
, (35548, 8, 100674287) /* Icon */
, (35548, 22, 872415275) /* PhysicsEffectTable */
, (35548, 52, 100689403) /* IconUnderlay */
, (35548, 8001, 2327056) /* PCAPRecordedWeenieHeader - Usable, CombatUse, Wielder, ValidLocations, CurrentlyWieldedLocation, Burden */
, (35548, 8002, 1) /* PCAPRecordedWeenieHeader2 - IconUnderlay */
, (35548, 8003, 67108882) /* PCAPRecordedObjectDesc - Inscribable, Attackable, IncludesSecondHeader */
, (35548, 8005, 170017) /* PCAPRecordedPhysicsDesc - CSetup, Parent, STable, PeTable, Position, AnimationFrame */
, (35548, 8009, 1) /* PCAPRecordedParentLocation - RightHand */;
INSERT INTO `weenie_properties_position` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`)
VALUES (35548, 8040, 23855631, 93.55366, -21.31657, -0.071, -0.5565441, -0.5565441, -0.4361865, -0.4361865) /* PCAPRecordedLocation */
/* @teleloc 0x016C020F [93.553660 -21.316570 -0.071000] -0.556544 -0.556544 -0.436187 -0.436187 */;
INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`)
VALUES (35548, 8000, 3358114065) /* PCAPRecordedObjectIID */
, (35548, 8008, 1342620634) /* PCAPRecordedParentIID */;
| LtRipley36706/ACE-World | Database/3-Core/9 WeenieDefaults/SQL/MeleeWeapon/MeleeWeapon/35548 Assassin's Dagger.sql | SQL | agpl-3.0 | 2,502 |
<?php
/**
* SowerPHP
* Copyright (C) SowerPHP (http://sowerphp.org)
*
* Este programa es software libre: usted puede redistribuirlo y/o
* modificarlo bajo los términos de la Licencia Pública General Affero de GNU
* publicada por la Fundación para el Software Libre, ya sea la versión
* 3 de la Licencia, o (a su elección) cualquier versión posterior de la
* misma.
*
* Este programa se distribuye con la esperanza de que sea útil, pero
* SIN GARANTÍA ALGUNA; ni siquiera la garantía implícita
* MERCANTIL o de APTITUD PARA UN PROPÓSITO DETERMINADO.
* Consulte los detalles de la Licencia Pública General Affero de GNU para
* obtener una información más detallada.
*
* Debería haber recibido una copia de la Licencia Pública General Affero de GNU
* junto a este programa.
* En caso contrario, consulte <http://www.gnu.org/licenses/agpl.html>.
*/
// namespace del modelo
namespace website\Honorarios;
/**
* Clase para mapear la tabla boleta_tercero de la base de datos
* Comentario de la tabla:
* Esta clase permite trabajar sobre un conjunto de registros de la tabla boleta_tercero
* @author SowerPHP Code Generator
* @version 2019-08-09 15:59:48
*/
class Model_BoletaTerceros extends \Model_Plural_App
{
// Datos para la conexión a la base de datos
protected $_database = 'default'; ///< Base de datos del modelo
protected $_table = 'boleta_tercero'; ///< Tabla del modelo
private $tasas_retencion = [
201608 => 0.1000,
202001 => 0.1075,
202101 => 0.1150,
202201 => 0.1225,
202301 => 0.1300,
202401 => 0.1375,
202501 => 0.1450,
202601 => 0.1525,
202701 => 0.1600,
202801 => 0.1700,
];
/**
* Método que sincroniza las boletas de terceros recibidas por la empresa
* en el SII con el registro local de boletas en LibreDTE
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
* @version 2021-06-29
*/
public function sincronizar($meses)
{
// periodos a procesar
$periodo_actual = (int)date('Ym');
$periodos = [$periodo_actual];
for ($i = 0; $i < $meses-1; $i++) {
$periodos[] = \sowerphp\general\Utility_Date::previousPeriod($periodos[$i]);
}
sort($periodos);
// sincronizar periodos
foreach ($periodos as $periodo) {
$boletas = $this->getBoletas($periodo);
foreach ($boletas as $boleta) {
list($receptor_rut, $receptor_dv) = explode('-', $boleta['receptor_rut']);
$Receptor = new \website\Dte\Model_Contribuyente($receptor_rut);
if (!$Receptor->razon_social) {
$Receptor->rut = $receptor_rut;
$Receptor->dv = $receptor_dv;
$Receptor->razon_social = mb_substr($boleta['receptor_nombre'], 0, 100);
$Receptor->save();
}
$BoletaTercero = new Model_BoletaTercero($this->getContribuyente()->rut, $boleta['numero']);
$BoletaTercero->receptor = $Receptor->rut;
$BoletaTercero->anulada = (int)($boleta['estado'] == 'ANUL');
$BoletaTercero->set($boleta);
if (!$BoletaTercero->save()) {
throw new \Exception('No fue posible guardar la BTE #'.$BoletaTercero->numero.' de '.$Receptor->getRUT().' del día '.\sowerphp\general\Utility_Date::format($BoletaTercero->fecha));
}
}
}
}
/**
* Método que obtiene las boletas emitidas desde el SII
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
* @version 2020-01-26
*/
public function getBoletas($periodo)
{
$r = libredte_api_consume('/sii/bte/emitidas/documentos/'.$this->getContribuyente()->getRUT().'/'.$periodo.'?formato=json', [
'auth' => [
'pass' => [
'rut' => $this->getContribuyente()->getRUT(),
'clave' => $this->getContribuyente()->config_sii_pass,
],
],
]);
if ($r['status']['code']!=200) {
if ($r['status']['code']==404) {
return [];
}
throw new \Exception('Error al obtener boletas de terceros del período '.(int)$periodo.' desde el SII: '.$r['body'], $r['status']['code']);
}
return $r['body'];
}
/**
* Método que entrega un resumen por período de las boletas de terceros
* emitidas
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
* @version 2019-08-10
*/
public function getPeriodos($periodo = null)
{
$periodo_col = $this->db->date('Ym', 'fecha');
$where = ['emisor = :emisor', 'anulada = false'];
$vars = [':emisor'=>$this->getContribuyente()->rut];
if ($periodo) {
$where[] = $periodo_col.' = :periodo';
$vars[':periodo'] = $periodo;
}
return $this->db->getTable('
SELECT
'.$periodo_col.' AS periodo,
COUNT(*) AS cantidad,
MIN(fecha) AS fecha_inicial,
MAX(fecha) AS fecha_final,
SUM(total_honorarios) AS honorarios,
SUM(total_liquido) AS liquido,
SUM(total_retencion) AS retencion
FROM boleta_tercero
WHERE '.implode(' AND ', $where).'
GROUP BY '.$periodo_col.'
ORDER BY '.$periodo_col.' DESC
', $vars);
}
/**
* Método que entrega el resumen de cierto período
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
* @version 2019-08-10
*/
public function getPeriodo($periodo)
{
$datos = $this->getPeriodos($periodo);
return !empty($datos) ? $datos[0] : [];
}
/**
* Método que entrega las boletas de cierto período
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
* @version 2019-08-23
*/
public function buscar(array $filtros = [], $order = 'ASC')
{
$where = ['b.emisor = :emisor'];
$vars = [':emisor'=>$this->getContribuyente()->rut];
if (!empty($filtros['periodo'])) {
$periodo_col = $this->db->date('Ym', 'b.fecha');
$where[] = $periodo_col.' = :periodo';
$vars[':periodo'] = $filtros['periodo'];
}
if (!empty($filtros['receptor'])) {
if (strpos($filtros['receptor'], '-')) {
list($rut, $dv) = explode('-', str_replace('.', '', $filtros['receptor']));
} else {
$rut = (int)$filtros['receptor'];
}
$where[] = 'b.receptor = :receptor';
$vars[':receptor'] = $rut;
}
if (!empty($filtros['fecha_desde'])) {
$where[] = 'b.fecha >= :fecha_desde';
$vars[':fecha_desde'] = $filtros['fecha_desde'];
}
if (!empty($filtros['fecha_hasta'])) {
$where[] = 'b.fecha <= :fecha_hasta';
$vars[':fecha_hasta'] = $filtros['fecha_hasta'];
}
if (!empty($filtros['honorarios_desde'])) {
$where[] = 'b.total_honorarios >= :honorarios_desde';
$vars[':honorarios_desde'] = $filtros['honorarios_desde'];
}
if (!empty($filtros['honorarios_hasta'])) {
$where[] = 'b.total_honorarios <= :honorarios_hasta';
$vars[':honorarios_hasta'] = $filtros['honorarios_hasta'];
}
if (isset($filtros['anulada'])) {
if ($filtros['anulada']) {
$where[] = 'b.anulada = true';
} else {
$where[] = 'b.anulada = false';
}
}
if (isset($filtros['sucursal_sii']) and is_numeric($filtros['sucursal_sii'])) {
if ($filtros['sucursal_sii']) {
$where[] = 'b.sucursal_sii = :sucursal_sii';
$vars[':sucursal_sii'] = $filtros['sucursal_sii'];
} else {
$where[] = 'b.sucursal_sii IS NULL';
}
}
$boletas = $this->db->getTable('
SELECT
b.codigo,
b.receptor AS receptor_rut,
c.dv AS receptor_dv,
c.razon_social AS receptor_razon_social,
b.numero,
b.fecha,
b.fecha_emision,
b.total_honorarios AS honorarios,
b.total_liquido AS liquido,
b.total_retencion AS retencion,
b.anulada,
b.sucursal_sii
FROM
boleta_tercero AS b
LEFT JOIN contribuyente AS c ON c.rut = b.receptor
WHERE
'.implode(' AND ', $where).'
ORDER BY b.fecha '.$order.', b.numero '.$order.'
', $vars);
foreach ($boletas as &$b) {
$b['sucursal'] = $this->getContribuyente()->getSucursal($b['sucursal_sii'])->sucursal;
}
return $boletas;
}
/**
* Método que emite una BTE en el SII y entrega el objeto local para trabajar
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
* @version 2021-07-29
*/
public function emitir($boleta)
{
// crear receptor si no existe
list($receptor_rut, $receptor_dv) = explode('-', $boleta['Encabezado']['Receptor']['RUTRecep']);
$Receptor = new \website\Dte\Model_Contribuyente($receptor_rut);
if (!$Receptor->razon_social) {
$Receptor->rut = $receptor_rut;
$Receptor->dv = $receptor_dv;
$Receptor->razon_social = mb_substr($boleta['Encabezado']['Receptor']['RznSocRecep'], 0, 100);
$Receptor->save();
}
// consumir servicio web y emitir boleta
$r = libredte_api_consume('/sii/bte/emitidas/emitir', [
'auth' => [
'pass' => [
'rut' => $this->getContribuyente()->getRUT(),
'clave' => $this->getContribuyente()->config_sii_pass,
],
],
'boleta' => $boleta,
]);
if ($r['status']['code']!=200) {
throw new \Exception('Error al emitir boleta: '.$r['body'], $r['status']['code']);
}
$boleta = $r['body'];
if (empty($boleta['Encabezado']['IdDoc']['CodigoBarras'])) {
throw new \Exception('No fue posible emitir la boleta o bien no se pudo obtener el código de barras de la boleta emitida');
}
// crear registro de la boleta en la base de datos
$BoletaTercero = new Model_BoletaTercero();
$BoletaTercero->emisor = $this->getContribuyente()->rut;
$BoletaTercero->numero = $boleta['Encabezado']['IdDoc']['Folio'];
$BoletaTercero->codigo = $boleta['Encabezado']['IdDoc']['CodigoBarras'];
$BoletaTercero->receptor = $Receptor->rut;
$BoletaTercero->fecha = $boleta['Encabezado']['IdDoc']['FchEmis'];
$BoletaTercero->fecha_emision = date('Y-m-d');
$BoletaTercero->total_honorarios = $boleta['Encabezado']['Totales']['MntBruto'];
$BoletaTercero->total_retencion = $boleta['Encabezado']['Totales']['MntRetencion'];
$BoletaTercero->total_liquido = $boleta['Encabezado']['Totales']['MntNeto'];
$BoletaTercero->anulada = 0;
if (!empty($boleta['Encabezado']['Emisor']['CdgSIISucur'])) {
$BoletaTercero->sucursal_sii = $boleta['Encabezado']['Emisor']['CdgSIISucur'];
}
$BoletaTercero->save();
// guardar datos del receptor si es posible
$Receptor = $BoletaTercero->getReceptor();
if (!$Receptor->usuario) {
$Receptor->razon_social = mb_substr($boleta['Encabezado']['Receptor']['RznSocRecep'],0,100);
$Receptor->direccion = mb_substr($boleta['Encabezado']['Receptor']['DirRecep'],0,70);
$comuna = (new \sowerphp\app\Sistema\General\DivisionGeopolitica\Model_Comunas())->getComunaByName($boleta['Encabezado']['Receptor']['CmnaRecep']);
if ($comuna) {
$Receptor->comuna = $comuna;
}
try {
$Receptor->save();
} catch (\Exception $e) {
}
}
// entregar boleta emitida
return $BoletaTercero;
}
/**
* Método que entrega las tasas de retencion para personas a honorarios
* @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
* @version 2020-01-26
*/
public function getTasasRetencion()
{
krsort($this->tasas_retencion);
return $this->tasas_retencion;
}
}
| LibreDTE/libredte-webapp | website/Module/Honorarios/Model/BoletaTerceros.php | PHP | agpl-3.0 | 12,733 |
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/cryptlib.h"
#include "buildinf.h"
unsigned long OpenSSL_version_num(void)
{
return OPENSSL_VERSION_NUMBER;
}
unsigned int OPENSSL_version_major(void)
{
return OPENSSL_VERSION_MAJOR;
}
unsigned int OPENSSL_version_minor(void)
{
return OPENSSL_VERSION_MINOR;
}
unsigned int OPENSSL_version_patch(void)
{
return OPENSSL_VERSION_PATCH;
}
const char *OPENSSL_version_pre_release(void)
{
return OPENSSL_VERSION_PRE_RELEASE_STR;
}
const char *OPENSSL_version_build_metadata(void)
{
return OPENSSL_VERSION_BUILD_METADATA_STR;
}
extern char ossl_cpu_info_str[];
const char *OpenSSL_version(int t)
{
switch (t) {
case OPENSSL_VERSION:
return OPENSSL_VERSION_TEXT;
case OPENSSL_VERSION_STRING:
return OPENSSL_VERSION_STR;
case OPENSSL_FULL_VERSION_STRING:
return OPENSSL_FULL_VERSION_STR;
case OPENSSL_BUILT_ON:
return DATE;
case OPENSSL_CFLAGS:
return compiler_flags;
case OPENSSL_PLATFORM:
return PLATFORM;
case OPENSSL_DIR:
#ifdef OPENSSLDIR
return "OPENSSLDIR: \"" OPENSSLDIR "\"";
#else
return "OPENSSLDIR: N/A";
#endif
case OPENSSL_ENGINES_DIR:
#ifdef ENGINESDIR
return "ENGINESDIR: \"" ENGINESDIR "\"";
#else
return "ENGINESDIR: N/A";
#endif
case OPENSSL_MODULES_DIR:
#ifdef MODULESDIR
return "MODULESDIR: \"" MODULESDIR "\"";
#else
return "MODULESDIR: N/A";
#endif
case OPENSSL_CPU_INFO:
if (OPENSSL_info(OPENSSL_INFO_CPU_SETTINGS) != NULL)
return ossl_cpu_info_str;
else
return "CPUINFO: N/A";
}
return "not available";
}
| FriendSoftwareLabs/friendup | libs-ext/openssl/crypto/cversion.c | C | agpl-3.0 | 1,997 |
#!/usr/bin/env python
from __future__ import print_function, division
import multiprocessing
import os
import csv
import datetime
import logging
from datetime import datetime
import argparse
import shutil
import math
from glob import glob
import gzip
from shi7 import __version__
from shi7.shi7 import TRUE_FALSE_DICT, read_fastq, axe_adaptors_single_end, axe_adaptors_paired_end, flash_part1, \
flash_part2, split_fwd_rev, match_pairs, link_manicured_names
def make_arg_parser():
parser = argparse.ArgumentParser(description='This is the commandline interface for shi7_learning',
usage='shi7_learning v{version}\nshi7_learning.py -i <input> -o <output> ...'.format(version=__version__))
parser.add_argument('-i', '--input', help='Set the directory path of the fastq directory OR oligos.txt if splitting', required=True)
parser.add_argument('-o', '--output', help='Set the directory path of the output (default: cwd)', default=os.getcwd())
parser.add_argument('--debug', help='Retain all intermediate files (default: Disabled)', dest='debug', action='store_true')
parser.add_argument('-t', '--threads', help='Set the number of threads (default: %(default)s)',
default=min(multiprocessing.cpu_count(), 16))
parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + __version__)
parser.set_defaults()
return parser
def subsample_fastqs(path_fastqs, num_files=10, num_sequences=1000):
for i, path_fastq in enumerate(path_fastqs):
if i >= num_files:
return
with open(path_fastq) as fastq_inf:
fastq_gen = read_fastq(fastq_inf)
yield limit_fastq(fastq_gen, num_sequences=num_sequences)
def limit_fastq(fastq_gen, num_sequences=1000):
for i in range(num_sequences):
try:
yield next(fastq_gen)
except StopIteration:
return
def get_seq_length_qual_scores(path_fastqs, output_path, num_files=10, num_sequences=1000):
subsampled_fastqs = subsample_fastqs(path_fastqs, num_files=num_files, num_sequences=num_sequences)
sequence_len_sum = 0.
quality_sum = 0
num_sequences = 0.
for fastq_path, fastq_gen in zip(path_fastqs, subsampled_fastqs):
with open(os.path.join(output_path, os.path.basename(fastq_path)), 'w') as outf:
for header, sequence, quality in fastq_gen:
outf.write("@%s\n%s\n+\n%s\n" % (header, sequence, quality))
sequence_len_sum += len(sequence)
quality_sum += sum([ord(i) for i in quality])
num_sequences += 1.
# Return (average length of sequences, average quality score)
return sequence_len_sum/num_sequences, quality_sum/sequence_len_sum
def count_num_lines(path):
with open(path) as path_inf:
return sum(1 for line in path_inf)
def get_file_size(path):
return os.path.getsize(path)
def check_sequence_name(path_R1, path_R2):
with open(path_R1) as path_inf_R1, open(path_R2) as path_inf_R2:
fastq_gen_R1 = read_fastq(path_inf_R1)
fastq_gen_R2 = read_fastq(path_inf_R2)
for gen_R1, gen_R2 in zip(fastq_gen_R1,fastq_gen_R2):
title_R1, title_R2 = gen_R1[0], gen_R2[0]
if len(title_R1) != len(title_R2):
return False
diff_idx = [i for i in range(len(title_R1)) if title_R1[i] != title_R2[i]]
if len(diff_idx) != 1:
return False
if int(title_R2[diff_idx[0]]) - int(title_R1[diff_idx[0]]) != 1:
return False
return True
def detect_paired_end(path_fastqs):
path_fastqs = [f for f in path_fastqs if f.endswith('.fastq') or f.endswith('.fq') or f.endswith('.fastq.gz') or f.endswith('.fq.gz')]
if len(path_fastqs) % 2 == 1: return False, [path_fastqs, None, None, None]
pair_obj = match_pairs(path_fastqs, True)
path_fastqs = pair_obj[0]
if pair_obj[1]==None: return False, pair_obj
return True, pair_obj
def get_directory_size(path):
return sum([get_file_size(os.path.join(path, fastq)) for fastq in os.listdir(path)])
def remove_directory_contents(path):
for f in os.listdir(path):
os.remove(os.path.join(path, f))
def choose_axe_adaptors(path_subsampled_fastqs, paired_end, output_path, threads):
adapters = ['TruSeq2', 'TruSeq3', 'TruSeq3-2', 'Nextera']
threads = min(threads, multiprocessing.cpu_count(), 16)
original_size = get_directory_size(os.path.dirname(path_subsampled_fastqs[0]))
logging.info('Original size of the subsampled_fastqs = ' + str(original_size))
best_size = original_size
best_adap = None
for adapter in adapters:
if paired_end:
axe_adaptors_paired_end(path_subsampled_fastqs, output_path, adapter, threads, shell=False)
else:
axe_adaptors_single_end(path_subsampled_fastqs, output_path, adapter, threads, shell=False)
fastqs_path_size = get_directory_size(output_path)
logging.info("Adapters: {adapter}\tFile Size: {filesize}".format(adapter=adapter, filesize=fastqs_path_size))
if fastqs_path_size <= best_size:
best_size = fastqs_path_size
best_adap = adapter
if best_size < 0.995*original_size:
# Actually write the best files again for use in later steps
logging.info("Best Adapters: {adapter}\tFile Size: {filesize}".format(adapter=best_adap, filesize=best_size))
if paired_end:
files = axe_adaptors_paired_end(path_subsampled_fastqs, output_path, best_adap, threads, shell=False)
else:
files = axe_adaptors_single_end(path_subsampled_fastqs, output_path, best_adap, threads, shell=False)
return best_adap, best_size, files
else:
return None, original_size, path_subsampled_fastqs
def flash_stitchable_and_check_outies(adapter_output_filenames, flash_output_path, threads):
flash_output_str = flash_part1(adapter_output_filenames, flash_output_path, max_overlap=700, \
min_overlap=10, allow_outies=True, threads=threads, shell=False)
allow_outies_count = 0
for flash_out in flash_output_str:
flash_str_list = flash_out.strip().split('\n')
outies_info = flash_str_list[-8]
outies_percent = float(outies_info[outies_info.find('(')+1:outies_info.find('%')])
if outies_percent >= 15:
allow_outies_count += 1
path_flash_fqs = flash_part2(flash_output_str, flash_output_path)
path_R1_fastqs, _ = split_fwd_rev(adapter_output_filenames)
matched_count = 0
for original_fq, flash_fq in zip(path_R1_fastqs, path_flash_fqs):
if count_num_lines(flash_fq) > count_num_lines(original_fq)*0.3:
matched_count = matched_count + 1
return matched_count/len(path_flash_fqs) >= 0.75, allow_outies_count/len(flash_output_str) >= 0.75, path_flash_fqs
def flash_check_cv(flash_output_path):
hist_files = [os.path.join(flash_output_path, f) for f in os.listdir(flash_output_path) if f.endswith('.hist')]
total_cv = total_mean = 0
for f in hist_files:
with open(f) as inf:
csv_inf = csv.reader(inf, delimiter="\t")
x2f = 0
sum = 0
cnt = 0
for row in csv_inf:
row = [int(r) for r in row]
cnt = cnt + row[1]
sum = sum + row[0] * row[1]
x2f = x2f + row[0] * row[0] * row[1]
mean = sum/cnt
std = math.sqrt((x2f - sum*sum/cnt)/(cnt-1))
cv = std/mean
total_cv = total_cv + cv
total_mean = total_mean + mean
total_files = len(hist_files)
return total_cv/total_files, total_mean/total_files
def trimmer_learning(flash_output_filenames):
filter_q_sum = 0
trim_q_sum = 0
totbases = 0
tottrim = 0
num = 0
for fq_path in flash_output_filenames:
with open(fq_path) as fq_inf:
fq_gen = read_fastq(fq_inf)
for gen in fq_gen:
num = num + 1
qualities = gen[2]
totbases = totbases + len(qualities)
qualities = [ord(qual)-33 for qual in qualities]
filter_q_sum = filter_q_sum + sum(qualities)
if (len(qualities) >= 20):
trim_q_sum = trim_q_sum + sum(qualities[:10]) + sum(qualities[-10:])
tottrim = tottrim + 20
logging.info('num seqs: %d' % num)
logging.info('filter_q_sum: %d' % filter_q_sum)
logging.info('trim_q_sum: %d' % trim_q_sum)
logging.info('total bases considered: %d (trim: %d)' % (totbases, tottrim))
logging.info('filter_q: %d' % (filter_q_sum/totbases))
logging.info('trim_q: %d' % (trim_q_sum/tottrim))
filter_q = math.floor(filter_q_sum/totbases)
trim_q = math.floor(trim_q_sum/tottrim)-1
trim_q = trim_q if trim_q > filter_q - 3 else filter_q - 3
return filter_q, trim_q
def template_input(input):
input = os.path.abspath(input)
# input, input_cmd
return "input\t{}".format(input), ["--input", input]
def template_paired_end(bool):
# bool, paired_end
if bool:
return "paired_end\t{}".format(str(bool)), None
else:
return "paired_end\t{}".format(str(bool)), ["-SE"]
def template_trim(filt_q, trim_q):
return "filt_q: %d, trim_q: %d" % (filt_q, trim_q), ["--filter_qual", str(filt_q), "--trim_qual", str(trim_q)]
def template_cv(minstitch, maxstitch):
return "minstitch: %d, maxstitch: %d" % (minstitch, maxstitch), ["--min_overlap", str(minstitch), "--max_overlap", str(maxstitch)]
def template_output(output):
# output, output_cmd
output = os.path.abspath(output)
return "output\t{}".format(output), ["--output", output]
def template_choose_axe_adaptors(best_adapt, best_size):
if best_adapt:
return "axe_adaptors\t" + best_adapt, ["--adaptor", best_adapt]
else:
return "axe_adaptors\tNA", ["--adaptor", "None"]
def template_flash(stitches, do_outies):
return "stitches: %s, outies: %s" % (stitches, do_outies), ["--flash", str(stitches), "--allow_outies", str(do_outies)]
def main():
start_time = datetime.now()
parser = make_arg_parser()
args = parser.parse_args()
learning_params = ["shi7.py"]
learning_pretty = ["SHI7 version", __version__]
input = os.path.abspath(args.input)
output = os.path.abspath(args.output)
# Make output folder
if not os.path.exists(output):
os.makedirs(output)
# Put in the logging file
logging.basicConfig(filename=os.path.join(output, 'shi7_learning.log'), filemode='w', level=logging.DEBUG, \
format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
# Make temp outfolder
if os.path.exists(os.path.join(args.output, 'temp')):
shutil.rmtree(os.path.join(args.output, 'temp'))
logging.info('Existing temp directory deleted.')
os.makedirs(os.path.join(args.output, 'temp'))
else:
os.makedirs(os.path.join(args.output, 'temp'))
path_fastqs = [os.path.join(input, f) for f in os.listdir(input) if f.endswith('fastq') or f.endswith('fq') or f.endswith('fq.gz') or f.endswith('fastq.gz')]
if len(path_fastqs) == 0:
msg = "No FASTQS found in input folder {}".format(input)
logging.critical(msg)
raise IOError(msg)
# Record the input
results, addon = template_input(input)
logging.info(results)
if addon:
learning_params.extend(addon)
# Write temp subsampled fastqs
subsampled_fastq_path = os.path.join(output, 'temp', 'subsampled')
os.makedirs(subsampled_fastq_path)
totbases = totseqs = 0
for file in path_fastqs:
basename = os.path.basename(file)
if(file.endswith('.fastq') or file.endswith('.fq')):
fastq_inf = open(file)
else:
fastq_inf = gzip.open(file, 'rt')
fastq_gen = read_fastq(fastq_inf)
if(basename.endswith('.gz')):
basename = basename[:-3]
with open(os.path.join(subsampled_fastq_path, basename), 'w') as outf:
for header, seq, quality in limit_fastq(fastq_gen):
outf.write("@{header}\n{seq}\n+\n{quality}\n".format(header=header, seq=seq, quality=quality))
totbases += len(seq)
totseqs += 1
avlen = totbases/totseqs
path_fastqs = glob(os.path.join(subsampled_fastq_path , "*"))
# Detect if paired end
paired_end, pair_obj = detect_paired_end(path_fastqs)
path_fastqs = pair_obj[0]
link_outdir = os.path.join(output, 'temp', 'link')
os.makedirs(link_outdir)
snames = [os.path.basename(n) for n in path_fastqs]
path_fastqs = link_manicured_names(path_fastqs, snames, link_outdir, not paired_end, pair_obj[1:])
results, addon = template_paired_end(paired_end)
logging.info(results)
if addon: learning_params.extend(addon)
learning_pretty += ["Paired end",paired_end]
# Detect adapters
axe_adaptors_path = os.path.join(output, 'temp', 'axe_adaptors')
os.makedirs(axe_adaptors_path)
best_adap, best_size, fastq_paths = choose_axe_adaptors(path_fastqs, paired_end, axe_adaptors_path, int(args.threads))
results, addon = template_choose_axe_adaptors(best_adap, best_size)
logging.info(results)
if addon: learning_params.extend(addon)
learning_pretty += ["Detected adaptors",best_adap]
# Detect output folder
results, addon = template_output(output)
logging.info(results)
if addon: learning_params.extend(addon)
# Detect stitching
stitched_path = os.path.join(output, 'temp', 'flash')
os.makedirs(stitched_path)
if paired_end:
stitches, do_outies, fastq_paths = flash_stitchable_and_check_outies(fastq_paths, stitched_path, int(args.threads))
else: stitches, do_outies = False, False
results, addon = template_flash(stitches, do_outies)
logging.info(results)
if addon: learning_params.extend(addon)
if paired_end:
learning_pretty += ["Stitching",stitches]
if stitches: learning_pretty += ["Outies allowed",do_outies]
filt_q, trim_q = trimmer_learning(fastq_paths)
results, addon = template_trim(int(filt_q), int(trim_q))
logging.info(results)
if addon: learning_params.extend(addon)
learning_pretty += ["Filter quality",filt_q,"Trimming quality",trim_q]
# Check whether to implement stitching bounds
if stitches:
cv, mean = flash_check_cv(stitched_path)
if cv < 0.1:
learning_pretty += ["Amplicon mode",True]
logging.info("CV: %f, Mean: %f, Avlen: %f" % (cv, mean, avlen))
if avlen > mean: avlen = mean
mr = math.ceil(cv*mean)
logging.info("SD was: %d" % mr)
minstitch, maxstitch = int(2*avlen - mean-mr), int(2*avlen - mean+mr)
if minstitch < 8: minstitch = 8
logging.info("Amplicon mode: stitch range [%d, %d]" % (minstitch, maxstitch))
results, addon = template_cv(minstitch, maxstitch)
logging.info(results)
if addon: learning_params.extend(addon)
learning_pretty += ["Amplicon stitch minimum",minstitch]
learning_pretty += ["Amplicon stitch maximum",maxstitch]
else: learning_pretty += ["Amplicon mode",False]
#print(str(learning_params))
with open(os.path.join(args.output, "shi7_cmd.sh"), "w") as output:
cmd = " ".join(learning_params)
output.write(cmd)
print(cmd)
with open(os.path.join(args.output, "learning_params.txt"),"w") as output:
for ix in range(0,len(learning_pretty),2):
output.write(str(learning_pretty[ix]) + "\t" + str(learning_pretty[ix+1]) + "\n")
if not args.debug:
shutil.rmtree(os.path.join(args.output, 'temp'))
logging.info('Execution time: %s' % (datetime.now() - start_time))
if __name__ == "__main__":
main()
| knights-lab/shi7 | shi7/shi7_learning.py | Python | agpl-3.0 | 15,977 |
package cn.dlb.bim.ifc.engine.jvm;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.dlb.bim.component.PlatformServer;
import cn.dlb.bim.component.PlatformServerConfig;
import cn.dlb.bim.ifc.emf.PackageMetaData;
import cn.dlb.bim.ifc.engine.IRenderEngine;
import cn.dlb.bim.ifc.engine.IRenderEngineFactory;
import cn.dlb.bim.ifc.engine.RenderEngineException;
import cn.dlb.bim.utils.PathUtils;
public class JvmRenderEngineFactory implements IRenderEngineFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(JvmRenderEngineFactory.class);
private Path nativeFolder;
private Path schemaFile;
private PlatformServer server;
public JvmRenderEngineFactory(PlatformServer server) {
this.server = server;
initialize();
}
public void initialize() {
try {
String os = System.getProperty("os.name").toLowerCase();
String libraryName = "";
if (os.contains("windows")) {
libraryName = "ifcengine.dll";
} else if (os.contains("osx") || os.contains("os x") || os.contains("darwin")) {
libraryName = "libIFCEngine.dylib";
} else if (os.contains("linux")) {
libraryName = "libifcengine.so";
}
InputStream inputStream = Files.newInputStream(server.getPlatformServerConfig().getCompileClassRoute().resolve("lib/" + System.getProperty("sun.arch.data.model") + "/" + libraryName));
if (inputStream != null) {
try {
Path tmpFolder = server.getPlatformServerConfig().getTempDir();
nativeFolder = tmpFolder.resolve("ifcenginedll");
Path file = nativeFolder.resolve(libraryName);
if (Files.exists(nativeFolder)) {
try {
PathUtils.removeDirectoryWithContent(nativeFolder);
} catch (IOException e) {
// Ignore
}
}
Files.createDirectories(nativeFolder);
OutputStream outputStream = Files.newOutputStream(file);
try {
IOUtils.copy(inputStream, outputStream);
} finally {
outputStream.close();
}
} finally {
inputStream.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public IRenderEngine createRenderEngine(String schema) throws RenderEngineException {
try {
PackageMetaData packageMetaData = server.getMetaDataManager().getPackageMetaData(schema);
schemaFile = packageMetaData.getSchemaPath();
if (schemaFile == null) {
throw new RenderEngineException("No schema file");
}
List<String> classPathEntries = new ArrayList<>();
// for (Dependency dependency : pluginContext.getDependencies()) {
// Path path = dependency.getPath();
// classPathEntries.add(path.toAbsolutePath().toString());
// }
return new JvmIfcEngine(schemaFile, nativeFolder, server.getPlatformServerConfig().getTempDir(), server.getPlatformServerConfig().getClassPath()
, classPathEntries);
} catch (RenderEngineException e) {
throw e;
}
}
}
| shenan4321/BIMplatform | src/cn/dlb/bim/ifc/engine/jvm/JvmRenderEngineFactory.java | Java | agpl-3.0 | 3,114 |
<div class="modal__header modal__header--flex">
<h3 class="modal__heading">{{ :: 'Monitoring settings' | translate }} <span ng-if="settings.desk" translate>for "{{settings.desk.name}}" Desk</span></h3>
<a href="" class="modal__close icn-btn" sd-hotkey="esc" ng-click="cancel()"><i class="icon-close-small"></i></a>
</div>
<div class="modal__body aggregate-settings" sd-wizard data-name="aggregatesettings"
data-current-step="step.current" ng-init="setCurrentStep()" data-finish="cancel()">
<div sd-wizard-step data-title="{{ :: 'Desks' | translate }}" data-code="desks"
data-hide="shouldHideStep('desks')">
<div class="content">
<div ng-if="widget">
<div class="sd-line-input sd-line-input--required sd-line-input--boxed">
<label class="sd-line-input__label" translate>View name</label>
<input class="sd-line-input__input" type="text" ng-model="widget.configuration.label" ng-keyup="handleEdit($event);" required>
<div class="sd-line-input__char-count" sd-character-count data-item="widget.configuration.label" data-limit="30"></div>
</div>
</div>
<div class="legend" translate>Select desks for view</div>
<div class="desk-container">
<div class="desk" ng-repeat="desk in desks | orderBy: 'name' track by desk._id">
<div class="desk-title">
<span sd-switch ng-model="editGroups[desk._id].selected" ng-click="setDeskInfo(desk._id)"></span>
<span class="desk-title__text">{{desk.name}}</span>
</div>
<ul class="stages" ng-if="editGroups[desk._id].selected">
<li ng-repeat="stage in deskStages[desk._id]">
<span sd-check ng-model="editGroups[stage._id].selected" ng-click="setStageInfo(stage._id)" label-position="inside">{{stage.name}}</span>
</li>
<li ng-repeat="output in deskOutputs track by output.id">
<span sd-check ng-model="editGroups[desk._id + output.id].selected" ng-click="setDeskOutputInfo(desk._id + output.id, output.type)" label-position="inside">{{ output.label }}</span>
</li>
</ul>
</div>
<div class="desk">
<div class="desk-title">
<span sd-switch ng-model="editGroups['personal'].selected" ng-click="setPersonalInfo()"></span>
<span class="desk-title__text" translate>Personal</span>
</div>
</div>
</div>
</div>
</div>
<div sd-wizard-step data-title="{{ :: 'Saved Searches' | translate }}" data-code="searches"
data-hide="shouldHideStep('searches')">
<div class="content">
<div class="legend" translate>Select saved searches for view</div>
<div sd-toggle-box data-title="{{ :: 'Global saved searches' | translate}}" data-style="circle" data-open="true">
<div class="desk" ng-repeat="search in globalSavedSearches track by search._id | orderBy: 'name'">
<div class="desk-title desk-title--saved-search">
<div class="switch">
<span sd-switch ng-model="editGroups[search._id].selected" ng-click="setSearchInfo(search._id)"></span>
</div>
<div class="desk-title__text">
{{:: search.name}} <i>by {{:: userLookup[search.user].display_name}}</i>
<div class="search-description">{{:: search.description}} </div>
</div>
</div>
</div>
</div>
<div sd-toggle-box data-title="{{ :: 'Private saved searches' | translate}}" data-style="circle" data-open="true" ng-if="showPrivateSavedSearches">
<div class="desk" ng-repeat="search in privateSavedSearches track by search._id | orderBy: 'name'" ng-if="showPrivateSavedSearches">
<div class="desk-title desk-title--saved-search">
<div class="switch">
<span sd-switch ng-model="editGroups[search._id].selected" ng-click="setSearchInfo(search._id)"></span>
</div>
<div class="desk-title__text">
{{:: search.name}}
<div class="search-description">{{:: search.description}} </div>
</div>
</div>
</div>
</div>
</div>
</div>
<div sd-wizard-step data-title="{{ :: 'Reorder Sections' | translate }}" data-code="reorder"
data-hide="shouldHideStep('reorder')">
<div class="content">
<div class="legend" translate>Reorder stages and saved searches for view</div>
<ul class="groups draggable-list" sd-sort-groups>
<li class="sort-item draggable-list__item draggable-list__item--small" ng-class="{'active': item.order < columnsLimit}"
ng-repeat="item in getValues() track by item.order">
<div class="group-title" ng-if="item.type === 'stage'">
{{deskLookup[stageLookup[item._id].desk].name}} : <span>{{stageLookup[item._id].name}}</span>
</div>
<div class="group-title" ng-repeat="output in deskOutputs" ng-if="item.type === output.type">
{{item.name}} : <span translate>{{ output.listLabel }}</span>
</div>
<div class="group-title" ng-if="item.type === 'search'">
{{searchLookup[item._id].name}}
</div>
<div class="group-title" ng-if="item.type === 'personal'" translate>Personal</div>
</li>
</ul>
</div>
</div>
<div sd-wizard-step data-title="{{ :: 'Items Count' | translate }}" data-code="maxitems"
data-hide="shouldHideStep('maxitems')">
<div class="content">
<div class="legend" translate>Set maximum items per stages and saved searches for view</div>
<div class="groups">
<div ng-repeat="max in getValues()" class="desk desk--item-count" >
<div class="desk-title" ng-if="max.type === 'stage'">
{{deskLookup[stageLookup[max._id].desk].name}} : <span>{{stageLookup[max._id].name}}</span>
</div>
<div class="desk-title" ng-repeat="output in deskOutputs" ng-if="max.type === output.type">
{{max.name}} : <span translate>{{ output.listLabel }}</span>
</div>
<div class="desk-title" ng-if="max.type === 'search'">
{{searchLookup[max._id].name}}
</div>
<div class="desk-title" ng-if="max.type === 'personal'" translate>Personal</div>
<div class="box-items-count sd-line-input sd-line-input--no-margin sd-line-input--no-label sd-line-input--boxed">
<input class="sd-line-input__input" type="number" id="maxItems" ng-model="max.max_items" min="1" max="25" required>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal__footer">
<button id="previousBtn" class="btn btn--hollow pull-left" ng-if="step.current !== 'desks' && !displayOnlyCurrentStep" ng-click="previous()" translate>Previous</button>
<button class="btn" ng-click="cancel()" translate>Cancel</button>
<button class="btn btn--primary" ng-click="save()" translate>Done</button>
<button id="nextBtn" class="btn btn--hollow" ng-if="step.current !== 'maxitems' && !displayOnlyCurrentStep" ng-click="next()" translate>Next</button>
</div>
| marwoodandrew/superdesk-client-core | scripts/apps/monitoring/views/aggregate-settings.html | HTML | agpl-3.0 | 8,098 |
'use strict';
angular.module('GO.Modules.GroupOffice.Contacts').factory('GO.Modules.GroupOffice.Contacts.Model.ContactGroup', [
'GO.Core.Factories.Data.Model',
function (Model) {
var ContactGroup = GO.extend(Model, function () {
//rename function because this record has a delete attribute on the server
this.deleteRecord = this.delete;
this.$parent.constructor.call(this, arguments);
});
ContactGroup.prototype.getStoreRoute = function () {
return 'contacts/'+this.contactId+'/permissions';
};
ContactGroup.prototype.$keys = ['groupId'];
return ContactGroup;
}]);
| Intermesh/groupoffice-webclient | app/modules/groupoffice/contacts/model/contact-group.js | JavaScript | agpl-3.0 | 610 |
<?php
namespace WEEEOpen\TaralloTest\Database;
use PHPUnit\Framework\TestCase;
use WEEEOpen\Tarallo\Database\Database;
use WEEEOpen\Tarallo\Item;
abstract class DatabaseTest extends TestCase {
protected $db = null;
// this cannot be done, PLAIN AND SIMPLE. Even though it comes straight from an example inside documentation.
// setUp() comes from a trait, so there's no way to override it AND call it. parent::setUp() calls a pointless empty function.
// Excellent documentation, very clear, would rate it 10/10.
//protected function setUp() {
// if(!extension_loaded('pdo_mysql')) {
// $this->markTestSkipped('The PDO MySQL extension is not available.');
// }
//}
protected static function getPdo(): \PDO {
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';
return new \PDO(TARALLO_DB_DSN, TARALLO_DB_USERNAME, TARALLO_DB_PASSWORD, [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_CASE => \PDO::CASE_NATURAL,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
// \PDO::ATTR_AUTOCOMMIT => false, // PHPUnit crashes and burns with autocommits disabled and, for some unfathomable reason, two SEPARATE, DISTINCT, UNIQUE PDO object will forcefully share the same connection to MySQL (apparently?), so there's no way to have a connection with autocommits and another one without.
\PDO::ATTR_EMULATE_PREPARES => false,
]);
}
public static function setUpBeforeClass(): void {
$pdo = null;
$retries = 0;
$started = false;
while($retries <= 20) {
try {
$pdo = self::getPdo();
$started = true;
break;
} catch(\PDOException $e) {
$retries++;
sleep(1);
}
}
if(!$started) {
throw new \RuntimeException("Database not up after $retries seconds");
}
$retries = 0;
$found = false;
while($retries <= 20) {
$result = $pdo->query("SHOW EVENTS LIKE 'DuplicateItemProductFeaturesCleanup'");
if($result !== false) {
$result->fetchAll(\PDO::FETCH_ASSOC);
$found = true;
break;
}
sleep(1);
$retries++;
}
if(!$found) {
throw new \RuntimeException("Database not ready after $retries seconds");
}
}
public function setUp(): void {
$pdo = self::getPdo();
$pdo->exec(/** @lang MariaDB */ "SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE Audit; SET FOREIGN_KEY_CHECKS = 1;");
$pdo->exec(/** @lang MariaDB */ "SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE AuditProduct; SET FOREIGN_KEY_CHECKS = 1;");
$pdo->exec(/** @lang MariaDB */ "SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE Item; SET FOREIGN_KEY_CHECKS = 1;");
$pdo->exec(/** @lang MariaDB */ "SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE ItemFeature; SET FOREIGN_KEY_CHECKS = 1;");
$pdo->exec(/** @lang MariaDB */ "SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE Product; SET FOREIGN_KEY_CHECKS = 1;");
$pdo->exec(/** @lang MariaDB */ "SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE ProductFeature; SET FOREIGN_KEY_CHECKS = 1;");
$pdo->exec(/** @lang MariaDB */ "SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE Tree; SET FOREIGN_KEY_CHECKS = 1;");
$pdo->exec(/** @lang MariaDB */ "SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE Prefixes; SET FOREIGN_KEY_CHECKS = 1;");
$pdo->exec(/** @lang MariaDB */ "SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE Product; SET FOREIGN_KEY_CHECKS = 1;");
$pdo->exec(/** @lang MariaDB */ "SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE SearchResult; SET FOREIGN_KEY_CHECKS = 1;");
$pdo->exec(/** @lang MariaDB */ "SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE Search; SET FOREIGN_KEY_CHECKS = 1;");
$pdo->exec(/** @lang MariaDB */ "INSERT INTO Prefixes(Prefix, `Integer`) VALUES ('M', 10), ('T', 75), ('', 60);");
}
/**
* @return Database
*/
protected function getDb(): Database {
if($this->db === null) {
$this->getPdo();
$db = new Database(TARALLO_DB_USERNAME, TARALLO_DB_PASSWORD, TARALLO_DB_DSN);
//$dbr = new \ReflectionObject($db);
//$prop = $dbr->getProperty('pdo');
//$prop->setAccessible(true);
//$prop->setValue($db, $this->getPdo());
$this->db = $db;
}
return $this->db;
}
protected static function itemCompare(Item $a, Item $b): bool {
if($a->getCode() !== $b->getCode()) {
return false;
}
// TODO: compare recursively
//if($a->getProductFromStrings() !== $b->getProductFromStrings()) {
// return false;
//}
if(count($a->getFeatures()) !== count($b->getFeatures())) {
return false;
}
if(!empty(array_diff_assoc($a->getFeatures(), $b->getFeatures()))) {
return false;
}
if(count($a->getContent()) !== count($b->getContent())) {
return false;
}
$bContent = $b->getContent();
foreach($a->getContent() as $item) {
$code = $item->getCode();
foreach($bContent as $item2) {
if($code === $item2->getCode()) {
if(!static::itemCompare($item, $item2)) {
return false;
}
}
}
}
return true;
}
} | WEEE-Open/tarallo-backend | tests/Database/DatabaseTest.php | PHP | agpl-3.0 | 4,897 |
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: OpenDrive Ltda
# Copyright (c) 2013 Opendrive Ltda
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##############################################################################
from openerp.osv import osv, fields
from openerp.tools.translate import _
class Partner(osv.osv):
_inherit = 'res.partner'
_columns = {
'legal_representative': fields.char(
'Legal Representative',
),
}
| kailIII/emaresa | rent.resp/partner.py | Python | agpl-3.0 | 1,548 |
# Rule 1.4.5
## Summary
This test consists in detecting captcha embedded images and thus defining the applicability of the test.
Human check will be then needed to determine whether the alternative is pertinent.
## Business description
### Criterion
[1.4](http://references.modernisation.gouv.fr/referentiel-technique-0#crit-1-4)
###Test
[1.4.5](http://references.modernisation.gouv.fr/referentiel-technique-0#test-1-4-5)
### Description
Pour chaque image embarquée (balise `embed` avec l'attribut `type="image/..."`) utilisée comme <a href="http://references.modernisation.gouv.fr/referentiel-technique-0#mcaptcha">CAPTCHA</a> ou comme <a href="http://references.modernisation.gouv.fr/referentiel-technique-0#mimgTest">image-test</a>, et ayant une <a href="http://references.modernisation.gouv.fr/referentiel-technique-0#mAltTexteImg">alternative textuelle</a>, l'<a href="http://references.modernisation.gouv.fr/referentiel-technique-0#mAltTexteImg">alternative textuelle</a> permet-elle d'identifier la nature et la fonction de l'image ?
### Level
**A**
## Technical description
### Scope
**Page**
### Decision level
**Semi-Decidable**
## Algorithm
### Selection
##### Set1
All the `<embed>` tags of the page not within a link and with a `"type"` attribute that starts with "image/..." (css selector : embed[type^=image]:not(a embed))
#### Set2
All the elements of **Set1** identified as a CAPTCHA (see Notes for details about CAPTCHA characterisation).
### Process
#### Test1
For each element of **Set2**, raise a MessageA
##### MessageA : Check captcha alternative
- code : **CheckCaptchaAlternative**
- status: Pre-Qualified
- parameter : `"src"` attribute, tag name, snippet
- present in source : yes
### Analysis
#### Not Applicable
The page has no `<embed>` tag with an `"type"` attribute that starts with "image" identified as a captcha (**Set2** is empty)
#### Pre-qualified
In all other cases
## Notes
### Captcha detection
An element is identified as a CAPTCHA when the "captcha" occurrence is found :
- on one attribute of the element
- or within the text of the element
- or on one attribute of one parent of the element
- or within the text of one parent of the element
- or on one attribute of a sibling of the element
- or within the text of a sibling of the element
| Tanaguru/Tanaguru-rules-RGAA-3-doc | docs/Rule-1-4-5.md | Markdown | agpl-3.0 | 2,350 |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SSCMS.Dto;
using SSCMS.Utils;
namespace SSCMS.Web.Controllers.Admin.Common.Form
{
public partial class LayerImageUploadController
{
[HttpGet, Route(Route)]
public async Task<ActionResult<Options>> Get([FromQuery] SiteRequest request)
{
var options = new Options();
if (request.SiteId > 0)
{
var site = await _siteRepository.GetAsync(request.SiteId);
if (site == null) return this.Error("无法确定内容对应的站点");
options = TranslateUtils.JsonDeserialize(site.Get<string>(nameof(LayerImageUploadController)), new Options
{
IsEditor = true,
IsMaterial = true,
IsThumb = false,
ThumbWidth = 1024,
ThumbHeight = 1024,
IsLinkToOriginal = true
});
}
return options;
}
}
} | siteserver/cms | src/SSCMS.Web/Controllers/Admin/Common/Form/LayerImageUploadController.Get.cs | C# | agpl-3.0 | 1,054 |
(function() {
'use strict';
var getModulesList = function(modules) {
return modules.map(function(moduleName) {
return {name: moduleName};
});
};
var jsOptimize = process.env.REQUIRE_BUILD_PROFILE_OPTIMIZE !== undefined ?
process.env.REQUIRE_BUILD_PROFILE_OPTIMIZE : 'uglify2';
return {
namespace: 'RequireJS',
/**
* List the modules that will be optimized. All their immediate and deep
* dependencies will be included in the module's file when the build is
* done.
*/
modules: getModulesList([
'course_bookmarks/js/course_bookmarks_factory',
'course_search/js/course_search_factory',
'course_search/js/dashboard_search_factory',
'discussion/js/discussion_board_factory',
'discussion/js/discussion_profile_page_factory',
'js/api_admin/catalog_preview_factory',
'js/courseware/courseware_factory',
'js/discovery/discovery_factory',
'js/edxnotes/views/notes_visibility_factory',
'js/edxnotes/views/page_factory',
'js/financial-assistance/financial_assistance_form_factory',
'js/groups/views/cohorts_dashboard_factory',
'js/discussions_management/views/discussions_dashboard_factory',
'js/header_factory',
'js/learner_dashboard/course_entitlement_factory',
'js/learner_dashboard/unenrollment_factory',
'js/learner_dashboard/entitlement_unenrollment_factory',
'js/learner_dashboard/program_details_factory',
'js/learner_dashboard/program_list_factory',
'js/student_account/logistration_factory',
'js/student_account/views/account_settings_factory',
'js/student_account/views/finish_auth_factory',
'js/views/message_banner',
'learner_profile/js/learner_profile_factory',
'lms/js/preview/preview_factory',
'support/js/certificates_factory',
'support/js/enrollment_factory',
'support/js/manage_user_factory',
'teams/js/teams_tab_factory',
'js/dateutil_factory'
]),
/**
* By default all the configuration for optimization happens from the command
* line or by properties in the config file, and configuration that was
* passed to requirejs as part of the app's runtime "main" JS file is *not*
* considered. However, if you prefer the "main" JS file configuration
* to be read for the build so that you do not have to duplicate the values
* in a separate configuration, set this property to the location of that
* main JS file. The first requirejs({}), require({}), requirejs.config({}),
* or require.config({}) call found in that file will be used.
* As of 2.1.10, mainConfigFile can be an array of values, with the last
* value's config take precedence over previous values in the array.
*/
mainConfigFile: 'require-config.js',
/**
* Set paths for modules. If relative paths, set relative to baseUrl above.
* If a special value of "empty:" is used for the path value, then that
* acts like mapping the path to an empty file. It allows the optimizer to
* resolve the dependency to path, but then does not include it in the output.
* Useful to map module names that are to resources on a CDN or other
* http: URL when running in the browser and during an optimization that
* file should be skipped because it has no dependencies.
*/
paths: {
gettext: 'empty:',
'coffee/src/ajax_prefix': 'empty:',
jquery: 'empty:',
'jquery-migrate': 'empty:',
'jquery.cookie': 'empty:',
'jquery.url': 'empty:',
backbone: 'empty:',
underscore: 'empty:',
'underscore.string': 'empty:',
logger: 'empty:',
utility: 'empty:',
URI: 'empty:',
'common/js/discussion/views/discussion_inline_view': 'empty:',
modernizr: 'empty',
'which-country': 'empty',
// Don't bundle UI Toolkit helpers as they are loaded into the "edx" namespace
'edx-ui-toolkit/js/utils/html-utils': 'empty:',
'edx-ui-toolkit/js/utils/string-utils': 'empty:'
},
/**
* Inline requireJS text templates.
*/
inlineText: true,
/**
* Stub out requireJS text in the optimized file, but leave available for non-optimized development use.
*/
stubModules: ['text'],
/**
* If shim config is used in the app during runtime, duplicate the config
* here. Necessary if shim config is used, so that the shim's dependencies
* are included in the build. Using "mainConfigFile" is a better way to
* pass this information though, so that it is only listed in one place.
* However, if mainConfigFile is not an option, the shim config can be
* inlined in the build config.
*/
shim: {},
/**
* Introduced in 2.1.2: If using "dir" for an output directory, normally the
* optimize setting is used to optimize the build bundles (the "modules"
* section of the config) and any other JS file in the directory. However, if
* the non-build bundle JS files will not be loaded after a build, you can
* skip the optimization of those files, to speed up builds. Set this value
* to true if you want to skip optimizing those other non-build bundle JS
* files.
*/
skipDirOptimize: true,
/**
* When the optimizer copies files from the source location to the
* destination directory, it will skip directories and files that start
* with a ".". If you want to copy .directories or certain .files, for
* instance if you keep some packages in a .packages directory, or copy
* over .htaccess files, you can set this to null. If you want to change
* the exclusion rules, change it to a different regexp. If the regexp
* matches, it means the directory will be excluded. This used to be
* called dirExclusionRegExp before the 1.0.2 release.
* As of 1.0.3, this value can also be a string that is converted to a
* RegExp via new RegExp().
*/
fileExclusionRegExp: /^\.|spec|spec_helpers/,
/**
* Allow CSS optimizations. Allowed values:
* - "standard": @import inlining and removal of comments, unnecessary
* whitespace and line returns.
* Removing line returns may have problems in IE, depending on the type
* of CSS.
* - "standard.keepLines": like "standard" but keeps line returns.
* - "none": skip CSS optimizations.
* - "standard.keepComments": keeps the file comments, but removes line
* returns. (r.js 1.0.8+)
* - "standard.keepComments.keepLines": keeps the file comments and line
* returns. (r.js 1.0.8+)
* - "standard.keepWhitespace": like "standard" but keeps unnecessary whitespace.
*/
optimizeCss: 'none',
/**
* How to optimize all the JS files in the build output directory.
* Right now only the following values are supported:
* - "uglify": Uses UglifyJS to minify the code.
* - "uglify2": Uses UglifyJS2.
* - "closure": Uses Google's Closure Compiler in simple optimization
* mode to minify the code. Only available if REQUIRE_ENVIRONMENT is "rhino" (the default).
* - "none": No minification will be done.
*/
optimize: jsOptimize,
/**
* Sets the logging level. It is a number:
* TRACE: 0,
* INFO: 1,
* WARN: 2,
* ERROR: 3,
* SILENT: 4
* Default is 0.
*/
logLevel: 1
};
}());
| TeachAtTUM/edx-platform | lms/static/lms/js/build.js | JavaScript | agpl-3.0 | 8,162 |
import React from 'react'
import {intlEnzyme} from 'tocco-test-util'
import MenuChildrenWrapper from './MenuChildrenWrapper'
import {StyledMenuChildrenWrapper} from './StyledComponents'
describe('admin', () => {
describe('components', () => {
describe('Navigation', () => {
describe('menuType', () => {
describe('MenuChildrenWrapper', () => {
test('should render children when expanded', () => {
const isOpen = true
const canCollapse = true
const children = <div id="child">Hallo</div>
const props = {
isOpen,
canCollapse,
menuTreePath: 'address',
preferencesPrefix: ''
}
const wrapper = intlEnzyme.mountWithIntl(<MenuChildrenWrapper {...props}>{children}</MenuChildrenWrapper>)
expect(wrapper.find(StyledMenuChildrenWrapper).prop('isOpen')).to.be.true
})
test('should not render children when collapsed', () => {
const isOpen = false
const canCollapse = true
const children = <div id="child">Hallo</div>
const props = {
isOpen,
canCollapse,
menuTreePath: 'address',
preferencesPrefix: ''
}
const wrapper = intlEnzyme.mountWithIntl(<MenuChildrenWrapper {...props}>{children}</MenuChildrenWrapper>)
expect(wrapper.find(StyledMenuChildrenWrapper).prop('isOpen')).to.be.false
})
test('should render children when not collapsible', () => {
const isOpen = false
const canCollapse = false
const children = <div id="child">Hallo</div>
const props = {
isOpen,
canCollapse,
menuTreePath: 'address',
preferencesPrefix: ''
}
const wrapper = intlEnzyme.mountWithIntl(<MenuChildrenWrapper {...props}>{children}</MenuChildrenWrapper>)
expect(wrapper.find(StyledMenuChildrenWrapper).prop('isOpen')).to.be.true
})
})
})
})
})
})
| tocco/tocco-client | packages/apps/admin/src/components/Navigation/menuType/MenuChildrenWrapper.spec.js | JavaScript | agpl-3.0 | 2,143 |
# -*- coding: utf-8 -*-
import time
from datetime import timedelta
class CookieJar:
def __init__(self, pluginname, account=None):
self.cookies = {}
self.plugin = pluginname
self.account = account
def add_cookies(self, clist):
for c in clist:
name = c.split("\t")[5]
self.cookies[name] = c
def get_cookies(self):
return list(self.cookies.values())
def parse_cookie(self, name):
if name in self.cookies:
return self.cookies[name].split("\t")[6]
else:
return None
def get_cookie(self, name):
return self.parse_cookie(name)
def set_cookie(
self,
domain,
name,
value,
path="/",
exp=time.time() + timedelta(hours=744).total_seconds(), #: 31 days retention
):
self.cookies[
name
] = f".{domain}\tTRUE\t{path}\tFALSE\t{exp}\t{name}\t{value}"
def clear(self):
self.cookies = {}
| vuolter/pyload | src/pyload/core/network/cookie_jar.py | Python | agpl-3.0 | 1,007 |
/**
* vinimay
* Vinimay is a decentralised social network focused on giving back control of its data to the user
*
* OpenAPI spec version: 0.1.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
export interface DeletionServerInput {
/**
* The token identifying the relationship
*/
token: string;
/**
* Request signature, required if the frienship was previously accepted
*/
signature?: string;
}
| JosephCaillet/vinimay | client/src/providers/apiClient/model/deletionServerInput.ts | TypeScript | agpl-3.0 | 569 |
<?php
/**
* Message translations.
*
* This file is automatically generated by 'yii message/extract' command.
* It contains the localizable messages extracted from source code.
* You may modify this file by translating the extracted messages.
*
* Each array element represents the translation (value) of a message (key).
* If the value is empty, the message is considered as not translated.
* Messages that no longer need translation will have their translations
* enclosed between a pair of '@@' marks.
*
* Message string can be used with plural forms format. Check i18n section
* of the guide for details.
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
return [
'Access granted' => 'Acceso concedido',
'Access removed' => 'Acceso quitado',
'All wheels already fullfilled. Emails not sent.' => 'Todas las ruedas ya completadas. Correos electrónicos no enviados.',
'Allowed coaches' => 'Coaches invitados',
'Are you sure you want to delete this team?' => '¿Está seguro que quiere eliminar este equipo?',
'Are you sure you want to discard and redo this wheel?' => '¿Está seguro que quiere descartar y rehacer esta rueda?',
'Are you sure you want to duplicate this team type?' => '¿Está seguro que quiere duplicar ese tipo de equipo?',
'CPC: access to {wheel_type} of team {team}' => 'CPC: acceso a {wheel_type} del equipo {team}',
'CPC: stock added' => 'CPC: licencias agregadas',
'CPC: team fulfilled' => 'CPC: equipo completado',
'Coach' => 'Coach',
'Company' => 'Empresa',
'Delete licence type' => 'Borrar tipo de licencia',
'Delete team type' => 'Borra tipo de equipo',
'Deleting team' => 'Eliminando equipo',
'Edit team type' => 'Editar tipo de equipo',
'Email to send' => 'Correo electrónico a enviar',
'Go to dashboard...' => 'Ir al tablero...',
'Go to report...' => 'Ir al informe...',
'Grant access' => 'Permitir acceso',
'Group wheels' => 'Ruedas grupales',
'Individual wheels' => 'Ruedas individuales',
'Licence' => 'Licencia',
'Licence Type' => 'Tipo de licencia',
'Member' => 'Miembro',
'Members' => 'Miembros',
'Natural Team' => 'Equipo natural',
'New member' => 'Nuevo miembro',
'New team' => 'Nuevo equipo',
'New team type' => 'Nuevo tipo de equipo',
'Organizational wheels' => 'Ruedas organizacionales',
'Please ask the audience to enter this site and token in his/her phone browser' => 'Por favor pida al público que ingrese este sitio e indentificador en su teléfono',
'Please fill out the following fields with team data:' => 'Por favor, complete los campos con los datos del equipo',
'Please send this email' => 'Por favor envíe este correo electrónico',
'Product' => 'Producto',
'Remove access' => 'Quitar acceso',
'Run on smartphones' => 'Ejectuar en teléfonos celulares',
'Select coach...' => 'Elija coach...',
'Select new member...' => 'Elegir nuevo miembro...',
'Sponsor' => 'Patrocinador',
'Team' => 'Equipo',
'Team Type' => 'Tipo de equipo',
'Team Types' => 'Tipos de equipos',
'Team data' => 'Datos del equipo',
'Team fullfilled' => 'Equipo completado',
'Team has been successfully deleted.' => 'Equipo ha sido exitosamente eliminado.',
'Teams' => 'Equipos',
'Update Team' => 'Actualizar equipo',
'Wheel already fullfilled. Email not sent.' => 'Rueda ya completada. Correo electrónico no enviado.',
'Wheel forms has been successfully created.' => 'Formularios de ruedas han sido creados exitosamente.',
'Wheels' => 'Ruedas',
'{wheel_type} not sent to {user}.' => '{wheel_type} no enviada a {user}',
'{wheel_type} sent to {user}.' => '{wheel_type} enviada a {user}',
];
| fundacionempowerment/VACH | messages/es/team.php | PHP | agpl-3.0 | 3,747 |
"""
Test scenarios for the review xblock.
"""
import ddt
import unittest
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from nose.plugins.attrib import attr
from lms.djangoapps.courseware.tests.factories import GlobalStaffFactory
from lms.djangoapps.courseware.tests.helpers import LoginEnrollmentTestCase
from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory
from review import get_review_ids
import crum
class TestReviewXBlock(SharedModuleStoreTestCase, LoginEnrollmentTestCase):
"""
Create the test environment with the review xblock.
"""
STUDENTS = [
{'email': '[email protected]', 'password': 'foo'},
]
XBLOCK_NAMES = ['review']
URL_BEGINNING = settings.LMS_ROOT_URL + \
'/xblock/block-v1:DillonX/DAD101x_review/3T2017+type@'
@classmethod
def setUpClass(cls):
# Nose runs setUpClass methods even if a class decorator says to skip
# the class: https://github.com/nose-devs/nose/issues/946
# So, skip the test class here if we are not in the LMS.
if settings.ROOT_URLCONF != 'lms.urls':
raise unittest.SkipTest('Test only valid in lms')
super(TestReviewXBlock, cls).setUpClass()
# Set up for the actual course
cls.course_actual = CourseFactory.create(
display_name='Review_Test_Course_ACTUAL',
org='DillonX',
number='DAD101x',
run='3T2017'
)
# There are multiple sections so the learner can load different
# problems, but should only be shown review problems from what they have loaded
with cls.store.bulk_operations(cls.course_actual.id, emit_signals=False):
cls.chapter_actual = ItemFactory.create(
parent=cls.course_actual, display_name='Overview'
)
cls.section1_actual = ItemFactory.create(
parent=cls.chapter_actual, display_name='Section 1'
)
cls.unit1_actual = ItemFactory.create(
parent=cls.section1_actual, display_name='New Unit 1'
)
cls.xblock1_actual = ItemFactory.create(
parent=cls.unit1_actual,
category='problem',
display_name='Problem 1'
)
cls.xblock2_actual = ItemFactory.create(
parent=cls.unit1_actual,
category='problem',
display_name='Problem 2'
)
cls.xblock3_actual = ItemFactory.create(
parent=cls.unit1_actual,
category='problem',
display_name='Problem 3'
)
cls.xblock4_actual = ItemFactory.create(
parent=cls.unit1_actual,
category='problem',
display_name='Problem 4'
)
cls.section2_actual = ItemFactory.create(
parent=cls.chapter_actual, display_name='Section 2'
)
cls.unit2_actual = ItemFactory.create(
parent=cls.section2_actual, display_name='New Unit 2'
)
cls.xblock5_actual = ItemFactory.create(
parent=cls.unit2_actual,
category='problem',
display_name='Problem 5'
)
cls.section3_actual = ItemFactory.create(
parent=cls.chapter_actual, display_name='Section 3'
)
cls.unit3_actual = ItemFactory.create(
parent=cls.section3_actual, display_name='New Unit 3'
)
cls.xblock6_actual = ItemFactory.create(
parent=cls.unit3_actual,
category='problem',
display_name='Problem 6'
)
cls.course_actual_url = reverse(
'courseware_section',
kwargs={
'course_id': unicode(cls.course_actual.id),
'chapter': 'Overview',
'section': 'Welcome',
}
)
# Set up for the review course where the review problems are hosted
cls.course_review = CourseFactory.create(
display_name='Review_Test_Course_REVIEW',
org='DillonX',
number='DAD101x_review',
run='3T2017'
)
with cls.store.bulk_operations(cls.course_review.id, emit_signals=True):
cls.chapter_review = ItemFactory.create(
parent=cls.course_review, display_name='Overview'
)
cls.section_review = ItemFactory.create(
parent=cls.chapter_review, display_name='Welcome'
)
cls.unit1_review = ItemFactory.create(
parent=cls.section_review, display_name='New Unit 1'
)
cls.xblock1_review = ItemFactory.create(
parent=cls.unit1_review,
category='problem',
display_name='Problem 1'
)
cls.xblock2_review = ItemFactory.create(
parent=cls.unit1_review,
category='problem',
display_name='Problem 2'
)
cls.xblock3_review = ItemFactory.create(
parent=cls.unit1_review,
category='problem',
display_name='Problem 3'
)
cls.xblock4_review = ItemFactory.create(
parent=cls.unit1_review,
category='problem',
display_name='Problem 4'
)
cls.unit2_review = ItemFactory.create(
parent=cls.section_review, display_name='New Unit 2'
)
cls.xblock5_review = ItemFactory.create(
parent=cls.unit2_review,
category='problem',
display_name='Problem 5'
)
cls.unit3_review = ItemFactory.create(
parent=cls.section_review, display_name='New Unit 3'
)
cls.xblock6_review = ItemFactory.create(
parent=cls.unit3_review,
category='problem',
display_name='Problem 6'
)
cls.course_review_url = reverse(
'courseware_section',
kwargs={
'course_id': unicode(cls.course_review.id),
'chapter': 'Overview',
'section': 'Welcome',
}
)
def setUp(self):
super(TestReviewXBlock, self).setUp()
for idx, student in enumerate(self.STUDENTS):
username = 'u{}'.format(idx)
self.create_account(username, student['email'], student['password'])
self.activate_user(student['email'])
self.staff_user = GlobalStaffFactory()
def enroll_student(self, email, password, course):
"""
Student login and enroll for the course
"""
self.login(email, password)
self.enroll(course, verify=True)
@attr(shard=1)
@ddt.ddt
class TestReviewFunctions(TestReviewXBlock):
"""
Check that the essential functions of the Review xBlock work as expected.
Tests cover the basic process of receiving a hint, adding a new hint,
and rating/reporting hints.
"""
def test_no_review_problems(self):
"""
If a user has not seen any problems, they should
receive a response to go out and try more problems so they have
material to review.
"""
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_actual)
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_review)
with self.store.bulk_operations(self.course_actual.id, emit_signals=False):
review_section_actual = ItemFactory.create(
parent=self.chapter_actual, display_name='Review Subsection'
)
review_unit_actual = ItemFactory.create(
parent=review_section_actual, display_name='Review Unit'
)
review_xblock_actual = ItemFactory.create( # pylint: disable=unused-variable
parent=review_unit_actual,
category='review',
display_name='Review Tool'
)
# Loading the review section
response = self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': review_section_actual.location.name,
}
))
expected_h2 = 'Nothing to review'
self.assertIn(expected_h2, response.content)
@ddt.data(5, 7)
def test_too_few_review_problems(self, num_desired):
"""
If a user does not have enough problems to review, they should
receive a response to go out and try more problems so they have
material to review.
Testing loading 4 problems and asking for 5 and then loading every
problem and asking for more than that.
"""
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_actual)
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_review)
# Want to load fewer problems than num_desired
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section1_actual.location.name,
}
))
if num_desired > 6:
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section2_actual.location.name,
}
))
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section3_actual.location.name,
}
))
with self.store.bulk_operations(self.course_actual.id, emit_signals=False):
review_section_actual = ItemFactory.create(
parent=self.chapter_actual, display_name='Review Subsection'
)
review_unit_actual = ItemFactory.create(
parent=review_section_actual, display_name='Review Unit'
)
review_xblock_actual = ItemFactory.create( # pylint: disable=unused-variable
parent=review_unit_actual,
category='review',
display_name='Review Tool',
num_desired=num_desired
)
# Loading the review section
response = self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': review_section_actual.location.name,
}
))
expected_h2 = 'Nothing to review'
self.assertIn(expected_h2, response.content)
@ddt.data(2, 6)
def test_review_problems(self, num_desired):
"""
If a user has enough problems to review, they should
receive a response where there are review problems for them to try.
"""
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_actual)
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_review)
# Loading problems so the learner has enough problems in the CSM
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section1_actual.location.name,
}
))
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section2_actual.location.name,
}
))
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section3_actual.location.name,
}
))
with self.store.bulk_operations(self.course_actual.id, emit_signals=False):
review_section_actual = ItemFactory.create(
parent=self.chapter_actual, display_name='Review Subsection'
)
review_unit_actual = ItemFactory.create(
parent=review_section_actual, display_name='Review Unit'
)
review_xblock_actual = ItemFactory.create( # pylint: disable=unused-variable
parent=review_unit_actual,
category='review',
display_name='Review Tool',
num_desired=num_desired
)
# Loading the review section
response = self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': review_section_actual.location.name,
}
))
expected_header_text = 'Review Problems'
# The problems are defaulted to correct upon load
# This happens because the problems "raw_possible" field is 0 and the
# "raw_earned" field is also 0.
expected_correctness_text = 'correct'
expected_problems = ['Review Problem 1', 'Review Problem 2', 'Review Problem 3',
'Review Problem 4', 'Review Problem 5', 'Review Problem 6']
self.assertIn(expected_header_text, response.content)
self.assertEqual(response.content.count(expected_correctness_text), num_desired)
# Since the problems are randomly selected, we have to check
# the correct number of problems are returned.
count = 0
for problem in expected_problems:
if problem in response.content:
count += 1
self.assertEqual(count, num_desired)
self.assertEqual(response.content.count(self.URL_BEGINNING), num_desired)
@ddt.data(2, 6)
def test_review_problem_urls(self, num_desired):
"""
Verify that the URLs returned from the Review xBlock are valid and
correct URLs for the problems the learner has seen.
"""
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_actual)
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_review)
# Loading problems so the learner has enough problems in the CSM
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section1_actual.location.name,
}
))
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section2_actual.location.name,
}
))
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section3_actual.location.name,
}
))
user = User.objects.get(email=self.STUDENTS[0]['email'])
crum.set_current_user(user)
result_urls = get_review_ids.get_problems(num_desired, self.course_actual.id)
expected_urls = [
(self.URL_BEGINNING + 'problem+block@Problem_1', True, 0),
(self.URL_BEGINNING + 'problem+block@Problem_2', True, 0),
(self.URL_BEGINNING + 'problem+block@Problem_3', True, 0),
(self.URL_BEGINNING + 'problem+block@Problem_4', True, 0),
(self.URL_BEGINNING + 'problem+block@Problem_5', True, 0),
(self.URL_BEGINNING + 'problem+block@Problem_6', True, 0)
]
# Since the problems are randomly selected, we have to check
# the correct number of urls are returned.
count = 0
for url in expected_urls:
if url in result_urls:
count += 1
self.assertEqual(count, num_desired)
@ddt.data(2, 5)
def test_review_problem_urls_unique_problem(self, num_desired):
"""
Verify that the URLs returned from the Review xBlock are valid and
correct URLs for the problems the learner has seen. This test will give
a unique problem to a learner and verify only that learner sees
it as a review. It will also ensure that if a learner has not loaded a
problem, it should never show up as a review problem
"""
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_actual)
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_review)
# Loading problems so the learner has enough problems in the CSM
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section1_actual.location.name,
}
))
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section3_actual.location.name,
}
))
user = User.objects.get(email=self.STUDENTS[0]['email'])
crum.set_current_user(user)
result_urls = get_review_ids.get_problems(num_desired, self.course_actual.id)
expected_urls = [
(self.URL_BEGINNING + 'problem+block@Problem_1', True, 0),
(self.URL_BEGINNING + 'problem+block@Problem_2', True, 0),
(self.URL_BEGINNING + 'problem+block@Problem_3', True, 0),
(self.URL_BEGINNING + 'problem+block@Problem_4', True, 0),
# This is the unique problem when num_desired == 5
(self.URL_BEGINNING + 'problem+block@Problem_6', True, 0)
]
expected_not_loaded_problem = (self.URL_BEGINNING + 'problem+block@Problem_5', True, 0)
# Since the problems are randomly selected, we have to check
# the correct number of urls are returned.
count = 0
for url in expected_urls:
if url in result_urls:
count += 1
self.assertEqual(count, num_desired)
self.assertNotIn(expected_not_loaded_problem, result_urls)
# NOTE: This test is failing because when I grab the problem from the CSM,
# it is unable to find its parents. This is some issue with the BlockStructure
# and it not being populated the way we want. For now, this is being left out
# since the first course I'm working with does not use this function.
# TODO: Fix get_vertical from get_review_ids to have the block structure for this test
# or fix something in this file to make sure it populates the block structure for the CSM
@unittest.skip
def test_review_vertical_url(self):
"""
Verify that the URL returned from the Review xBlock is a valid and
correct URL for the vertical the learner has seen.
"""
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_actual)
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_review)
# Loading problems so the learner has problems and thus a vertical in the CSM
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section1_actual.location.name,
}
))
user = User.objects.get(email=self.STUDENTS[0]['email'])
crum.set_current_user(user)
result_url = get_review_ids.get_vertical(self.course_actual.id)
expected_url = self.URL_BEGINNING + 'vertical+block@New_Unit_1'
self.assertEqual(result_url, expected_url)
| lduarte1991/edx-platform | openedx/tests/xblock_integration/test_review_xblock.py | Python | agpl-3.0 | 21,237 |
/****************************************************************
* *
* Copyright 2001, 2009 Fidelity Information Services, Inc *
* *
* This source code contains the intellectual property *
* of its copyright holder(s), and is made available *
* under a license. If you do not know the terms of *
* the license, please stop and do not read further. *
* *
****************************************************************/
#include "mdef.h"
#include "gtm_string.h"
#include <ssdef.h>
#include <descrip.h>
#include <rmsdef.h>
#include <prcdef.h>
#include "job.h"
#include "min_max.h"
static readonly unsigned char definput[] = "NL:";
static readonly unsigned char deflogfile[] = "NL:";
static unsigned char *defoutbuf;
static unsigned char *deferrbuf;
LITREF jp_datatype job_param_datatypes[];
LITREF mstr define_gtm$job$_;
LITREF mstr set_default_;
LITREF mstr atsign;
LITREF mstr run__nodebug_;
void ojparams(unsigned char *p, mval *routine, bool *defprcnam, int4 *cmaxmsg, mstr *image,
mstr *input, mstr *output, mstr *error, struct dsc$descriptor_s *prcnam, int4 *baspri,
int4 *stsflg, mstr *gbldir, mstr *startup, struct dsc$descriptor_s *logfile, mstr *deffs,
quadword *schedule)
{
jp_type ch;
int4 status;
struct dsc$descriptor_s timdsc;
int4 defstsflg;
MSTR_CONST(defoutext, ".MJO");
MSTR_CONST(deferrext, ".MJE");
error_def (ERR_IVTIME);
error_def (ERR_PRCNAMLEN);
error_def (ERR_PARFILSPC);
/* Initializations */
*defprcnam = FALSE;
defstsflg = PRC$M_DETACH;
*cmaxmsg = MAX(*cmaxmsg, (define_gtm$job$_.len + MAX_PIDSTR_LEN));
image->len = 0;
input->len = output->len = error->len = 0;
prcnam->dsc$w_length = 0;
prcnam->dsc$b_dtype = DSC$K_DTYPE_T;
prcnam->dsc$b_class = DSC$K_CLASS_S;
*baspri = JP_NO_BASPRI;
*stsflg = defstsflg;
gbldir->len = 0;
startup->len = 0;
logfile->dsc$w_length = 0;
logfile->dsc$b_dtype = DSC$K_DTYPE_T;
logfile->dsc$b_class = DSC$K_CLASS_S;
deffs->len = 0;
schedule->hi = schedule->lo = 0;
/* Process parameter list */
while (*p != jp_eol)
{
switch (ch = *p++)
{
case jp_account:
*stsflg &= (~PRC$M_NOACNT);
break;
case jp_default:
if (*p != 0)
{
deffs->len = *p;
deffs->addr = (p + 1);
}
break;
case jp_detached:
*stsflg |= PRC$M_DETACH;
break;
case jp_error:
if (*p != 0)
{
error->len = *p;
error->addr = (p + 1);
}
break;
case jp_gbldir:
if (*p != 0)
{
gbldir->len = *p;
gbldir->addr = (p + 1);
}
break;
case jp_image:
if (*p != 0)
{
image->len = *p;
image->addr = p + 1;
}
break;
case jp_input:
if (*p != 0)
{
input->len = *p;
input->addr = p + 1;
}
break;
case jp_logfile:
if (*p != 0)
{
logfile->dsc$w_length = *p;
logfile->dsc$a_pointer = p + 1;
}
break;
case jp_noaccount:
*stsflg |= PRC$M_NOACNT;
break;
case jp_nodetached:
*stsflg &= (~PRC$M_DETACH);
break;
case jp_noswapping:
*stsflg |= PRC$M_PSWAPM;
break;
case jp_output:
if (*p != 0)
{
output->len = *p;
output->addr = p + 1;
}
break;
case jp_priority:
*baspri = *(int4 *)p;
break;
case jp_process_name:
if (*p != 0)
{
prcnam->dsc$w_length = *p;
prcnam->dsc$a_pointer = p + 1;
}
break;
case jp_schedule:
timdsc.dsc$w_length = *p;
timdsc.dsc$b_dtype = DSC$K_DTYPE_T;
timdsc.dsc$b_class = DSC$K_CLASS_S;
timdsc.dsc$a_pointer = p + 1;
status = sys$bintim (&timdsc, schedule);
if (status != SS$_NORMAL)
rts_error(VARLSTCNT(4) ERR_IVTIME, 2, timdsc.dsc$w_length, timdsc.dsc$a_pointer);
break;
case jp_startup:
if (*p != 0)
{
startup->len = *p;
startup->addr = p + 1;
}
break;
case jp_swapping:
*stsflg &= (~PRC$M_PSWAPM);
break;
default:
GTMASSERT;
}
switch (job_param_datatypes[ch])
{
case jpdt_nul:
break;
case jpdt_num:
p += SIZEOF(int4);
break;
case jpdt_str:
p += (unsigned) *p + 1;
break;
default:
GTMASSERT;
}
}
/* Defaults and Checks */
if (image->len == 0)
ojdefimage (image);
else
if ((status = ojchkfs (image->addr, image->len, TRUE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 5, "IMAGE", image->len, image->addr, status);
*cmaxmsg = MAX(*cmaxmsg, run__nodebug_.len + image->len);
if (input->len == 0)
{
input->len = SIZEOF(definput) - 1;
input->addr = definput;
}
else
if ((status = ojchkfs (input->addr, input->len, TRUE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 5, "INPUT", input->len, input->addr, status);
*cmaxmsg = MAX(*cmaxmsg, 1 + input->len);
if (output->len == 0)
{
if (!defoutbuf)
defoutbuf = malloc(MAX_FILSPC_LEN);
memcpy (&defoutbuf[0], routine->str.addr, routine->str.len);
memcpy (&defoutbuf[routine->str.len], defoutext.addr, defoutext.len);
if (*defoutbuf == '%')
*defoutbuf = '_';
output->len = routine->str.len + defoutext.len;
output->addr = &defoutbuf[0];
}
else
if ((status = ojchkfs (output->addr, output->len, FALSE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 6, "OUTPUT", output->len, output->addr, status);
*cmaxmsg = MAX(*cmaxmsg, 1 + output->len);
if (error->len == 0)
{
if (!deferrbuf)
deferrbuf = malloc(MAX_FILSPC_LEN);
memcpy (&deferrbuf[0], routine->str.addr, routine->str.len);
memcpy (&deferrbuf[routine->str.len], deferrext.addr, deferrext.len);
if (*deferrbuf == '%')
*deferrbuf = '_';
error->len = routine->str.len + deferrext.len;
error->addr = &deferrbuf[0];
}
else
if ((status = ojchkfs (error->addr, error->len, FALSE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 5, "ERROR", error->len, error->addr, status);
*cmaxmsg = MAX(*cmaxmsg, 1 + error->len);
if (prcnam->dsc$w_length > MAX_PRCNAM_LEN)
rts_error(VARLSTCNT(5) ERR_PRCNAMLEN, 3, prcnam->dsc$w_length, prcnam->dsc$a_pointer, MAX_PRCNAM_LEN);
if (prcnam->dsc$w_length == 0)
{
ojdefprcnam (prcnam);
*defprcnam = TRUE;
}
if (*baspri == JP_NO_BASPRI)
ojdefbaspri (baspri);
if (gbldir->len != 0)
if ((status = ojchkfs (gbldir->addr, gbldir->len, FALSE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 6, "GBLDIR", gbldir->len, gbldir->addr, status);
*cmaxmsg = MAX(*cmaxmsg, 1 + gbldir->len);
if (startup->len != 0)
if ((status = ojchkfs (startup->addr, startup->len, TRUE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 7, "STARTUP", startup->len, startup->addr, status);
*cmaxmsg = MAX(*cmaxmsg, atsign.len + startup->len);
if (deffs->len == 0)
ojdefdeffs (deffs);
else
if ((status = ojchkfs (deffs->addr, deffs->len, FALSE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 7, "DEFAULT", deffs->len, deffs->addr, status);
*cmaxmsg = MAX(*cmaxmsg, set_default_.len + deffs->len);
if (logfile->dsc$w_length == 0)
{
logfile->dsc$w_length = SIZEOF(deflogfile) - 1;
logfile->dsc$a_pointer = deflogfile;
}
else
if ((status = ojchkfs (logfile->dsc$a_pointer, logfile->dsc$w_length, FALSE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 7, "LOGFILE", logfile->dsc$w_length,
logfile->dsc$a_pointer, status);
return;
}
| ChristyV/fis-gtm | sr_vvms/ojparams.c | C | agpl-3.0 | 7,183 |
<div id="page" style="display: none;" data-bind="visible: true, css: { withToolbox: $root.showToolbox, withPreviewFrame: showPreviewFrame }">
<div id="main-edit-area" data-bind="click: function(obj, evt) { $root.selectBlock(null); return true; }, clickBubble: false">
<!-- ko withProperties: { templateMode: 'wysiwyg', templateModeFallback: 'show' } -->
<div id="main-wysiwyg-area" data-bind="wysiwygScrollfix: true, scrollable: true, fudroppable: { active: draggingImage }, css: { isdragging: dragging, isdraggingimg: draggingImage }, block: content"></div>
<!-- /ko -->
</div>
<div id="toolbar" class="mo" data-bind="tooltips: {}">
<!-- ko if: typeof $root.undo != 'undefined' -->
<span data-bind="buttonset: { }" class="leftButtons">
<a title="Undo last operation" href="#" data-bind="attr: { title: $root.t('Undo last operation') }, click: $root.undo.execute, clickBubble: false, button: { disabled: !$root.undo.enabled(), icons: { primary: 'fa fa-reply' }, label: $root.undo.name, text: true }">UNDO</a>
<a title="Redo last operation" href="#" data-bind="attr: { title: $root.t('Redo last operation') }, click: $root.redo.execute, clickBubble: false, button: { disabled: !$root.redo.enabled(), icons: { primary: 'fa fa-share' }, label: $root.redo.name, text: true }">REDO</a>
</span>
<!-- ko if: $root.debug -->
<a href="#" data-bind="click: $root.undoReset, clickBubble: false, button: { disabled: !$root.undo.enabled() && !$root.redo.enabled(), label: 'reset', text: true }">RESET</a>
<!-- /ko -->
<!-- /ko -->
<span>
<input id="showGallery" type="checkbox" data-bind="checked: $root.showGallery, button: { refreshOn: $root.showGallery,
icons: { primary: 'fa fa-fw fa-picture-o', secondary: null }, text: true, label: $root.t('Gallery') }"><label title="Show image gallery" for="showGallery" data-bind="attr: { title: $root.t('Show image gallery') }">show gallery</label></input>
</span>
<input id="previewFrameToggle" type="checkbox" data-bind="checked: $root.showPreviewFrame, button: { refreshOn: $root.showPreviewFrame, icons: { primary: 'fa fa-fw fa-tablet', secondary: null }, text: false, label: $root.t('Preview') }"><label title="Show live preview" for="previewFrameToggle" data-bind="attr: { title: $root.t('Show live preview') }">PREVIEW</label></input>
<!-- ko if: $root.debug -->
<a href="#" data-bind="click: $root.export, clickBubble: false, button: { label: 'export', text: true }">EXPORT</a>
<input type="checkbox" data-bind="checked: $root.debug" /> debug
<a href="#" data-bind="click: $root.loadDefaultBlocks, clickBubble: false, button: { icons: { primary: 'fa fa-fw fa-upload' }, label: 'Default', text: true }">LOAD BLOCKS</a>
[<a id="subscriptionsCount" href="javascript:viewModel.loopSubscriptionsCount()">subs</a>]
<!-- /ko -->
<span data-bind="visible: false">
<input type="checkbox" data-bind="checked: $root.showToolbox" /> toolbox
</span>
<div class="rightButtons">
<!-- ko if: typeof $root.save !== 'undefined' -->
<a title="Save template" href="#" data-bind="attr: { title: $root.t('Save template') }, click: $root.save.execute, clickBubble: false, button: { disabled: !$root.save.enabled(), icons: { primary: 'fa fa-fw fa-cloud-upload' }, label: $root.t($root.save.name), text: true }">SALVA</a>
<!-- /ko -->
<!-- ko if: typeof $root.test !== 'undefined' -->
<a title="Show preview and send test" href="#" data-bind="attr: { title: $root.t('Show preview and send test') }, click: $root.test.execute, clickBubble: false, button: { disabled: !$root.test.enabled(), icons: { primary: 'fa fa-fw fa-paper-plane' }, label: $root.t($root.test.name), text: true }">TEST</a>
<!-- /ko -->
<!-- ko if: typeof $root.download !== 'undefined' -->
<form id="downloadForm" action="#" method="POST">
<input type="hidden" name="action" value="download" />
<input type="hidden" name="filename" value="email.html" />
<input type="hidden" name="html" id="downloadHtmlTextarea" />
<a title="Download template" href="#" data-bind="attr: { title: $root.t('Download template') }, click: $root.download.execute, clickBubble: false, button: { disabled: !$root.download.enabled(), icons: { primary: 'fa fa-fw fa-download' }, label: $root.t($root.download.name), text: true }">DOWNLOAD</a>
</form>
<!-- /ko -->
</div>
</div>
<!-- ko if: $root.showToolbox -->
<div id="main-toolbox" class="mo" data-bind="scrollable: true, withProperties: { templateMode: 'edit' }">
<div data-bind="template: { name: 'toolbox' }"></div>
</div>
<!-- /ko -->
<div id="main-preview" class="mo" data-bind="scrollable: true, if: $root.showPreviewFrame">
<div id="preview-toolbar">
<div data-bind="visible: $root.showPreviewFrame, buttonset: { }" style="display: inline-block">
<input id="previewLarge" type="radio" name="previewMode" value="large" data-bind="checked: $root.previewMode, button: { text: false, label: 'large', icons: { primary: 'fa fa-fw fa-desktop' } }" />
<label for="previewLarge" title="Large screen" data-bind="attr: { title: $root.t('Large screen') }">Large screen</label>
<input id="previewDesktop" type="radio" name="previewMode" value="desktop" data-bind="checked: $root.previewMode, button: { text: false, label: 'desktop', icons: { primary: 'fa fa-fw fa-tablet' } }" />
<label for="previewDesktop" title="Tablet" data-bind="attr: { title: $root.t('Tablet') }">Tablet</label>
<input id="previewMobile" type="radio" name="previewMode" value="mobile" data-bind="checked: $root.previewMode, button: { text: false, label: 'mobile', icons: { primary: 'fa fa-fw fa-mobile' } }" />
<label for="previewMobile" title="Smartphone" data-bind="attr: { title: $root.t('Smartphone') }">Smartphone</label>
</div>
</div>
<div id="frame-container" data-bind="css: { desktop: $root.previewMode() == 'desktop', mobile: $root.previewMode() == 'mobile', large: $root.previewMode() == 'large' }">
<iframe data-bind="bindIframe: $data"></iframe>
</div>
</div>
<div class="mo" id="mo-body"></div>
<!-- TODO REMOVE ME
<div id="incompatible-browser" title="Unsupported browser" style="display: none" data-bind="attr: { title: $root.t('Usupported browser') }, html: '<p>Your browser is not supported.</p><p>Use a different browser or try updaring your browser.</p><p>Supported browsers: <ul><li>Internet Explorer >= 10</li><li>Google Chrome >= 30</li><li>Apple Safari >= 5</li><li>Mozilla Firefix >= 20</li></ul></p>'">
Unsupported browser
</div>
-->
<div id="incompatible-template" title="Saved model is obsolete" style="display: none" data-bind="attr: { title: $root.t('Saved model is obsolete') }, html: $root.t('<p>The saved model has been created with a previous, non completely compatible version, of the template</p><p>Some content or style in the model <b>COULD BE LOST</b> if you will <b>save</b></p><p>Contact us for more informations!</p>')">
Incompatible template
</div>
<div id="fake-image-editor" title="Fake image editor" style="display: none" data-bind="attr: { title: $root.t('Fake image editor') }, html: $root.t('<p>Fake image editor</p>')">
<p>Fake image editor</p>
</div>
</div>
<div id="loading" class="loading" style="display: block; width: 300px; text-align: center; height: 32px; position: absolute; top:0; bottom: 0; left: 0; right: 0; margin: auto;" data-bind="attr: { style: 'position: absolute; top: 5px; left: 6px; z-index: 150;'}, css: { loading: false }">
<!-- DS: need to use url built from civi which is CMS agnostic. For now we use the mosaico url -->
<a href="/"><img src="//mosaico.io/dist/img/mosaico32.png" width="32" height="32" alt="mosaico" border="0" /></a>
<div style="opacity: 0" data-bind="visible: false">Oppps... !!</div>
</div>
| Kajakaran/uk.co.vedaconsulting.mosaico | packages/mosaico/src/tmpl/main.tmpl.html | HTML | agpl-3.0 | 7,906 |
#
# Copyright (C) 2011 - present Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
class ContextModulesController < ApplicationController
include Api::V1::ContextModule
include WebZipExportHelper
before_action :require_context
add_crumb(proc { t('#crumbs.modules', "Modules") }) { |c| c.send :named_context_url, c.instance_variable_get("@context"), :context_context_modules_url }
before_action { |c| c.active_tab = "modules" }
module ModuleIndexHelper
include ContextModulesHelper
def load_module_file_details
attachment_tags = @context.module_items_visible_to(@current_user).where(content_type: 'Attachment').preload(:content => :folder)
attachment_tags.inject({}) do |items, file_tag|
items[file_tag.id] = {
id: file_tag.id,
content_id: file_tag.content_id,
content_details: content_details(file_tag, @current_user, :for_admin => true)
}
items
end
end
def modules_cache_key
@modules_cache_key ||= begin
visible_assignments = @current_user.try(:assignment_and_quiz_visibilities, @context)
cache_key_items = [@context.cache_key, @can_edit, @is_student, @can_view_unpublished, 'all_context_modules_draft_10', collection_cache_key(@modules), Time.zone, Digest::MD5.hexdigest(visible_assignments.to_s)]
cache_key = cache_key_items.join('/')
cache_key = add_menu_tools_to_cache_key(cache_key)
cache_key = add_mastery_paths_to_cache_key(cache_key, @context, @modules, @current_user)
end
end
def load_modules
@modules = @context.modules_visible_to(@current_user)
@modules.each(&:check_for_stale_cache_after_unlocking!)
@collapsed_modules = ContextModuleProgression.for_user(@current_user).for_modules(@modules).pluck(:context_module_id, :collapsed).select{|cm_id, collapsed| !!collapsed }.map(&:first)
@can_edit = can_do(@context, @current_user, :manage_content)
@is_student = @context.grants_right?(@current_user, session, :participate_as_student)
@can_view_unpublished = @context.grants_right?(@current_user, session, :read_as_admin)
modules_cache_key
@is_cyoe_on = @current_user && ConditionalRelease::Service.enabled_in_context?(@context)
if allow_web_export_download?
@allow_web_export_download = true
@last_web_export = @context.web_zip_exports.visible_to(@current_user).order('epub_exports.created_at').last
end
@menu_tools = {}
placements = [:assignment_menu, :discussion_topic_menu, :file_menu, :module_menu, :quiz_menu, :wiki_page_menu]
tools = ContextExternalTool.all_tools_for(@context, placements: placements,
:root_account => @domain_root_account, :current_user => @current_user).to_a
placements.select { |p| @menu_tools[p] = tools.select{|t| t.has_placement? p} }
module_file_details = load_module_file_details if @context.grants_right?(@current_user, session, :manage_content)
js_env :course_id => @context.id,
:CONTEXT_URL_ROOT => polymorphic_path([@context]),
:FILES_CONTEXTS => [{asset_string: @context.asset_string}],
:MODULE_FILE_DETAILS => module_file_details,
:MODULE_FILE_PERMISSIONS => {
usage_rights_required: @context.feature_enabled?(:usage_rights_required),
manage_files: @context.grants_right?(@current_user, session, :manage_files)
}
if master_courses?
is_master_course = MasterCourses::MasterTemplate.is_master_course?(@context)
is_child_course = MasterCourses::ChildSubscription.is_child_course?(@context)
if is_master_course || is_child_course
js_env(:MASTER_COURSE_SETTINGS => {
:IS_MASTER_COURSE => is_master_course,
:IS_CHILD_COURSE => is_child_course,
:MASTER_COURSE_DATA_URL => context_url(@context, :context_context_modules_master_course_info_url)
})
end
end
conditional_release_js_env(includes: :active_rules)
end
end
include ModuleIndexHelper
def index
if authorized_action(@context, @current_user, :read)
log_asset_access([ "modules", @context ], "modules", "other")
load_modules
set_tutorial_js_env
if @is_student && tab_enabled?(@context.class::TAB_MODULES)
@modules.each{|m| m.evaluate_for(@current_user) }
session[:module_progressions_initialized] = true
end
end
end
def choose_mastery_path
if authorized_action(@context, @current_user, :participate_as_student)
id = params[:id]
item = @context.context_module_tags.not_deleted.find(params[:id])
if item.present? && item.published? && item.context_module.published?
rules = ConditionalRelease::Service.rules_for(@context, @current_user, item, session)
rule = conditional_release_rule_for_module_item(item, conditional_release_rules: rules)
# locked assignments always have 0 sets, so this check makes it not return 404 if locked
# but instead progress forward and return a warning message if is locked later on
if rule.present? && (rule[:locked] || !rule[:selected_set_id] || rule[:assignment_sets].length > 1)
if !rule[:locked]
options = rule[:assignment_sets].map { |set|
option = {
setId: set[:id]
}
option[:assignments] = set[:assignments].map { |a|
assg = assignment_json(a[:model], @current_user, session)
assg[:assignmentId] = a[:assignment_id]
assg
}
option
}
js_env({
CHOOSE_MASTERY_PATH_DATA: {
options: options,
selectedOption: rule[:selected_set_id],
courseId: @context.id,
moduleId: item.context_module.id,
itemId: id
}
})
css_bundle :choose_mastery_path
js_bundle :choose_mastery_path
@page_title = join_title(t('Choose Assignment Set'), @context.name)
return render :html => '', :layout => true
else
flash[:warning] = t('Module Item is locked.')
return redirect_to named_context_url(@context, :context_context_modules_url)
end
end
end
return render status: 404, template: 'shared/errors/404_message'
end
end
def item_redirect
if authorized_action(@context, @current_user, :read)
@tag = @context.context_module_tags.not_deleted.find(params[:id])
if !(@tag.unpublished? || @tag.context_module.unpublished?) || authorized_action(@tag.context_module, @current_user, :view_unpublished_items)
reevaluate_modules_if_locked(@tag)
@progression = @tag.context_module.evaluate_for(@current_user) if @tag.context_module
@progression.uncollapse! if @progression && @progression.collapsed?
content_tag_redirect(@context, @tag, :context_context_modules_url, :modules)
end
end
end
def item_redirect_mastery_paths
@tag = @context.context_module_tags.not_deleted.find(params[:id])
type_controllers = {
assignment: 'assignments',
quiz: 'quizzes/quizzes',
discussion_topic: 'discussion_topics'
}
if @tag
if authorized_action(@tag.content, @current_user, :update)
controller = type_controllers[@tag.content_type_class.to_sym]
if controller.present?
redirect_to url_for(
controller: controller,
action: 'edit',
id: @tag.content_id,
anchor: 'mastery-paths-editor',
return_to: params[:return_to]
)
else
render status: 404, template: 'shared/errors/404_message'
end
end
else
render status: 404, template: 'shared/errors/404_message'
end
end
def module_redirect
if authorized_action(@context, @current_user, :read)
@module = @context.context_modules.not_deleted.find(params[:context_module_id])
@tags = @module.content_tags_visible_to(@current_user)
if params[:last]
@tags.pop while @tags.last && @tags.last.content_type == 'ContextModuleSubHeader'
else
@tags.shift while @tags.first && @tags.first.content_type == 'ContextModuleSubHeader'
end
@tag = params[:last] ? @tags.last : @tags.first
if !@tag
flash[:notice] = t 'module_empty', %{There are no items in the module "%{module}"}, :module => @module.name
redirect_to named_context_url(@context, :context_context_modules_url, :anchor => "module_#{@module.id}")
return
end
reevaluate_modules_if_locked(@tag)
@progression = @tag.context_module.evaluate_for(@current_user) if @tag && @tag.context_module
@progression.uncollapse! if @progression && @progression.collapsed?
content_tag_redirect(@context, @tag, :context_context_modules_url)
end
end
def reevaluate_modules_if_locked(tag)
# if the object is locked for this user, reevaluate all the modules and clear the cache so it will be checked again when loaded
if tag.content && tag.content.respond_to?(:locked_for?)
locked = tag.content.locked_for?(@current_user, :context => @context)
if locked
@context.context_modules.active.each { |m| m.evaluate_for(@current_user) }
if tag.content.respond_to?(:clear_locked_cache)
tag.content.clear_locked_cache(@current_user)
end
end
end
end
def create
if authorized_action(@context.context_modules.temp_record, @current_user, :create)
@module = @context.context_modules.build
@module.workflow_state = 'unpublished'
@module.attributes = context_module_params
respond_to do |format|
if @module.save
format.html { redirect_to named_context_url(@context, :context_context_modules_url) }
format.json { render :json => @module.as_json(:include => :content_tags, :methods => :workflow_state, :permissions => {:user => @current_user, :session => session}) }
else
format.html
format.json { render :json => @module.errors, :status => :bad_request }
end
end
end
end
def reorder
if authorized_action(@context.context_modules.temp_record, @current_user, :update)
m = @context.context_modules.not_deleted.first
m.update_order(params[:order].split(","))
# Need to invalidate the ordering cache used by context_module.rb
@context.touch
# I'd like to get rid of this saving every module, but we have to
# update the list of prerequisites since a reorder can cause
# prerequisites to no longer be valid
@modules = @context.context_modules.not_deleted.to_a
@modules.each do |m|
m.updated_at = Time.now
m.save_without_touching_context
end
@context.touch
# # Background this, not essential that it happen right away
# ContextModule.send_later(:update_tag_order, @context)
render :json => @modules.map{ |m| m.as_json(include: :content_tags, methods: :workflow_state) }
end
end
def content_tag_assignment_data
if authorized_action(@context, @current_user, :read)
info = {}
now = Time.now.utc.iso8601
all_tags = @context.module_items_visible_to(@current_user)
user_is_admin = @context.grants_right?(@current_user, session, :read_as_admin)
preload_assignments_and_quizzes(all_tags, user_is_admin)
all_tags.each do |tag|
info[tag.id] = if tag.can_have_assignment? && tag.assignment
tag.assignment.context_module_tag_info(@current_user, @context, user_is_admin: user_is_admin)
elsif tag.content_type_quiz?
tag.content.context_module_tag_info(@current_user, @context, user_is_admin: user_is_admin)
else
{:points_possible => nil, :due_date => nil}
end
end
render :json => info
end
end
def content_tag_master_course_data
return not_found unless master_courses?
if authorized_action(@context, @current_user, :read_as_admin)
info = {}
is_child_course = MasterCourses::ChildSubscription.is_child_course?(@context)
is_master_course = MasterCourses::MasterTemplate.is_master_course?(@context)
if is_child_course || is_master_course
tag_scope = @context.module_items_visible_to(@current_user).where(:content_type => %w{Assignment Attachment DiscussionTopic Quizzes::Quiz WikiPage})
tag_scope = tag_scope.where(:id => params[:tag_id]) if params[:tag_id]
tag_ids = tag_scope.pluck(:id)
restriction_info = {}
if tag_ids.any?
restriction_info = is_child_course ?
MasterCourses::MasterContentTag.fetch_module_item_restrictions_for_child(tag_ids) :
MasterCourses::MasterContentTag.fetch_module_item_restrictions_for_master(tag_ids)
end
info[:tag_restrictions] = restriction_info
end
render :json => info
end
end
def prerequisites_needing_finishing_for(mod, progression, before_tag=nil)
tags = mod.content_tags_visible_to(@current_user)
pres = []
tags.each do |tag|
if req = (mod.completion_requirements || []).detect{|r| r[:id] == tag.id }
progression.requirements_met ||= []
if !progression.requirements_met.any?{|r| r[:id] == req[:id] && r[:type] == req[:type] }
if !before_tag || tag.position <= before_tag.position
pre = {
:url => named_context_url(@context, :context_context_modules_item_redirect_url, tag.id),
:id => tag.id,
:context_module_id => mod.id,
:title => tag.title
}
pre[:requirement] = req
pre[:requirement_description] = ContextModule.requirement_description(req)
pre[:available] = !progression.locked? && (!mod.require_sequential_progress || tag.position <= progression.current_position)
pres << pre
end
end
end
end
pres
end
protected :prerequisites_needing_finishing_for
def content_tag_prerequisites_needing_finishing
type, id = ActiveRecord::Base.parse_asset_string params[:code]
raise ActiveRecord::RecordNotFound if id == 0
if type == 'ContentTag'
@tag = @context.context_module_tags.active.where(id: id).first
else
@tag = @context.context_module_tags.active.where(context_module_id: params[:context_module_id], content_id: id, content_type: type).first
end
@module = @context.context_modules.active.find(params[:context_module_id])
@progression = @module.evaluate_for(@current_user)
@progression.current_position ||= 0 if @progression
res = {};
if !@progression
elsif @progression.locked?
res[:locked] = true
res[:modules] = []
previous_modules = @context.context_modules.active.where('position<?', @module.position).order(:position).to_a
previous_modules.reverse!
valid_previous_modules = []
prereq_ids = @module.prerequisites.select{|p| p[:type] == 'context_module' }.map{|p| p[:id] }
previous_modules.each do |mod|
if prereq_ids.include?(mod.id)
valid_previous_modules << mod
prereq_ids += mod.prerequisites.select{|p| p[:type] == 'context_module' }.map{|p| p[:id] }
end
end
valid_previous_modules.reverse!
valid_previous_modules.each do |mod|
prog = mod.evaluate_for(@current_user)
res[:modules] << {
:id => mod.id,
:name => mod.name,
:prerequisites => prerequisites_needing_finishing_for(mod, prog),
:locked => prog.locked?
} unless prog.completed?
end
elsif @module.require_sequential_progress && @progression.current_position && @tag && @tag.position && @progression.current_position < @tag.position
res[:locked] = true
pres = prerequisites_needing_finishing_for(@module, @progression, @tag)
res[:modules] = [{
:id => @module.id,
:name => @module.name,
:prerequisites => pres,
:locked => false
}]
else
res[:locked] = false
end
render :json => res
end
def toggle_collapse
if authorized_action(@context, @current_user, :read)
@module = @context.modules_visible_to(@current_user).find(params[:context_module_id])
@progression = @module.evaluate_for(@current_user) #context_module_progressions.find_by_user_id(@current_user)
@progression ||= ContextModuleProgression.new
if params[:collapse] == '1'
@progression.collapsed = true
elsif params[:collapse]
@progression.uncollapse!
else
@progression.collapsed = [email protected]
end
@progression.save unless @progression.new_record?
respond_to do |format|
format.html { redirect_to named_context_url(@context, :context_context_modules_url) }
format.json { render :json => (@progression.collapsed ? @progression : @module.content_tags_visible_to(@current_user) )}
end
end
end
def show
@module = @context.context_modules.not_deleted.find(params[:id])
if authorized_action @module, @current_user, :read
respond_to do |format|
format.html { redirect_to named_context_url(@context, :context_context_modules_url, :anchor => "module_#{params[:id]}") }
format.json { render :json => @module.content_tags_visible_to(@current_user) }
end
end
end
def reorder_items
@module = @context.context_modules.not_deleted.find(params[:context_module_id])
if authorized_action(@module, @current_user, :update)
order = params[:order].split(",").map{|id| id.to_i}
tags = @context.context_module_tags.not_deleted.where(id: order)
affected_module_ids = (tags.map(&:context_module_id) + [@module.id]).uniq.compact
affected_items = []
items = order.map{|id| tags.detect{|t| t.id == id.to_i } }.compact.uniq
items.each_with_index do |item, idx|
item.position = idx + 1
item.context_module_id = @module.id
if item.changed?
item.skip_touch = true
item.save
affected_items << item
end
end
ContentTag.touch_context_modules(affected_module_ids)
ContentTag.update_could_be_locked(affected_items)
@context.touch
@module.reload
render :json => @module.as_json(:include => :content_tags, :methods => :workflow_state, :permissions => {:user => @current_user, :session => session})
end
end
def item_details
if authorized_action(@context, @current_user, :read)
# namespaced models are separated by : in the url
code = params[:id].gsub(":", "/").split("_")
id = code.pop.to_i
type = code.join("_").classify
@modules = @context.modules_visible_to(@current_user)
@tags = @context.context_module_tags.active.sort_by{|t| t.position ||= 999}
result = {}
possible_tags = @tags.find_all {|t| t.content_type == type && t.content_id == id }
if possible_tags.size > 1
# if there's more than one tag for the item, but the caller didn't
# specify which one they want, we don't want to return any information.
# this way the module item prev/next links won't appear with misleading navigation info.
if params[:module_item_id]
result[:current_item] = possible_tags.detect { |t| t.id == params[:module_item_id].to_i }
end
else
result[:current_item] = possible_tags.first
if !result[:current_item]
obj = @context.find_asset(params[:id], [:attachment, :discussion_topic, :assignment, :quiz, :wiki_page, :content_tag])
if obj.is_a?(ContentTag)
result[:current_item] = @tags.detect{|t| t.id == obj.id }
elsif obj.is_a?(DiscussionTopic) && obj.assignment_id
result[:current_item] = @tags.detect{|t| t.content_type == 'Assignment' && t.content_id == obj.assignment_id }
elsif obj.is_a?(Quizzes::Quiz) && obj.assignment_id
result[:current_item] = @tags.detect{|t| t.content_type == 'Assignment' && t.content_id == obj.assignment_id }
end
end
end
result[:current_item].evaluate_for(@current_user) rescue nil
if result[:current_item] && result[:current_item].position
result[:previous_item] = @tags.reverse.detect{|t| t.id != result[:current_item].id && t.context_module_id == result[:current_item].context_module_id && t.position && t.position <= result[:current_item].position && t.content_type != "ContextModuleSubHeader" }
result[:next_item] = @tags.detect{|t| t.id != result[:current_item].id && t.context_module_id == result[:current_item].context_module_id && t.position && t.position >= result[:current_item].position && t.content_type != "ContextModuleSubHeader" }
current_module = @modules.detect{|m| m.id == result[:current_item].context_module_id}
if current_module
result[:previous_module] = @modules.reverse.detect{|m| (m.position || 0) < (current_module.position || 0) }
result[:next_module] = @modules.detect{|m| (m.position || 0) > (current_module.position || 0) }
end
end
render :json => result
end
end
include ContextModulesHelper
def add_item
@module = @context.context_modules.not_deleted.find(params[:context_module_id])
if authorized_action(@module, @current_user, :update)
@tag = @module.add_item(params[:item])
unless @tag.valid?
return render :json => @tag.errors, :status => :bad_request
end
json = @tag.as_json
json['content_tag'].merge!(
publishable: module_item_publishable?(@tag),
published: @tag.published?,
publishable_id: module_item_publishable_id(@tag),
unpublishable: module_item_unpublishable?(@tag),
graded: @tag.graded?,
content_details: content_details(@tag, @current_user),
assignment_id: @tag.assignment.try(:id),
is_cyoe_able: cyoe_able?(@tag),
is_duplicate_able: @tag.duplicate_able?,
)
render json: json
end
end
def remove_item
@tag = @context.context_module_tags.not_deleted.find(params[:id])
if authorized_action(@tag.context_module, @current_user, :update)
@module = @tag.context_module
@tag.destroy
render :json => @tag
end
end
def update_item
@tag = @context.context_module_tags.not_deleted.find(params[:id])
if authorized_action(@tag.context_module, @current_user, :update)
@tag.title = params[:content_tag][:title] if params[:content_tag] && params[:content_tag][:title]
@tag.url = params[:content_tag][:url] if %w(ExternalUrl ContextExternalTool).include?(@tag.content_type) && params[:content_tag] && params[:content_tag][:url]
@tag.indent = params[:content_tag][:indent] if params[:content_tag] && params[:content_tag][:indent]
@tag.new_tab = params[:content_tag][:new_tab] if params[:content_tag] && params[:content_tag][:new_tab]
unless @tag.save
return render :json => @tag.errors, :status => :bad_request
end
@tag.update_asset_name!(@current_user) if params[:content_tag][:title]
render :json => @tag
end
end
def progressions
if authorized_action(@context, @current_user, :read)
if request.format == :json
if @context.grants_right?(@current_user, session, :view_all_grades)
if params[:user_id] && @user = @context.students.find(params[:user_id])
@progressions = @context.context_modules.active.map{|m| m.evaluate_for(@user) }
else
if @context.large_roster
@progressions = []
else
context_module_ids = @context.context_modules.active.pluck(:id)
@progressions = ContextModuleProgression.where(:context_module_id => context_module_ids).each{|p| p.evaluate }
end
end
elsif @context.grants_right?(@current_user, session, :participate_as_student)
@progressions = @context.context_modules.active.order(:id).map{|m| m.evaluate_for(@current_user) }
else
# module progressions don't apply, but unlock_at still does
@progressions = @context.context_modules.active.order(:id).map do |m|
{ :context_module_progression =>
{ :context_module_id => m.id,
:workflow_state => (m.to_be_unlocked ? 'locked' : 'unlocked'),
:requirements_met => [],
:incomplete_requirements => [] } }
end
end
render :json => @progressions
elsif [email protected]_right?(@current_user, session, :view_all_grades)
@restrict_student_list = true
student_ids = @context.observer_enrollments.for_user(@current_user).map(&:associated_user_id)
student_ids << @current_user.id if @context.user_is_student?(@current_user)
students = UserSearch.scope_for(@context, @current_user, {:enrollment_type => 'student'}).where(:id => student_ids)
@visible_students = students.map { |u| user_json(u, @current_user, session) }
end
end
end
def update
@module = @context.context_modules.not_deleted.find(params[:id])
if authorized_action(@module, @current_user, :update)
if params[:publish]
@module.publish
@module.publish_items!
elsif params[:unpublish]
@module.unpublish
end
if @module.update_attributes(context_module_params)
json = @module.as_json(:include => :content_tags, :methods => :workflow_state, :permissions => {:user => @current_user, :session => session})
json['context_module']['relock_warning'] = true if @module.relock_warning?
render :json => json
else
render :json => @module.errors, :status => :bad_request
end
end
end
def destroy
@module = @context.context_modules.not_deleted.find(params[:id])
if authorized_action(@module, @current_user, :delete)
@module.destroy
respond_to do |format|
format.html { redirect_to named_context_url(@context, :context_context_modules_url) }
format.json { render :json => @module.as_json(:methods => :workflow_state) }
end
end
end
private
def preload_assignments_and_quizzes(tags, user_is_admin)
assignment_tags = tags.select{|ct| ct.can_have_assignment?}
return unless assignment_tags.any?
ActiveRecord::Associations::Preloader.new.preload(assignment_tags, :content)
content_with_assignments = assignment_tags.
select{|ct| ct.content_type != "Assignment" && ct.content.assignment_id}.map(&:content)
ActiveRecord::Associations::Preloader.new.preload(content_with_assignments, :assignment) if content_with_assignments.any?
if user_is_admin && should_preload_override_data?
assignments = assignment_tags.map(&:assignment).compact
plain_quizzes = assignment_tags.select{|ct| ct.content.is_a?(Quizzes::Quiz) && !ct.content.assignment}.map(&:content)
preload_has_too_many_overrides(assignments, :assignment_id)
preload_has_too_many_overrides(plain_quizzes, :quiz_id)
overrideables = (assignments + plain_quizzes).select{|o| !o.has_too_many_overrides}
if overrideables.any?
ActiveRecord::Associations::Preloader.new.preload(overrideables, :assignment_overrides)
overrideables.each { |o| o.has_no_overrides = true if o.assignment_overrides.size == 0 }
end
end
end
def should_preload_override_data?
key = ['preloaded_module_override_data', @context.global_asset_string, @current_user].cache_key
# if the user has been touched we should preload all of the overrides because it's almost certain we'll need them all
if Rails.cache.read(key)
false
else
Rails.cache.write(key, true)
true
end
end
def preload_has_too_many_overrides(assignments_or_quizzes, override_column)
# find the assignments/quizzes with too many active overrides and mark them as such
if assignments_or_quizzes.any?
ids = AssignmentOverride.active.where(override_column => assignments_or_quizzes).
group(override_column).having("COUNT(*) > ?", Setting.get('assignment_all_dates_too_many_threshold', '25').to_i).
active.pluck(override_column)
if ids.any?
assignments_or_quizzes.each{|o| o.has_too_many_overrides = true if ids.include?(o.id) }
end
end
end
def context_module_params
params.require(:context_module).permit(:name, :unlock_at, :require_sequential_progress, :publish_final_grade, :requirement_count,
:completion_requirements => strong_anything, :prerequisites => strong_anything)
end
end
| venturehive/canvas-lms | app/controllers/context_modules_controller.rb | Ruby | agpl-3.0 | 29,429 |
/*
* opencog/embodiment/Control/Procedure/ComboInterpreter.h
*
* Copyright (C) 2002-2009 Novamente LLC
* All Rights Reserved
* Author(s): Novamente team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef _COMBO_INTERPRETER_H
#define _COMBO_INTERPRETER_H
#include <opencog/comboreduct/combo/vertex.h>
#include <opencog/comboreduct/combo/variable_unifier.h>
#include <opencog/embodiment/Control/PerceptionActionInterface/PAI.h>
#include <opencog/embodiment/RuleValidation/VirtualWorldData/VirtualWorldState.h>
#include <opencog/embodiment/WorldWrapper/PAIWorldWrapper.h>
#include <opencog/embodiment/WorldWrapper/RuleValidationWorldWrapper.h>
#include "RunningProcedureId.h"
#include "RunningComboProcedure.h"
#include <vector>
#include <boost/noncopyable.hpp>
#include <opencog/server/CogServer.h>
#include <opencog/embodiment/Control/MessagingSystem/NetworkElement.h>
namespace Procedure
{
typedef std::map<RunningProcedureId, RunningComboProcedure> Map;
typedef std::vector<Map::iterator> Vec;
//
class DonePred : public std::unary_function<Vec::iterator, bool>
{
private:
std::set<RunningProcedureId> _set;
public:
explicit DonePred(const std::set<RunningProcedureId>& s) : _set(s) {}
// return true if the element is not in the set and false otherwise.
// This will be used to split the predicates that are not finished yet
// from the ones that already finished and must be removed from the
// running procedure list
bool operator()(Map::iterator& elem) {
return _set.find((*elem).first) == _set.end();
}
}; // DoneSet
//
class ComboInterpreter : public boost::noncopyable
{
public:
ComboInterpreter(PerceptionActionInterface::PAI& p, opencog::RandGen& rng);
ComboInterpreter(VirtualWorldData::VirtualWorldState& v, opencog::RandGen& rng);
virtual ~ComboInterpreter();
//run executes a single action plan of some procedure (if any are ready)
void run(MessagingSystem::NetworkElement *ne);
//add a procedure to be run by the interpreter
RunningProcedureId runProcedure(const combo::combo_tree& tr, const std::vector<combo::vertex>& arguments);
//add a procedure to be run by the interpreter with variable unifier
RunningProcedureId runProcedure(const combo::combo_tree& tr, const std::vector<combo::vertex>& arguments,
combo::variable_unifier& vu);
bool isFinished(RunningProcedureId id);
// Note: this will return false if the stopProcedure() method was previously called for this same procedure id,
// even if the procedure execution has failed before
bool isFailed(RunningProcedureId id);
// Get the result of the procedure with the given id
// Can be called only if the following conditions are true:
// - procedure execution is finished (checked by isFinished() method)
// - procedure execution has not failed (checked by isFailed() method)
// - procedure execution was not stopped (by calling stopProcedure() method)
combo::vertex getResult(RunningProcedureId id);
// Get the result of the variable unification carried within the procedure
// execution.
// Can be called only if the following conditions are true:
// - procedure execution is finished (checked by isFinished() method)
// - procedure execution has not failed (checked by isFailed() method)
// - procedure execution was not stopped (by calling stopProcedure() method)
combo::variable_unifier& getUnifierResult(RunningProcedureId id);
// makes the procedure with the given id to stop and remove it from the interpreter
void stopProcedure(RunningProcedureId id);
protected:
typedef std::set<RunningProcedureId> Set;
typedef std::map<RunningProcedureId, combo::vertex> ResultMap;
typedef std::map<RunningProcedureId, combo::variable_unifier> UnifierResultMap;
opencog::RandGen& rng;
// WorldWrapper::PAIWorldWrapper _ww;
WorldWrapper::WorldWrapperBase * _ww;
Map _map;
Vec _vec;
Set _failed;
ResultMap _resultMap;
UnifierResultMap _unifierResultMap;
unsigned long _next;
}; // ComboInterpreter
} //~namespace Procedure
#endif
| fakena/myoc4078 | opencog/embodiment/Control/Procedure/ComboInterpreter.h | C | agpl-3.0 | 4,853 |
<?php
/**
* Copyright (c) 2012, Agence Française Informatique (AFI). All rights reserved.
*
* AFI-OPAC 2.0 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.
*
* There are special exceptions to the terms and conditions of the AGPL as it
* is applied to this software (see README file).
*
* AFI-OPAC 2.0 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 AFI-OPAC 2.0; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
////////////////////////////////////////////////////////////////////////////////
// OPAC3 - Catalogues de notices
////////////////////////////////////////////////////////////////////////////////
class CatalogueLoader extends Storm_Model_Loader {
const DEFAULT_ITEMS_BY_PAGE = 100;
public function loadNoticesFor($catalogue, $itemsByPage = self::DEFAULT_ITEMS_BY_PAGE, $page = 1, $find_all_params = null) {
if (!is_array($find_all_params))
$find_all_params = array();
if (!isset($find_all_params['limitPage']))
$find_all_params['limitPage'] = array($page, $itemsByPage);
if (null == $catalogue)
return array();
if ('' == ($where = $this->clausesFor($catalogue)))
return array();
$find_all_params['where'] = $where;
return Class_Notice::getLoader()->findAllBy($find_all_params);
}
public function countNoticesFor($catalogue) {
if (!$catalogue)
return 0;
if ('' == ($where = $this->clausesFor($catalogue)))
return 0;
return Class_Notice::getLoader()->countBy(array('where' => $where));
}
public function clausesFor($catalogue) {
$conditions = array();
if ($fromUntil = $this->fromUntilClauseFor($catalogue))
$conditions[] = $fromUntil;
if ($catalogue->isMatchingAllNotices())
return $fromUntil ? $fromUntil : '1=1';
if ($facets = $this->facetsClauseFor($catalogue))
$conditions[] = $facets;
if ($docType = $this->docTypeClauseFor($catalogue))
$conditions[] = $docType;
if ($year = $this->yearClauseFor($catalogue))
$conditions[] = $year;
if ($cote = $this->coteClauseFor($catalogue))
$conditions[] = $cote;
if ($new = $this->nouveauteClauseFor($catalogue))
$conditions[] = $new;
if (0 == count($conditions))
return '';
return implode(' and ', $conditions);
}
/**
* @param $catalogue Class_Catalogue
* @return string
*/
public function facetsClauseFor($catalogue, $against = '') {
$against_ou = '';
$facets = array('B' => $catalogue->getBibliotheque(),
'S' => $catalogue->getSection(),
'G' => $catalogue->getGenre(),
'L' => $catalogue->getLangue(),
'Y' => $catalogue->getAnnexe(),
'E' => $catalogue->getEmplacement());
foreach ($facets as $k => $v)
$against .= Class_Catalogue::getSelectionFacette($k, $v);
$facets = array('A' => $catalogue->getAuteur(),
'M' => $catalogue->getMatiere(),
'D' => $catalogue->getDewey(),
'P' => $catalogue->getPcdm4(),
'T' => $catalogue->getTags(),
'F' => $catalogue->getInteret());
foreach ($facets as $k => $v)
$against_ou .= Class_Catalogue::getSelectionFacette($k, $v, in_array($k, array('M', 'D', 'P')), false);
if ('' != $against_ou)
$against .= ' +(' . $against_ou . ")";
if ('' == $against)
return '';
return "MATCH(facettes) AGAINST('".$against."' IN BOOLEAN MODE)";
}
public function docTypeClauseFor($catalogue) {
if (!$docType = $catalogue->getTypeDoc())
return '';
$parts = explode(';', $docType);
if (1 == count($parts))
return 'type_doc=' . $parts[0];
return 'type_doc IN (' . implode(', ', $parts) . ')';
}
public function yearClauseFor($catalogue) {
$clauses = array();
if ($start = $catalogue->getAnneeDebut())
$clauses[] = "annee >= '" . $start . "'";
if($end = $catalogue->getAnneeFin())
$clauses[] = "annee <= '" . $end . "'";
if (0 == count($clauses))
return '';
return implode(' and ', $clauses);
}
public function coteClauseFor($catalogue) {
$clauses = array();
if ($start = $catalogue->getCoteDebut())
$clauses[] = "cote >= '" . strtoupper($start) . "'";
if ($end = $catalogue->getCoteFin())
$clauses[] = "cote <= '". strtoupper($end) . "'";
if (0 == count($clauses))
return '';
return implode(' and ', $clauses);
}
public function nouveauteClauseFor($catalogue) {
if (1 != $catalogue->getNouveaute())
return '';
return 'date_creation >= \'' . date('Y-m-d') . '\'';
}
public function fromUntilClauseFor($catalogue) {
$clauses = array();
if ($start = $catalogue->getFrom())
$clauses[] = "left(date_maj, 10) >= '" . $start . "'";
if($end = $catalogue->getUntil())
$clauses[] = "left(date_maj, 10) <= '" . $end . "'";
if (0 == count($clauses))
return '';
return implode(' and ', $clauses);
}
}
class Class_Catalogue extends Storm_Model_Abstract {
protected $_table_name = 'catalogue';
protected $_table_primary = 'ID_CATALOGUE';
protected $_loader_class = 'CatalogueLoader';
protected $_default_attribute_values = array('oai_spec' => '',
'description' => '',
'bibliotheque' => '',
'section' => '',
'genre' => '',
'langue' => '',
'annexe' => '',
'emplacement' => '',
'auteur' => '',
'matiere' => '',
'dewey' => '',
'pcdm4' => '',
'tags' => '',
'interet' => '',
'type_doc' => '',
'annee_debut' => '',
'annee_fin' => '',
'cote_debut' => '',
'cote_fin' => '',
'nouveaute' => '');
protected $_from;
protected $_until;
public static function getLoader() {
return self::getLoaderFor(__CLASS__);
}
public static function newCatalogueForAll() {
return new AllNoticesCatalogue();
}
public function acceptVisitor($visitor) {
$visitor->visitOaiSpec($this->getOaiSpec());
$visitor->visitLibelle($this->getLibelle());
if ($this->hasDescription())
$visitor->visitDescription($this->getDescription());
}
public function getNotices($page = 1, $itemsByPage = CatalogueLoader::DEFAULT_ITEMS_BY_PAGE, $params = null) {
return self::getLoader()->loadNoticesFor($this, $itemsByPage, $page, $params);
}
public function getNoticesCount() {
return self::getLoader()->countNoticesFor($this);
}
public function isMatchingAllNotices() {
return false;
}
//------------------------------------------------------------------------------
// Rend les notices et les stats (test d'un catalogue)
//------------------------------------------------------------------------------
public function getTestCatalogue() {
// Notices et temps d'execution
$preferences = $this->toArray();
$preferences['nb_notices'] = 20;
$requetes=$this->getRequetes($preferences);
$ret["requete"]=$requetes["req_liste"];
$temps=time();
$ret["notices"] = $this->getNotices(null, null,
array('limitPage' => array(1, $preferences['nb_notices']),
'order' => 'alpha_titre'));
$ret["temps_execution"]=(time()-$temps);
$ret["nb_notices"]=fetchOne($requetes["req_comptage"]);
// Avec vignettes en cache
$req=$requetes["req_comptage"];
if(strpos($req,"where") > 0) $req.=" and "; else $req.=" where ";
$req.="url_vignette > '' and url_vignette != 'NO'";
$ret["avec_vignettes"]=fetchOne($req);
return $ret;
}
public function shouldCacheContent() {
if (Class_Users::getLoader()->isCurrentUserAdmin())
return false;
return Class_AdminVar::isCacheEnabled();
}
public function getNoticesFromCacheByPreferences($preferences, $cache_vignette) {
$cache_key = md5(serialize($preferences).$cache_vignette);
$cache = Zend_Registry::get('cache');
if ($this->shouldCacheContent() && $cache->test($cache_key))
return unserialize($cache->load($cache_key));
$notices = $this->_fetchAllNoticesByPreferences($preferences, $cache_vignette);
$cache->save(serialize($notices), $cache_key);
return $notices;
}
//------------------------------------------------------------------------------
// Rend les notices selon les preferences (kiosques)
//------------------------------------------------------------------------------
public function getNoticesByPreferences($preferences,$cache_vignette=false) {
$notices = $this->getNoticesFromCacheByPreferences($preferences, $cache_vignette);
if ((int)$preferences["aleatoire"] !== 1)
return $notices;
shuffle($notices);
return array_slice ($notices, 0, $preferences["nb_notices"]);
}
public function _fetchAllNoticesByPreferences($preferences, $cache_vignette) {
// Lancer la requete
$requetes=$this->getRequetes($preferences);
if (!array_key_exists("req_liste", $requetes))
return array();
$req_liste = str_replace('select *',
'select notices.id_notice, notices.editeur, notices.annee, notices.date_creation, notices.facettes, notices.clef_oeuvre',
$requetes["req_liste"]);
$catalogue=fetchAll($req_liste);
if (!$catalogue)
return array();
//Instanciations
$class_notice = new Class_Notice();
$class_img = new Class_WebService_Vignette();
$notices = array();
// Formatter les notices
foreach($catalogue as $notice) {
$enreg=$class_notice->getNotice($notice["id_notice"],'TA');
$vignette = '';
if ($cache_vignette) {
if($cache_vignette=="url") $mode=false; else $mode=true;
$vignette=$class_img->getImage($enreg["id_notice"],$mode);
}
if (!$cache_vignette or $vignette) {
$notices[]=array(
"id_notice" => $enreg["id_notice"],
"titre" => $enreg["T"],
"auteur" => $enreg["A"],
"vignette" => $vignette,
"type_doc" => $enreg["type_doc"],
"editeur" => $notice["editeur"],
"annee" => $notice["annee"],
"date_creation" => $notice["date_creation"],
"facettes" => $notice["facettes"],
"clef_oeuvre" => $notice["clef_oeuvre"]);
}
}
return $notices;
}
//------------------------------------------------------------------------------
// Rend les notices selon les preferences
//------------------------------------------------------------------------------
public function getRequetes($preferences, $no_limit=false) {
// Si panier traitement special
if (isset($preferences["id_panier"]) && (0 !== (int)$preferences["id_panier"]))
return $this->getRequetesPanier($preferences);
// Lire les proprietes du catalogue
$against = $this->selectionFacettesForCatalogueRequestByPreferences($preferences);
if ($catalogue = $this->getLoader()->find($preferences['id_catalogue'])) {
$conditions = array($this->getLoader()->facetsClauseFor($catalogue, $against));
$conditions []= $this->getLoader()->docTypeClauseFor($catalogue);
$conditions []= $this->getLoader()->yearClauseFor($catalogue);
$conditions []= $this->getLoader()->coteClauseFor($catalogue);
$conditions []= $this->getLoader()->nouveauteClauseFor($catalogue);
} else {
$conditions = $against ? array("MATCH(facettes) AGAINST('".$against."' IN BOOLEAN MODE)") : array();
}
// Notices avec vignettes uniquement
if (isset($preferences['only_img']) && ($preferences["only_img"] == 1))
$conditions[]="url_vignette > '' and url_vignette != 'NO'";
// Notices avec avis seulement
$join = (isset($preferences['avec_avis']) && ($preferences["avec_avis"] == 1))
? " INNER JOIN notices_avis ON notices.clef_oeuvre=notices_avis.clef_oeuvre "
: '';
// Clause where
if ($where = implode(' and ', array_filter($conditions)))
$where = ' where '.$where;
// Calcul des requetes
$order_by = $this->orderByForCatalogueRequestByPreferences($preferences);
$limite = $this->limitForCatalogueRequestByPreferences($preferences, $no_limit);
$ret["req_liste"]="select * from notices ".$join.$where.$order_by.$limite;
$ret["req_comptage"]="select count(*) from notices ".$join.$where;
$ret["req_facettes"]="select notices.id_notice,type_doc,facettes from notices ".$join.$where.$limite;
return $ret;
}
public function selectionFacettesForCatalogueRequestByPreferences($preferences) {
if (!isset($preferences["facettes"]))
return '';
$against = '';
$facettes=explode(";", $preferences["facettes"]);
foreach($facettes as $facette) {
$facette=trim($facette);
$against.=$this->getSelectionFacette(substr($facette,0,1),substr($facette,1));
}
return $against;
}
public function orderByForCatalogueRequestByPreferences($preferences) {
if(!array_key_exists("tri", $preferences) || $preferences["tri"]==0)
return " order by alpha_titre ";
if ($preferences["tri"]==1)
return " order by date_creation DESC ";
if ($preferences["tri"]==2)
return " order by nb_visu DESC ";
}
public function limitForCatalogueRequestByPreferences($preferences, $no_limit=false) {
$limite = 0;
if (isset($preferences["aleatoire"]) && (int)$preferences["aleatoire"]==1)
$limite = (int)$preferences["nb_analyse"];
else if (isset($preferences['nb_notices']))
$limite = (int)$preferences["nb_notices"];
if ($limite and !$no_limit)
return " LIMIT 0,".$limite;
return " LIMIT 5000"; //LL: j'ai rajouté une limite max car explosion mémoire sur des catalogues mal définis
}
//----------------------------------------------------------------------------
// Calcul de la clause against pour une facette
//----------------------------------------------------------------------------
public static function getSelectionFacette($type, $valeurs, $descendants = false, $signe = true) {
if (!$valeurs)
return false;
$valeurs = explode(';', $valeurs);
$cond = '';
foreach ($valeurs as $valeur) {
if (!$valeur)
continue;
if (!$descendants) {
$cond .= $type . $valeur . ' ';
continue;
}
if ('M' != $type) {
$cond .= $type . $valeur . '* ';
continue;
}
if (!$matiere = Class_Matiere::getLoader()->find($valeur))
continue;
if ('' != ($sous_vedettes = trim($matiere->getSousVedettes())))
$valeur .= str_replace(' ', ' M', ' ' . $sous_vedettes);
$cond .= $type . $valeur . ' ';
}
$cond = trim($cond);
if ($signe)
return ' +(' . $cond . ')';
return ' ' . $cond;
}
//------------------------------------------------------------------------------
// Rend les requetes pour un panier selon les preferences
//------------------------------------------------------------------------------
public function getRequetesPanier($preferences)
{
if (array_key_exists('id_user', $preferences))
$panier = Class_PanierNotice::getLoader()->findFirstBy(array('id_user' => $preferences['id_user'],
'id_panier' => $preferences['id_panier']));
else $panier = Class_PanierNotice::getLoader()->find($preferences['id_panier']);
if (!$panier)
return array("nombre" => 0);
$cles_notices = $panier->getClesNotices();
if (empty($cles_notices))
{
$ret["nombre"]=0;
return $ret;
}
foreach($cles_notices as $notice) {
if(!trim($notice)) continue;
if(isset($in_sql)) $in_sql .=","; else $in_sql = '';
$in_sql.="'".$notice."'";
}
// Nombre a lire
if($preferences["aleatoire"]==1) $limite=$preferences["nb_analyse"];
else $limite=$preferences["nb_notices"];
if($limite) $limite="LIMIT 0,".$limite; else $limite="";
// Ordre
$order_by ="";
if($preferences["tri"]==0) $order_by=" order by alpha_titre ";
if($preferences["tri"]==1) $order_by=" order by date_creation DESC ";
if($preferences["tri"]==2) $order_by=" order by nb_visu DESC ";
$condition = '';
// Notices avec vignettes uniquement
if (array_isset("only_img", $preferences) && $preferences["only_img"] == 1)
$condition=" and url_vignette > '' and url_vignette != 'NO' ";
// Notices avec avis seulement
$join = '';
if (array_isset("avec_avis", $preferences) && $preferences["avec_avis"] == 1)
$join = " INNER JOIN notices_avis ON notices.clef_oeuvre=notices_avis.clef_oeuvre ";
// Retour
$ret["req_liste"]="select * from notices ".$join."where notices.clef_alpha in(".$in_sql.")".$condition.$order_by.$limite;
$ret["req_comptage"]="select count(*) from notices ".$join."where notices.clef_alpha in(".$in_sql.")".$condition;
$ret["req_facettes"]="select id_notice,type_doc,facettes from notices ".$join."where notices.clef_alpha in(".$in_sql.") ".$condition.$limite;
return $ret;
}
//-------------------------------------------------------------------------------
// liste des catalogues (structure complete)
//-------------------------------------------------------------------------------
public function getCatalogue($id_catalogue)
{
if($id_catalogue) return fetchEnreg("select * from catalogue where ID_CATALOGUE=$id_catalogue");
else return fetchAll("select * from catalogue order by LIBELLE");
}
//-------------------------------------------------------------------------------
// liste des catalogues pour une combo
//-------------------------------------------------------------------------------
static function getCataloguesForCombo() {
$liste = array();
$catalogues=fetchAll("select * from catalogue order by libelle");
if(!$catalogues) return $liste;
$liste[""]=" ";
foreach($catalogues as $catalogue)
$liste[$catalogue["ID_CATALOGUE"]]=$catalogue["LIBELLE"];
return $liste;
}
public function setAnneeDebut($value) {
return $this->checkAndSetAnnee('annee_debut', $value);
}
public function setAnneeFin($value) {
return $this->checkAndSetAnnee('annee_fin', $value);
}
public function checkAndSetAnnee($attribute, $value) {
$value = (int)$value;
if ($value < 1000 || $value > date("Y"))
$value = '';
return parent::_set($attribute, $value);
}
public function validate() {
$this->checkAttribute('libelle', $this->getLibelle(), 'Le libellé est requis');
$this->checkAttribute('annee_fin',
!($this->getAnneeDebut() and $this->getAnneeFin()) || $this->getAnneeDebut() <= $this->getAnneeFin(),
"L'année de début doit être inférieure ou égale à l'année de fin");
$this->checkAttribute('oai_spec',
!$this->getOaiSpec() || preg_match('/^[a-zA-Z0-9_.-]+$/', $this->getOaiSpec()),
"La spec OAI ne peut contenir que les caractères suivants: de a à z, 0 à 9, - _ .");
}
public function setFrom($from) {
$this->_from = $from;
return $this;
}
public function getFrom() {
return $this->_from;
}
public function setUntil($until) {
$this->_until = $until;
return $this;
}
public function getUntil() {
return $this->_until;
}
}
class AllNoticesCatalogue extends Class_Catalogue {
public function isMatchingAllNotices() {
return true;
}
}
?> | lolgzs/opacce | library/Class/Catalogue.php | PHP | agpl-3.0 | 19,460 |
class WorkAssignmentPlugin < Noosfero::Plugin
def self.plugin_name
"Work Assignment"
end
def self.plugin_description
_("New kind of content for organizations.")
end
def self.can_download_submission?(user, submission)
return unless submission
submission.published? || (user && (submission.author == user || user.has_permission?('view_private_content', submission.profile) ||
submission.display_unpublished_article_to?(user)))
end
def self.is_submission?(content)
content && content.parent && content.parent.parent && content.parent.parent.kind_of?(WorkAssignmentPlugin::WorkAssignment)
end
def content_types
[WorkAssignmentPlugin::WorkAssignment] if context.respond_to?(:profile) && context.profile.organization?
end
def stylesheet?
true
end
def content_remove_new(content)
content.kind_of?(WorkAssignmentPlugin::WorkAssignment)
end
def content_remove_upload(content)
if content.kind_of?(WorkAssignmentPlugin::WorkAssignment)
!content.profile.members.include?(context.send(:user))
end
end
def content_viewer_controller_filters
block = proc do
path = get_path(params[:page], params[:format])
content = profile.articles.find_by_path(path)
if WorkAssignmentPlugin.is_submission?(content) && !WorkAssignmentPlugin.can_download_submission?(user, content)
render_access_denied
end
end
{ :type => 'before_filter',
:method_name => 'work_assingment_only_admin_or_owner_download',
:options => {:only => 'view_page'},
:block => block }
end
def cms_controller_filters
block = proc do
if request.post? && params[:uploaded_files]
email_notification = params[:article_email_notification]
unless !email_notification || email_notification.empty?
email_contact = WorkAssignmentPlugin::EmailContact.new(:subject => @parent.name, :receiver => email_notification, :sender => user)
WorkAssignmentPlugin::EmailContact::EmailSender.build_mail_message(email_contact, @uploaded_files)
if email_contact.deliver
session[:notice] = _('Notification successfully sent')
else
session[:notice] = _('Notification not sent')
end
end
end
end
{ :type => 'after_filter',
:method_name => 'send_email_after_upload_file',
:options => {:only => 'upload_files'},
:block => block }
end
def upload_files_extra_fields(article)
proc do
@article = Article.find_by_id(article)
if params[:parent_id] && [email protected]? && @article.type == "WorkAssignmentPlugin::WorkAssignment"
render :partial => 'notify_text_field', :locals => { :size => '45'}
end
end
end
end
| EcoAlternative/noosfero-ecosol | plugins/work_assignment/lib/work_assignment_plugin.rb | Ruby | agpl-3.0 | 2,790 |
<?php namespace OniiChan\Domain;
interface Entity
{
/**
* Return an Entity identifier
*
* @return Identifier
*/
public function id();
}
| flaxandteal/onii-chan | laravel/src/lib/OniiChan/Domain/Entity.php | PHP | agpl-3.0 | 153 |
/*
* Copyright 2015 Erwin Müller <[email protected]>
*
* This file is part of sscontrol-httpd-yourls.
*
* sscontrol-httpd-yourls 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.
*
* sscontrol-httpd-yourls 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 sscontrol-httpd-yourls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.anrisoftware.sscontrol.httpd.yourls;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.ACCESS_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.API_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.BACKUP_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.CONVERT_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.DATABASE_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.DEBUG_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.DRIVER_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.GMT_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.HOST_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.LANGUAGE_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.MODE_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.OFFSET_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.OVERRIDE_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.PASSWORD_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.PORT_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.PREFIX_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.RESERVED_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.SITE_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.STATS_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.TARGET_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.UNIQUE_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.URLS_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.USER_KEY;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import com.anrisoftware.sscontrol.core.api.ServiceException;
import com.anrisoftware.sscontrol.core.groovy.statementsmap.StatementsException;
import com.anrisoftware.sscontrol.core.groovy.statementsmap.StatementsMap;
import com.anrisoftware.sscontrol.core.groovy.statementstable.StatementsTable;
import com.anrisoftware.sscontrol.core.groovy.statementstable.StatementsTableFactory;
import com.anrisoftware.sscontrol.core.overridemode.OverrideMode;
import com.anrisoftware.sscontrol.core.yesno.YesNoFlag;
import com.anrisoftware.sscontrol.httpd.domain.Domain;
import com.anrisoftware.sscontrol.httpd.webserviceargs.DefaultWebService;
import com.anrisoftware.sscontrol.httpd.webserviceargs.DefaultWebServiceFactory;
import com.google.inject.assistedinject.Assisted;
/**
* <i>Yourls</i> service.
*
* @see <a href="http://yourls.org/>http://yourls.org/</a>
*
* @author Erwin Mueller, [email protected]
* @since 1.0
*/
class YourlsServiceImpl implements YourlsService {
/**
* The <i>Yourls</i> service name.
*/
public static final String SERVICE_NAME = "yourls";
private final DefaultWebService service;
private final StatementsMap statementsMap;
private StatementsTable statementsTable;
/**
* @see YourlsServiceFactory#create(Map, Domain)
*/
@Inject
YourlsServiceImpl(DefaultWebServiceFactory webServiceFactory,
@Assisted Map<String, Object> args, @Assisted Domain domain) {
this.service = webServiceFactory.create(SERVICE_NAME, args, domain);
this.statementsMap = service.getStatementsMap();
setupStatements(statementsMap, args);
}
private void setupStatements(StatementsMap map, Map<String, Object> args) {
map.addAllowed(DATABASE_KEY, OVERRIDE_KEY, BACKUP_KEY, ACCESS_KEY,
USER_KEY, GMT_KEY, UNIQUE_KEY, CONVERT_KEY, RESERVED_KEY,
SITE_KEY, LANGUAGE_KEY);
map.setAllowValue(true, DATABASE_KEY, ACCESS_KEY, RESERVED_KEY,
SITE_KEY, LANGUAGE_KEY);
map.addAllowedKeys(DATABASE_KEY, USER_KEY, PASSWORD_KEY, HOST_KEY,
PORT_KEY, PREFIX_KEY, DRIVER_KEY);
map.addAllowedKeys(OVERRIDE_KEY, MODE_KEY);
map.addAllowedKeys(BACKUP_KEY, TARGET_KEY);
map.addAllowedKeys(ACCESS_KEY, STATS_KEY, API_KEY);
map.addAllowedKeys(GMT_KEY, OFFSET_KEY);
map.addAllowedKeys(UNIQUE_KEY, URLS_KEY);
map.addAllowedKeys(CONVERT_KEY, MODE_KEY);
}
@Inject
public final void setStatementsTable(StatementsTableFactory factory) {
StatementsTable table = factory.create(this, SERVICE_NAME);
table.addAllowed(DEBUG_KEY, USER_KEY);
table.setAllowArbitraryKeys(true, DEBUG_KEY);
table.addAllowedKeys(USER_KEY, PASSWORD_KEY);
this.statementsTable = table;
}
@Override
public Domain getDomain() {
return service.getDomain();
}
@Override
public String getName() {
return SERVICE_NAME;
}
public void setAlias(String alias) throws ServiceException {
service.setAlias(alias);
}
@Override
public String getAlias() {
return service.getAlias();
}
public void setId(String id) throws ServiceException {
service.setId(id);
}
@Override
public String getId() {
return service.getId();
}
public void setRef(String ref) throws ServiceException {
service.setRef(ref);
}
@Override
public String getRef() {
return service.getRef();
}
public void setRefDomain(String ref) throws ServiceException {
service.setRefDomain(ref);
}
@Override
public String getRefDomain() {
return service.getRefDomain();
}
public void setPrefix(String prefix) throws ServiceException {
service.setPrefix(prefix);
}
@Override
public String getPrefix() {
return service.getPrefix();
}
@Override
public Map<String, Object> debugLogging(String key) {
return statementsTable.tableKeys(DEBUG_KEY, key);
}
@Override
public Map<String, Object> getDatabase() {
@SuppressWarnings("serial")
Map<String, Object> map = new HashMap<String, Object>() {
@Override
public Object put(String key, Object value) {
if (value != null) {
return super.put(key, value);
} else {
return null;
}
}
};
StatementsMap m = statementsMap;
map.put(DATABASE_KEY.toString(), m.value(DATABASE_KEY));
map.put(USER_KEY.toString(), m.mapValue(DATABASE_KEY, USER_KEY));
map.put(PASSWORD_KEY.toString(), m.mapValue(DATABASE_KEY, PASSWORD_KEY));
map.put(HOST_KEY.toString(), m.mapValue(DATABASE_KEY, HOST_KEY));
map.put(PORT_KEY.toString(), m.mapValue(DATABASE_KEY, PORT_KEY));
map.put(PREFIX_KEY.toString(), m.mapValue(DATABASE_KEY, PREFIX_KEY));
map.put(DRIVER_KEY.toString(), m.mapValue(DATABASE_KEY, DRIVER_KEY));
return map.size() == 0 ? null : map;
}
@Override
public OverrideMode getOverrideMode() {
return statementsMap.mapValue(OVERRIDE_KEY, MODE_KEY);
}
@Override
public URI getBackupTarget() {
return statementsMap.mapValueAsURI(BACKUP_KEY, TARGET_KEY);
}
@Override
public Access getSiteAccess() {
return statementsMap.value(ACCESS_KEY);
}
@Override
public Access getStatsAccess() {
return statementsMap.mapValue(ACCESS_KEY, STATS_KEY);
}
@Override
public Access getApiAccess() {
return statementsMap.mapValue(ACCESS_KEY, API_KEY);
}
@Override
public Integer getGmtOffset() {
return statementsMap.mapValue(GMT_KEY, OFFSET_KEY);
}
@Override
public Boolean getUniqueUrls() {
Object value = statementsMap.mapValue(UNIQUE_KEY, URLS_KEY);
if (value instanceof YesNoFlag) {
return ((YesNoFlag) value).asBoolean();
} else {
return (Boolean) value;
}
}
@Override
public Convert getUrlConvertMode() {
return statementsMap.mapValue(CONVERT_KEY, MODE_KEY);
}
@Override
public List<String> getReserved() {
return statementsMap.valueAsStringList(RESERVED_KEY);
}
@Override
public String getLanguage() {
return statementsMap.value(LANGUAGE_KEY);
}
@Override
public Map<String, String> getUsers() {
return statementsTable.tableKeys(USER_KEY, PASSWORD_KEY);
}
@Override
public String getSite() {
return statementsMap.value(SITE_KEY);
}
public Object methodMissing(String name, Object args) {
try {
return service.methodMissing(name, args);
} catch (StatementsException e) {
return statementsTable.methodMissing(name, args);
}
}
@Override
public String toString() {
return service.toString();
}
}
| devent/sscontrol | sscontrol-httpd-yourls/src/main/java/com/anrisoftware/sscontrol/httpd/yourls/YourlsServiceImpl.java | Java | agpl-3.0 | 10,069 |
/**
******************************************************************************
* @file USB_Host/DynamicSwitch_Standalon/Inc/lcd_log_conf.h
* @author MCD Application Team
* @version V1.0.3
* @date 29-January-2016
* @brief LCD Log configuration file.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __LCD_LOG_CONF_H
#define __LCD_LOG_CONF_H
/* Includes ------------------------------------------------------------------*/
#include "stm32469i_discovery_lcd.h"
#include "stm32469i_discovery.h"
#include <stdio.h>
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Define the LCD default text color */
#define LCD_LOG_DEFAULT_COLOR LCD_COLOR_WHITE
/* Comment the line below to disable the scroll back and forward features */
#define LCD_SCROLL_ENABLED 1
#define LCD_LOG_HEADER_FONT Font16
#define LCD_LOG_FOOTER_FONT Font16
#define LCD_LOG_TEXT_FONT Font16
/* Define the LCD LOG Color */
#define LCD_LOG_BACKGROUND_COLOR LCD_COLOR_BLACK
#define LCD_LOG_TEXT_COLOR LCD_COLOR_WHITE
#define LCD_LOG_SOLID_BACKGROUND_COLOR LCD_COLOR_BLUE
#define LCD_LOG_SOLID_TEXT_COLOR LCD_COLOR_WHITE
/* Define the cache depth */
#define CACHE_SIZE 100
#define YWINDOW_SIZE 10
#if (YWINDOW_SIZE > 14)
#error "Wrong YWINDOW SIZE"
#endif
/* Redirect the printf to the LCD */
#ifdef __GNUC__
/* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
set to 'Yes') calls __io_putchar() */
#define LCD_LOG_PUTCHAR int __io_putchar(int ch)
#else
#define LCD_LOG_PUTCHAR int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
#endif /* __LCD_LOG_CONF_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| mariobarbareschi/stm32-compiler-docker | STM32Cube_FW_F4_V1.11.0/Projects/STM32469I-Discovery/Applications/USB_Host/DynamicSwitch_Standalone/Inc/lcd_log_conf.h | C | agpl-3.0 | 4,076 |
// OCC_2dView.h: interface for the OCC_2dView class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_OCC_2dVIEW_H__2E048CC9_38F9_11D7_8611_0060B0EE281E__INCLUDED_)
#define AFX_OCC_2dVIEW_H__2E048CC9_38F9_11D7_8611_0060B0EE281E__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "OCC_BaseView.h"
#include "OCC_2dDoc.h"
#include "Resource2d/RectangularGrid.h"
#include "Resource2d/CircularGrid.h"
enum CurrentAction2d {
CurAction2d_Nothing,
CurAction2d_DynamicZooming,
CurAction2d_WindowZooming,
CurAction2d_DynamicPanning,
CurAction2d_GlobalPanning,
};
class AFX_EXT_CLASS OCC_2dView : public OCC_BaseView
{
DECLARE_DYNCREATE(OCC_2dView)
public:
OCC_2dView();
virtual ~OCC_2dView();
CDocument* GetDocument();
Handle_V2d_View& GetV2dView() {return myV2dView;};
void FitAll();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(OCC_2dView)
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
virtual void OnInitialUpdate(); // called first time after construct
//}}AFX_VIRTUAL
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(OCC_2dView)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
afx_msg void OnFileExportImage();
afx_msg void OnBUTTONGridRectLines();
afx_msg void OnBUTTONGridRectPoints();
afx_msg void OnBUTTONGridCircLines();
afx_msg void OnBUTTONGridCircPoints();
afx_msg void OnBUTTONGridValues();
afx_msg void OnUpdateBUTTONGridValues(CCmdUI* pCmdUI);
afx_msg void OnBUTTONGridCancel();
afx_msg void OnUpdateBUTTONGridCancel(CCmdUI* pCmdUI);
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg void OnMButtonDown(UINT nFlags, CPoint point);
afx_msg void OnMButtonUp(UINT nFlags, CPoint point);
afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnBUTTONFitAll();
afx_msg void OnBUTTONGlobPanning();
afx_msg void OnBUTTONPanning();
afx_msg void OnBUTTONZoomProg();
afx_msg void OnBUTTONZoomWin();
afx_msg void OnUpdateBUTTON2DGlobPanning(CCmdUI* pCmdUI);
afx_msg void OnUpdateBUTTON2DPanning(CCmdUI* pCmdUI);
afx_msg void OnUpdateBUTTON2DZoomProg(CCmdUI* pCmdUI);
afx_msg void OnUpdateBUTTON2DZoomWin(CCmdUI* pCmdUI);
afx_msg void OnChangeBackground();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
protected:
CurrentAction2d myCurrentMode;
Standard_Integer myXmin;
Standard_Integer myYmin;
Standard_Integer myXmax;
Standard_Integer myYmax;
Quantity_Factor myCurZoom;
enum LineStyle { Solid, Dot, ShortDash, LongDash, Default };
CPen* m_Pen;
virtual void DrawRectangle2D (const Standard_Integer MinX ,
const Standard_Integer MinY ,
const Standard_Integer MaxX ,
const Standard_Integer MaxY ,
const Standard_Boolean Draw ,
const LineStyle aLineStyle = Default );
virtual void DragEvent2D (const Standard_Integer x ,
const Standard_Integer y ,
const Standard_Integer TheState);
virtual void InputEvent2D (const Standard_Integer x ,
const Standard_Integer y );
virtual void MoveEvent2D (const Standard_Integer x ,
const Standard_Integer y );
virtual void MultiMoveEvent2D (const Standard_Integer x ,
const Standard_Integer y );
virtual void MultiDragEvent2D (const Standard_Integer x ,
const Standard_Integer y ,
const Standard_Integer TheState);
virtual void MultiInputEvent2D (const Standard_Integer x ,
const Standard_Integer y );
virtual void Popup2D (const Standard_Integer x ,
const Standard_Integer y );
protected:
CRectangularGrid TheRectangularGridDialog;
CCircularGrid TheCircularGridDialog;
Handle_V2d_View myV2dView;
};
#ifndef _DEBUG // debug version in 2DDisplayView.cpp
inline CDocument* OCC_2dView::GetDocument()
{ return m_pDocument; }
#endif
#endif // !defined(AFX_OCC_2dVIEW_H__2E048CC9_38F9_11D7_8611_0060B0EE281E__INCLUDED_)
| AsherBond/MondocosmOS | opencascade-6.5.1/samples/mfc/Common/OCC_2dView.h | C | agpl-3.0 | 4,741 |
Title: 40423119_W17作業
Date: 2017-06-15 11:17
Category: HomeWork
Tags: 期末協同查驗與自評
Author: 40423119
1.solvespace 檔案推送
2.solvespace 2D 繪圖 程式碼
3.子模組建立與運用
4.Solvespace 近端零組件繪圖
5.Solvespace 零件轉入 V-rep
6.期末分組專題
7.上傳 Fossil SCM 倉儲
<!-- PELICAN_END_SUMMARY -->
#1. solvespace 檔案推送
<iframe width="560" height="315" src="https://www.youtube.com/embed/MRbDxwXsouE" frameborder="0" allowfullscreen></iframe>
<iframe src="./../w17/40423119.html" width="800" height="600"></iframe>
#2.solvespace 2D 繪圖 程式碼
<iframe width="560" height="315" src="https://www.youtube.com/embed/W1ERK57jgyA" frameborder="0" allowfullscreen></iframe>
<!-- 導入 Brython 標準程式庫 -->
<script src="../data/Brython-3.3.1/brython.js"></script>
<script src="../data/Brython-3.3.1/brython_stdlib.js"></script>
<!-- 啟動 Brython -->
<script>
window.onload=function(){
// 設定 data/py 為共用程式路徑
brython({debug:1, pythonpath:['./../data/py']});
}
</script>
<!-- 以下實際利用 Brython 繪圖-->
<canvas id="onegear2" width="800" height="600"></canvas>
<div id="onegear_div" width="800" height="20"></div>
<script type="text/python3">
from browser import document as doc
import math
# deg 為角度轉為徑度的轉換因子
deg = math.pi/180.
# 定義 Spur 類別
class Spur(object):
def __init__(self, ctx):
self.ctx = ctx
# 設定畫線參數
def create_line(self, x1, y1, x2, y2, width=3, fill="#54fff6"):
self.ctx.beginPath()
self.ctx.lineWidth = width
self.ctx.moveTo(x1, y1)
self.ctx.lineTo(x2, y2)
self.ctx.strokeStyle = fill
self.ctx.stroke()
def create_line2(self, x1, y1, x2, y2, width=3, fill="#54ff5f"):
self.ctx.beginPath()
self.ctx.lineWidth = width
self.ctx.moveTo(x1, y1)
self.ctx.lineTo(x2, y2)
self.ctx.strokeStyle = fill
self.ctx.stroke()
def create_line3(self, x1, y1, x2, y2, width=3, fill="#f354ff"):
self.ctx.beginPath()
self.ctx.lineWidth = width
self.ctx.moveTo(x1, y1)
self.ctx.lineTo(x2, y2)
self.ctx.strokeStyle = fill
self.ctx.stroke()
def Gear(self, midx, midy, rp, n=20, pa=20, color="black"):
rp = 250
imax = 15
m=2*rp/n
a=m
d=1.25*m
ra=rp+a
# self.create_line(起點X, 起點Y, 終點X, 終點Y)
self.create_line2(400.0092358669, 99.7467537143, 251.9547191519, 442.8435006599)
self.create_line3(400.0092358669, 99.7467537143, 537.4903413459, 440.1127860465)
self.create_line2(143.0084564396, 393.7995926042, 314.6469023490, 471.0653927376)
self.create_line3(143.0084564396, 393.7995926042, 202.3690092639, 492.0551734376)
self.create_line2(202.3690092639, 492.0551734376, 314.6469023490, 471.0653927376)
self.create_line3(465.4788879723, 480.3190039124, 593.2602222967, 408.9747395441)
self.create_line2(465.4788879723, 480.3190039124, 567.9291276424, 502.4572906272)
self.create_line3(567.9291276424, 502.4572906272, 593.2602222967, 408.9747395441)
if rd>rb:
dr = (ra-rd)/imax
else:
dr=(ra-rb)/imax
sigma=math.pi/(2*n)+math.tan(pa*deg)-pa*deg
for j in range(-9, 10, +1):
ang=-2.*j*math.pi/n+sigma
ang2=2.*j*math.pi/n+sigma
lxd=midx+rd*math.sin(ang2-2.*math.pi/n)
lyd=midy-rd*math.cos(ang2-2.*math.pi/n)
for i in range(imax+1):
if rd>rb:
r=rd+i*dr
else:
r=rb+i*dr
theta=math.sqrt((r*r)/(rb*rb)-1.)
alpha=theta-math.atan(theta)
xpt=r*math.sin(alpha-ang)
ypt=r*math.cos(alpha-ang)
xd=rd*math.sin(-ang)
yd=rd*math.cos(-ang)
if(i==0):
last_x = midx+xd
last_y = midy-yd
self.create_line((lxd),(lyd),(midx+xd),(midy-yd),fill=color)
for i in range(imax+1):
if rd>rb:
r=rd+i*dr
else:
r=rb+i*dr
theta=math.sqrt((r*r)/(rb*rb)-1.)
alpha=theta-math.atan(theta)
xpt=r*math.sin(ang2-alpha)
ypt=r*math.cos(ang2-alpha)
xd=rd*math.sin(ang2)
yd=rd*math.cos(ang2)
if(i==0):
last_x = midx+xd
last_y = midy-yd
self.create_line((midx+xpt),(midy-ypt),(last_x),(last_y),fill=color)
if(i==imax):
rfx=midx+xpt
rfy=midy-ypt
last_x = midx+xpt
last_y = midy-ypt
self.create_line(lfx,lfy,rfx,rfy,fill=color)
canvas = doc['onegear2']
ctx = canvas.getContext("2d")
x = (canvas.width)/2
y = (canvas.height)/2
r = 0.8*(canvas.height/2)
# 齒數
n = 36
# 壓力角
pa = 20
Spur(ctx).Gear(x, y, r, n, pa, "blue")
</script>
#3.子模組建立與運用
<iframe width="560" height="315" src="https://www.youtube.com/embed/eAu4W6WtSns" frameborder="0" allowfullscreen></iframe>
#4.Solvespace 近端零組件繪圖
<iframe width="560" height="315" src="https://www.youtube.com/embed/0of4dnA_m6Q" frameborder="0" allowfullscreen></iframe>
<iframe src="./../w17/two link.html" width="800" height="600"></iframe>
#5.Solvespace 零件轉入 V-rep
<iframe width="560" height="315" src="https://www.youtube.com/embed/J4XD9bjRzkQ" frameborder="0" allowfullscreen></iframe>
#6.期末分組專題
<a href="https://40423119.github.io/2017springcd_hw/blog/40423119_qi-mo-fen-zu-zhuan-ti-_ag1.html">期末分組專題_AG1</a>
#7.上傳 Fossil SCM 倉儲
<iframe width="560" height="315" src="https://www.youtube.com/embed/iZb8CQ_iJRs" frameborder="0" allowfullscreen></iframe>
| 40423119/2017springcd_hw | content/20170615.md | Markdown | agpl-3.0 | 6,030 |
/*
* This file is part of ELKI:
* Environment for Developing KDD-Applications Supported by Index-Structures
*
* Copyright (C) 2019
* ELKI Development Team
*
* 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 elki.utilities.datastructures;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Random;
import org.junit.Test;
/**
* Test the Kuhn-Munkres implementation.
*
* @author Erich Schubert
*/
public class KuhnMunkresWongTest {
@Test
public void test1() {
int[] assignment = new KuhnMunkresWong().run(KuhnMunkresTest.TEST1);
double sum = 0.;
for(int i = 0; i < assignment.length; i++) {
assertTrue("Unassigned row " + i, assignment[i] >= 0);
sum += KuhnMunkresTest.TEST1[i][assignment[i]];
}
assertEquals("Assignment not optimal", 55, sum, 0);
}
@Test
public void test2() {
int[] assignment = new KuhnMunkresWong().run(KuhnMunkresTest.TEST2);
double sum = 0.;
for(int i = 0; i < assignment.length; i++) {
assertTrue("Unassigned row " + i, assignment[i] >= 0);
sum += KuhnMunkresTest.TEST2[i][assignment[i]];
}
assertEquals("Assignment not optimal", 4, sum, 0);
}
@Test
public void testNonSq() {
int[] assignment = new KuhnMunkresWong().run(KuhnMunkresTest.NONSQUARE);
double sum = 0.;
for(int i = 0; i < assignment.length; i++) {
assertTrue("Unassigned row " + i, assignment[i] >= 0);
sum += KuhnMunkresTest.NONSQUARE[i][assignment[i]];
}
assertEquals("Assignment not optimal", 637518, sum, 0);
}
@Test
public void testDifficult() {
int[] assignment = new KuhnMunkresWong().run(KuhnMunkresTest.DIFFICULT);
double sum = 0.;
for(int i = 0; i < assignment.length; i++) {
assertTrue("Unassigned row " + i, assignment[i] >= 0);
sum += KuhnMunkresTest.DIFFICULT[i][assignment[i]];
}
assertEquals("Assignment not optimal", 2.24, sum, 1e-4);
}
@Test
public void testDifficult2() {
int[] assignment = new KuhnMunkresWong().run(KuhnMunkresTest.DIFFICULT2);
double sum = 0.;
for(int i = 0; i < assignment.length; i++) {
assertTrue("Unassigned row " + i, assignment[i] >= 0);
sum += KuhnMunkresTest.DIFFICULT2[i][assignment[i]];
}
assertEquals("Assignment not optimal", 0.8802, sum, 1e-4);
}
@Test
public void testLarge() {
long seed = 0L;
Random rnd = new Random(seed);
double[][] mat = new double[100][100];
for(int i = 0; i < mat.length; i++) {
double[] row = mat[i];
for(int j = 0; j < row.length; j++) {
row[j] = Math.abs(rnd.nextDouble());
}
}
int[] assignment = new KuhnMunkresWong().run(mat);
double sum = 0.;
for(int i = 0; i < assignment.length; i++) {
assertTrue("Unassigned row " + i, assignment[i] >= 0);
sum += mat[i][assignment[i]];
}
if(seed == 0) {
if(mat.length == 10 && mat[0].length == 10) {
assertEquals("sum", 1.467733381753002, sum, 1e-8);
// Duration: 0.007970609
}
if(mat.length == 100 && mat[0].length == 100) {
assertEquals("sum", 1.5583906418867581, sum, 1e-8);
// Duration: 0.015696813
}
if(mat.length == 1000 && mat[0].length == 1000) {
assertEquals("sum", 1.6527526146559663, sum, 1e-8);
// Duration: 0.8892345580000001
}
if(mat.length == 10000 && mat[0].length == 10000) {
assertEquals("sum", 1.669458072091596, sum, 1e-8);
// Duration: 3035.95495334
}
}
}
}
| elki-project/elki | elki-core-util/src/test/java/elki/utilities/datastructures/KuhnMunkresWongTest.java | Java | agpl-3.0 | 4,174 |
Brimir::Application.routes.draw do
devise_for :users, controllers: { omniauth_callbacks: 'omniauth' }
resources :users
namespace :tickets do
resource :deleted, only: :destroy, controller: :deleted
resource :selected, only: :update, controller: :selected
end
resources :tickets, only: [:index, :show, :update, :new, :create]
resources :labelings, only: [:destroy, :create]
resources :rules
resources :labels, only: [:destroy, :update, :index]
resources :replies, only: [:create, :new]
get '/attachments/:id/:format' => 'attachments#show'
resources :attachments, only: [:index, :new]
resources :email_addresses, only: [:index, :create, :new, :destroy]
root to: 'tickets#index'
namespace :api do
namespace :v1 do
resources :tickets, only: [ :index, :show ]
resources :sessions, only: [ :create ]
end
end
end
| vartana/brimir | config/routes.rb | Ruby | agpl-3.0 | 876 |
#include <stddef.h>
#include "logger/logger.h"
#include "wrappers.h"
using namespace drivers::i2c;
I2CResult I2CFallbackBus::Write(const I2CAddress address, gsl::span<const uint8_t> inData)
{
const I2CResult systemBusResult = this->_innerBuses.Bus.Write(address, inData);
if (systemBusResult == I2CResult::OK)
{
return systemBusResult;
}
LOGF(LOG_LEVEL_WARNING, "Fallbacking to payload bus. System bus error %d. Transfer to %X", num(systemBusResult), address);
const I2CResult payloadBusResult = this->_innerBuses.Payload.Write(address, inData);
return payloadBusResult;
}
I2CResult I2CFallbackBus::Read(const I2CAddress address, gsl::span<uint8_t> outData)
{
const I2CResult systemBusResult = this->_innerBuses.Bus.Read(address, outData);
if (systemBusResult == I2CResult::OK)
{
return systemBusResult;
}
LOGF(LOG_LEVEL_WARNING, "Fallbacking to payload bus. System bus error %d. Transfer to %X", num(systemBusResult), address);
const I2CResult payloadBusResult = this->_innerBuses.Payload.Read(address, outData);
return payloadBusResult;
}
I2CResult I2CFallbackBus::WriteRead(const I2CAddress address, gsl::span<const uint8_t> inData, gsl::span<uint8_t> outData)
{
const I2CResult systemBusResult = this->_innerBuses.Bus.WriteRead(address, inData, outData);
if (systemBusResult == I2CResult::OK)
{
return systemBusResult;
}
LOGF(LOG_LEVEL_WARNING, "Fallbacking to payload bus. System bus error %d. Transfer to %X", num(systemBusResult), address);
const I2CResult payloadBusResult = this->_innerBuses.Payload.WriteRead(address, inData, outData);
return payloadBusResult;
}
I2CFallbackBus::I2CFallbackBus(I2CInterface& buses) : _innerBuses(buses)
{
}
| PW-Sat2/PWSat2OBC | libs/drivers/i2c/fallback.cpp | C++ | agpl-3.0 | 1,832 |
<?php
/**
* Soap Handler Class
*
*
* @package Np_Soap
* @subpackage Np_Soap
* @copyright Copyright (C) 2012-2013 S.D.O.C. LTD. All rights reserved.
* @license GNU Affero Public License version 3 or later; see LICENSE.txt
*/
/**
* Np_Db Class Definition
*
* @package Np_Soap
* @subpackage Np_Soap
*/
class Np_Soap_Handler {
/**
* sendMessage os the function defined by our wsdl .
*
* it will be called by
* other providers in order to send transactio messages to internal.
* 1.the functions receives the params .
* 2.logs them to database
* 3.validates whether they are in correct format and not null
* 4.sends Internal the message to internal via http request.
* 5.returns the resulting ack code from the params validation.
*
* @param Array $params
* @return array "NP_ACK" or string
*/
public function sendMessage($params) {
$data = $this->intoArray($params);
$reqModel = new Application_Model_Request($data); //prepares data for sending internal the message
$ack = $reqModel->Execute();
// log all received calls if request log enabled
if (Application_Model_General::getSettings('EnableRequestLog')) {
Application_Model_General::logRequestResponse($params, $ack, $data['REQUEST_ID'], '[Input] ');
}
if ($ack === FALSE || (strpos(strtolower($ack), "ack") === FALSE)) {
$ack = "Ack00";
}
return array('NP_ACK' => array('ACK_CODE' => $ack, //returns default value for testing need to fix
'ACK_DATE' => Application_Model_General::getDateIso()));
}
/**
* turns the soap array into a simple array for sending to internal.
* sets soap "signature" so array may be validated and sent back
* through soap after it reaches internal's proxy
*
* @param Array $params
* @return Array $params associative array
*/
public function intoArray($params) {
$data = (array) $params->NP_MESSAGE; //takes data out of np message array
$xmlString = simplexml_load_string($data['BODY']); //loads xml string from xml object in body
if ($xmlString == NULL) {
$xmlString[0] = "NULL";
}
$header = (array) $data['HEADER'];
$msgtype = $header['MSG_TYPE'];
$xmlArray = $xmlString[0]->$msgtype;
$convertedData = $this->convertArray($msgtype, $xmlArray, $header);
//sets soap "signature"
$convertedData['SOAP'] = 1;
return $convertedData; //returns simple array (1 level only)
}
/**
* convert Xml data to associative array
*
* @param string $msgType message type
* @param simple_xml $xmlArray simple xml object
* @param array $header the header data to join to the return data
*
* @return array converted data with header and the xml
* @todo refactoring to inner bridge classes
*/
function convertArray($msgType, $xmlArray, $header) {
$data = $header;
switch ($msgType) {
case "Check":
$nType = Application_Model_General::getSettings("NetworkType");
if ($nType === "M") {
$networkType = "mobile";
$data['NETWORK_TYPE'] = (string) $nType;
} else {
$networkType = "fixed";
$data['NETWORK_TYPE'] = (string) $nType;
}
if (!empty($xmlArray->$networkType->mobileNumberIdentified) && $xmlArray->$networkType->mobileNumberIdentified !== NULL) {
$data['IDENTIFICATION_VALUE'] = (string) $xmlArray->$networkType->mobileNumberIdentified->identificationValue;
$data['IDENTIFICATION_VALUE_2ND'] = (string) $xmlArray->$networkType->mobileNumberIdentified->identificationValue2nd;
$data['IDENTIFICATION_VALUE_3RD'] = (string) $xmlArray->$networkType->mobileNumberIdentified->identificationValue3rd;
$data['NUMBER_TYPE'] = (string) $xmlArray->$networkType->mobileNumberIdentified->numberType;
$data['NUMBER'] = (string) $xmlArray->$networkType->mobileNumberIdentified->number;
} else {
$data['NUMBER_TYPE'] = (string) $xmlArray->$networkType->mobileNumberUnidentified->numberType;
$data['NUMBER'] = (string) $xmlArray->$networkType->mobileNumberUnidentified->number;
}
break;
case "Request":
$data['PORT_TIME'] = (string) $xmlArray->portingDateTime;
break;
case "Update":
$data['PORT_TIME'] = (string) $xmlArray->portingDateTime;
break;
case "Cancel":
break;
case "KD_update":
$data['KD_UPDATE_TYPE'] = (string) $xmlArray[0];
$data['REMARK'] = (string) $xmlArray->remark;
break;
case "Execute":
break;
case "Publish":
$data['DONOR'] = (string) $xmlArray->donor;
$data['CONNECT_TIME'] = (string) $xmlArray->connectDateTime;
$data['PUBLISH_TYPE'] = (string) $xmlArray->publishType;
$data['DISCONNECT_TIME'] = (string) $xmlArray->disconnectDateTime;
if (isset($xmlArray->fixed)) {
$data['NUMBER_TYPE'] = (string) $xmlArray->fixed->fixedNumberSingle->numberType;
if (isset($xmlArray->fixed->fixedNumberRange)) {
$data['NUMBER_TYPE'] = (string) $xmlArray->fixed->fixedNumberRange->numberType;
$data['FROM_NUMBER'] = (string) $xmlArray->fixed->fixedNumberRange->fromNumber;
$data['TO_NUMBER'] = (string) $xmlArray->fixed->fixedNumberRange->toNumber;
} else {
$data['NUMBER'] = (string) $xmlArray->fixed->fixedNumberSingle->number;
}
} else {
$data['NUMBER_TYPE'] = (string) $xmlArray->mobile->numberType;
$data['NUMBER'] = (string) $xmlArray->mobile->number;
}
break;
case "Cancel_publish":
$data['DONOR'] = (string) $xmlArray->donor;
break;
case "Return":
$data['NUMBER'] = (string) $xmlArray->number;
if (isset($xmlArray->mobile)) {
$data['NETWORK_TYPE'] = (string) $xmlArray->mobile->networkType;
$data['NUMBER_TYPE'] = (string) $xmlArray->mobile->numberType;
} else {
$data['NETWORK_TYPE'] = (string) $xmlArray->fixed->networkType;
$data['NUMBER_TYPE'] = (string) $xmlArray->fixed->numberType;
}
break;
case "Inquire_number":
$data['NUMBER'] = (string) $xmlArray->number;
break;
case "Up_system":
$res = Application_Model_General::saveShutDownDetails($data['FROM'], "UP");
break;
case "Down_system":
$res = Application_Model_General::saveShutDownDetails($data['FROM'], "DOWN");
break;
case "Check_response":
$data['ESSENTIAL_INFO_1'] = (string) $xmlArray->essentialInfo1;
$data['ESSENTIAL_INFO_2'] = (string) $xmlArray->essentialInfo2;
$data['ESSENTIAL_INFO_3'] = (string) $xmlArray->essentialInfo3;
$data['ESSENTIAL_INFO_4'] = (string) $xmlArray->essentialInfo4;
$data['ESSENTIAL_INFO_5'] = (string) $xmlArray->essentialInfo5;
case "Request_response":
// this check because check_response go through this code (TODO: refactoring)
if (isset($xmlArray->portingDateTime)) {
$data['PORT_TIME'] = (string) $xmlArray->portingDateTime;
}
case "Update_response":
case "Cancel_response":
case "Execute_response":
case "Publish_response":
case "KD_update_response":
case "Inquire_number_response":
case "Cancel_publish_response":
case "Return_response":
if (isset($xmlArray->positiveApproval)) {
$data['APPROVAL_IND'] = "Y";
} else {
$data['APPROVAL_IND'] = "N";
$data['REJECT_REASON_CODE'] = (string) $xmlArray->negativeApproval->rejectReasonCode;
}
$data['REQUEST_TRX_NO'] = (string) $xmlArray->requestTrxNo;
$data['REQUEST_RETRY_DATE'] = (string) $xmlArray->requestRetryDate;
}
return $data;
}
}
| mehulsbhatt/NPG | library/Np/Soap/Handler.php | PHP | agpl-3.0 | 7,386 |
DELETE FROM `weenie` WHERE `class_Id` = 20478;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (20478, 'scrollfireprotectionself7', 34, '2019-02-10 00:00:00') /* Scroll */;
INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`)
VALUES (20478, 1, 8192) /* ItemType - Writable */
, (20478, 5, 30) /* EncumbranceVal */
, (20478, 16, 8) /* ItemUseable - Contained */
, (20478, 19, 2000) /* Value */
, (20478, 93, 1044) /* PhysicsState - Ethereal, IgnoreCollisions, Gravity */
, (20478, 8041, 101) /* PCAPRecordedPlacement - Resting */;
INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`)
VALUES (20478, 22, True ) /* Inscribable */;
INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`)
VALUES (20478, 39, 1.5) /* DefaultScale */;
INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`)
VALUES (20478, 1, 'Scroll of Fiery Blessing') /* Name */
, (20478, 14, 'Use this item to attempt to learn its spell.') /* Use */
, (20478, 16, 'Inscribed spell: Fiery Blessing
Reduces damage the caster takes from Fire by 65%.') /* LongDesc */;
INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`)
VALUES (20478, 1, 0x0200018A) /* Setup */
, (20478, 8, 0x06003555) /* Icon */
, (20478, 22, 0x3400002B) /* PhysicsEffectTable */
, (20478, 28, 2157) /* Spell - FireProtectionSelf7 */
, (20478, 8001, 6307864) /* PCAPRecordedWeenieHeader - Value, Usable, Container, Burden, Spell */
, (20478, 8003, 18) /* PCAPRecordedObjectDesc - Inscribable, Attackable */
, (20478, 8005, 135297) /* PCAPRecordedPhysicsDesc - CSetup, ObjScale, PeTable, AnimationFrame */;
INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`)
VALUES (20478, 8000, 0xDC32EF42) /* PCAPRecordedObjectIID */;
| ACEmulator/ACE-World | Database/3-Core/9 WeenieDefaults/SQL/Scroll/Writable/20478 Scroll of Fiery Blessing.sql | SQL | agpl-3.0 | 1,929 |
# -*- coding: utf-8 -*-
# © 2014 Elico Corp (https://www.elico-corp.com)
# Licence AGPL-3.0 or later(http://www.gnu.org/licenses/agpl.html)
import time
from datetime import datetime
import openerp.addons.decimal_precision as dp
from openerp.osv import fields, osv
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT, DATETIME_FORMATS_MAP
from openerp.tools import float_compare
from openerp.tools.translate import _
from openerp import SUPERUSER_ID
from openerp import netsvc
from openerp import tools
class mrp_production(osv.osv):
_inherit = 'mrp.production'
def _action_compute_lines(self, cr, uid, ids, properties=None, context=None):
""" Computes bills of material of a product.
@param properties: List containing dictionaries of properties.
@return: No. of products.
"""
if properties is None:
properties = []
results = []
bom_obj = self.pool.get('mrp.bom')
uom_obj = self.pool.get('product.uom')
prod_line_obj = self.pool.get('mrp.production.product.line')
workcenter_line_obj = self.pool.get('mrp.production.workcenter.line')
for production in self.browse(cr, uid, ids):
#unlink product_lines
prod_line_obj.unlink(cr, SUPERUSER_ID, [line.id for line in production.product_lines], context=context)
#unlink workcenter_lines
workcenter_line_obj.unlink(cr, SUPERUSER_ID, [line.id for line in production.workcenter_lines], context=context)
# search BoM structure and route
bom_point = production.bom_id
bom_id = production.bom_id.id
if not bom_point:
bom_id = bom_obj._bom_find(cr, uid, production.product_id.id, production.product_uom.id, properties)
if bom_id:
bom_point = bom_obj.browse(cr, uid, bom_id)
routing_id = bom_point.routing_id.id or False
self.write(cr, uid, [production.id], {'bom_id': bom_id, 'routing_id': routing_id})
if not bom_id:
continue
# get components and workcenter_lines from BoM structure
factor = uom_obj._compute_qty(cr, uid, production.product_uom.id, production.product_qty, bom_point.product_uom.id)
res = bom_obj._bom_explode(cr, uid, bom_point, factor / bom_point.product_qty, properties, routing_id=production.routing_id.id)
results = res[0] # product_lines
results2 = res[1] # workcenter_lines
# reset product_lines in production order
for line in results:
line['production_id'] = production.id
prod_line_obj.create(cr, uid, line)
#reset workcenter_lines in production order
for line in results2:
line['production_id'] = production.id
workcenter_line_obj.create(cr, uid, line)
return results
def action_ready(self, cr, uid, ids, context=None):
""" Changes the production state to Ready and location id of stock move.
@return: True
"""
move_obj = self.pool.get('stock.move')
self.write(cr, uid, ids, {'state': 'ready'})
for production in self.browse(cr, uid, ids, context=context):
if not production.bom_id:
produce_move_id = self._make_production_produce_line(cr, uid, production, context=context)
for (production_id,name) in self.name_get(cr, uid, ids):
production = self.browse(cr, uid, production_id)
if production.move_prod_id and production.move_prod_id.location_id.id != production.location_dest_id.id:
move_obj.write(cr, uid, [production.move_prod_id.id],
{'location_id': production.location_dest_id.id})
return True
def action_produce(self, cr, uid, production_id, production_qty, production_mode, context=None):
production = self.browse(cr, uid, production_id, context=context)
if not production.bom_id and production.state == 'ready':
wf_service = netsvc.LocalService("workflow")
wf_service.trg_validate(uid, 'mrp.production', production_id, 'button_produce', cr)
return super(mrp_production, self).action_produce(cr, uid, production_id, production_qty, production_mode, context=context)
mrp_production()
| Elico-Corp/openerp-7.0 | mrp_mo_nopicking/mrp.py | Python | agpl-3.0 | 4,435 |
/**
* @(#)MediaExportParameters.java
*
* This file is part of the Non-Linear Book project.
* Copyright (c) 2012-2016 Anton P. Kolosov
* Authors: Anton P. Kolosov, et al.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License version 3
* as published by the Free Software Foundation with the addition of the
* following permission added to Section 15 as permitted in Section 7(a):
* FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
* ANTON P. KOLOSOV. ANTON P. KOLOSOV DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
* OF THIRD PARTY RIGHTS
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA, 02110-1301 USA.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License.
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial activities involving the Non-Linear Book software without
* disclosing the source code of your own applications.
*
* For more information, please contact Anton P. Kolosov at this
* address: [email protected]
*
* Copyright (c) 2012 Anton P. Kolosov All rights reserved.
*/
package com.nlbhub.nlb.domain;
import com.nlbhub.nlb.api.PropertyManager;
/**
* The MediaExportParameters class represents parameters used when saving media files during export of the scheme
* to some end format (such as INSTEAD game).
*
* @author Anton P. Kolosov
* @version 1.0 8/9/12
*/
public class MediaExportParameters {
public enum Preset {CUSTOM, DEFAULT, NOCHANGE, COMPRESSED};
private static final MediaExportParameters NOCHANGE = new MediaExportParameters(Preset.NOCHANGE, false, 0);
private static final MediaExportParameters COMPRESSED = new MediaExportParameters(Preset.COMPRESSED, true, 80);
private static final MediaExportParameters DEFAULT = (
new MediaExportParameters(
Preset.DEFAULT,
PropertyManager.getSettings().getDefaultConfig().getExport().isConvertpng2jpg(),
PropertyManager.getSettings().getDefaultConfig().getExport().getQuality()
)
);
private Preset m_preset = Preset.CUSTOM;
private boolean m_convertPNG2JPG;
private int m_quality;
public static MediaExportParameters fromPreset(Preset preset) {
switch (preset) {
case NOCHANGE:
return MediaExportParameters.NOCHANGE;
case COMPRESSED:
return MediaExportParameters.COMPRESSED;
default:
return MediaExportParameters.DEFAULT;
}
}
public static MediaExportParameters getDefault() {
return DEFAULT;
}
/*
public MediaExportParameters(boolean convertPNG2JPG, int quality) {
m_preset = Preset.CUSTOM;
m_convertPNG2JPG = convertPNG2JPG;
m_quality = quality;
}
*/
private MediaExportParameters(Preset preset, boolean convertPNG2JPG, int quality) {
m_preset = preset;
m_convertPNG2JPG = convertPNG2JPG;
m_quality = quality;
}
public Preset getPreset() {
return m_preset;
}
public boolean isConvertPNG2JPG() {
return m_convertPNG2JPG;
}
public int getQuality() {
return m_quality;
}
}
| Antokolos/NLB | NLBL/src/main/java/com/nlbhub/nlb/domain/MediaExportParameters.java | Java | agpl-3.0 | 3,959 |
# Friend Chat
Friend Chat is a chat integration platform for Friend. It is built to make
it fairly straightforward to add access to 3rd party chat APIs. It is a
client - server architecture where the server handles the connection to the
remote API and presents the content to the client. Multiple clients can
be connected per account, all staying in sync. Accounts are created and
logged in through Friend, no extra setup required.
## Video / Audio Conferencing, aka Live
Friend Chat allows peer to peer video and audio calls over webRTC, supported
by the presence service. The limits to number of participants is
practical; the bandwidth and power of your device.
#### Invites
Live invites can be sent through any module. It is sent as a data string,
and as long as the invitee is also using Friend Chat, it will be intercepted
and presented to the user. The live session is then established over the
presence service.
#### Guests
Any live session can be shared through a clickable link. This is a public invite
and can be used by any number of people until it is explicitly canceled. People
using this link will join as a guest with either a randomly generated name or
one they choose themselves.
#### Share your screen or app
Screen sharing is available for chrome through an extension. The option
is found in the live view menu, and will either prompt you install the
extension or offer to initiate screen sharing.
## Modules
Modules are integrations towards 3rd party chat services. They have a server part
that communicates with the remote service/server API and a client part with a custom
UI that presents the data. Current modules are IRC, Presence and Treeroot. Presence
is always there and IRC is added by default.
#### IRC
Internet Relay Chat, because it would be weird not to have it. Covers
most basic needs and commands. An abbreviated list of commands if you are new to IRC:
* /nick new_nick - change your nick
* /action does something silly - *me does something silly*
* /join #channel_name - join a channel
* /part - in channel, leave the channel
This can also be changed in settings. More commands and how irc works in general
can be found on the internet.
#### Presence
Presence provides temporary or persistent many-to-many rooms for chatting and
video / audio conferencing. Invites to presence rooms can be sent through the other
modules. More info in the FriendSoftwareLabs/presence repository!
#### Treeroot
The Treeroot module integrates the chat part of the Treeroot system. It provides
one to one chat, optionally end to end encrypted. You'll need to add the module
( 'add chat account' in the menu ) then log in with ( or create a new ) Treeroot
account. | FriendSoftwareLabs/friendchat | client/Readme.md | Markdown | agpl-3.0 | 2,716 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../style.css');
@import url('../../../../tree.css');
</style>
<script src="../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../clover.js" type="text/javascript"></script>
<script src="../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../cloud.js" type="text/javascript"></script>
<title>rapidminer-studio-core 转换结果 </title>
</head>
<body >
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://www.atlassian.com/clover" title="Open Atlassian Clover home page"><span class="aui-header-logo-device">Clover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online Clover documentation" target="_blank"
href="https://confluence.atlassian.com/display/CLOVER/Clover+Documentation+Home">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</div>
<div class="aui-page-header-main" >
<h1>
rapidminer-studio-core 转换结果
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../" data-package-name="com.rapidminer.gui.dnd">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../dashboard.html">Project Clover database 星期二 九月 5 2017 16:40:29 CST</a></li>
</ol>
<h1 class="aui-h2-clover">
Package com.rapidminer.gui.dnd
</h1>
<div class="aui-tabs horizontal-tabs">
<ul class="tabs-menu">
<li class="menu-item ">
<a href="pkg-summary.html"><strong>Application code</strong></a>
</li>
<li class="menu-item active-tab">
<a href="top-risks.html"><strong>Top risks</strong></a>
</li>
<li class="menu-item ">
<a href="quick-wins.html"><strong>Quick wins</strong></a>
</li>
</ul>
<div class="tabs-pane active-pane" id="tabs-first">
<div> </div>
<div class="aui-message aui-message-warning">
<p class="title">
<strong>Evaluation License</strong>
</p>
<p>
This report was generated with an evaluation server license. <a href="http://www.atlassian.com/software/clover">Purchase Clover</a> or <a href="http://confluence.atlassian.com/x/JAgQCQ">configure your license.</a>
</p>
</div>
<div style="text-align: right; margin-bottom: 10px">
<button class="aui-button aui-button-subtle" id="popupHelp">
<span class="aui-icon aui-icon-small aui-iconfont-help"></span> How to read this chart
</button>
<script>
AJS.InlineDialog(AJS.$("#popupHelp"), "helpDialog",
function (content, trigger, showPopup) {
var description = topRisksDescription();
var title = 'Top Risks';
content.css({"padding": "20px"}).html(
'<h2>' + title + '</h2>' + description);
showPopup();
return false;
},
{
width: 600
}
);
</script>
</div>
<div style="padding: 20px; border: 1px solid #cccccc; background-color: #f5f5f5; border-radius: 3px">
<div id="shallowPackageCloud" >
</div>
</div>
</div> <!-- tabs-pane active-pane -->
</div> <!-- aui-tabs horizontal-tabs -->
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://www.atlassian.com/software/clover">Atlassian Clover</a> v 4.1.2
on 星期二 九月 5 2017 17:24:16 CST using coverage data from 星期四 一月 1 1970 08:00:00 CST.
</li>
</ul>
<ul>
<li>Clover Evaluation License registered to Clover Plugin. You have 29 day(s) before your license expires.</li>
</ul>
<div id="footer-logo">
<a target="_blank" href="http://www.atlassian.com/">
Atlassian
</a>
</div>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html> | cm-is-dog/rapidminer-studio-core | report/html/com/rapidminer/gui/dnd/top-risks.html | HTML | agpl-3.0 | 8,358 |
<div align="center" class="heading_gray">
<h3>User Registration</h3>
</div>
<br/>
<?php echo form_open('user/user_registration/userinsert', array('id' => 'formUser'));
echo blue_box_top();
?>
<table width="100%" border="0" cellspacing="0" cellpadding="4" align="center" class="heading_tab" style="margin-top:15px;">
<tr>
<th colspan="4" align="left">User Creation</th>
</tr>
<tr>
<td width="10%" class=""> </td>
<td align="left" width="27%" class="table_row_first"> User Name : </td>
<td align="left" width="55%" class="table_row_first"><?php echo form_input("txtNewUserName",@$selected_user[0]['user_name'], 'class="input_box" id="txtNewUserName"' );?></td>
<td width="18%"> </td>
</tr>
<tr>
<td> </td>
<td align="left" width="27%" class="table_row_first"> Password : </td>
<td align="left" width="55%" class="table_row_first"><?php echo form_password("txtNewPassword",'', 'class="input_box" id="txtNewPassword"' );?></td>
<td width="18%"> </td>
</tr>
<!--<tr>
<td> </td>
<td align="left" width="27%" class="table_row_first"> User Type : </td>
<td align="left" width="55%" class="table_row_first"><?php echo (@$school_show == 'show') ? @$school_details[0]['class_end'] : form_dropdown("userType", array(0=>'...........', 1=>'Admin', 2 => 'User'), 'id="userType"','id="userType"');?></td>
<td width="18%"> </td>
</tr>-->
<?php
if(count(@$user_rights) > 0 ){?>
<tr>
<td> </td>
<td align="left" width="27%" class="table_row_first" valign="top"> User Rights : </td>
<td align="left" width="55%" class="table_row_first">
<?php
$functionality_label = '';
for($i=0; $i<count($user_rights); $i++){
if($functionality_label != $user_rights[$i]['label_name']){
$functionality_label = $user_rights[$i]['label_name'];
?>
<div class="clear_both"></div>
<div class="functionality_label"><?php echo $user_rights[$i]['label_name']?></div>
<?php
}
if(count(@$selected_user_rights) > 0 && @$selected_user_rights[0] != 0){
$checked = (in_array($user_rights[$i]['rf_id'], @$selected_user_rights)) ? 'TRUE' : '';
} else {
$checked = '';
}
$data = array(
'name' => 'chkRight_'.$user_rights[$i]['rf_id'],
'id' => 'chkRight_'.$user_rights[$i]['rf_id'],
'value' => $user_rights[$i]['rf_id'],
'checked' => $checked,
'style' => 'margin:5px',
);
?>
<div class="clear_both"></div>
<div class="functionalities">
<?php
echo form_checkbox($data);
echo form_label($user_rights[$i]['rf_functionality'], 'chkRight_'.$user_rights[$i]['rf_id']).'<br>';
?>
</div>
<?php
}
?>
</td>
<td width="18%"> </td>
</tr>
<?php }?>
<tr>
<td align="center" colspan="4">
<?php echo (@$selected_user[0]['user_id'] != '') ? form_button('Update User', 'Update User', 'onClick="javascript: return fnsUserUpdate(\''.@$selected_user[0]['user_id'].'\')"').' '.form_button('Cancel', 'Cancel', 'onClick="javascript: return cancel()"'):form_submit('Add User', 'Add User', 'onClick="javascript: return fnsUserAdd()"');?> </td>
</tr>
</table>
<input type="hidden" name="hidUserId" id="hidUserId" />
<?php
echo blue_box_bottom();
echo form_close();
?>
| itschool/kalolsavam-subdistrict | system/application/views/user/user_registration.php | PHP | agpl-3.0 | 3,619 |
jaleela_protestor_leader = Creature:new {
objectName = "",
socialGroup = "thug",
faction = "thug",
level = 17,
chanceHit = 0.320000,
damageMin = 180,
damageMax = 190,
baseXp = 1102,
baseHAM = 2400,
baseHAMmax = 3000,
armor = 0,
resists = {0,0,0,0,0,0,0,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0.000000,
ferocity = 0,
pvpBitmask = ATTACKABLE + ENEMY + AGGRESSIVE,
creatureBitmask = PACK,
optionsBitmask = 128,
diet = HERBIVORE,
templates = { "object/mobile/dressed_criminal_thug_human_male_01.iff" },
lootGroups = {
{
groups = {
{group = "junk", chance = 4000000},
{group = "wearables_common", chance = 3000000},
{group = "loot_kit_parts", chance = 2000000},
{group = "tailor_components", chance = 1000000},
}
}
},
weapons = {"pirate_weapons_heavy"},
attacks = merge(brawlermaster,marksmanmaster)
}
CreatureTemplates:addCreatureTemplate(jaleela_protestor_leader, "jaleela_protestor_leader")
| lasko2112/legend-of-hondo | MMOCoreORB/bin/scripts/mobile/quest/rori/jaleela_protestor_leader.lua | Lua | agpl-3.0 | 1,034 |
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateOauthAuthCodesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('oauth_auth_codes', function (Blueprint $table) {
$table->string('id', 100)->primary();
$table->unsignedBigInteger('user_id')->index();
$table->unsignedBigInteger('client_id');
$table->text('scopes')->nullable();
$table->boolean('revoked');
$table->dateTime('expires_at')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('oauth_auth_codes');
}
}
| monicahq/monica | database/migrations/2016_06_01_000001_create_oauth_auth_codes_table.php | PHP | agpl-3.0 | 852 |
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AppModule } from '../../../../app.module';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material';
import { ConfirmDialogComponent } from './confirm-dialog.component';
describe('ConfirmDialogComponent', () => {
let component: ConfirmDialogComponent;
let dialog: MatDialog;
let fixture: ComponentFixture<ConfirmDialogComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
AppModule,
],
providers: [
{ provide: MAT_DIALOG_DATA, useValue: {} },
{ provide: MatDialogRef }
]
})
.compileComponents();
}));
beforeEach(() => {
dialog = TestBed.get(MatDialog);
fixture = TestBed.createComponent(ConfirmDialogComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| dhlab-basel/Salsah | src/app/view/modules/dialog/confirm-dialog/confirm-dialog.component.spec.ts | TypeScript | agpl-3.0 | 1,082 |
{% extends 'task/default.html' %}
{% block task-content %}
<dl class="task__data">
{% if task.category %}
<dt>Category</dt>
<dd>{{ task.get_category_display }}</dd>
{% endif %}
{% if task.text %}
<dt>Message</dt>
<dd>{{task.text}}</dd>
{% endif %}
{% if task.user %}
<dt>User</dt>
<dd><a href="{% url 'admin:auth_user_change' task.user.pk %}">{{task.user.profile.full_name}}</a></dd>
{% endif %}
{% if task.foia %}
<dt>Request</dt>
<dd><a href="{{task.foia.get_absolute_url}}">{{task.foia}}</a> (<a href="{% url 'admin:foia_foiarequest_change' task.foia.pk %}">admin</a>) - MR #{{task.foia.pk}}</dd>
{% elif task.agency %}
<dt>Agency</dt>
<dd><a href="{% url 'admin:agency_agency_change' task.agency.pk %}">{{task.agency}}</a></dd>
{% elif task.jurisdiction %}
<dt>Jurisdiction</dt>
<dd><a href="{% url 'admin:jurisdiction_jurisdiction_change' task.jurisdiction.pk %}">{{task.jurisdiction}}</a></dd>
{% endif %}
</dl>
<form method="POST" action="{{ endpoint }}" class="collapsable flag-reply">
<header>
<p>↵ Reply to {{task.user.profile.full_name}} <<a href="mailto:{{task.user.email}}">{{task.user.email}}</a>></p>
</header>
{% csrf_token %}
<input type="hidden" name="task" value="{{task.pk}}">
{{ flag_form.text }}
<footer class="submission-control">
<button type="submit" name="reply" value="true" class="primary button">Reply</button>
<div class="checkbox-field">
<input type="checkbox" name="resolve" id="resolve-with-reply" checked>
<label for="resolve-with-reply">Resolve after sending</label>
</div>
</footer>
</form>
{% endblock %}
| MuckRock/muckrock | muckrock/templates/task/flagged.html | HTML | agpl-3.0 | 1,743 |
require 'spec_helper'
require 'rollbar/middleware/sinatra'
require 'sinatra/base'
require 'rack/test'
class SinatraDummy < Sinatra::Base
class DummyError < StandardError; end
use Rollbar::Middleware::Sinatra
get '/foo' do
raise DummyError.new
end
get '/bar' do
'this will not crash'
end
post '/crash_post' do
raise DummyError.new
end
end
describe Rollbar::Middleware::Sinatra, :reconfigure_notifier => true do
include Rack::Test::Methods
def app
SinatraDummy
end
let(:logger_mock) { double('logger').as_null_object }
before do
Rollbar.configure do |config|
config.logger = logger_mock
config.framework = 'Sinatra'
end
end
let(:uncaught_level) do
Rollbar.configuration.uncaught_exception_level
end
let(:expected_report_args) do
[uncaught_level, exception, { :use_exception_level_filters => true }]
end
describe '#call' do
context 'for a crashing endpoint' do
# this is the default for test mode in Sinatra
context 'with raise_errors? == true' do
let(:exception) { kind_of(SinatraDummy::DummyError) }
before do
allow(app.settings).to receive(:raise_errors?).and_return(true)
end
it 'reports the error to Rollbar API and raises error' do
expect(Rollbar).to receive(:log).with(*expected_report_args)
expect do
get '/foo'
end.to raise_error(SinatraDummy::DummyError)
end
end
context 'with raise_errors? == false' do
let(:exception) { kind_of(SinatraDummy::DummyError) }
before do
allow(app.settings).to receive(:raise_errors?).and_return(false)
end
it 'reports the error to Rollbar, but nothing is raised' do
expect(Rollbar).to receive(:log).with(*expected_report_args)
get '/foo'
end
end
end
context 'for a NOT crashing endpoint' do
it 'doesnt report any error to Rollbar API' do
expect(Rollbar).not_to receive(:log)
get '/bar'
end
end
context 'if the middleware itself fails' do
let(:exception) { Exception.new }
before do
allow_any_instance_of(described_class).to receive(:framework_error).and_raise(exception)
allow(app.settings).to receive(:raise_errors?).and_return(false)
end
it 'reports the report error' do
expect(Rollbar).to receive(:log).with(*expected_report_args)
expect do
get '/foo'
end.to raise_error(exception)
end
end
context 'with GET parameters' do
let(:exception) { kind_of(SinatraDummy::DummyError) }
let(:params) do
{
'key' => 'value'
}
end
it 'appear in the sent payload' do
expect do
get '/foo', params
end.to raise_error(exception)
expect(Rollbar.last_report[:request][:GET]).to be_eql(params)
end
end
context 'with POST parameters' do
let(:exception) { kind_of(SinatraDummy::DummyError) }
let(:params) do
{
'key' => 'value'
}
end
it 'appear in the sent payload' do
expect do
post '/crash_post', params
end.to raise_error(exception)
expect(Rollbar.last_report[:request][:POST]).to be_eql(params)
end
end
context 'with JSON POST parameters' do
let(:exception) { kind_of(SinatraDummy::DummyError) }
let(:params) do
{
'key' => 'value'
}
end
it 'appears in the sent payload when application/json is the content type' do
expect do
post '/crash_post', params.to_json, { 'CONTENT_TYPE' => 'application/json' }
end.to raise_error(exception)
expect(Rollbar.last_report[:request][:body]).to be_eql(params.to_json)
end
it 'appears in the sent payload when the accepts header contains json' do
expect do
post '/crash_post', params, { 'ACCEPT' => 'application/vnd.github.v3+json' }
end.to raise_error(exception)
expect(Rollbar.last_report[:request][:POST]).to be_eql(params)
end
end
it 'resets the notifier scope in every request' do
get '/bar'
id1 = Rollbar.scope_object.object_id
get '/bar'
id2 = Rollbar.scope_object.object_id
expect(id1).not_to be_eql(id2)
end
context 'with person data' do
let(:exception) { kind_of(SinatraDummy::DummyError) }
let(:person_data) do
{ 'email' => '[email protected]' }
end
it 'includes person data from env' do
expect do
get '/foo', {}, 'rollbar.person_data' => person_data
end.to raise_error(exception)
expect(Rollbar.last_report[:person]).to be_eql(person_data)
end
it 'includes empty person data when not in env' do
expect do
get '/foo'
end.to raise_error(exception)
expect(Rollbar.last_report[:person]).to be_eql({})
end
end
end
end
| NullVoxPopuli/aeonvera | vendor/bundle/ruby/2.4.0/gems/rollbar-2.15.2/spec/rollbar/middleware/sinatra_spec.rb | Ruby | agpl-3.0 | 5,036 |
/*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2020 Asqatasun.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.rules.rgaa30;
import org.asqatasun.ruleimplementation.AbstractNotTestedRuleImplementation;
/**
* Implementation of the rule 1.10.1 of the referential Rgaa 3.0.
*
* For more details about the implementation, refer to <a href="http://doc.asqatasun.org/en/90_Rules/rgaa3.0/01.Images/Rule-1-10-1.html">the rule 1.10.1 design page.</a>
* @see <a href="http://references.modernisation.gouv.fr/referentiel-technique-0#test-1-10-1"> 1.10.1 rule specification</a>
*/
public class Rgaa30Rule011001 extends AbstractNotTestedRuleImplementation {
/**
* Default constructor
*/
public Rgaa30Rule011001 () {
super();
}
}
| Asqatasun/Asqatasun | rules/rules-rgaa3.0/src/main/java/org/asqatasun/rules/rgaa30/Rgaa30Rule011001.java | Java | agpl-3.0 | 1,487 |
'use strict';
var phonetic = require('phonetic');
var socketio = require('socket.io');
var _ = require('underscore');
var load = function(http) {
var io = socketio(http);
var ioNamespace = '/';
var getEmptyRoomId = function() {
var roomId = null;
do {
roomId = phonetic.generate().toLowerCase()
} while (io.nsps[ioNamespace].adapter.rooms[roomId]);
return roomId;
};
var sendRoomInfo = function(socket, info) {
if (!info.roomId) {
return;
}
var clients = io.nsps[ioNamespace].adapter.rooms[info.roomId];
io.sockets.in(info.roomId).emit('room.info', {
id: info.roomId,
count: clients ? Object.keys(clients).length : 0
});
};
var onJoin = function(socket, info, data) {
if (info.roomId) {
return;
}
info.roomId = data && data.roomId ? data.roomId : null;
if (!info.roomId || !io.nsps[ioNamespace].adapter.rooms[data.roomId]) {
info.roomId = getEmptyRoomId(socket);
console.log('[Socket] Assigning room id ' + info.roomId + ' to ip ' + socket.handshake.address);
} else {
console.log('[Socket] Assigning room id ' + info.roomId + ' to ip ' + socket.handshake.address + ' (from client)');
}
socket.join(info.roomId);
socket.emit('join', {
roomId: info.roomId
});
sendRoomInfo(socket, info);
};
var onEvent = function(socket, info, event, data) {
if (!info.roomId) {
return;
}
socket.broadcast.to(info.roomId).emit(event, data);
};
var onChunk = function(socket, info, data) {
socket.emit('file.ack', {
guid: data.guid
});
onEvent(socket, info, 'file.chunk', data);
};
var onConnection = function(socket) {
console.log('[Socket] New connection from ip ' + socket.handshake.address);
var info = {
roomId: null
};
socket.on('disconnect', function() {
console.log('[Socket] Connection from ip ' + socket.handshake.address + ' disconnected');
sendRoomInfo(socket, info);
});
socket.on('join', _.partial(onJoin, socket, info));
socket.on('file.start', _.partial(onEvent, socket, info, 'file.start'));
socket.on('file.chunk', _.partial(onChunk, socket, info));
}
io.on('connection', onConnection);
};
module.exports = {
load: load
}; | ryanpetris/droppy | socket.js | JavaScript | agpl-3.0 | 2,696 |
#pragma once
class cosmos;
#include "game/transcendental/step_declaration.h"
class position_copying_system {
public:
void update_transforms(const logic_step step);
}; | DaTa-/Hypersomnia | src/game/systems_stateless/position_copying_system.h | C | agpl-3.0 | 169 |
# Does it have wifi?
## Development
Requires **Node 0.12+**.
Install:
```bash
$ npm install -g gulp
$ npm install
```
Run server with auto-reload (without minification):
```bash
$ gulp
```
To force minification of assets (build takes a bit longer) include the `--minified` flag:
```bash
$ gulp --minified
```
## Production deployment
SSH as root into the production server:
```
$ ssh [email protected]
$ cd /opt/doesithavewifi
$ git pull
$ npm run build
```
## Credits
* [Ramesh Nair](https://github.com/hiddentao)
* [Jeff Lau](https://github.com/jefflau)
* [Leon Talbert](https://github.com/LeonmanRolls)
## License
AGPLv3 - see LICENSE.txt
| taipowerapps/doesithavewifi | README.md | Markdown | agpl-3.0 | 659 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
</head>
<body bgcolor="white">
Provides test classes.
</body>
</html>
| aborg0/rapidminer-vega | src/com/rapidminer/test/package.html | HTML | agpl-3.0 | 144 |
ALTER TABLE `album` CHANGE fichier fichier varchar(250); | lolgzs/opacce | cosmogramme/sql/patch/patch_073.sql | SQL | agpl-3.0 | 57 |
/*
* Fluffy Meow - Torrent RSS generator for TV series
* Copyright (C) 2015 Victor Denisov
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.plukh.fluffymeow.aws;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.DescribeTagsRequest;
import com.amazonaws.services.ec2.model.DescribeTagsResult;
import com.amazonaws.services.ec2.model.Filter;
import com.amazonaws.services.ec2.model.TagDescription;
import org.apache.http.client.fluent.Request;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
public class AWSInstanceInfoProviderImpl implements InstanceInfoProvider {
private static final Logger log = LogManager.getLogger(AWSInstanceInfoProviderImpl.class);
private static final String NAME_TAG = "Name";
private static final String DEPLOYMENT_ID_TAG = "deploymentId";
private InstanceInfo instanceInfo;
public AWSInstanceInfoProviderImpl() {
}
@Override
public InstanceInfo getInstanceInfo() {
if (instanceInfo == null) {
try {
AmazonEC2 ec2 = new AmazonEC2Client();
String instanceId = Request.Get("http://169.254.169.254/latest/meta-data/instance-id").execute().returnContent().asString();
if (log.isDebugEnabled()) log.debug("Instance Id: " + instanceId);
DescribeTagsRequest tagsRequest = new DescribeTagsRequest().withFilters(
new Filter().withName("resource-id").withValues(instanceId),
new Filter().withName("key").withValues(NAME_TAG, DEPLOYMENT_ID_TAG));
DescribeTagsResult tagsResult = ec2.describeTags(tagsRequest);
String name = getTag(tagsResult, NAME_TAG);
if (log.isDebugEnabled()) log.debug("Instance name: " + name);
String deploymentId = getTag(tagsResult, DEPLOYMENT_ID_TAG);
if (log.isDebugEnabled()) log.debug("Deployment: " + deploymentId);
instanceInfo = new InstanceInfo()
.withInstanceId(instanceId)
.withName(name)
.withDeploymentId(deploymentId);
} catch (IOException e) {
throw new AWSInstanceInfoException("Error retrieving AWS instance info", e);
}
}
return instanceInfo;
}
private String getTag(DescribeTagsResult tagsResult, String tagName) {
for (TagDescription tag : tagsResult.getTags()) {
if (tag.getKey().equals(tagName)) return tag.getValue();
}
return null;
}
}
| vdenisov/fluffy-meow | src/main/java/org/plukh/fluffymeow/aws/AWSInstanceInfoProviderImpl.java | Java | agpl-3.0 | 3,343 |
require_relative 'api_fixtures_helper'
class FakeApiResponse
include ApiFixturesHelper
def app_init
parse(app_init_plist)
end
def all_cinemas
parse(all_cinemas_plist)
end
def film_times(cinema_id, film_id)
parse(film_times_plist(cinema_id, film_id))
end
end
| andycroll/odeon_uk | test/support/fake_api_response.rb | Ruby | agpl-3.0 | 288 |
# ETConf -- web-based user-friendly computer hardware configurator
# Copyright (C) 2010-2011 ETegro Technologies, PLC <http://etegro.com/>
# Sergey Matveev <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.conf.urls.defaults import *
urlpatterns = patterns( "configurator.giver.views",
( r"^perform/(?P<computermodel_alias>.+)/$", "perform" ),
( r"^configurator/(?P<computermodel_alias>.+)/$", "configurator" ),
( r"^computermodel/request/(?P<computermodel_alias>.+)$", "computermodel_request" ),
)
| ETegro/ETConf | giver/urls.py | Python | agpl-3.0 | 1,178 |
/*
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
* Copyright (c) 2016-2017 metaverse core developers (see MVS-AUTHORS)
*
* This file is part of metaverse.
*
* metaverse is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <metaverse/bitcoin/message/alert.hpp>
#include <boost/iostreams/stream.hpp>
#include <metaverse/bitcoin/message/version.hpp>
#include <metaverse/bitcoin/utility/assert.hpp>
#include <metaverse/bitcoin/utility/container_sink.hpp>
#include <metaverse/bitcoin/utility/container_source.hpp>
#include <metaverse/bitcoin/utility/istream_reader.hpp>
#include <metaverse/bitcoin/utility/ostream_writer.hpp>
namespace libbitcoin {
namespace message {
const std::string alert::command = "alert";
const uint32_t alert::version_minimum = version::level::minimum;
const uint32_t alert::version_maximum = version::level::maximum;
alert alert::factory_from_data(uint32_t version, const data_chunk& data)
{
alert instance;
instance.from_data(version, data);
return instance;
}
alert alert::factory_from_data(uint32_t version, std::istream& stream)
{
alert instance;
instance.from_data(version, stream);
return instance;
}
alert alert::factory_from_data(uint32_t version, reader& source)
{
alert instance;
instance.from_data(version, source);
return instance;
}
bool alert::is_valid() const
{
return !payload.empty() || !signature.empty();
}
void alert::reset()
{
payload.clear();
payload.shrink_to_fit();
signature.clear();
signature.shrink_to_fit();
}
bool alert::from_data(uint32_t version, const data_chunk& data)
{
boost::iostreams::stream<byte_source<data_chunk>> istream(data);
return from_data(version, istream);
}
bool alert::from_data(uint32_t version, std::istream& stream)
{
istream_reader source(stream);
return from_data(version, source);
}
bool alert::from_data(uint32_t version, reader& source)
{
reset();
auto size = source.read_variable_uint_little_endian();
BITCOIN_ASSERT(size <= bc::max_size_t);
const auto payload_size = static_cast<size_t>(size);
size_t signature_size = 0;
auto result = static_cast<bool>(source);
if (result)
{
payload = source.read_data(payload_size);
result = source && (payload.size() == payload_size);
}
if (result)
{
size = source.read_variable_uint_little_endian();
BITCOIN_ASSERT(size <= bc::max_size_t);
signature_size = static_cast<size_t>(size);
result = source;
}
if (result)
{
signature = source.read_data(signature_size);
result = source && (signature.size() == signature_size);
}
if (!result)
reset();
return result;
}
data_chunk alert::to_data(uint32_t version) const
{
data_chunk data;
boost::iostreams::stream<byte_sink<data_chunk>> ostream(data);
to_data(version, ostream);
ostream.flush();
BITCOIN_ASSERT(data.size() == serialized_size(version));
return data;
}
void alert::to_data(uint32_t version, std::ostream& stream) const
{
ostream_writer sink(stream);
to_data(version, sink);
}
void alert::to_data(uint32_t version, writer& sink) const
{
sink.write_variable_uint_little_endian(payload.size());
sink.write_data(payload);
sink.write_variable_uint_little_endian(signature.size());
sink.write_data(signature);
}
uint64_t alert::serialized_size(uint32_t version) const
{
return variable_uint_size(payload.size()) + payload.size() +
variable_uint_size(signature.size()) + signature.size();
}
bool operator==(const alert& left, const alert& right)
{
bool result = (left.payload.size() == right.payload.size()) &&
(left.signature.size() == right.signature.size());
for (size_t i = 0; i < left.payload.size() && result; i++)
result = (left.payload[i] == right.payload[i]);
for (size_t i = 0; i < left.signature.size() && result; i++)
result = (left.signature[i] == right.signature[i]);
return result;
}
bool operator!=(const alert& left, const alert& right)
{
return !(left == right);
}
} // end message
} // end libbitcoin
| sikamedia/metaverse | src/lib/bitcoin/message/alert.cpp | C++ | agpl-3.0 | 4,834 |
module BABYLON {
export class Animation {
private _keys: Array<any>;
private _offsetsCache = {};
private _highLimitsCache = {};
private _stopped = false;
public _target;
private _easingFunction: IEasingFunction;
public targetPropertyPath: string[];
public currentFrame: number;
public static CreateAndStartAnimation(name: string, mesh: AbstractMesh, tartgetProperty: string,
framePerSecond: number, totalFrame: number,
from: any, to: any, loopMode?: number) {
var dataType = undefined;
if (!isNaN(parseFloat(from)) && isFinite(from)) {
dataType = Animation.ANIMATIONTYPE_FLOAT;
} else if (from instanceof Quaternion) {
dataType = Animation.ANIMATIONTYPE_QUATERNION;
} else if (from instanceof Vector3) {
dataType = Animation.ANIMATIONTYPE_VECTOR3;
} else if (from instanceof Vector2) {
dataType = Animation.ANIMATIONTYPE_VECTOR2;
} else if (from instanceof Color3) {
dataType = Animation.ANIMATIONTYPE_COLOR3;
}
if (dataType == undefined) {
return null;
}
var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
var keys = [];
keys.push({ frame: 0, value: from });
keys.push({ frame: totalFrame, value: to });
animation.setKeys(keys);
mesh.animations.push(animation);
return mesh.getScene().beginAnimation(mesh, 0, totalFrame,(animation.loopMode === 1));
}
constructor(public name: string, public targetProperty: string, public framePerSecond: number, public dataType: number, public loopMode?: number) {
this.targetPropertyPath = targetProperty.split(".");
this.dataType = dataType;
this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
}
// Methods
public isStopped(): boolean {
return this._stopped;
}
public getKeys(): any[] {
return this._keys;
}
public getEasingFunction() {
return this._easingFunction;
}
public setEasingFunction(easingFunction: EasingFunction) {
this._easingFunction = easingFunction;
}
public floatInterpolateFunction(startValue: number, endValue: number, gradient: number): number {
return startValue + (endValue - startValue) * gradient;
}
public quaternionInterpolateFunction(startValue: Quaternion, endValue: Quaternion, gradient: number): Quaternion {
return Quaternion.Slerp(startValue, endValue, gradient);
}
public vector3InterpolateFunction(startValue: Vector3, endValue: Vector3, gradient: number): Vector3 {
return Vector3.Lerp(startValue, endValue, gradient);
}
public vector2InterpolateFunction(startValue: Vector2, endValue: Vector2, gradient: number): Vector2 {
return Vector2.Lerp(startValue, endValue, gradient);
}
public color3InterpolateFunction(startValue: Color3, endValue: Color3, gradient: number): Color3 {
return Color3.Lerp(startValue, endValue, gradient);
}
public matrixInterpolateFunction(startValue: Matrix, endValue: Matrix, gradient: number): Matrix {
var startScale = new Vector3(0, 0, 0);
var startRotation = new Quaternion();
var startTranslation = new Vector3(0, 0, 0);
startValue.decompose(startScale, startRotation, startTranslation);
var endScale = new Vector3(0, 0, 0);
var endRotation = new Quaternion();
var endTranslation = new Vector3(0, 0, 0);
endValue.decompose(endScale, endRotation, endTranslation);
var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
var result = Matrix.Compose(resultScale, resultRotation, resultTranslation);
return result;
}
public clone(): Animation {
var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
clone.setKeys(this._keys);
return clone;
}
public setKeys(values: Array<any>): void {
this._keys = values.slice(0);
this._offsetsCache = {};
this._highLimitsCache = {};
}
private _getKeyValue(value: any): any {
if (typeof value === "function") {
return value();
}
return value;
}
private _interpolate(currentFrame: number, repeatCount: number, loopMode: number, offsetValue?, highLimitValue?) {
if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
}
this.currentFrame = currentFrame;
// Try to get a hash to find the right key
var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
if (this._keys[startKey].frame >= currentFrame) {
while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
startKey--;
}
}
for (var key = startKey; key < this._keys.length ; key++) {
if (this._keys[key + 1].frame >= currentFrame) {
var startValue = this._getKeyValue(this._keys[key].value);
var endValue = this._getKeyValue(this._keys[key + 1].value);
// gradient : percent of currentFrame between the frame inf and the frame sup
var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
// check for easingFunction and correction of gradient
if (this._easingFunction != null) {
gradient = this._easingFunction.ease(gradient);
}
switch (this.dataType) {
// Float
case Animation.ANIMATIONTYPE_FLOAT:
switch (loopMode) {
case Animation.ANIMATIONLOOPMODE_CYCLE:
case Animation.ANIMATIONLOOPMODE_CONSTANT:
return this.floatInterpolateFunction(startValue, endValue, gradient);
case Animation.ANIMATIONLOOPMODE_RELATIVE:
return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
}
break;
// Quaternion
case Animation.ANIMATIONTYPE_QUATERNION:
var quaternion = null;
switch (loopMode) {
case Animation.ANIMATIONLOOPMODE_CYCLE:
case Animation.ANIMATIONLOOPMODE_CONSTANT:
quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
break;
case Animation.ANIMATIONLOOPMODE_RELATIVE:
quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
break;
}
return quaternion;
// Vector3
case Animation.ANIMATIONTYPE_VECTOR3:
switch (loopMode) {
case Animation.ANIMATIONLOOPMODE_CYCLE:
case Animation.ANIMATIONLOOPMODE_CONSTANT:
return this.vector3InterpolateFunction(startValue, endValue, gradient);
case Animation.ANIMATIONLOOPMODE_RELATIVE:
return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
}
// Vector2
case Animation.ANIMATIONTYPE_VECTOR2:
switch (loopMode) {
case Animation.ANIMATIONLOOPMODE_CYCLE:
case Animation.ANIMATIONLOOPMODE_CONSTANT:
return this.vector2InterpolateFunction(startValue, endValue, gradient);
case Animation.ANIMATIONLOOPMODE_RELATIVE:
return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
}
// Color3
case Animation.ANIMATIONTYPE_COLOR3:
switch (loopMode) {
case Animation.ANIMATIONLOOPMODE_CYCLE:
case Animation.ANIMATIONLOOPMODE_CONSTANT:
return this.color3InterpolateFunction(startValue, endValue, gradient);
case Animation.ANIMATIONLOOPMODE_RELATIVE:
return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
}
// Matrix
case Animation.ANIMATIONTYPE_MATRIX:
switch (loopMode) {
case Animation.ANIMATIONLOOPMODE_CYCLE:
case Animation.ANIMATIONLOOPMODE_CONSTANT:
// return this.matrixInterpolateFunction(startValue, endValue, gradient);
case Animation.ANIMATIONLOOPMODE_RELATIVE:
return startValue;
}
default:
break;
}
break;
}
}
return this._getKeyValue(this._keys[this._keys.length - 1].value);
}
public animate(delay: number, from: number, to: number, loop: boolean, speedRatio: number): boolean {
if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
this._stopped = true;
return false;
}
var returnValue = true;
// Adding a start key at frame 0 if missing
if (this._keys[0].frame !== 0) {
var newKey = { frame: 0, value: this._keys[0].value };
this._keys.splice(0, 0, newKey);
}
// Check limits
if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
from = this._keys[0].frame;
}
if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
to = this._keys[this._keys.length - 1].frame;
}
// Compute ratio
var range = to - from;
var offsetValue;
// ratio represents the frame delta between from and to
var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
var highLimitValue = 0;
if (ratio > range && !loop) { // If we are out of range and not looping get back to caller
returnValue = false;
highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
} else {
// Get max value if required
if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
var keyOffset = to.toString() + from.toString();
if (!this._offsetsCache[keyOffset]) {
var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
switch (this.dataType) {
// Float
case Animation.ANIMATIONTYPE_FLOAT:
this._offsetsCache[keyOffset] = toValue - fromValue;
break;
// Quaternion
case Animation.ANIMATIONTYPE_QUATERNION:
this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
break;
// Vector3
case Animation.ANIMATIONTYPE_VECTOR3:
this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
// Vector2
case Animation.ANIMATIONTYPE_VECTOR2:
this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
// Color3
case Animation.ANIMATIONTYPE_COLOR3:
this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
default:
break;
}
this._highLimitsCache[keyOffset] = toValue;
}
highLimitValue = this._highLimitsCache[keyOffset];
offsetValue = this._offsetsCache[keyOffset];
}
}
if (offsetValue === undefined) {
switch (this.dataType) {
// Float
case Animation.ANIMATIONTYPE_FLOAT:
offsetValue = 0;
break;
// Quaternion
case Animation.ANIMATIONTYPE_QUATERNION:
offsetValue = new Quaternion(0, 0, 0, 0);
break;
// Vector3
case Animation.ANIMATIONTYPE_VECTOR3:
offsetValue = Vector3.Zero();
break;
// Vector2
case Animation.ANIMATIONTYPE_VECTOR2:
offsetValue = Vector2.Zero();
break;
// Color3
case Animation.ANIMATIONTYPE_COLOR3:
offsetValue = Color3.Black();
}
}
// Compute value
var repeatCount = (ratio / range) >> 0;
var currentFrame = returnValue ? from + ratio % range : to;
var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
// Set value
if (this.targetPropertyPath.length > 1) {
var property = this._target[this.targetPropertyPath[0]];
for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
property = property[this.targetPropertyPath[index]];
}
property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
} else {
this._target[this.targetPropertyPath[0]] = currentValue;
}
if (this._target.markAsDirty) {
this._target.markAsDirty(this.targetProperty);
}
if (!returnValue) {
this._stopped = true;
}
return returnValue;
}
// Statics
private static _ANIMATIONTYPE_FLOAT = 0;
private static _ANIMATIONTYPE_VECTOR3 = 1;
private static _ANIMATIONTYPE_QUATERNION = 2;
private static _ANIMATIONTYPE_MATRIX = 3;
private static _ANIMATIONTYPE_COLOR3 = 4;
private static _ANIMATIONTYPE_VECTOR2 = 5;
private static _ANIMATIONLOOPMODE_RELATIVE = 0;
private static _ANIMATIONLOOPMODE_CYCLE = 1;
private static _ANIMATIONLOOPMODE_CONSTANT = 2;
public static get ANIMATIONTYPE_FLOAT(): number {
return Animation._ANIMATIONTYPE_FLOAT;
}
public static get ANIMATIONTYPE_VECTOR3(): number {
return Animation._ANIMATIONTYPE_VECTOR3;
}
public static get ANIMATIONTYPE_VECTOR2(): number {
return Animation._ANIMATIONTYPE_VECTOR2;
}
public static get ANIMATIONTYPE_QUATERNION(): number {
return Animation._ANIMATIONTYPE_QUATERNION;
}
public static get ANIMATIONTYPE_MATRIX(): number {
return Animation._ANIMATIONTYPE_MATRIX;
}
public static get ANIMATIONTYPE_COLOR3(): number {
return Animation._ANIMATIONTYPE_COLOR3;
}
public static get ANIMATIONLOOPMODE_RELATIVE(): number {
return Animation._ANIMATIONLOOPMODE_RELATIVE;
}
public static get ANIMATIONLOOPMODE_CYCLE(): number {
return Animation._ANIMATIONLOOPMODE_CYCLE;
}
public static get ANIMATIONLOOPMODE_CONSTANT(): number {
return Animation._ANIMATIONLOOPMODE_CONSTANT;
}
}
}
| brosnanyuen/Project-S | Babylon.js-master/Babylon/Animations/babylon.animation.ts | TypeScript | agpl-3.0 | 17,965 |
//
//{block name="backend/create_backend_order/view/toolbar"}
//
Ext.define('Shopware.apps.SwagBackendOrder.view.main.Toolbar', {
extend: 'Ext.toolbar.Toolbar',
alternateClassName: 'SwagBackendOrder.view.main.Toolbar',
alias: 'widget.createbackendorder-toolbar',
dock: 'top',
ui: 'shopware-ui',
padding: '0 10 0 10',
snippets: {
buttons: {
openCustomer: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/button/open_customer"}Open Customer{/s}',
createCustomer: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/button/create_customer"}Create Customer{/s}',
createGuest: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/button/create_guest"}Create Guest{/s}'
},
shop: {
noCustomer: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/shop/label/no_costumer"}Shop: No customer selected.{/s}',
default: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/shop/label/default"}Shop: {/s}'
},
currencyLabel: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/currency/label"}Choose currency{/s}',
languageLabel: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/language/label"}Language{/s}'
},
/**
*
*/
initComponent: function () {
var me = this;
me.items = me.createToolbarItems();
me.languageStore = Ext.create('Ext.data.Store', {
name: 'languageStore',
fields: ['id', 'mainId', 'categoryId', 'name', 'title', 'default']
});
/**
* automatically selects the standard currency
*/
me.currencyStore = me.subApplication.getStore('Currency');
me.currencyStore.on('load', function () {
me.changeCurrencyComboBox.bindStore(me.currencyStore);
var standardCurrency = me.currencyStore.findExact('default', 1);
if (standardCurrency > -1) {
me.currencyModel = me.currencyStore.getAt(standardCurrency);
me.changeCurrencyComboBox.select(me.currencyModel);
me.currencyModel.set('selected', 1);
} else {
me.changeCurrencyComboBox.select(me.currencyStore.first());
me.currencyStore.first().set('selected', 1);
}
});
me.customerSearchField.on('valueselect', function () {
me.openCustomerButton.setDisabled(false);
});
//selects and loads the language sub shops
var customerStore = me.subApplication.getStore('Customer');
customerStore.on('load', function () {
if (typeof customerStore.getAt(0) !== 'undefined') {
var shopName = '',
customerModel = customerStore.getAt(0);
var languageId = customerModel.get('languageId');
var index = customerModel.languageSubShop().findExact('id', languageId);
if (index >= 0) {
shopName = customerModel.languageSubShop().getAt(index).get('name');
} else {
index = customerModel.shop().findExact('id', languageId);
shopName = customerModel.shop().getAt(index).get('name');
}
me.shopLabel.setText(me.snippets.shop.default + shopName);
me.fireEvent('changeCustomer');
me.getLanguageShops(customerModel.shop().getAt(0).get('id'), customerStore.getAt(0).get('languageId'));
}
});
me.callParent(arguments);
},
/**
* register the events
*/
registerEvents: function () {
this.addEvents(
'changeSearchField'
)
},
/**
* creates the top toolbar items
*
* @returns []
*/
createToolbarItems: function () {
var me = this;
me.customerSearchField = me.createCustomerSearch('customerName', 'id', 'email');
me.createCustomerButton = Ext.create('Ext.button.Button', {
text: me.snippets.buttons.createCustomer,
handler: function () {
me.fireEvent('createCustomer', false);
}
});
me.createGuestButton = Ext.create('Ext.button.Button', {
text: me.snippets.buttons.createGuest,
handler: function () {
me.fireEvent('createCustomer', true);
}
});
me.openCustomerButton = Ext.create('Ext.button.Button', {
text: me.snippets.buttons.openCustomer,
disabled: true,
margin: '0 30 0 0',
handler: function () {
me.fireEvent('openCustomer');
}
});
me.shopLabel = Ext.create('Ext.form.Label', {
text: me.snippets.shop.noCustomer,
style: {
fontWeight: 'bold'
}
});
me.languageComboBox = Ext.create('Ext.form.field.ComboBox', {
fieldLabel: me.snippets.languageLabel,
labelWidth: 65,
store: me.languageStore,
queryMode: 'local',
displayField: 'name',
width: '20%',
valueField: 'id',
listeners: {
change: {
fn: function (comboBox, newValue, oldValue, eOpts) {
me.fireEvent('changeLanguage', newValue);
}
}
}
});
me.changeCurrencyComboBox = Ext.create('Ext.form.field.ComboBox', {
fieldLabel: me.snippets.currencyLabel,
stores: me.currencyStore,
queryMode: 'local',
displayField: 'currency',
width: '20%',
valueField: 'id',
listeners: {
change: {
fn: function (comboBox, newValue, oldValue, eOpts) {
me.fireEvent('changeCurrency', comboBox, newValue, oldValue, eOpts);
}
}
}
});
return [
me.changeCurrencyComboBox, me.languageComboBox, me.shopLabel, '->',
me.createCustomerButton, me.createGuestButton, me.openCustomerButton, me.customerSearchField
];
},
/**
*
* @param returnValue
* @param hiddenReturnValue
* @param name
* @return Shopware.form.field.ArticleSearch
*/
createCustomerSearch: function (returnValue, hiddenReturnValue, name) {
var me = this;
me.customerStore = me.subApplication.getStore('Customer');
return Ext.create('Shopware.apps.SwagBackendOrder.view.main.CustomerSearch', {
name: name,
subApplication: me.subApplication,
returnValue: returnValue,
hiddenReturnValue: hiddenReturnValue,
articleStore: me.customerStore,
allowBlank: false,
getValue: function () {
me.store.getAt(me.record.rowIdx).set(name, this.getSearchField().getValue());
return this.getSearchField().getValue();
},
setValue: function (value) {
this.getSearchField().setValue(value);
}
});
},
/**
* @param mainShopId
* @param languageId
*/
getLanguageShops: function (mainShopId, languageId) {
var me = this;
Ext.Ajax.request({
url: '{url action="getLanguageSubShops"}',
params: {
mainShopId: mainShopId
},
success: function (response) {
me.languageStore.removeAll();
var languageSubShops = Ext.JSON.decode(response.responseText);
languageSubShops.data.forEach(function (record) {
me.languageStore.add(record);
});
me.languageComboBox.bindStore(me.languageStore);
//selects the default language shop
var languageIndex = me.languageStore.findExact('mainId', null);
me.languageComboBox.setValue(languageId);
}
});
}
});
//
//{/block}
// | GerDner/luck-docker | engine/Shopware/Plugins/Default/Backend/SwagBackendOrder/Views/backend/swag_backend_order/view/main/toolbar.js | JavaScript | agpl-3.0 | 8,411 |
/**
* This file is part of mycollab-services.
*
* mycollab-services is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* mycollab-services is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with mycollab-services. If not, see <http://www.gnu.org/licenses/>.
*/
package com.esofthead.mycollab.module.crm.service.ibatis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.esofthead.mycollab.common.interceptor.aspect.Auditable;
import com.esofthead.mycollab.common.interceptor.aspect.Traceable;
import com.esofthead.mycollab.core.persistence.ICrudGenericDAO;
import com.esofthead.mycollab.core.persistence.ISearchableDAO;
import com.esofthead.mycollab.core.persistence.service.DefaultService;
import com.esofthead.mycollab.module.crm.dao.ProductMapper;
import com.esofthead.mycollab.module.crm.dao.ProductMapperExt;
import com.esofthead.mycollab.module.crm.domain.Product;
import com.esofthead.mycollab.module.crm.domain.criteria.ProductSearchCriteria;
import com.esofthead.mycollab.module.crm.service.ProductService;
@Service
@Transactional
public class ProductServiceImpl extends DefaultService<Integer, Product, ProductSearchCriteria>
implements ProductService {
@Autowired
private ProductMapper productMapper;
@Autowired
private ProductMapperExt productMapperExt;
@Override
public ICrudGenericDAO<Integer, Product> getCrudMapper() {
return productMapper;
}
@Override
public ISearchableDAO<ProductSearchCriteria> getSearchMapper() {
return productMapperExt;
}
}
| uniteddiversity/mycollab | mycollab-services/src/main/java/com/esofthead/mycollab/module/crm/service/ibatis/ProductServiceImpl.java | Java | agpl-3.0 | 2,122 |
/*
* jHears, acoustic fingerprinting framework.
* Copyright (C) 2009-2010 Juha Heljoranta.
*
* This file is part of jHears.
*
* jHears is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* jHears is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with jHears. If not, see <http://www.gnu.org/licenses/>.
*/
/**
*
*/
package org.jhears.server;
import java.util.Map;
public interface IUser {
String getName();
Long getId();
Map<String, String> getProperties();
} | inter6/jHears | jhears-server/src/main/java/org/jhears/server/IUser.java | Java | agpl-3.0 | 950 |
<?php
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
//Vardef Handler Object
class VarDefHandler {
var $meta_array_name;
var $target_meta_array = false;
var $start_none = false;
var $extra_array = array(); //used to add custom items
var $options_array = array();
var $module_object;
var $start_none_lbl = null;
function VarDefHandler(& $module, $meta_array_name=null){
$this->module_object = $module;
if($meta_array_name!=null){
global $vardef_meta_array;
include("include/VarDefHandler/vardef_meta_arrays.php");
$this->target_meta_array = $vardef_meta_array[$meta_array_name];
}
//end function setup
}
function get_vardef_array($use_singular=false, $remove_dups = false, $use_field_name = false, $use_field_label = false){
global $dictionary;
global $current_language;
global $app_strings;
global $app_list_strings;
$temp_module_strings = return_module_language($current_language, $this->module_object->module_dir);
$base_array = $this->module_object->field_defs;
//$base_array = $dictionary[$this->module_object->object_name]['fields'];
///Inclue empty none set or not
if($this->start_none==true){
if(!empty($this->start_none_lbl)){
$this->options_array[''] = $this->start_none_lbl;
} else {
$this->options_array[''] = $app_strings['LBL_NONE'];
}
}
///used for special one off items added to filter array ex. would be href link for alert templates
if(!empty($this->extra_array)){
foreach($this->extra_array as $key => $value){
$this->options_array[$key] = $value;
}
}
/////////end special one off//////////////////////////////////
foreach($base_array as $key => $value_array){
$compare_results = $this->compare_type($value_array);
if($compare_results == true){
$label_name = '';
if($value_array['type'] == 'link' && !$use_field_label){
$this->module_object->load_relationship($value_array['name']);
if(!empty($app_list_strings['moduleList'][$this->module_object->$value_array['name']->getRelatedModuleName()])){
$label_name = $app_list_strings['moduleList'][$this->module_object->$value_array['name']->getRelatedModuleName()];
}else{
$label_name = $this->module_object->$value_array['name']->getRelatedModuleName();
}
}
else if(!empty($value_array['vname'])){
$label_name = $value_array['vname'];
} else {
$label_name = $value_array['name'];
}
$label_name = get_label($label_name, $temp_module_strings);
if(!empty($value_array['table'])){
//Custom Field
$column_table = $value_array['table'];
} else {
//Non-Custom Field
$column_table = $this->module_object->table_name;
}
if($value_array['type'] == 'link'){
if($use_field_name){
$index = $value_array['name'];
}else{
$index = $this->module_object->$key->getRelatedModuleName();
}
}else{
$index = $key;
}
$value = trim($label_name, ':');
if($remove_dups){
if(!in_array($value, $this->options_array))
$this->options_array[$index] = $value;
}
else
$this->options_array[$index] = $value;
//end if field is included
}
//end foreach
}
if($use_singular == true){
return convert_module_to_singular($this->options_array);
} else {
return $this->options_array;
}
//end get_vardef_array
}
function compare_type($value_array){
//Filter nothing?
if(!is_array($this->target_meta_array)){
return true;
}
////////Use the $target_meta_array;
if(isset($this->target_meta_array['inc_override'])){
foreach($this->target_meta_array['inc_override'] as $attribute => $value){
foreach($value as $actual_value){
if(isset($value_array[$attribute]) && $value_array[$attribute] == $actual_value) return true;
}
if(isset($value_array[$attribute]) && $value_array[$attribute] == $value) return true;
}
}
if(isset($this->target_meta_array['ex_override'])){
foreach($this->target_meta_array['ex_override'] as $attribute => $value){
foreach($value as $actual_value){
if(isset($value_array[$attribute]) && $value_array[$attribute] == $actual_value) return false;
if(isset($value_array[$attribute]) && $value_array[$attribute] == $value) return false;
}
//end foreach inclusion array
}
}
if(isset($this->target_meta_array['inclusion'])){
foreach($this->target_meta_array['inclusion'] as $attribute => $value){
if($attribute=="type"){
foreach($value as $actual_value){
if(isset($value_array[$attribute]) && $value_array[$attribute] != $actual_value) return false;
}
} else {
if(isset($value_array[$attribute]) && $value_array[$attribute] != $value) return false;
}
//end foreach inclusion array
}
}
if(isset($this->target_meta_array['exclusion'])){
foreach($this->target_meta_array['exclusion'] as $attribute => $value){
foreach($value as $actual_value){
if ( $attribute == 'reportable' ) {
if ( $actual_value == 'true' ) $actual_value = 1;
if ( $actual_value == 'false' ) $actual_value = 0;
}
if(isset($value_array[$attribute]) && $value_array[$attribute] == $actual_value) return false;
}
//end foreach inclusion array
}
}
return true;
//end function compare_type
}
//end class VarDefHandler
}
?>
| minh10huy/HiringBossCRM | include/VarDefHandler/VarDefHandler.php | PHP | agpl-3.0 | 7,729 |
/*
* Copyright (C) 2000 - 2021 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "https://www.silverpeas.org/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.silverpeas.core.pdc.pdc.model;
import org.silverpeas.core.pdc.pdc.service.PdcManager;
import org.silverpeas.core.pdc.tree.model.TreeNode;
import org.silverpeas.core.persistence.datasource.model.CompositeEntityIdentifier;
import org.silverpeas.core.persistence.datasource.model.jpa.BasicJpaEntity;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Spliterator;
import java.util.function.Consumer;
/**
* A value of one of the PdC's axis. A value belongs to an axis. An axis represents a given concept
* for which it defines an hierarchic tree of semantic terms belonging to the concept. A value of
* an axis is then the path from the axis origin down to a given node of the tree, where each node
* is a term refining or specifying the parent term a little more. For example, for an axis
* representing the concept of geography, one possible value can be
* "France / Rhônes-Alpes / Isère / Grenoble" where France, Rhônes-Alpes, Isère and Grenoble are
* each a term (thus a node) in the axis.
* "France" is another value, parent of the above one, and that is also a base value of the axis as
* it has no parent (one of the root values of the axis).
*/
@Entity
@Table(name = "pdcaxisvalue")
@NamedQuery(name = "findByAxisId", query = "from PdcAxisValue where axisId = :axisId")
public class PdcAxisValue extends BasicJpaEntity<PdcAxisValue, PdcAxisValuePk> {
private static final long serialVersionUID = 2345886411781136417L;
@Transient
private transient TreeNode treeNode;
@Transient
private transient TreeNodeList treeNodeParents = new TreeNodeList();
protected PdcAxisValue() {
}
/**
* Creates a value of a PdC's axis from the specified tree node. Currently, an axis of the PdC is
* persisted as an hierarchical tree in which each node is a value of the axis.
* @param treeNode the current persistence representation of the axis value.
* @return a PdC axis value.
*/
public static PdcAxisValue aPdcAxisValueFromTreeNode(final TreeNode treeNode) {
try {
List<? extends TreeNode> parents = null;
if (treeNode.hasFather()) {
PdcManager pdcManager = getPdcManager();
parents = pdcManager.getFullPath(treeNode.getFatherId(), treeNode.getTreeId());
}
return new PdcAxisValue().fromTreeNode(treeNode).withAsTreeNodeParents(parents).
inAxisId(treeNode.getTreeId());
} catch (PdcException ex) {
throw new PdcRuntimeException(ex);
}
}
/**
* Creates a value of a PdC's axis from the specified value information. Currently, an axis of the
* PdC is persisted as an hierarchical tree in which each node is a value of the axis. The
* parameters refers the unique identifier of the node and in the tree related to the axis
* identifier.
* @param valueId the unique identifier of the existing value.
* @param axisId the unique identifier of the axis the value belongs to.
* @return a PdC axis value.
*/
public static PdcAxisValue aPdcAxisValue(String valueId, String axisId) {
return new PdcAxisValue().setId(
valueId + CompositeEntityIdentifier.COMPOSITE_SEPARATOR + axisId);
}
/**
* Gets the unique identifier of the axis to which this value belongs to.
* @return the unique identifier of the axis value.
*/
public String getAxisId() {
return getNativeId().getAxisId().toString();
}
/**
* Gets the unique value identifier.
* @return the unique value identifier.
*/
public String getValueId() {
return getNativeId().getValueId().toString();
}
/**
* Gets all the values into which this one can be refined or specifying in a little more. Theses
* values are the children of this one in the semantic tree represented by the axis to which this
* value belongs.
* @return an unmodifiable set of values that are children of this one. If this value is a leaf,
* then an empty set is returned.
*/
public Set<PdcAxisValue> getChildValues() {
try {
Set<PdcAxisValue> children = new HashSet<>();
List<String> childNodeIds = getPdcManager().getDaughterValues(getAxisId(), getValueId());
for (String aNodeId : childNodeIds) {
children.add(aPdcAxisValue(aNodeId, getAxisId()));
}
return Collections.unmodifiableSet(children);
} catch (PdcException ex) {
throw new PdcRuntimeException(ex);
}
}
/**
* Gets the value this one refines or specifies a little more. The returned value is the parent
* of this one in the semantic tree represented by the axis to which this value belongs.
* @return the axis value parent of this one or null if this value has no parent (in that case,
* this value is a base one).
*/
public PdcAxisValue getParentValue() {
final PdcAxisValue parent;
TreeNode node = getTreeNode();
if (node.hasFather()) {
int lastNodeIndex = treeNodeParents.size() - 1;
TreeNode aTreeNode = treeNodeParents.get(lastNodeIndex);
String valueId = aTreeNode.getPK().getId();
String axisId = getAxisId();
PdcAxisValue pdcAxisValue = new PdcAxisValue().setId(
valueId + CompositeEntityIdentifier.COMPOSITE_SEPARATOR + axisId);
parent =
pdcAxisValue.fromTreeNode(aTreeNode).inAxisId(getAxisId())
.withAsTreeNodeParents(treeNodeParents.subList(0, lastNodeIndex));
} else {
parent = null;
}
return parent;
}
/**
* Gets the term carried by this value.
* @return the term of the value.
*/
public String getTerm() {
return getTreeNode().getName();
}
/**
* Gets the term carried by this value and translated in the specified language.
* @param language the language in which the term should be translated.
* @return the term translated in the specified language. If no such translation exists, then
* return the default term as get by calling getTerm() method.
*/
public String getTermTranslatedIn(String language) {
return getTreeNode().getName(language);
}
/**
* Is this value is a base one?
* @return true if this value is an axis base value.
*/
public boolean isBaseValue() {
// as the root in the tree represents the axis itself, a base value is a direct children of the
// root.
return getTreeNodeParents().size() <= 1;
}
/**
* Gets the meaning carried by this value. The meaning is in fact the complete path of terms that
* made this value. For example, in an axis representing the geography, the meaning of the value
* "France / Rhônes-Alpes / Isère" is "Geography / France / Rhônes-Alpes / Isère".
* @return the meaning carried by this value, in other words the complete path of this value.
*/
public String getMeaning() {
return getMeaningTranslatedIn("");
}
/**
* Gets the meaning carried by this value translated in the specified language. The meaning is in
* fact the complete path of translated terms that made this value. For example, in an axis
* representing the geography, the meaning of the value "France / Rhônes-Alpes / Isère" is in
* french "Geographie / France / Rhônes-Alpes / Isère".
* @return the meaning carried by this value, in other words the complete path of this value
* translated in the specified language. If no such translations exist, then the result is
* equivalent to the call of the getMeaning() method.
*/
public String getMeaningTranslatedIn(String language) {
final String meaning;
final String theLanguage = (language == null ? "" : language);
PdcAxisValue theParent = getParentValue();
if (theParent != null) {
meaning = theParent.getMeaningTranslatedIn(theLanguage) + " / ";
} else {
meaning = "";
}
return meaning + getTerm();
}
/**
* Gets the path of this value from the root value (that is a base value of the axis). The path
* is
* made up of the identifiers of each parent value; for example : /0/2/3
* @return the path of its value.
*/
public String getValuePath() {
return getTreeNode().getPath() + getValueId();
}
/**
* Copies this value into another one. In fact, the attributes of the copy refers to the same
* object referred by the attributes of this instance.
* @return a copy of this PdC axis value.
*/
protected PdcAxisValue copy() {
PdcAxisValue copy = PdcAxisValue.aPdcAxisValue(getValueId(), getAxisId());
copy.treeNode = treeNode;
copy.treeNodeParents = treeNodeParents;
return copy;
}
/**
* Gets the axis to which this value belongs to and that is used to classify contents on the PdC.
* @return a PdC axis configured to be used in the classification of contents.
*/
protected UsedAxis getUsedAxis() {
try {
PdcManager pdc = getPdcManager();
UsedAxis usedAxis = pdc.getUsedAxis(getAxisId());
AxisHeader axisHeader = pdc.getAxisHeader(getAxisId());
usedAxis._setAxisHeader(axisHeader);
usedAxis._setAxisName(axisHeader.getName());
return usedAxis;
} catch (PdcException ex) {
throw new PdcRuntimeException(ex);
}
}
/**
* Gets the persisted representation of this axis value. By the same way, the parents of this
* tree node are also set.
* @return a tree node representing this axis value in the persistence layer.
*/
protected TreeNode getTreeNode() {
if (this.treeNode == null || (this.treeNodeParents == null && this.treeNode.hasFather())) {
loadTreeNodes();
}
return this.treeNode;
}
protected void setId(long id) {
getNativeId().setValueId(id);
}
protected PdcAxisValue withId(String id) {
getNativeId().setValueId(Long.valueOf(id));
return this;
}
protected PdcAxisValue inAxisId(String axisId) {
getNativeId().setAxisId(Long.valueOf(axisId));
return this;
}
protected PdcAxisValue fromTreeNode(final TreeNode treeNode) {
getNativeId().setValueId(Long.valueOf(treeNode.getPK().getId()));
this.treeNode = treeNode;
return this;
}
protected PdcAxisValue withAsTreeNodeParents(final List<? extends TreeNode> parents) {
this.treeNodeParents.setAll(parents);
return this;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final PdcAxisValue other = (PdcAxisValue) obj;
if (this.getNativeId().getValueId() != other.getNativeId().getValueId() &&
(this.getNativeId().getValueId() == null ||
!this.getNativeId().getValueId().equals(other.getNativeId().getValueId()))) {
return false;
}
return this.getNativeId().getAxisId() == other.getNativeId().getAxisId() ||
(this.getNativeId().getAxisId() != null &&
!this.getNativeId().getAxisId().equals(other.getNativeId().getAxisId()));
}
@Override
public int hashCode() {
int hash = 5;
hash = 89 * hash +
(this.getNativeId().getValueId() != null ? this.getNativeId().getValueId().hashCode() : 0);
hash = 89 * hash +
(this.getNativeId().getAxisId() != null ? this.getNativeId().getAxisId().hashCode() : 0);
return hash;
}
@Override
public String toString() {
return "";
}
/**
* Converts this PdC axis value to a ClassifyValue instance. This method is for compatibility
* with the old way to manage the classification.
* @return a ClassifyValue instance.
* @throws PdcException if an error occurs while transforming this value into a ClassifyValue
* instance.
*/
public ClassifyValue toClassifyValue() {
ClassifyValue value = new ClassifyValue(Integer.valueOf(getAxisId()), getValuePath() + "/");
List<Value> fullPath = new ArrayList<>();
for (TreeNode aTreeNode : getTreeNodeParents()) {
fullPath.add(new Value(aTreeNode.getPK().getId(), aTreeNode.getTreeId(), aTreeNode.getName(),
aTreeNode.getDescription(), aTreeNode.getCreationDate(), aTreeNode.getCreatorId(),
aTreeNode.getPath(), aTreeNode.getLevelNumber(), aTreeNode.
getOrderNumber(), aTreeNode.getFatherId()));
}
TreeNode lastValue = getTreeNode();
fullPath.add(new Value(lastValue.getPK().getId(), lastValue.getTreeId(), lastValue.getName(),
lastValue.getDescription(), lastValue.getCreationDate(), lastValue.getCreatorId(),
lastValue.getPath(), lastValue.getLevelNumber(), lastValue.getOrderNumber(),
lastValue.getFatherId()));
value.setFullPath(fullPath);
return value;
}
protected TreeNodeList getTreeNodeParents() {
if (this.treeNodeParents == null) {
loadTreeNodes();
}
return this.treeNodeParents;
}
private void loadTreeNodes() {
try {
PdcManager pdc = getPdcManager();
String treeId = pdc.getTreeId(getAxisId());
List<? extends TreeNode> paths = pdc.getFullPath(getValueId(), treeId);
int lastNodeIndex = paths.size() - 1;
this.treeNode = paths.get(lastNodeIndex);
this.treeNodeParents.setAll(paths.subList(0, lastNodeIndex));
} catch (PdcException ex) {
throw new PdcRuntimeException(ex);
}
}
private static PdcManager getPdcManager() {
return PdcManager.get();
}
private class TreeNodeList implements Iterable<TreeNode> {
private final List<TreeNode> treeNodes = new ArrayList<>();
public int size() {
return treeNodes.size();
}
public TreeNode get(final int index) {
return treeNodes.get(index);
}
public List<TreeNode> subList(final int fromIndex, final int toIndex) {
return treeNodes.subList(fromIndex, toIndex);
}
public void setAll(final Collection<? extends TreeNode> nodes) {
this.treeNodes.clear();
this.treeNodes.addAll(nodes);
}
@Override
public Iterator<TreeNode> iterator() {
return this.treeNodes.iterator();
}
@Override
public void forEach(final Consumer<? super TreeNode> action) {
this.treeNodes.forEach(action);
}
@Override
public Spliterator<TreeNode> spliterator() {
return this.treeNodes.spliterator();
}
}
}
| SilverDav/Silverpeas-Core | core-services/pdc/src/main/java/org/silverpeas/core/pdc/pdc/model/PdcAxisValue.java | Java | agpl-3.0 | 15,496 |
## Device Admin user stories
#### Install app on device
#### Register app with right instance
#### Sign in to app
#### Create, update, delete enumerator users on the app
#### Clean data from the app
#### Check daily work of enumerators
#### Manual backup of data
#### Manual upload of data
| akvo/akvo-product-design | FLOW/UseCases/FieldManager.md | Markdown | agpl-3.0 | 298 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/transitional.dtd">
<html><head>
<meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="estilos.css" />
<title> Indice de Ley Orgánica de Educación Enmarcada en los Derechos Humanos, como contribució en EDUCERE</title>
</head><body>
<div id="container">
<div id="pageHeader">
</div>
<div id="pageContehome">
<center><big><a href="../index.html">Indices EDUCERE</a><br></big></center>
<entry>
<number>
811<br> </number>
<results>
<titulo>
Ley Orgánica de Educación Enmarcada en los Derechos Humanos<br> </titulo>
<subtitulo>
-- <br> </subtitulo>
<autores>
[[Trejo Urquiola, Walter]]<br> </autores>
<titulo>
<a href="http://www.saber.ula.ve/handle/123456789/19615">http://www.saber.ula.ve/handle/123456789/19615</a><br> <creado>
2001-07-01<br> </creado>
</titulo>
<results>
<div></div>
<h2 align="center">La frase: Ley Orgánica de Educación Enmarcada en los Derechos Humanos</h2>
<h3 align="center">Produjo 7 resultados</h3>
<table align="center" border="1" width="100%">
<tr><th>Relevancia</th><th>Archivo (URL implicito)</th><th>Tama�o (en Bytes)</th></tr>
<tr><td>1000</td><td><a href=".%2fpdfs%2fv12n41%2farticulo14.pdf">articulo14.pdf</a></td><td><em>2380231</em></td></tr>
<tr><td>930</td><td><a href=".%2fpdfs%2fv5n14%2farticulo11.pdf">articulo11.pdf</a></td><td><em>77241</em></td></tr>
<tr><td>848</td><td><a href=".%2fpdfs%2fv11n36%2farticulo17.pdf">articulo17.pdf</a></td><td><em>875718</em></td></tr>
<tr><td>822</td><td><a href=".%2fpdfs%2fv3n8%2farticulo3-8-11.pdf">articulo3-8-11.pdf</a></td><td><em>755003</em></td></tr>
<tr><td>819</td><td><a href=".%2fpdfs%2fv6n17%2farticulo18.pdf">articulo18.pdf</a></td><td><em>363494</em></td></tr>
<tr><td>794</td><td><a href=".%2fpdfs%2fv13n45%2farticulo11.pdf">articulo11.pdf</a></td><td><em>301176</em></td></tr>
<tr><td>768</td><td><a href=".%2fpdfs%2fv5n16%2farticulo7.pdf">articulo7.pdf</a></td><td><em>408479</em></td></tr>
</table>
</results>
</entry>
</div>
<div id="footer"><p>EDUCERE. La Revista Venezolana de Educación Escuela de Educación. <br/>
Facultad de Humanidades y Educación Universidad de Los Andes,<br/>
Mérida - Venezuela<br/>
<br/>
<br/>
</p>
</div>
</div>
</body>
</html>
| jacintodavila/catalogoelectronicoautonomo | ceaWeb/indices/t00811.html | HTML | agpl-3.0 | 2,338 |
package io.github.jhg543.mellex.operation;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import io.github.jhg543.mellex.ASTHelper.*;
import io.github.jhg543.mellex.antlrparser.DefaultSQLBaseListener;
import io.github.jhg543.mellex.antlrparser.DefaultSQLLexer;
import io.github.jhg543.mellex.antlrparser.DefaultSQLParser;
import io.github.jhg543.mellex.antlrparser.DefaultSQLParser.Sql_stmtContext;
import io.github.jhg543.mellex.inputsource.BasicTableDefinitionProvider;
import io.github.jhg543.mellex.inputsource.TableDefinitionProvider;
import io.github.jhg543.mellex.listeners.ColumnDataFlowListener;
import io.github.jhg543.mellex.util.Misc;
import io.github.jhg543.nyallas.graphmodel.*;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
public class StringEdgePrinter {
private static final Logger log = LoggerFactory.getLogger(StringEdgePrinter.class);
private static int ERR_NOSQL = 1;
private static int ERR_PARSE = 2;
private static int ERR_SEMANTIC = 3;
private static int ERR_OK = 0;
private static int printSingleFile(Path srcdir, Path dstdir, int scriptNumber, TableDefinitionProvider tp) {
// generate a hash to mark vt table names
String srcHash = Integer.toHexString(srcdir.hashCode());
// create destination dir
try {
Files.createDirectories(dstdir);
} catch (IOException e) {
throw new RuntimeException(e);
}
try (PrintWriter err = new PrintWriter(dstdir.resolve("log").toAbsolutePath().toString(), "utf-8")) {
// trim perl code
String sql = Misc.trimPerlScript(srcdir, StandardCharsets.UTF_8);
if (sql == null) {
err.println("Can't extract sql from file " + srcdir.toString());
return ERR_NOSQL;
}
// log actual sql statement ( for corrent line number ..)
try (PrintWriter writer = new PrintWriter(dstdir.resolve("sql").toAbsolutePath().toString(), "utf-8")) {
writer.append(sql);
}
// antlr parse
AtomicInteger errorCount = new AtomicInteger();
ANTLRInputStream in = new ANTLRInputStream(sql);
DefaultSQLLexer lexer = new DefaultSQLLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
DefaultSQLParser parser = new DefaultSQLParser(tokens);
parser.removeErrorListeners();
parser.addErrorListener(new BaseErrorListener() {
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine,
String msg, RecognitionException e) {
err.println("line" + line + ":" + charPositionInLine + "at" + offendingSymbol + ":" + msg);
errorCount.incrementAndGet();
}
});
err.println("-------Parse start---------");
ParseTree tree = null;
try {
tree = parser.parse();
if (errorCount.get() > 0) {
return ERR_PARSE;
}
} catch (Exception e) {
e.printStackTrace(err);
return ERR_PARSE;
}
err.println("-------Parse OK, Semantic Analysis start --------");
ParseTreeWalker w = new ParseTreeWalker();
try {
ColumnDataFlowListener s = new ColumnDataFlowListener(tp, tokens);
w.walk(s, tree);
} catch (Exception e) {
e.printStackTrace(err);
return ERR_SEMANTIC;
}
err.println("-------Semantic OK, Writing result --------");
// Remove volatile tables
VolatileTableRemover graph = new VolatileTableRemover();
// DAG dag = new DAG();
// ZeroBasedStringIdGenerator ids = new
// ZeroBasedStringIdGenerator();
Map<String, Vertex<String, Integer>> vmap = new HashMap<>();
// Output result and initialize volatile tables removal process
try (PrintWriter out = new PrintWriter(dstdir.resolve("out").toAbsolutePath().toString(), "utf-8")) {
out.println("ScriptID StmtID StmtType DestCol SrcCol ConnectionType");
String template = "%d %d %s %s.%s %s.%s %d\n";
DefaultSQLBaseListener pr = new DefaultSQLBaseListener() {
int stmtNumber = 0;
@Override
public void exitSql_stmt(Sql_stmtContext ctx) {
super.exitSql_stmt(ctx);
String stmtType = null;
SubQuery q = null;
if (ctx.insert_stmt() != null) {
stmtType = "I";
q = ctx.insert_stmt().stmt;
}
if (ctx.create_table_stmt() != null) {
if (ctx.create_table_stmt().insert != null) {
stmtType = "C";
q = ctx.create_table_stmt().insert;
}
}
if (ctx.create_view_stmt() != null) {
stmtType = "V";
q = ctx.create_view_stmt().insert;
}
if (ctx.update_stmt() != null) {
stmtType = "U";
q = ctx.update_stmt().q;
}
if (q != null) {
// what's vt's scope?
Set<String> vts = tp.getVolatileTables().keySet();
String dstTable = q.dbobj.toDotString();
boolean isDstVT = vts.contains(dstTable);
if (isDstVT) {
dstTable = "VT_" + srcHash + "_" + dstTable;
}
for (ResultColumn c : q.columns) {
for (InfSource source : c.inf.getSources()) {
ObjectName srcname = source.getSourceObject();
String srcTable = srcname.toDotStringExceptLast();
boolean isSrcVT = vts.contains(srcTable);
if (isSrcVT) {
srcTable = "VT_" + srcHash + "_" + srcTable;
}
out.append(String.format(template, scriptNumber, stmtNumber, stmtType, dstTable, c.name,
srcTable, srcname.toDotStringLast(), source.getConnectionType().getMarker()));
// collapse volatile table
String dst = dstTable + "." + c.name;
String src = srcTable + "." + srcname.toDotStringLast();
// Integer dstnum = ids.queryNumber(dst);
// Integer srcnum = ids.queryNumber(src);
Vertex<String, Integer> srcv;
srcv = vmap.get(src);
if (srcv == null) {
srcv = graph.addVertex(BasicVertex::new);
vmap.put(src, srcv);
srcv.setVertexData(src);
if (isSrcVT) {
srcv.setMarker(0);
}
}
Vertex<String, Integer> dstv;
dstv = vmap.get(dst);
if (dstv == null) {
dstv = graph.addVertex(BasicVertex::new);
vmap.put(dst, dstv);
dstv.setVertexData(dst);
if (isDstVT) {
dstv.setMarker(0);
}
}
Edge<String, Integer> edge = new BasicEdge<String, Integer>(srcv, dstv);
edge.setEdgeData(source.getConnectionType().getMarker());
graph.addEdge(edge);
}
}
} else {
// log.warn("query null for sm " + stmtNumber);
}
stmtNumber++;
}
};
w.walk(pr, tree);
}
// Int2ObjectMap<Node> collapsed = dag.collapse(scriptNumber);
graph.remove();
// write result (with volatile tables removed)
try (PrintWriter out = new PrintWriter(dstdir.resolve("novt").toAbsolutePath().toString(), "utf-8")) {
out.println("scriptid,dstsch,dsttbl,dstcol,srcsch,srctbl,srccol,contype");
String template = "%d,%s,%s,%s,%s,%s,%s,%d\n";
for (Vertex<String, Integer> v : graph.getVertexes()) {
for (Edge<String, Integer> e : v.getOutgoingEdges()) {
String dst = e.getTarget().getVertexData();
String src = e.getSource().getVertexData();
List<String> t1 = Splitter.on('.').splitToList(dst);
if (t1.size() == 2) {
t1 = new ArrayList<String>(t1);
t1.add(0, "3X_NOSCHEMA_" + scriptNumber);
}
List<String> t2 = Splitter.on('.').splitToList(src);
if (t2.size() == 2) {
t2 = new ArrayList<String>(t1);
t2.add(0, "3X_NOSCHEMA_" + scriptNumber);
}
out.append(String.format(template, scriptNumber, t1.get(0), t1.get(1), t1.get(2), t2.get(0), t2.get(1),
t2.get(2), e.getEdgeData()));
}
}
}
tp.clearVolatileTables();
err.println("-------Success --------");
return 0;
} catch (FileNotFoundException | UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public static int[] printStringEdge(Path srcdir, Path dstdir, Predicate<Path> filefilter, int scriptNumberStart,
boolean caseSensitive) {
// ensure directories exist
Preconditions.checkState(Files.isDirectory(srcdir));
try {
Files.createDirectories(dstdir);
} catch (IOException e1) {
throw new RuntimeException(e1);
}
// set up variables
GlobalSettings.setCaseSensitive(caseSensitive);
AtomicInteger scriptNumber = new AtomicInteger(scriptNumberStart);
TableDefinitionProvider tp = new BasicTableDefinitionProvider(Misc::nameSym);
int[] stats = new int[10];
// open global output files
try (PrintWriter out = new PrintWriter(dstdir.resolve("stats").toAbsolutePath().toString(), "utf-8");
PrintWriter cols = new PrintWriter(dstdir.resolve("cols").toAbsolutePath().toString(), "utf-8");
PrintWriter numbers = new PrintWriter(dstdir.resolve("number").toAbsolutePath().toString(), "utf-8")) {
// for each file
Files.walk(srcdir).filter(filefilter).sorted().forEach(path -> {
int sn = scriptNumber.getAndIncrement();
numbers.println("" + sn + " " + path.toString());
String srcHash = Integer.toHexString(path.hashCode());
Path workdir = dstdir.resolve(path.getFileName()).resolve(srcHash);
// deal with single files.
int retcode = printSingleFile(path, workdir, sn, tp);
if (retcode > 0) {
out.println(String.format("%s %d %d", path.toString(), retcode, sn));
}
stats[retcode]++;
});
out.println("OK=" + stats[ERR_OK]);
out.println("NOSQL=" + stats[ERR_NOSQL]);
out.println("PARSE=" + stats[ERR_PARSE]);
out.println("SEMANTIC=" + stats[ERR_SEMANTIC]);
tp.getPermanentTables().forEach((name, stmt) -> {
stmt.columns.forEach(colname -> cols.println(name + "." + colname.name));
});
return stats;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws Exception {
Predicate<Path> filefilter = x -> Files.isRegularFile(x)
&& (x.getFileName().toString().toLowerCase().endsWith(".sql") || x.getFileName().toString().toLowerCase()
.endsWith(".pl"))
&& x.toString().toUpperCase().endsWith("BIN\\" + x.getFileName().toString().toUpperCase());
// printStringEdge(Paths.get("d:/dataflow/work1/script/mafixed"),
// Paths.get("d:/dataflow/work2/mares"), filefilter, 0, false);
printStringEdge(Paths.get("d:/dataflow/work1/debug"), Paths.get("d:/dataflow/work2/debugres"), filefilter, 0, false);
// printStringEdge(Paths.get("d:/dataflow/work1/f1/sor"),
// Paths.get("d:/dataflow/work2/result2/sor"), filefilter, 0, false);
}
}
| jhg543/mellex | src/main/java/io/github/jhg543/mellex/operation/StringEdgePrinter.java | Java | agpl-3.0 | 11,043 |
require 'open_food_network/referer_parser'
module Admin
class EnterprisesController < ResourceController
before_filter :load_enterprise_set, :only => :index
before_filter :load_countries, :except => [:index, :register, :check_permalink]
before_filter :load_methods_and_fees, :only => [:new, :edit, :update, :create]
before_filter :load_groups, :only => [:new, :edit, :update, :create]
before_filter :load_taxons, :only => [:new, :edit, :update, :create]
before_filter :check_can_change_sells, only: :update
before_filter :check_can_change_bulk_sells, only: :bulk_update
before_filter :override_owner, only: :create
before_filter :override_sells, only: :create
before_filter :check_can_change_owner, only: :update
before_filter :check_can_change_bulk_owner, only: :bulk_update
before_filter :check_can_change_managers, only: :update
before_filter :strip_new_properties, only: [:create, :update]
before_filter :load_properties, only: [:edit, :update]
before_filter :setup_property, only: [:edit]
helper 'spree/products'
include ActionView::Helpers::TextHelper
include OrderCyclesHelper
def index
respond_to do |format|
format.html
format.json do
render json: @collection, each_serializer: Api::Admin::IndexEnterpriseSerializer, spree_current_user: spree_current_user
end
end
end
def welcome
render layout: "spree/layouts/bare_admin"
end
def update
invoke_callbacks(:update, :before)
if @object.update_attributes(params[object_name])
invoke_callbacks(:update, :after)
flash[:success] = flash_message_for(@object, :successfully_updated)
respond_with(@object) do |format|
format.html { redirect_to location_after_save }
format.js { render :layout => false }
format.json { render json: @object, serializer: Api::Admin::IndexEnterpriseSerializer, spree_current_user: spree_current_user }
end
else
invoke_callbacks(:update, :fails)
respond_with(@object) do |format|
format.json { render json: { errors: @object.errors.messages }, status: :unprocessable_entity }
end
end
end
def register
if params[:sells] == 'unspecified'
flash[:error] = "Please select a package"
return render :welcome, layout: "spree/layouts/bare_admin"
end
attributes = { sells: params[:sells], visible: true }
if ['own', 'any'].include? params[:sells]
attributes[:shop_trial_start_date] = @enterprise.shop_trial_start_date || Time.now
end
if @enterprise.update_attributes(attributes)
flash[:success] = "Congratulations! Registration for #{@enterprise.name} is complete!"
redirect_to admin_path
else
flash[:error] = "Could not complete registration for #{@enterprise.name}"
render :welcome, layout: "spree/layouts/bare_admin"
end
end
def bulk_update
@enterprise_set = EnterpriseSet.new(collection, params[:enterprise_set])
touched_enterprises = @enterprise_set.collection.select(&:changed?)
if @enterprise_set.save
flash[:success] = "Enterprises updated successfully"
# 18-3-2015: It seems that the form for this action sometimes loads bogus values for
# the 'sells' field, and submitting that form results in a bunch of enterprises with
# values that have mysteriously changed. This statement is here to help debug that
# issue, and should be removed (along with its display in index.html.haml) when the
# issue has been resolved.
flash[:action] = "Updated #{pluralize(touched_enterprises.count, 'enterprise')}: #{touched_enterprises.map(&:name).join(', ')}"
redirect_to main_app.admin_enterprises_path
else
@enterprise_set.collection.select! { |e| touched_enterprises.include? e }
flash[:error] = 'Update failed'
render :index
end
end
def for_order_cycle
respond_to do |format|
format.json do
render json: ActiveModel::ArraySerializer.new( @collection,
each_serializer: Api::Admin::ForOrderCycle::EnterpriseSerializer, spree_current_user: spree_current_user
).to_json
end
end
end
protected
def build_resource_with_address
enterprise = build_resource_without_address
enterprise.address = Spree::Address.new
enterprise.address.country = Spree::Country.find_by_id(Spree::Config[:default_country_id])
enterprise
end
alias_method_chain :build_resource, :address
# Overriding method on Spree's resource controller,
# so that resources are found using permalink
def find_resource
Enterprise.find_by_permalink(params[:id])
end
private
def load_enterprise_set
@enterprise_set = EnterpriseSet.new(collection) if spree_current_user.admin?
end
def load_countries
@countries = Spree::Country.order(:name)
end
def collection
case action
when :for_order_cycle
order_cycle = OrderCycle.find_by_id(params[:order_cycle_id]) if params[:order_cycle_id]
coordinator = Enterprise.find_by_id(params[:coordinator_id]) if params[:coordinator_id]
order_cycle = OrderCycle.new(coordinator: coordinator) if order_cycle.nil? && coordinator.present?
return OpenFoodNetwork::OrderCyclePermissions.new(spree_current_user, order_cycle).visible_enterprises
when :index
if spree_current_user.admin?
OpenFoodNetwork::Permissions.new(spree_current_user).
editable_enterprises.
order('is_primary_producer ASC, name')
elsif json_request?
OpenFoodNetwork::Permissions.new(spree_current_user).editable_enterprises
else
Enterprise.where("1=0") unless json_request?
end
else
# TODO was ordered with is_distributor DESC as well, not sure why or how we want to sort this now
OpenFoodNetwork::Permissions.new(spree_current_user).
editable_enterprises.
order('is_primary_producer ASC, name')
end
end
def collection_actions
[:index, :for_order_cycle, :bulk_update]
end
def load_methods_and_fees
@payment_methods = Spree::PaymentMethod.managed_by(spree_current_user).sort_by!{ |pm| [(@enterprise.payment_methods.include? pm) ? 0 : 1, pm.name] }
@shipping_methods = Spree::ShippingMethod.managed_by(spree_current_user).sort_by!{ |sm| [(@enterprise.shipping_methods.include? sm) ? 0 : 1, sm.name] }
@enterprise_fees = EnterpriseFee.managed_by(spree_current_user).for_enterprise(@enterprise).order(:fee_type, :name).all
end
def load_groups
@groups = EnterpriseGroup.managed_by(spree_current_user) | @enterprise.groups
end
def load_taxons
@taxons = Spree::Taxon.order(:name)
end
def check_can_change_bulk_sells
unless spree_current_user.admin?
params[:enterprise_set][:collection_attributes].each do |i, enterprise_params|
enterprise_params.delete :sells unless spree_current_user == Enterprise.find_by_id(enterprise_params[:id]).owner
end
end
end
def check_can_change_sells
unless spree_current_user.admin? || spree_current_user == @enterprise.owner
params[:enterprise].delete :sells
end
end
def override_owner
params[:enterprise][:owner_id] = spree_current_user.id unless spree_current_user.admin?
end
def override_sells
unless spree_current_user.admin?
has_hub = spree_current_user.owned_enterprises.is_hub.any?
new_enterprise_is_producer = Enterprise.new(params[:enterprise]).is_primary_producer
params[:enterprise][:sells] = (has_hub && !new_enterprise_is_producer) ? 'any' : 'none'
end
end
def check_can_change_owner
unless ( spree_current_user == @enterprise.owner ) || spree_current_user.admin?
params[:enterprise].delete :owner_id
end
end
def check_can_change_bulk_owner
unless spree_current_user.admin?
params[:enterprise_set][:collection_attributes].each do |i, enterprise_params|
enterprise_params.delete :owner_id
end
end
end
def check_can_change_managers
unless ( spree_current_user == @enterprise.owner ) || spree_current_user.admin?
params[:enterprise].delete :user_ids
end
end
def strip_new_properties
unless spree_current_user.admin? || params[:enterprise][:producer_properties_attributes].nil?
names = Spree::Property.pluck(:name)
params[:enterprise][:producer_properties_attributes].each do |key, property|
params[:enterprise][:producer_properties_attributes].delete key unless names.include? property[:property_name]
end
end
end
def load_properties
@properties = Spree::Property.pluck(:name)
end
def setup_property
@enterprise.producer_properties.build
end
# Overriding method on Spree's resource controller
def location_after_save
referer_path = OpenFoodNetwork::RefererParser::path(request.referer)
refered_from_edit = referer_path == main_app.edit_admin_enterprise_path(@enterprise)
if params[:enterprise].key?(:producer_properties_attributes) && !refered_from_edit
main_app.admin_enterprises_path
else
main_app.edit_admin_enterprise_path(@enterprise)
end
end
end
end
| stveep/openfoodnetwork | app/controllers/admin/enterprises_controller.rb | Ruby | agpl-3.0 | 9,547 |
# Slight modification from: https://nodejs.org/en/docs/guides/nodejs-docker-webapp/
# Assumes there is Orchestrator like Nomad to handle process dying :P
FROM node:boron
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Copy source code over (including package.json)
COPY ./Code /usr/src/app
# and Yarn it
# and Set the right permission
RUN yarn && chown -R node:node .
# Copy the Top Secret ENV
COPY env-example /usr/src/app/.env
USER node
CMD [ "npm", "start" ]
EXPOSE 3000
| leowmjw/playground-docker | nodejs-express-env/Dockerfile | Dockerfile | agpl-3.0 | 484 |
---
"layout": contract
"datum podpisu": 2020-07-01
"datum účinnosti": 2020-07-01
"datum ukončení": 0000-00-00
"title": "NDA - Blanka Lednická"
"použité smluvní typy":
- NDA
"předmět": "Dohoda o ochraně důvěrných informací"
"stav": V plnění
"náklady": 0
"místo uložení": Centrální spisovna
"smluvní strany":
-
"jméno": "Blanka Lednická"
"bydliště": Olešná
"narozen": 1980
"orgán": Česká pirátská strana
"zástupce": Aleš Krupa
"funkce": Vedoucí kanceláře - Česká pirátská strana
"soubory":
-
"podepsaná verze": nda_lednicka.pdf
---
| pirati-web/smlouvy.pirati.cz | smlouvy/2020/07/01/NDA-Lednicka/index.html | HTML | agpl-3.0 | 593 |
package com.neverwinterdp.scribengin.dataflow.example.wire;
import java.util.Properties;
import com.neverwinterdp.message.Message;
import com.neverwinterdp.scribengin.dataflow.DataSet;
import com.neverwinterdp.scribengin.dataflow.Dataflow;
import com.neverwinterdp.scribengin.dataflow.DataflowDescriptor;
import com.neverwinterdp.scribengin.dataflow.DataflowSubmitter;
import com.neverwinterdp.scribengin.dataflow.KafkaDataSet;
import com.neverwinterdp.scribengin.dataflow.KafkaWireDataSetFactory;
import com.neverwinterdp.scribengin.dataflow.Operator;
import com.neverwinterdp.scribengin.shell.ScribenginShell;
import com.neverwinterdp.storage.kafka.KafkaStorageConfig;
import com.neverwinterdp.util.JSONSerializer;
import com.neverwinterdp.vm.client.VMClient;
public class ExampleWireDataflowSubmitter {
private String dataflowID;
private int defaultReplication;
private int defaultParallelism;
private int numOfWorker;
private int numOfExecutorPerWorker;
private String inputTopic;
private String outputTopic;
private ScribenginShell shell;
private DataflowSubmitter submitter;
private String localAppHome;
private String dfsAppHome;
public ExampleWireDataflowSubmitter(ScribenginShell shell){
this(shell, new Properties());
}
/**
* Constructor - sets shell to access Scribengin and configuration properties
* @param shell ScribenginShell to connect to Scribengin with
* @param props Properties to configure the dataflow
*/
public ExampleWireDataflowSubmitter(ScribenginShell shell, Properties props){
//This it the shell to communicate with Scribengin with
this.shell = shell;
//The dataflow's ID. All dataflows require a unique ID when running
dataflowID = props.getProperty("dataflow.id", "WireDataflow");
//The default replication factor for Kafka
defaultReplication = Integer.parseInt(props.getProperty("dataflow.replication", "1"));
//The number of DataStreams to deploy
defaultParallelism = Integer.parseInt(props.getProperty("dataflow.parallelism", "2"));
//The number of workers to deploy (i.e. YARN containers)
numOfWorker = Integer.parseInt(props.getProperty("dataflow.numWorker", "5"));
//The number of executors per worker (i.e. threads per YARN container)
numOfExecutorPerWorker = Integer.parseInt(props.getProperty("dataflow.numExecutorPerWorker", "5"));
//The kafka input topic
inputTopic = props.getProperty("dataflow.inputTopic", "input.topic");
//The kafka output topic
outputTopic = props.getProperty("dataflow.outputTopic", "output.topic");
//The example hdfs dataflow local location
localAppHome = props.getProperty("dataflow.localapphome", "N/A");
//DFS location to upload the example dataflow
dfsAppHome = props.getProperty("dataflow.dfsAppHome", "/applications/dataflow/splitterexample");
}
/**
* The logic to submit the dataflow
* @param kafkaZkConnect [host]:[port] of Kafka's Zookeeper conenction
* @throws Exception
*/
public void submitDataflow(String kafkaZkConnect) throws Exception{
//Upload the dataflow to HDFS
VMClient vmClient = shell.getScribenginClient().getVMClient();
vmClient.uploadApp(localAppHome, dfsAppHome);
Dataflow dfl = buildDataflow(kafkaZkConnect);
//Get the dataflow's descriptor
DataflowDescriptor dflDescriptor = dfl.buildDataflowDescriptor();
//Output the descriptor in human-readable JSON
System.out.println(JSONSerializer.INSTANCE.toString(dflDescriptor));
//Ensure all your sources and sinks are up and running first, then...
//Submit the dataflow and wait until it starts running
submitter = new DataflowSubmitter(shell.getScribenginClient(), dfl).submit().waitForDataflowRunning(60000);
}
/**
* Wait for the dataflow to complete within the given timeout
* @param timeout Timeout in ms
* @throws Exception
*/
public void waitForDataflowCompletion(int timeout) throws Exception{
submitter.waitForDataflowStop(timeout);
}
/**
* The logic to build the dataflow configuration
* The main takeaway between this dataflow and the ExampleSimpleDataflowSubmitter
* is the use of dfl.useWireDataSetFactory()
* This factory allows us to tie together operators
* with Kafka topics between them
* @param kafkaZkConnect [host]:[port] of Kafka's Zookeeper conenction
* @return
*/
public Dataflow buildDataflow(String kafkaZkConnect){
//Create the new Dataflow object
// <Message,Message> pertains to the <input,output> object for the data
Dataflow dfl = new Dataflow(dataflowID);
//Example of how to set the KafkaWireDataSetFactory
dfl.
setDefaultParallelism(defaultParallelism).
setDefaultReplication(defaultReplication).
useWireDataSetFactory(new KafkaWireDataSetFactory(kafkaZkConnect));
dfl.getWorkerDescriptor().setNumOfInstances(numOfWorker);
dfl.getWorkerDescriptor().setNumOfExecutor(numOfExecutorPerWorker);
//Define our input source - set name, ZK host:port, and input topic name
KafkaDataSet<Message> inputDs =
dfl.createInput(new KafkaStorageConfig("input", kafkaZkConnect, inputTopic));
//Define our output sink - set name, ZK host:port, and output topic name
DataSet<Message> outputDs =
dfl.createOutput(new KafkaStorageConfig("output", kafkaZkConnect, outputTopic));
//Define which operators to use.
//This will be the logic that ties the datasets and operators together
Operator splitter = dfl.createOperator("splitteroperator", SplitterDataStreamOperator.class);
Operator odd = dfl.createOperator("oddoperator", PersisterDataStreamOperator.class);
Operator even = dfl.createOperator("evenoperator", PersisterDataStreamOperator.class);
//Send all input to the splitter operator
inputDs.useRawReader().connect(splitter);
//The splitter operator then connects to the odd and even operators
splitter.connect(odd)
.connect(even);
//Both the odd and even operator connect to the output dataset
// This is arbitrary, we could connect them to any dataset or operator we wanted
odd.connect(outputDs);
even.connect(outputDs);
return dfl;
}
public String getDataflowID() { return dataflowID; }
public String getInputTopic() { return inputTopic; }
public String getOutputTopic() { return outputTopic; }
} | DemandCube/NeverwinterDP | scribengin/dataflow/example/src/main/java/com/neverwinterdp/scribengin/dataflow/example/wire/ExampleWireDataflowSubmitter.java | Java | agpl-3.0 | 6,521 |
package com.gmail.nossr50.commands.party;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.commands.CommandHelper;
import com.gmail.nossr50.datatypes.PlayerProfile;
import com.gmail.nossr50.events.chat.McMMOPartyChatEvent;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.Party;
import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.Users;
public class PCommand implements CommandExecutor {
private final mcMMO plugin;
public PCommand (mcMMO plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
PlayerProfile profile;
String usage = ChatColor.RED + "Proper usage is /p <party-name> <message>"; //TODO: Needs more locale.
if (CommandHelper.noCommandPermissions(sender, "mcmmo.commands.party")) {
return true;
}
switch (args.length) {
case 0:
if (sender instanceof Player) {
profile = Users.getProfile((Player) sender);
if (profile.getAdminChatMode()) {
profile.toggleAdminChat();
}
profile.togglePartyChat();
if (profile.getPartyChatMode()) {
sender.sendMessage(LocaleLoader.getString("Commands.Party.Chat.On"));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.Party.Chat.Off"));
}
}
else {
sender.sendMessage(usage);
}
return true;
default:
if (sender instanceof Player) {
Player player = (Player) sender;
Party party = Users.getProfile(player).getParty();
if (party == null) {
player.sendMessage(LocaleLoader.getString("Commands.Party.None"));
return true;
}
StringBuffer buffer = new StringBuffer();
buffer.append(args[0]);
for (int i = 1; i < args.length; i++) {
buffer.append(" ");
buffer.append(args[i]);
}
String message = buffer.toString();
McMMOPartyChatEvent chatEvent = new McMMOPartyChatEvent(player.getName(), party.getName(), message);
plugin.getServer().getPluginManager().callEvent(chatEvent);
if (chatEvent.isCancelled()) {
return true;
}
message = chatEvent.getMessage();
String prefix = ChatColor.GREEN + "(" + ChatColor.WHITE + player.getName() + ChatColor.GREEN + ") ";
plugin.getLogger().info("[P](" + party.getName() + ")" + "<" + player.getName() + "> " + message);
for (Player member : party.getOnlineMembers()) {
member.sendMessage(prefix + message);
}
}
else {
if (args.length < 2) {
sender.sendMessage(usage);
return true;
}
if (!PartyManager.getInstance().isParty(args[0])) {
sender.sendMessage(LocaleLoader.getString("Party.InvalidName"));
return true;
}
StringBuffer buffer = new StringBuffer();
buffer.append(args[1]);
for (int i = 2; i < args.length; i++) {
buffer.append(" ");
buffer.append(args[i]);
}
String message = buffer.toString();
McMMOPartyChatEvent chatEvent = new McMMOPartyChatEvent("Console", args[0], message);
plugin.getServer().getPluginManager().callEvent(chatEvent);
if (chatEvent.isCancelled()) {
return true;
}
message = chatEvent.getMessage();
String prefix = ChatColor.GREEN + "(" + ChatColor.WHITE + "*Console*" + ChatColor.GREEN + ") ";
plugin.getLogger().info("[P](" + args[0] + ")" + "<*Console*> " + message);
for (Player member : PartyManager.getInstance().getOnlineMembers(args[0])) {
member.sendMessage(prefix + message);
}
}
return true;
}
}
}
| javalangSystemwin/mcMMOPlus | src/main/java/com/gmail/nossr50/commands/party/PCommand.java | Java | agpl-3.0 | 4,799 |
DELETE FROM `weenie` WHERE `class_Id` = 46553;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (46553, 'ace46553-oyoroisandals', 2, '2019-02-10 00:00:00') /* Clothing */;
INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`)
VALUES (46553, 1, 2) /* ItemType - Armor */
, (46553, 4, 65536) /* ClothingPriority - Feet */
, (46553, 5, 420) /* EncumbranceVal */
, (46553, 9, 384) /* ValidLocations - LowerLegWear, FootWear */
, (46553, 10, 384) /* CurrentWieldedLocation - LowerLegWear, FootWear */
, (46553, 16, 1) /* ItemUseable - No */
, (46553, 19, 70) /* Value */
, (46553, 28, 660) /* ArmorLevel */
, (46553, 33, 1) /* Bonded - Bonded */
, (46553, 93, 1044) /* PhysicsState - Ethereal, IgnoreCollisions, Gravity */
, (46553, 106, 100) /* ItemSpellcraft */
, (46553, 107, 0) /* ItemCurMana */
, (46553, 108, 1000) /* ItemMaxMana */
, (46553, 109, 0) /* ItemDifficulty */
, (46553, 158, 7) /* WieldRequirements - Level */
, (46553, 159, 1) /* WieldSkillType - Axe */
, (46553, 160, 180) /* WieldDifficulty */
, (46553, 265, 14) /* EquipmentSetId - Adepts */
, (46553, 8041, 101) /* PCAPRecordedPlacement - Resting */;
INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`)
VALUES (46553, 22, True ) /* Inscribable */
, (46553, 100, True ) /* Dyable */;
INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`)
VALUES (46553, 5, -0.033) /* ManaRate */
, (46553, 13, 2.9) /* ArmorModVsSlash */
, (46553, 14, 3.2) /* ArmorModVsPierce */
, (46553, 15, 2.9) /* ArmorModVsBludgeon */
, (46553, 16, 2.3) /* ArmorModVsCold */
, (46553, 17, 2.3) /* ArmorModVsFire */
, (46553, 18, 2.5) /* ArmorModVsAcid */
, (46553, 19, 2.3) /* ArmorModVsElectric */
, (46553, 165, 1) /* ArmorModVsNether */;
INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`)
VALUES (46553, 1, 'O-Yoroi Sandals') /* Name */;
INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`)
VALUES (46553, 1, 33554654) /* Setup */
, (46553, 3, 536870932) /* SoundTable */
, (46553, 6, 67108990) /* PaletteBase */
, (46553, 8, 100676025) /* Icon */
, (46553, 22, 872415275) /* PhysicsEffectTable */
, (46553, 8001, 2588696) /* PCAPRecordedWeenieHeader - Value, Usable, Wielder, ValidLocations, CurrentlyWieldedLocation, Priority, Burden */
, (46553, 8003, 18) /* PCAPRecordedObjectDesc - Inscribable, Attackable */
, (46553, 8005, 137217) /* PCAPRecordedPhysicsDesc - CSetup, STable, PeTable, AnimationFrame */;
INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`)
VALUES (46553, 8000, 2345789235) /* PCAPRecordedObjectIID */;
INSERT INTO `weenie_properties_spell_book` (`object_Id`, `spell`, `probability`)
VALUES (46553, 4391, 2) /* AcidBane8 */
, (46553, 4393, 2) /* BladeBane8 */
, (46553, 4397, 2) /* BludgeonBane8 */
, (46553, 4401, 2) /* FlameBane8 */
, (46553, 4403, 2) /* FrostBane8 */
, (46553, 4407, 2) /* Impenetrability8 */
, (46553, 4409, 2) /* LightningBane8 */
, (46553, 4412, 2) /* PiercingBane8 */
, (46553, 4700, 2) /* CANTRIPLIFEMAGICAPTITUDE3 */;
INSERT INTO `weenie_properties_palette` (`object_Id`, `sub_Palette_Id`, `offset`, `length`)
VALUES (46553, 67110021, 160, 8);
INSERT INTO `weenie_properties_texture_map` (`object_Id`, `index`, `old_Id`, `new_Id`)
VALUES (46553, 0, 83889344, 83895201)
, (46553, 0, 83887066, 83895202);
INSERT INTO `weenie_properties_anim_part` (`object_Id`, `index`, `animation_Id`)
VALUES (46553, 0, 16778416);
| LtRipley36706/ACE-World | Database/3-Core/9 WeenieDefaults/SQL/Clothing/Armor/46553 O-Yoroi Sandals.sql | SQL | agpl-3.0 | 3,955 |
import { TYPES } from 'core/app/types'
import { StateManager } from 'core/dialog'
import { ContainerModule, interfaces } from 'inversify'
import { DecisionEngine } from './decision-engine'
import { DialogEngine } from './dialog-engine'
import { FlowService } from './flow/flow-service'
import { FlowNavigator } from './flow/navigator'
import { InstructionFactory } from './instruction/factory'
import { InstructionProcessor } from './instruction/processor'
import { ActionStrategy, TransitionStrategy } from './instruction/strategy'
import { DialogJanitor } from './janitor'
export const DialogContainerModule = new ContainerModule((bind: interfaces.Bind) => {
bind<DialogEngine>(TYPES.DialogEngine)
.to(DialogEngine)
.inSingletonScope()
bind<DecisionEngine>(TYPES.DecisionEngine)
.to(DecisionEngine)
.inSingletonScope()
bind<FlowNavigator>(TYPES.FlowNavigator)
.to(FlowNavigator)
.inSingletonScope()
bind<FlowService>(TYPES.FlowService)
.to(FlowService)
.inSingletonScope()
bind<InstructionFactory>(TYPES.InstructionFactory)
.to(InstructionFactory)
.inSingletonScope()
bind<InstructionProcessor>(TYPES.InstructionProcessor)
.to(InstructionProcessor)
.inSingletonScope()
bind<ActionStrategy>(TYPES.ActionStrategy)
.to(ActionStrategy)
.inRequestScope()
bind<TransitionStrategy>(TYPES.TransitionStrategy)
.to(TransitionStrategy)
.inRequestScope()
bind<DialogJanitor>(TYPES.DialogJanitorRunner)
.to(DialogJanitor)
.inSingletonScope()
bind<StateManager>(TYPES.StateManager)
.to(StateManager)
.inSingletonScope()
})
| botpress/botpress | packages/bp/src/core/dialog/dialog.inversify.ts | TypeScript | agpl-3.0 | 1,613 |
/*
uSquare 1.0 - Universal Responsive Grid
Copyright (c) 2012 Br0 (shindiristudio.com)
Project site: http://codecanyon.net/
Project demo: http://shindiristudio.com/usquare/
*/
(function($) {
function uSquareItem(element, options) {
this.$item = $(element);
this.$parent = options.$parent;
this.options = options;
this.$trigger = this.$(options.trigger);
this.$close = this.$('.close');
this.$info = this.$(options.moreInfo);
this.$trigger_text = this.$trigger.find('.usquare_square_text_wrapper');
this.$usquare_about = this.$info.find('.usquare_about');
this.$trigger.on('click', $.proxy(this.show, this));
this.$close.on('click', $.proxy(this.close, this));
options.$overlay.on('click', $.proxy(this.close, this));
};
uSquareItem.prototype = {
show: function(e) {
e.preventDefault();
if (!this.$parent.data('in_trans'))
{
if (!this.$item.data('showed'))
{
this.$parent.data('in_trans', 1);
this.$item.data('showed', 1);
if (this.options.before_item_opening_callback) this.options.before_item_opening_callback(this.$item);
var item_position = this.$item.position();
var trigger_text_position;
var this_backup=this;
var moving=0;
if (item_position.top>0) // && this.$parent.width()>=640)
{
var parent_position=this.$parent.offset();
var parent_top = parent_position.top;
var non_visible_area=$(window).scrollTop()-parent_top;
var going_to=item_position.top;
if (non_visible_area>0)
{
var non_visible_row=Math.floor(non_visible_area/this.$item.height())+1;
going_to=this.$item.height()*non_visible_row;
going_to=item_position.top-going_to;
}
if (going_to>0) moving=1;
if (moving)
{
this.$item.data('moved', going_to);
var top_string='-'+going_to+'px';
var speed=this.options.opening_speed+(going_to/160)*100;
this.$item.animate({top: top_string}, speed, this.options.easing, function(){
trigger_text_position = this_backup.$item.height() - this_backup.$trigger_text.height();
this_backup.$trigger_text.data('top', trigger_text_position);
this_backup.$trigger_text.css('top', trigger_text_position);
this_backup.$trigger_text.css('bottom', 'auto');
this_backup.$trigger_text.animate({'top': 0}, 'slow');
});
}
}
if (!moving)
{
trigger_text_position = this_backup.$item.height() - this_backup.$trigger_text.height();
this_backup.$trigger_text.data('top', trigger_text_position);
this_backup.$trigger_text.css('top', trigger_text_position);
this_backup.$trigger_text.css('bottom', 'auto');
this_backup.$trigger_text.animate({'top': 0}, 'slow');
}
this.$item.addClass('usquare_block_selected');
var height_backup=this.$info.css('height');
this.$info.css('height', 0);
this.$info.show();
this.$usquare_about.mCustomScrollbar("update");
if (this.options.before_info_rolling_callback) this.options.before_info_rolling_callback(this.$item);
this.$info.animate({height:height_backup}, 'slow', this.options.easing, function()
{
this_backup.$parent.data('in_trans', 0);
if (this_backup.options.after_info_rolling_callback) this_backup.options.after_info_rolling_callback(this_backup.$item);
});
}
}
},
close: function(e) {
e.preventDefault();
if (!this.$parent.data('in_trans'))
{
if (this.$item.data('showed'))
{
var this_backup=this;
this.$info.hide();
var trigger_text_position_top = this_backup.$item.height() - this_backup.$trigger_text.height();
this_backup.$item.removeClass('usquare_block_selected');
if (this.$item.data('moved'))
{
var top_backup=this.$item.data('moved');
var speed=this.options.closing_speed+(top_backup/160)*100;
this.$item.data('moved', 0);
this.$item.animate({'top': 0}, speed, this.options.easing, function()
{
this_backup.$trigger_text.animate({'top': trigger_text_position_top}, 'slow');
});
}
else
{
this_backup.$trigger_text.animate({'top': trigger_text_position_top}, 'slow');
}
this.$item.data('showed', 0);
}
}
},
$: function (selector) {
return this.$item.find(selector);
}
};
function uSquare(element, options) {
var self = this;
this.options = $.extend({}, $.fn.uSquare.defaults, options);
this.$element = $(element);
this.$overlay = this.$('.usquare_module_shade');
this.$items = this.$(this.options.block);
this.$triggers = this.$(this.options.trigger);
this.$closes = this.$('.close');
this.$triggers.on('click', $.proxy(this.overlayShow, this));
this.$closes.on('click', $.proxy(this.overlayHide, this));
this.$overlay.on('click', $.proxy(this.overlayHide, this));
$.each( this.$items, function(i, element) {
new uSquareItem(element, $.extend(self.options, {$overlay: self.$overlay, $parent: self.$element }) );
});
};
uSquare.prototype = {
$: function (selector) {
return this.$element.find(selector);
},
overlayShow: function() {
this.$overlay.fadeIn('slow', function(){
$(this).css({opacity : 0.5});
})
},
overlayHide: function() {
if (!this.$element.data('in_trans'))
{
this.$overlay.fadeOut('slow');
}
}
};
$.fn.uSquare = function ( option ) {
return this.each(function () {
var $this = $(this),
data = $this.data('tooltip'),
options = typeof option == 'object' && option;
data || $this.data('tooltip', (data = new uSquare(this, options)));
(typeof option == 'string') && data[option]();
});
};
$.fn.uSquare.Constructor = uSquare;
$.fn.uSquare.defaults = {
block: '.usquare_block',
trigger: '.usquare_square',
moreInfo: '.usquare_block_extended',
opening_speed: 300,
closing_speed: 500,
easing: 'swing',
before_item_opening_callback: null,
before_info_rolling_callback: null,
after_info_rolling_callback: null
};
})(jQuery);
$(window).load(function() {
$(".usquare_about").mCustomScrollbar();
});
| AhoraMadrid/ahoramadrid.org | js/vendor/jquery.usquare.js | JavaScript | agpl-3.0 | 6,490 |
var searchData=
[
['backtrace',['backtrace',['../class_logger.html#a5deb9b10c43285287a9113f280ee8fab',1,'Logger']]],
['baseexception',['BaseException',['../class_base_exception.html',1,'']]],
['baseexception_2ephp',['BaseException.php',['../_base_exception_8php.html',1,'']]],
['basic_2ephp',['Basic.php',['../_menu_2_basic_8php.html',1,'']]],
['basic_2ephp',['Basic.php',['../_paginator_2_basic_8php.html',1,'']]],
['basic_2ephp',['Basic.php',['../_auth_2_basic_8php.html',1,'']]],
['basic_2ephp',['Basic.php',['../_t_mail_2_basic_8php.html',1,'']]],
['basic_2ephp',['Basic.php',['../_form_2_basic_8php.html',1,'']]],
['basic_2ephp',['Basic.php',['../_grid_2_basic_8php.html',1,'']]],
['basicauth',['BasicAuth',['../class_basic_auth.html',1,'']]],
['basicauth_2ephp',['BasicAuth.php',['../_basic_auth_8php.html',1,'']]],
['beforedelete',['beforeDelete',['../class_s_q_l___relation.html#a44c9d7a3b22619b53d4f49f1070d5235',1,'SQL_Relation']]],
['beforefield',['beforeField',['../class_form___field.html#aa4bbfb40048e1c3fe939621179652be1',1,'Form_Field']]],
['beforeinsert',['beforeInsert',['../class_s_q_l___relation.html#ada6a7f2abf3ba1c19e4ba3711da1a61e',1,'SQL_Relation']]],
['beforeload',['beforeLoad',['../class_s_q_l___relation.html#a665492752f54f9cbc3fd2cae51ca4373',1,'SQL_Relation']]],
['beforemodify',['beforeModify',['../class_s_q_l___relation.html#a3ad587772d12f99af11a3db64d879210',1,'SQL_Relation']]],
['beforesave',['beforeSave',['../class_s_q_l___relation.html#ab9e4fb36c177d9633b81fc184f7bd933',1,'SQL_Relation']]],
['begintransaction',['beginTransaction',['../class_d_b.html#af3380f3b13931d581fa973a382946b32',1,'DB\beginTransaction()'],['../class_d_blite__mysql.html#a06fdc3063ff49b8de811683aae3483e6',1,'DBlite_mysql\beginTransaction()']]],
['belowfield',['belowField',['../class_form___field.html#a27cd7c6e75ed8c09aae8af32905a888d',1,'Form_Field']]],
['box_2ephp',['Box.php',['../_box_8php.html',1,'']]],
['breakhook',['breakHook',['../class_abstract_object.html#a446b3f8327b3272c838ae46f40a9da06',1,'AbstractObject']]],
['bt',['bt',['../class_d_b__dsql.html#aa374d1bfaabf3f546fe8862d09f4a096',1,'DB_dsql']]],
['button',['Button',['../class_button.html',1,'']]],
['button_2ephp',['Button.php',['../_button_8php.html',1,'']]],
['button_2ephp',['Button.php',['../_form_2_button_8php.html',1,'']]],
['button_2ephp',['Button.php',['../_view_2_button_8php.html',1,'']]],
['buttonset',['ButtonSet',['../class_button_set.html',1,'']]],
['buttonset_2ephp',['ButtonSet.php',['../_button_set_8php.html',1,'']]],
['buttonset_2ephp',['ButtonSet.php',['../_view_2_button_set_8php.html',1,'']]]
];
| atk4/atk4-web | dox/html/search/all_62.js | JavaScript | agpl-3.0 | 2,662 |
<div class="role-filter">
<div class="fw-700 m-b-5">{{"ROLE"|translate}}</div>
<div>
<div class="checkbox-inline" ng-class="{'selected':roles.tank.selected}" uib-tooltip="{{'TANK'|translate}}">
<label class="tank">
<input ng-model="roles.tank.selected" type="checkbox">
</label>
</div>
<div class="checkbox-inline" ng-class="{'selected':roles.heal.selected}" uib-tooltip="{{'HEAL'|translate}}">
<label class="heal">
<input ng-model="roles.heal.selected" type="checkbox">
</label>
</div>
<div class="checkbox-inline" ng-class="{'selected':roles.melee_dps.selected}"
uib-tooltip="{{'MELEE_DPS'|translate}}">
<label class="melee_dps">
<input ng-model="roles.melee_dps.selected" type="checkbox">
</label>
</div>
<div class="checkbox-inline" ng-class="{'selected':roles.ranged_dps.selected}"
uib-tooltip="{{'RANGED_DPS'|translate}}">
<label class="ranged_dps">
<input ng-model="roles.ranged_dps.selected" type="checkbox">
</label>
</div>
</div>
</div> | warcraftlfg/warcraft-lfg | client/app/filter/character/filter.role.directive.html | HTML | agpl-3.0 | 1,208 |
body { font-family: 'DejaVu Sans Condensed'; font-size: 11pt; }
p { text-align: justify; margin-bottom: 4pt; margin-top:0pt; }
table {font-family: 'DejaVu Sans Condensed'; font-size: 10pt; line-height: 1.2;
margin-top: 2pt; margin-bottom: 5pt;
border-collapse: collapse; }
thead { font-weight: bold; vertical-align: bottom; }
tfoot { font-weight: bold; vertical-align: top; }
thead td { font-weight: bold; }
tfoot td { font-weight: bold; }
.Thead { font-weight: bold; vertical-align: bottom; }
.Thead td { font-weight: bold; }
.headerrow td, .headerrow th { background-gradient: linear #b7cebd #f5f8f5 0 1 0 0.2; }
.footerrow td, .footerrow th { background-gradient: linear #b7cebd #f5f8f5 0 1 0 0.2; }
th { font-weight: bold;
vertical-align: top;
padding-left: 2mm;
padding-right: 2mm;
padding-top: 0.5mm;
padding-bottom: 0.5mm;
}
td { padding-left: 2mm;
vertical-align: top;
padding-right: 2mm;
padding-top: 0.5mm;
padding-bottom: 0.5mm;
}
th p { margin:0pt; }
td p { margin:0pt; }
table.widecells td {
padding-left: 5mm;
padding-right: 5mm;
}
table.tallcells td {
padding-top: 3mm;
padding-bottom: 3mm;
}
hr { width: 70%; height: 1px;
text-align: center; color: #999999;
margin-top: 8pt; margin-bottom: 8pt; }
a { color: #000066; font-style: normal; text-decoration: underline;
font-weight: normal; }
pre { font-family: 'DejaVu Sans Mono'; font-size: 9pt; margin-top: 5pt; margin-bottom: 5pt; }
h1 { font-weight: normal; font-size: 26pt; color: #000066;
font-family: 'DejaVu Sans Condensed'; margin-top: 18pt; margin-bottom: 6pt;
border-top: 0.075cm solid #000000; border-bottom: 0.075cm solid #000000;
page-break-after:avoid; }
h2 { font-weight: bold; font-size: 12pt; color: #000066;
font-family: 'DejaVu Sans Condensed'; margin-top: 6pt; margin-bottom: 6pt;
border-top: 0.07cm solid #000000; border-bottom: 0.07cm solid #000000;
text-transform:uppercase; page-break-after:avoid; }
h3 { font-weight: normal; font-size: 26pt; color: #000000;
font-family: 'DejaVu Sans Condensed'; margin-top: 0pt; margin-bottom: 6pt;
border-top: 0; border-bottom: 0;
page-break-after:avoid; }
h4 { font-size: 13pt; color: #9f2b1e;
border-bottom: 0.07cm solid #000000; font-family: 'DejaVu Sans Condensed'; margin-top: 10pt; margin-bottom: 7pt; font-variant: small-caps;
/* margin-collapse:collapse; */page-break-after:avoid; }
h5 { font-weight: bold; font-style:italic; ; font-size: 11pt; color: #000044;
font-family: 'DejaVu Sans Condensed'; margin-top: 8pt; margin-bottom: 4pt;
page-break-after:avoid; }
h6 { font-weight: bold; font-size: 9.5pt; color: #333333;
font-family: 'DejaVu Sans Condensed'; margin-top: 6pt; margin-bottom: ;
page-break-after:avoid; }
.breadcrumb {
text-align: right; font-size: 8pt; font-family: 'DejaVu Serif Condensed'; color: #666666;
font-weight: bold; font-style: normal; margin-bottom: 6pt; }
.bpmTopic tbody tr:nth-child(even) { background-color: #f5f8f5; }
.bpmTopicC tbody tr:nth-child(even) { background-color: #f5f8f5; }
.bpmNoLines tbody tr:nth-child(even) { background-color: #f5f8f5; }
.bpmNoLinesC tbody tr:nth-child(even) { background-color: #f5f8f5; }
.bpmTopnTail tbody tr:nth-child(even) { background-color: #f5f8f5; }
.bpmTopnTailC tbody tr:nth-child(even) { background-color: #f5f8f5; }
.evenrow td, .evenrow th { background-color: #f5f8f5; }
.oddrow td, .oddrow th { background-color: #e3ece4; }
.bpmTopic { background-color: #e3ece4; }
.bpmTopicC { background-color: #e3ece4; }
.bpmNoLines { background-color: #e3ece4; }
.bpmNoLinesC { background-color: #e3ece4; }
.bpmClear { }
.bpmClearC { text-align: center; }
.bpmTopnTail { background-color: #e3ece4; topntail: 0.02cm solid #495b4a;}
.bpmTopnTailC { background-color: #e3ece4; topntail: 0.02cm solid #495b4a;}
.bpmTopnTailClear { topntail: 0.02cm solid #495b4a; }
.bpmTopnTailClearC { topntail: 0.02cm solid #495b4a; }
.bpmTopicC td, .bpmTopicC td p { text-align: center; }
.bpmNoLinesC td, .bpmNoLinesC td p { text-align: center; }
.bpmClearC td, .bpmClearC td p { text-align: center; }
.bpmTopnTailC td, .bpmTopnTailC td p { text-align: center; }
.bpmTopnTailClearC td, .bpmTopnTailClearC td p { text-align: center; }
.pmhMiddleCenter { text-align:center; vertical-align:middle; }
.pmhMiddleRight { text-align:right; vertical-align:middle; }
.pmhBottomCenter { text-align:center; vertical-align:bottom; }
.pmhBottomRight { text-align:right; vertical-align:bottom; }
.pmhTopCenter { text-align:center; vertical-align:top; }
.pmhTopRight { text-align:right; vertical-align:top; }
.pmhTopLeft { text-align:left; vertical-align:top; }
.pmhBottomLeft { text-align:left; vertical-align:bottom; }
.pmhMiddleLeft { text-align:left; vertical-align:middle; }
.infobox { margin-top:10pt; background-color:#DDDDBB; text-align:center; border:1px solid #880000; }
.bpmTopic td, .bpmTopic th { border-top: 1px solid #FFFFFF; }
.bpmTopicC td, .bpmTopicC th { border-top: 1px solid #FFFFFF; }
.bpmTopnTail td, .bpmTopnTail th { border-top: 1px solid #FFFFFF; }
.bpmTopnTailC td, .bpmTopnTailC th { border-top: 1px solid #FFFFFF; }
.dettaglio {
margin:0px;padding:0px;
width:100%;
box-shadow: 10px 10px 5px #888888;
border:1px solid #000000;
-moz-border-radius-bottomleft:0px;
-webkit-border-bottom-left-radius:0px;
border-bottom-left-radius:0px;
-moz-border-radius-bottomright:0px;
-webkit-border-bottom-right-radius:0px;
border-bottom-right-radius:0px;
-moz-border-radius-topright:0px;
-webkit-border-top-right-radius:0px;
border-top-right-radius:0px;
-moz-border-radius-topleft:0px;
-webkit-border-top-left-radius:0px;
border-top-left-radius:0px;
}
.dettaglio table{
border-collapse: collapse;
border-spacing: 0;
width:100%;
height:100%;
margin:0px;padding:0px;
}
.dettaglio tr:last-child td:last-child {
-moz-border-radius-bottomright:0px;
-webkit-border-bottom-right-radius:0px;
border-bottom-right-radius:0px;
}
.dettaglio table tr:first-child td:first-child {
-moz-border-radius-topleft:0px;
-webkit-border-top-left-radius:0px;
border-top-left-radius:0px;
}
.dettaglio table tr:first-child td:last-child {
-moz-border-radius-topright:0px;
-webkit-border-top-right-radius:0px;
border-top-right-radius:0px;
}
.dettaglio tr:last-child td:first-child{
-moz-border-radius-bottomleft:0px;
-webkit-border-bottom-left-radius:0px;
border-bottom-left-radius:0px;
}
.dettaglio tr:hover td{
}
.dettaglio tr:nth-child(odd){ background-color:#e5e5e5; }
.dettaglio tr:nth-child(even) { background-color:#ffffff; }
.dettaglio td{
vertical-align:middle;
border:1px solid #000000;
border-width:0px 1px 1px 0px;
text-align:left;
padding:7px;
font-size:10px;
font-family:Arial;
font-weight:normal;
color:#000000;
}
.dettaglio tr:last-child td{
border-width:0px 1px 0px 0px;
}
.dettaglio tr td:last-child{
border-width:0px 0px 1px 0px;
}
.dettaglio tr:last-child td:last-child{
border-width:0px 0px 0px 0px;
}
.dettaglio tr:first-child td{
background:-o-linear-gradient(bottom, #cccccc 5%, #b2b2b2 100%); background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #b2b2b2) );
background:-moz-linear-gradient( center top, #cccccc 5%, #b2b2b2 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#cccccc", endColorstr="#b2b2b2"); background: -o-linear-gradient(top,#cccccc,b2b2b2);
background-color:#cccccc;
border:0px solid #000000;
text-align:center;
border-width:0px 0px 1px 1px;
font-size:14px;
font-family:Arial;
font-weight:bold;
color:#000000;
}
.dettaglio tr:first-child:hover td{
background:-o-linear-gradient(bottom, #cccccc 5%, #b2b2b2 100%); background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #b2b2b2) );
background:-moz-linear-gradient( center top, #cccccc 5%, #b2b2b2 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#cccccc", endColorstr="#b2b2b2"); background: -o-linear-gradient(top,#cccccc,b2b2b2);
background-color:#cccccc;
}
.dettaglio tr:first-child td:first-child{
border-width:0px 0px 1px 0px;
}
.dettaglio tr:first-child td:last-child{
border-width:0px 0px 1px 1px;
} | ctlr/MailCtlr | public/css/pdf.css | CSS | agpl-3.0 | 8,461 |
/*
Copyright (c) 2014-2022 AscEmu Team <http://www.ascemu.org>
This file is released under the MIT license. See README-MIT for more information.
*/
#pragma once
#include <cstdint>
#include "ManagedPacket.h"
#include "WorldPacket.h"
namespace AscEmu::Packets
{
class CmsgQuestgiverRequestReward : public ManagedPacket
{
public:
WoWGuid questgiverGuid;
uint32_t questId;
CmsgQuestgiverRequestReward() : CmsgQuestgiverRequestReward(0, 0)
{
}
CmsgQuestgiverRequestReward(uint64_t questgiverGuid, uint32_t questId) :
ManagedPacket(CMSG_QUESTGIVER_REQUEST_REWARD, 12),
questgiverGuid(questgiverGuid),
questId(questId)
{
}
bool internalSerialise(WorldPacket& /*packet*/) override
{
return false;
}
bool internalDeserialise(WorldPacket& packet) override
{
uint64_t unpackedGuid;
packet >> unpackedGuid >> questId;
questgiverGuid.Init(unpackedGuid);
return true;
}
};
}
| AscEmu/AscEmu | src/world/Server/Packets/CmsgQuestgiverRequestReward.h | C | agpl-3.0 | 1,093 |
package org.demo.jdk.utilapis;
public class Bird implements Flyable {
private int speed = 15;
@Override
public void fly() {
System.out.println("I'm Bird, my speed is " + speed + ".");
}
}
| William-Hai/SimpleDemo | src/org/demo/jdk/utilapis/Bird.java | Java | agpl-3.0 | 220 |
<?php
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
namespace App\Libraries;
use App\Exceptions\UserVerificationException;
use App\Mail\UserVerification as UserVerificationMail;
use App\Models\Country;
use App\Models\LoginAttempt;
use Datadog;
use Mail;
class UserVerification
{
private $request;
private $state;
private $user;
public static function fromCurrentRequest()
{
$verification = request()->attributes->get('user_verification');
if ($verification === null) {
$verification = new static(
auth()->user(),
request(),
UserVerificationState::fromCurrentRequest()
);
request()->attributes->set('user_verification', $verification);
}
return $verification;
}
public static function logAttempt(string $source, string $type, string $reason = null): void
{
Datadog::increment(
config('datadog-helper.prefix_web').'.verification.attempts',
1,
compact('reason', 'source', 'type')
);
}
private function __construct($user, $request, $state)
{
$this->user = $user;
$this->request = $request;
$this->state = $state;
}
public function initiate()
{
$statusCode = 401;
app('route-section')->setError("{$statusCode}-verification");
// Workaround race condition causing $this->issue() to be called in parallel.
// Mainly observed when logging in as privileged user.
if ($this->request->ajax()) {
$routeData = app('route-section')->getOriginal();
if ($routeData['controller'] === 'notifications_controller' && $routeData['action'] === 'index') {
return response(['error' => 'verification'], $statusCode);
}
}
$email = $this->user->user_email;
if (!$this->state->issued()) {
static::logAttempt('input', 'new');
$this->issue();
}
if ($this->request->ajax()) {
return response([
'authentication' => 'verify',
'box' => view(
'users._verify_box',
compact('email')
)->render(),
], $statusCode);
} else {
return ext_view('users.verify', compact('email'), null, $statusCode);
}
}
public function isDone()
{
return $this->state->isDone();
}
public function issue()
{
$user = $this->user;
if (!present($user->user_email)) {
return;
}
$keys = $this->state->issue();
LoginAttempt::logAttempt($this->request->getClientIp(), $this->user, 'verify');
$requestCountry = Country
::where('acronym', request_country($this->request))
->pluck('name')
->first();
Mail::to($user)
->queue(new UserVerificationMail(
compact('keys', 'user', 'requestCountry')
));
}
public function markVerifiedAndRespond()
{
$this->state->markVerified();
return response([], 200);
}
public function reissue()
{
if ($this->state->isDone()) {
return $this->markVerifiedAndRespond();
}
$this->issue();
return response(['message' => trans('user_verification.errors.reissued')], 200);
}
public function verify()
{
$key = str_replace(' ', '', $this->request->input('verification_key'));
try {
$this->state->verify($key);
} catch (UserVerificationException $e) {
static::logAttempt('input', 'fail', $e->reasonKey());
if ($e->reasonKey() === 'incorrect_key') {
LoginAttempt::logAttempt($this->request->getClientIp(), $this->user, 'verify-mismatch', $key);
}
if ($e->shouldReissue()) {
$this->issue();
}
return error_popup($e->getMessage());
}
static::logAttempt('input', 'success');
return $this->markVerifiedAndRespond();
}
}
| omkelderman/osu-web | app/Libraries/UserVerification.php | PHP | agpl-3.0 | 4,310 |
<html>
<head>
<title>Frankenstein, 1831, Vol. 2, Chap. 3, Frame 6</title>
</head>
<body>
<p>
"Having thus arranged my dwelling, and carpeted it with clean
straw, I retired; for I saw the figure of a man at a distance,
and I remembered too well my treatment the night before, to trust
myself in his power. I had first, however, provided for my
sustenance for that day, by a loaf of coarse bread, which I
purloined, and a cup with which I could drink, more conveniently
than from my hand, of the pure water which flowed by my retreat.
The floor was a little raised, so that it was kept perfectly dry,
and by its vicinity to the chimney of the cottage it was
tolerably warm.</p><p>
"Being thus provided, I resolved to reside in this hovel, until something
should occur which might alter my determination. It was indeed <a
href="../V2notes/paradise.html">a paradise</a>, compared to the bleak
forest, my former residence, the rain-dropping branches, and dank earth. I
ate my breakfast with pleasure, and was about to remove a plank to procure
myself a little water, when I heard a step, and looking through a small
chink, I beheld a young creature, with a pail on her head, passing before
my hovel. The girl was young, and of gentle demeanour, <a
href="../V2notes/unlike.html">unlike what I have since found cottagers and
farm-house servants to be</a>. Yet she was <a
href="../V2notes/meanly.html">meanly dressed</a>, a coarse blue petticoat
and a linen jacket being her only garb; her fair hair was plaited, but not
adorned; she looked patient, yet sad. I lost sight of her; and in about a
quarter of an hour she returned, bearing the pail, which was now partly
filled with milk. As she walked along, seemingly incommoded by the burden,
a young man met her, whose countenance expressed a deeper despondence.
Uttering a few sounds with an air of melancholy, he took the pail from her
head, and bore it to the cottage himself. She followed, and they
disappeared. Presently I saw the young man again, with some tools in his
hand, cross the field behind the cottage; and the girl was also busied,
sometimes in the house, and sometimes in the yard.</p>
</body>
</html>
| ebeshero/Pittsburgh_Frankenstein | frankenTexts_HTML/PA_Electronic_Ed/1831_ed/00118-chapterContent-1831.html | HTML | agpl-3.0 | 2,174 |
/*
Copyright (C) 2018 by Claude SIMON (http://zeusw.org/epeios/contact.html).
This file is part of XDHWebQ.
XDHWebQ is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
XDHWebQ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with XDHWebQ. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef REGISTRY_INC_
# define REGISTRY_INC_
# include "xdwrgstry.h"
namespace registry {
using namespace xdwrgstry;
namespace parameter {
using namespace xdwrgstry::parameter;
}
namespace definition {
using namespace xdwrgstry::definition;
}
}
#endif
| epeios-q37/epeios | tools/xdhwebq.old_with_wrappers_do_not_delete/ZND/registry.h | C | agpl-3.0 | 1,040 |
/*
Copyright (C) 2015 Jack Fagner
This file is part of OpenTidl.
OpenTidl is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenTidl is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with OpenTidl. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenTidl.Models;
using OpenTidl.Models.Base;
using OpenTidl.Transport;
using OpenTidl.Enums;
using System.IO;
namespace OpenTidl
{
public partial class OpenTidlClient
{
#region image methods
/// <summary>
/// Helper method to retrieve a stream with an album cover image
/// </summary>
public Stream GetAlbumCover(AlbumModel model, AlbumCoverSize size)
{
return GetAlbumCover(model.Cover, model.Id, size);
}
/// <summary>
/// Helper method to retrieve a stream with an album cover image
/// </summary>
public Stream GetAlbumCover(String cover, Int32 albumId, AlbumCoverSize size)
{
var w = 750;
var h = 750;
if (!RestUtility.ParseImageSize(size.ToString(), out w, out h))
throw new ArgumentException("Invalid image size", "size");
String url = null;
if (!String.IsNullOrEmpty(cover))
url = String.Format("http://resources.wimpmusic.com/images/{0}/{1}x{2}.jpg", cover.Replace('-', '/'), w, h);
else
url = String.Format("http://images.tidalhifi.com/im/im?w={1}&h={2}&albumid={0}&noph", albumId, w, h);
return RestClient.GetStream(url);
}
/// <summary>
/// Helper method to retrieve a stream with an artists picture
/// </summary>
public Stream GetArtistPicture(ArtistModel model, ArtistPictureSize size)
{
return GetArtistPicture(model.Picture, model.Id, size);
}
/// <summary>
/// Helper method to retrieve a stream with an artists picture
/// </summary>
public Stream GetArtistPicture(String picture, Int32 artistId, ArtistPictureSize size)
{
var w = 750;
var h = 500;
if (!RestUtility.ParseImageSize(size.ToString(), out w, out h))
throw new ArgumentException("Invalid image size", "size");
String url = null;
if (!String.IsNullOrEmpty(picture))
url = String.Format("http://resources.wimpmusic.com/images/{0}/{1}x{2}.jpg", picture.Replace('-', '/'), w, h);
else
url = String.Format("http://images.tidalhifi.com/im/im?w={1}&h={2}&artistid={0}&noph", artistId, w, h);
return RestClient.GetStream(url);
}
/// <summary>
/// Helper method to retrieve a stream with a playlist image
/// </summary>
public Stream GetPlaylistImage(PlaylistModel model, PlaylistImageSize size)
{
return GetPlaylistImage(model.Image, model.Uuid, size);
}
/// <summary>
/// Helper method to retrieve a stream with a playlist image
/// </summary>
public Stream GetPlaylistImage(String image, String playlistUuid, PlaylistImageSize size)
{
var w = 750;
var h = 500;
if (!RestUtility.ParseImageSize(size.ToString(), out w, out h))
throw new ArgumentException("Invalid image size", "size");
String url = null;
if (!String.IsNullOrEmpty(image))
url = String.Format("http://resources.wimpmusic.com/images/{0}/{1}x{2}.jpg", image.Replace('-', '/'), w, h);
else
url = String.Format("http://images.tidalhifi.com/im/im?w={1}&h={2}&uuid={0}&rows=2&cols=3&noph", playlistUuid, w, h);
return RestClient.GetStream(url);
}
/// <summary>
/// Helper method to retrieve a stream with a video conver image
/// </summary>
public Stream GetVideoImage(VideoModel model, VideoImageSize size)
{
return GetVideoImage(model.ImageId, model.ImagePath, size);
}
/// <summary>
/// Helper method to retrieve a stream with a video conver image
/// </summary>
public Stream GetVideoImage(String imageId, String imagePath, VideoImageSize size)
{
var w = 750;
var h = 500;
if (!RestUtility.ParseImageSize(size.ToString(), out w, out h))
throw new ArgumentException("Invalid image size", "size");
String url = null;
if (!String.IsNullOrEmpty(imageId))
url = String.Format("http://resources.wimpmusic.com/images/{0}/{1}x{2}.jpg", imageId.Replace('-', '/'), w, h);
else
url = String.Format("http://images.tidalhifi.com/im/im?w={1}&h={2}&img={0}&noph", imagePath, w, h);
return RestClient.GetStream(url);
}
#endregion
#region track/video methods
/// <summary>
/// Helper method to retrieve the audio/video stream with correct user-agent, etc.
/// </summary>
public Stream GetStream(String streamUrl)
{
return RestClient.GetStream(streamUrl);
}
#endregion
}
}
| iamsi/OpenTidl | OpenTidl/Methods/OpenTidlStreamMethods.cs | C# | agpl-3.0 | 5,835 |
# -*- coding: utf-8 -*-
##############################################################################
#
# Infrastructure
# Copyright (C) 2014 Ingenieria ADHOC
# No email
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import re
from openerp import netsvc
from openerp.osv import osv, fields
class database_type(osv.osv):
""""""
_name = 'infrastructure.database_type'
_description = 'database_type'
_columns = {
'name': fields.char(string='Name', required=True),
'prefix': fields.char(string='Prefix', required=True, size=4),
'url_prefix': fields.char(string='URL Prefix'),
'automatic_drop': fields.boolean(string='Automatic Drop'),
'automatic_drop_days': fields.integer(string='Automatic Drop Days'),
'protect_db': fields.boolean(string='Protect DBs?'),
'color': fields.integer(string='Color'),
'automatic_deactivation': fields.boolean(string='Atumatic Deactivation?'),
'auto_deactivation_days': fields.integer(string='Automatic Drop Days'),
'url_example': fields.char(string='URL Example'),
'bd_name_example': fields.char(string='BD Name Example'),
'db_back_up_policy_ids': fields.many2many('infrastructure.db_back_up_policy', 'infrastructure_database_type_ids_db_back_up_policy_ids_rel', 'database_type_id', 'db_back_up_policy_id', string='Suggested Backup Policies'),
}
_defaults = {
}
_constraints = [
]
database_type()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| zhaohuaw/odoo-infrastructure | addons/infrastructure/database_type.py | Python | agpl-3.0 | 2,270 |
<span ng-if="editable" class="omny-edit-section" ng-click="changeUrl()">Edit</span>
<iframe ng-if="videoSource" width="854" height="510" ng-src="{{videoSource}}" frameborder="0" allowfullscreen></iframe>
| omnycms/omny-cms | ui/omny-angular/public_html/js/modules/Youtube/Youtube.html | HTML | agpl-3.0 | 204 |
# frozen_string_literal: true
require 'rails_helper'
describe StudentsController do
let(:user) { create(:student) }
before { allow(controller).to receive(:current_user) { user } }
it { should use_before_action :authorize! }
describe '#index' do
let!(:classroom) { create(:classroom) }
let!(:students_classrooms) { create(:students_classrooms, student_id: user.id, classroom_id: classroom.id) }
it 'should set the current user and js file' do
get :index
expect(assigns(:current_user)).to eq user
expect(assigns(:js_file)).to eq "student"
end
it 'should find the classroom and set flash' do
get :index, params: { joined: "success", classroom: classroom.id }
expect(flash["join-class-notification"]).to eq "You have joined #{classroom.name} 🎉🎊"
end
end
describe '#join_classroom' do
let(:student) { create(:student) }
before { allow(controller).to receive(:current_user) { student } }
it 'should redirect for an invalid class_code' do
get :join_classroom, params: { classcode: 'nonsense_doesnt_exist' }
expect(response).to redirect_to '/classes'
expect(flash[:error]).to match("Oops! There is no class with the code nonsense_doesnt_exist. Ask your teacher for help.")
end
it 'should redirect for a valid class_code' do
classroom = create(:classroom, code: 'existing_code')
get :join_classroom, params: { classcode: classroom.code }
expect(response).to redirect_to "/classrooms/#{classroom.id}?joined=success"
end
end
describe '#account_settings' do
it 'should set the current user and js file' do
get :account_settings
expect(assigns(:current_user)).to eq user
expect(assigns(:js_file)).to eq "student"
end
end
describe '#student_demo' do
context 'when Angie Thomas exists' do
let!(:angie) { create(:user, email: '[email protected]') }
it 'should sign in angie and redirect to profile' do
get :student_demo
expect(session[:user_id]).to eq angie.id
expect(response).to redirect_to '/classes'
end
end
context 'when angie thomas does not exist' do
it 'should destroy recreate the demo and redirect to student demo' do
expect(Demo::ReportDemoDestroyer).to receive(:destroy_demo).with(nil)
expect(Demo::ReportDemoCreator).to receive(:create_demo).with(nil)
get :student_demo
expect(response).to redirect_to "/student_demo"
end
end
end
describe '#student_demo_ap' do
context 'when bell hooks exists' do
let!(:bell) { create(:user, email: '[email protected]') }
it 'should sign in bell and redirect to profile' do
get :demo_ap
expect(session[:user_id]).to eq bell.id
expect(response).to redirect_to '/classes'
end
end
context 'when bell hooks does not exist' do
it 'should recreate the demo and redirect to student demo' do
expect(Demo::ReportDemoAPCreator).to receive(:create_demo).with(nil)
get :demo_ap
expect(response).to redirect_to "/student_demo_ap"
end
end
end
describe '#update_account' do
let!(:user) { create(:user, name: "Maya Angelou", email: '[email protected]', username: "maya-angelou", role: "student") }
let!(:second_user) { create(:user, name: "Harvey Milk", email: '[email protected]', username: "harvey-milk", role: "student") }
it 'should update the name, email and username' do
put :update_account, params: { email: "[email protected]", username: "pabllo-vittar", name: "Pabllo Vittar" }
expect(user.reload.email).to eq "[email protected]"
expect(user.reload.username).to eq "pabllo-vittar"
expect(user.reload.name).to eq "Pabllo Vittar"
end
it 'should update only the fields that are changed' do
put :update_account, params: { email: "[email protected]", username: "rainha-do-carnaval", name: "Pabllo Vittar" }
expect(user.reload.email).to eq "[email protected]"
expect(user.reload.username).to eq "rainha-do-carnaval"
expect(user.reload.name).to eq "Pabllo Vittar"
end
it 'should not update the email or username if already taken' do
put :update_account, params: { email: "[email protected]", username: "pabllo-vittar", name: "Pabllo Vittar" }
expect(user.reload.errors.messages[:email].first).to eq "That email is taken. Try another."
put :update_account, params: { email: "[email protected]", username: "harvey-milk", name: "Pabllo Vittar" }
expect(user.reload.errors.messages[:username].first).to eq "That username is taken. Try another."
end
end
end
| empirical-org/Empirical-Core | services/QuillLMS/spec/controllers/students_controller_spec.rb | Ruby | agpl-3.0 | 4,686 |
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
SepiaSearch (Videos)
"""
from json import loads
from dateutil import parser, relativedelta
from urllib.parse import urlencode
from datetime import datetime
# about
about = {
"website": 'https://sepiasearch.org',
"wikidata_id": None,
"official_api_documentation": "https://framagit.org/framasoft/peertube/search-index/-/tree/master/server/controllers/api", # NOQA
"use_official_api": True,
"require_api_key": False,
"results": 'JSON',
}
categories = ['videos']
paging = True
time_range_support = True
safesearch = True
supported_languages = [
'en', 'fr', 'ja', 'eu', 'ca', 'cs', 'eo', 'el',
'de', 'it', 'nl', 'es', 'oc', 'gd', 'zh', 'pt',
'sv', 'pl', 'fi', 'ru'
]
base_url = 'https://sepiasearch.org/api/v1/search/videos'
safesearch_table = {
0: 'both',
1: 'false',
2: 'false'
}
time_range_table = {
'day': relativedelta.relativedelta(),
'week': relativedelta.relativedelta(weeks=-1),
'month': relativedelta.relativedelta(months=-1),
'year': relativedelta.relativedelta(years=-1)
}
embedded_url = '<iframe width="540" height="304" src="{url}" frameborder="0" allowfullscreen></iframe>'
def minute_to_hm(minute):
if isinstance(minute, int):
return "%d:%02d" % (divmod(minute, 60))
return None
def request(query, params):
params['url'] = base_url + '?' + urlencode({
'search': query,
'start': (params['pageno'] - 1) * 10,
'count': 10,
'sort': '-match',
'nsfw': safesearch_table[params['safesearch']]
})
language = params['language'].split('-')[0]
if language in supported_languages:
params['url'] += '&languageOneOf[]=' + language
if params['time_range'] in time_range_table:
time = datetime.now().date() + time_range_table[params['time_range']]
params['url'] += '&startDate=' + time.isoformat()
return params
def response(resp):
results = []
search_results = loads(resp.text)
if 'data' not in search_results:
return []
for result in search_results['data']:
title = result['name']
content = result['description']
thumbnail = result['thumbnailUrl']
publishedDate = parser.parse(result['publishedAt'])
embedded = embedded_url.format(url=result.get('embedUrl'))
author = result.get('account', {}).get('displayName')
length = minute_to_hm(result.get('duration'))
url = result['url']
results.append({'url': url,
'title': title,
'content': content,
'author': author,
'length': length,
'template': 'videos.html',
'publishedDate': publishedDate,
'embedded': embedded,
'thumbnail': thumbnail})
return results
| dalf/searx | searx/engines/sepiasearch.py | Python | agpl-3.0 | 2,928 |
<?php
/*
Kevin Froman - Easy IPFS: easily interact with IPFS in php via this simple API
Copyright (C) 2017 Kevin Froman
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
class IPFS {
function foo(){
return 'bar';
}
function cat($hash){
$gotData = '';
$server = curl_init();
curl_setopt($server, CURLOPT_URL, 'http://127.0.0.1:5001/api/v0/cat?arg=' . $hash);
curl_setopt($server, CURLOPT_RETURNTRANSFER, true);
curl_setopt($server, CURLOPT_BINARYTRANSFER, false);
$gotData = curl_exec($server);
curl_close($server);
return $gotData;
}
function resolve($name){
$gotData = '';
$json = '';
$server = curl_init();
curl_setopt($server, CURLOPT_URL, 'http://127.0.0.1:5001/api/v0/name/resolve?arg=' . $name);
curl_setopt($server, CURLOPT_RETURNTRANSFER, true);
$gotData = curl_exec($server);
$gotData = json_decode($gotData, true);
if (isset($gotData['Path'])){
$gotData = str_replace('/ipfs/', '', $gotData['Path']);
}
else{
$gotData = 'invalid';
}
curl_close($server);
return $gotData;
}
function dataAdd($file){
$gotData = '';
$server = curl_init();
curl_setopt($server, CURLOPT_POST, 1);
curl_setopt($server, CURLOPT_RETURNTRANSFER, true);
$data = array('file' => new CurlFile($file));
curl_setopt($server, CURLOPT_SAFE_UPLOAD, false); // required as of PHP 5.6.0
curl_setopt($server, CURLOPT_POSTFIELDS, $data);
curl_setopt($server, CURLOPT_URL, 'http://127.0.0.1:5001/api/v0/add');
$data = curl_exec($server);
curl_close($server);
return $data;
}
function namePublish($data) {
$server = curl_init();
$data = dataAdd($data);
curl_setopt($server, CURLOPT_URL, 'http://127.0.0.1:5001/api/v0/name/publish?arg=' . $data . '&lifetime=1m&');
curl_exec($server);
curl_close($server);
return true;
}
}
?>
| beardog108/seedbin | easy-ipfs.php | PHP | agpl-3.0 | 2,545 |
import React from 'react';
import { render, waitForElement } from 'react-testing-library';
import FakeDataProvider from '@olimat/web/utils/test/FakeDataProvider';
import MockErrorProvider from '@olimat/web/utils/test/MockErrorProvider';
import MockNextContext from '@olimat/web/utils/test/MockNextContext';
import { renderApollo } from '@olimat/web/utils/test/test-utils';
import ExamDetails from './Details';
const MockExamDetails = () => (
<MockNextContext router={{ query: { id: 'theExamId1' } }}>
<ExamDetails />
</MockNextContext>
);
// Talvez uma solução melhor seria criar um mock para o contexto do Next.js
// https://github.com/zeit/next.js/issues/5205
// Outra opção é exportar o componente sem embrulhá-lo com os HoC, e passar os mocks
// https://stackoverflow.com/questions/44204828
describe('<ExamDetails />', () => {
test.skip('renders loading state initially', () => {
const { getByText } = renderApollo(<MockExamDetails />);
getByText(/loading/i);
});
test('renders the details of an exam', async () => {
const customResolvers = {
// We need to update the GraphQL API as well
Exam: () => ({
title: '2017 - Fase 3 - Ano 5',
}),
};
const { getByText, getByTestId } = render(
<FakeDataProvider customResolvers={customResolvers}>
<MockExamDetails />
</FakeDataProvider>,
);
await waitForElement(() => getByText(customResolvers.Exam().title));
const questionListNode = getByTestId('questionList');
expect(questionListNode).toBeInTheDocument();
// toBe(10) couples the test with the mocked server
// https://youtu.be/K445DtQ5oHY?t=1476
expect(questionListNode.children.length).toBe(10);
});
test('renders error message', async () => {
const errorMsg = 'Que pena';
const { getByText } = render(
<MockErrorProvider graphqlErrors={[{ message: errorMsg }]}>
<MockExamDetails />
</MockErrorProvider>,
);
await waitForElement(() => getByText(errorMsg, { exact: false }));
});
});
| iquabius/olimat | packages/web/src/components/Exam/Details.test.tsx | TypeScript | agpl-3.0 | 1,976 |
<?php
// This file declares a new entity type. For more details, see "hook_civicrm_entityTypes" at:
// https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_entityTypes
return [
[
'name' => 'CivirulesLog',
'class' => 'CRM_Civiruleslogger_DAO_CivirulesLog',
'table' => 'civicrm_civirules_log',
],
];
| CiviCooP/org.civicoop.civiruleslogger | xml/schema/CRM/Civiruleslogger/CivirulesLog.entityType.php | PHP | agpl-3.0 | 319 |
{% extends "podcast-base.html" %}
{% load i18n %}
{% load humanize %}
{% load episodes %}
{% load podcasts %}
{% load devices %}
{% load charts %}
{% load utils %}
{% load menu %}
{% block mainmenu %}{{ "/podcast/"|main_menu }}{% endblock %}
{% block sectionmenu %}
{% if podcast.title %}
{{ "/podcast/"|section_menu:podcast.title }}
{% else %}
{{ "/podcast/"|section_menu:"Unnamed Podcast" }}
{% endif %}
{% endblock %}
{% block title %}{{ podcast.title|default:"Unnamed Podcast"|striptags }}{% endblock %}
{% block content %}
{% if episode %}
<div class="first-episode">
{% include "components/episode-box.html" with podcast=podcast episode=episode long=True only %}
</div>
{% endif %}
<hr />
<div class="btn-toolbar">
{% if is_publisher %}
<div class="btn-group">
<a class="btn btn-default" href="{% podcast_link_target podcast "podcast-publisher-detail" %}">
<i class="icon-wrench"></i>
{% trans "Publisher Pages" %}
</a>
</div>
{% endif %}
{% if not user.is_authenticated %}
<div class="btn-group">
<a class="btn btn-default" href="{% podcast_link_target podcast "subscribe" %}">
<i class="icon-plus"></i>
{% trans "Login to Subscribe" %}
</a>
</div>
{% endif %}
{% if devices or can_subscribe %}
<div class="btn-group">
{% if can_subscribe %}
<button class="btn btn-primary" onclick="submitForm('subscribe+all');">
<i class="icon-plus-sign"></i>
{% trans "Subscribe" %}
</button>
<button class="btn dropdown-toggle btn-primary" data-toggle="dropdown">
<span class="caret"></span>
</button>
{% else %}
<button class="btn btn-default" onclick="submitForm('unsubscribe+all');">
<i class="icon-remove-sign"></i>
{% trans "Unsubscribe" %}
</button>
<button class="btn dropdown-toggle btn-default" data-toggle="dropdown">
<span class="caret"></span>
</button>
{% endif %}
<ul class="dropdown-menu">
{% if can_subscribe %}
<li value="+all">
<a href="javascript:void(0);" onclick="submitForm('subscribe+all');">
<i class="icon-plus-sign"></i>
{% trans "Subscribe on all devices" %}
</a>
<form class="internal"
method="post"
action="{% podcast_link_target podcast "subscribe-all" %}"
id="subscribe+all">
{% csrf_token %}
</form>
</li>
{% endif %}
{% for device in subscribe_targets %}
<li value="{{ device.uid }}">
<a href="javascript:void(0);" onclick="submitForm('subscribe-{{ device|devices_uids }}');">
<i class="icon-plus"></i>
{{ device|devices_name }}
</a>
<form class="internal"
action="{% podcast_link_target podcast "subscribe" %}"
method="post"
id="subscribe-{{ device|devices_uids }}">
{% csrf_token %}
<input type="hidden" name="targets" value="{{ device|devices_uids }}" />
</form>
</li>
{% endfor %}
{% if can_subscribe and devices %}
<li class="divider"></li>
{% endif %}
{% if devices %}
<li value="+none">
<a href="javascript:void(0);" onclick="submitForm('unsubscribe+all');">
<i class="icon-remove-sign"></i>
{% trans "Unsubscribe from all devices " %}
</a>
<form class="internal"
method="post"
action="{% podcast_link_target podcast "unsubscribe-all" %}"
id="unsubscribe+all">
{% csrf_token %}
</form>
</li>
{% endif %}
{% for device in devices %}
<li value="{{ device.uid }}">
<a href="javascript:void(0);" onclick="submitForm('unsubscribe-{{ device.uid }}');">
<i class="icon-remove"></i>
{{ device|devices_name }}
</a>
<form class="internal"
method="post"
action="{% podcast_link_target podcast "unsubscribe" device.uid %}?return_to={% podcast_link_target podcast %}"
id="unsubscribe-{{ device.uid }}">
{% csrf_token %}
</form>
</li>
{% endfor %}
</ul>
</div>
{% endif %}
{% if has_history %}
<a class="btn btn-default" href="{% podcast_link_target podcast "podcast-history" %}">
<i class="icon-calendar"></i>
{% trans "Subscription History" %}
</a>
{% endif %}
<a href="javascript:void(0);" onclick="$('#tag-box').toggle();" class="btn btn-default">
<i class="icon-tag"></i>
{% trans "Tags" %}
</a>
{% if user.is_staff %}
<a class="btn btn-default" href="{% edit_link podcast %}">
<i class="icon-cogs"></i>Admin
</a>
{% endif %}
</div>
<div id="tag-box">
<hr />
<i class="icon-tag"></i>
<strong>{% trans "Tags" %}: </strong>
{% for tag in tags %}
{% spaceless %}
{% if tag.is_own %}
<span class="own">{{ tag.tag }} <a class="remove" href="{% podcast_link_target podcast "remove-tag" %}?tag={{ tag.tag }}">X</a></span>
{% else %}
<span class="other">{{ tag.tag }}</span>
{% endif %}
{% if not forloop.last %}
<span class="seperator">,</span>
{% endif %}
{% endspaceless %}
{% endfor %}
{% if user.is_authenticated %}
<form class="form-inline" action="{% podcast_link_target podcast "add-tag" %}">
<div class="input-group">
<span class="input-group-addon input-sm"><i class="icon-tag"></i></span>
<input class="input-sm form-control" type="text" name="tag" />
<span class="input-group-btn">
<button class="btn btn-success btn-sm" type="submit">
<i class="icon-plus"></i>
</button>
</span>
</div>
</form>
{% endif %}
</div>
<hr />
{% if episodes %}
<h3>{% trans "Older Episodes" %}</h3>
<div class="episodes">
{% for episode in episodes %}
{% include "components/episode-box.html" with episode=episode podcast=podcast only %}
{% endfor %}
</div>
<ul class="pagination">
{% for page in page_list %}
<li>
{% if page == "..." %}
<span>{{ page }}</span>
{% else %}
{% if page == current_page %}
<a href="{% podcast_link_target podcast "podcast-all-episodes" %}?page={{ page }}"><strong>{{ page }}</strong></a>
{% else %}
<a href="{% podcast_link_target podcast "podcast-all-episodes" %}?page={{ page }}">{{ page }}</a>
{% endif %}
{% endif %}
</li>
{% endfor %}
</ul>
{% endif %}
{% endblock %}
{% block javascript %}
{{ block.super }}
<script language="javascript">
<!--
function submitForm(formid)
{
document.forms[formid].submit();
return true;
}
{% if not has_tagged %}
// done in JS so that box is always visible if JS is disabled
$('#tag-box').toggle();
{% endif %}
-->
</script>
{% endblock %}
| gpodder/mygpo | mygpo/podcasts/templates/podcast.html | HTML | agpl-3.0 | 6,895 |
/*
Classe gerada automaticamente pelo MSTech Code Creator
*/
namespace MSTech.GestaoEscolar.BLL
{
using MSTech.Business.Common;
using MSTech.GestaoEscolar.Entities;
using MSTech.GestaoEscolar.DAL;
using System.Data;
using MSTech.Data.Common;
using System.Collections.Generic;
using System.Linq;
using MSTech.Validation.Exceptions;
/// <summary>
/// Description: CLS_AlunoAvaliacaoTurmaQualidade Business Object.
/// </summary>
public class CLS_AlunoAvaliacaoTurmaQualidadeBO : BusinessBase<CLS_AlunoAvaliacaoTurmaQualidadeDAO, CLS_AlunoAvaliacaoTurmaQualidade>
{
#region Consultas
/// <summary>
/// Seleciona os tipo de qualidade por matrícula do aluno.
/// </summary>
/// <param name="tur_id">ID da turma.</param>
/// <param name="alu_id">ID do aluno.</param>
/// <param name="mtu_id">ID da matrícula turma do aluno.</param>
/// <param name="fav_id">ID do formato de avaliação.</param>
/// <param name="ava_id">ID da avaliação.</param>
/// <returns></returns>
public static DataTable SelecionaPorMatriculaTurma(long tur_id, long alu_id, int mtu_id, int fav_id, int ava_id)
{
return new CLS_AlunoAvaliacaoTurmaQualidadeDAO().SelecionaPorMatriculaTurma(tur_id, alu_id, mtu_id, fav_id, ava_id);
}
/// <summary>
/// Seleciona uma lista de tipo de qualidade por matrícula do aluno.
/// </summary>
/// <param name="tur_id">ID da turma.</param>
/// <param name="alu_id">ID do aluno.</param>
/// <param name="mtu_id">ID da matrícula turma do aluno.</param>
/// <param name="fav_id">ID do formato de avaliação.</param>
/// <param name="ava_id">ID da avaliação.</param>
/// <returns></returns>
public static List<CLS_AlunoAvaliacaoTurmaQualidade> SelecionaListaPorMatriculaTurma(long tur_id, long alu_id, int mtu_id, int fav_id, int ava_id, TalkDBTransaction banco = null)
{
CLS_AlunoAvaliacaoTurmaQualidadeDAO dao = banco == null ?
new CLS_AlunoAvaliacaoTurmaQualidadeDAO() :
new CLS_AlunoAvaliacaoTurmaQualidadeDAO { _Banco = banco };
return (from DataRow dr in dao.SelecionaPorMatriculaTurma(tur_id, alu_id, mtu_id, fav_id, ava_id).Rows
select dao.DataRowToEntity(dr, new CLS_AlunoAvaliacaoTurmaQualidade())).ToList();
}
#endregion
#region Saves
/// <summary>
/// O método salva as qualidade cadastradas para o aluno e deleta as que forem desmarcadas.
/// </summary>
/// <param name="tur_id">ID da turma.</param>
/// <param name="alu_id">ID do aluno.</param>
/// <param name="mtu_id">ID da matrícula turma do aluno.</param>
/// <param name="fav_id">ID do formato de avaliação.</param>
/// <param name="ava_id">ID da avaliação.</param>
/// <param name="lista">Lista de qualidades adicionadas</param>
/// <param name="banco"></param>
/// <returns></returns>
public static bool Salvar(long tur_id, long alu_id, int mtu_id, int fav_id, int ava_id, List<CLS_AlunoAvaliacaoTurmaQualidade> lista, TalkDBTransaction banco)
{
bool retorno = true;
List<CLS_AlunoAvaliacaoTurmaQualidade> listaCadastrados = SelecionaListaPorMatriculaTurma(tur_id, alu_id, mtu_id, fav_id, ava_id, banco);
if (lista.Any())
{
List<CLS_AlunoAvaliacaoTurmaQualidade> listaExcluir = !listaCadastrados.Any() ?
new List<CLS_AlunoAvaliacaoTurmaQualidade>() : listaCadastrados.Where(p => !lista.Contains(p)).ToList();
List<CLS_AlunoAvaliacaoTurmaQualidade> listaSalvar = listaCadastrados.Any() ?
lista.Where(p => !listaCadastrados.Contains(p)).ToList() : lista;
retorno &= !listaExcluir.Any() ? retorno : listaExcluir.Aggregate(true, (excluiu, qualidade) => excluiu & Delete(qualidade, banco));
retorno &= !listaSalvar.Any() ? retorno : listaSalvar.Aggregate(true, (salvou, qualidade) => salvou & Save(qualidade, banco));
}
else
{
retorno &= !listaCadastrados.Any() ? retorno : listaCadastrados.Aggregate(true, (excluiu, qualidade) => excluiu & Delete(qualidade, banco));
}
return retorno;
}
/// <summary>
/// O método salva um registro na tabela CLS_AlunoAvaliacaoTurmaQualidade.
/// </summary>
/// <param name="entity">Entidade CLS_AlunoAvaliacaoTurmaQualidade</param>
/// <param name="banco"></param>
/// <returns></returns>
public static new bool Save(CLS_AlunoAvaliacaoTurmaQualidade entity, TalkDBTransaction banco)
{
if (entity.Validate())
{
return new CLS_AlunoAvaliacaoTurmaQualidadeDAO { _Banco = banco }.Salvar(entity);
}
throw new ValidationException(GestaoEscolarUtilBO.ErrosValidacao(entity));
}
/// <summary>
/// O método salva um registro na tabela CLS_AlunoAvaliacaoTurmaQualidade.
/// </summary>
/// <param name="entity">Entidade CLS_AlunoAvaliacaoTurmaQualidade</param>
/// <returns></returns>
public static new bool Save(CLS_AlunoAvaliacaoTurmaQualidade entity)
{
if (entity.Validate())
{
return new CLS_AlunoAvaliacaoTurmaQualidadeDAO().Salvar(entity);
}
throw new ValidationException(GestaoEscolarUtilBO.ErrosValidacao(entity));
}
#endregion
}
} | prefeiturasp/SME-SGP | Src/MSTech.GestaoEscolar.BLL/CLS_AlunoAvaliacaoTurmaQualidadeBO.cs | C# | agpl-3.0 | 5,771 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.