code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
<h2 class="problem-header">
{{display_name}} (External resource)
</h2>
<div id="{{element_id}}" class="${{element_class}} lti-consumer-container">
{{ message }}
</div>
|
open-craft/xblock-dalite
|
dalite_xblock/templates/dalite_xblock_data_not_filled.html
|
HTML
|
agpl-3.0
| 177
|
{% extends "page.html" %}
{% block subtitle %}{{ _("Tag Manager") }}{% endblock %}
{% block breadcrumb_content %}
<li class="active">{{ h.nav_link(_('Tags Manager'), controller='package', action='search', highlight_actions = 'new index') }}</li>
{% endblock %}
{% block page_header %}{% endblock %}
{% block primary_content_inner %}
<h1 class="hide-heading">{{ _('Tags') }}</h1>
{% if h.check_access('group_create') %} <!-- TODO Tag create access! -->
{% block tags_list_with_remove %}
{% snippet "tagmanager/snippets/tags_list_with_remove.html" %}
{% endblock %}
{% else %}
{% block tags_list %}
{% snippet "tagmanager/snippets/tags_list.html" %}
{% endblock %}
{% endif %} <!-- tag create access -->
{% endblock %} <!--primary content inner -->
{% block secondary_content %}
{% snippet "group/snippets/helper.html" %}
{% endblock %}
|
alantygel/ckanext-tagmanager
|
ckanext/tagmanager/templates/tagmanager/edit.html
|
HTML
|
agpl-3.0
| 876
|
<?php
/*
* Github webhook In-game PR Announcer and Changelog Generator for /tg/Station13
* Author: MrStonedOne
* For documentation on the changelog generator see https://tgstation13.org/phpBB/viewtopic.php?f=5&t=5157
* To hide prs from being announced in game, place a [s] in front of the title
* All runtime errors are echo'ed to the webhook's logs in github
* Update = very yes
*/
/**CREDITS:
* GitHub webhook handler template.
*
* @see https://developer.github.com/webhooks/
* @author Miloslav Hula (https://github.com/milo)
*/
//CONFIG START (all defaults are random examples, do change them)
//Use single quotes for config options that are strings.
require_once 'secret.php';
$enable_live_tracking = true; //auto update this file from the repository
$path_to_script = 'tools/WebhookProcessor/github_webhook_processor.php';
$trackPRBalance = true; //set this to false to disable PR balance tracking
$prBalanceJson = ''; //Set this to the path you'd like the writable pr balance file to be stored, not setting it writes it to the working directory
$startingPRBalance = 3; //Starting balance for never before seen users
//team 133041: tgstation/commit-access
$maintainer_team_id = 133041; //org team id that is exempt from PR balance system, setting this to null will use anyone with write access to the repo. Get from https://api.github.com/orgs/:org/teams
//anti-spam measures. Don't announce PRs in game to people unless they've gotten a pr merged before
//options are:
// "repo" - user has to have a pr merged in the repo before.
// "org" - user has to have a pr merged in any repo in the organization (for repos owned directly by users, this applies to any repo directly owned by the same user.)
// "disable" - disables.
//defaults to org if left blank or given invalid values.
$validation = "org";
//how many merged prs must they have under the rules above to have their pr announced to the game servers.
$validation_count = 1;
//CONFIG END
set_error_handler(function($severity, $message, $file, $line) {
throw new \ErrorException($message, 0, $severity, $file, $line);
});
set_exception_handler(function($e) {
header('HTTP/1.1 500 Internal Server Error');
echo "Error on line {$e->getLine()}: " . htmlSpecialChars($e->getMessage());
die();
});
$rawPost = NULL;
if (!$hookSecret || $hookSecret == '08ajh0qj93209qj90jfq932j32r')
throw new \Exception("Hook secret is required and can not be default");
if (!isset($_SERVER['HTTP_X_HUB_SIGNATURE'])) {
throw new \Exception("HTTP header 'X-Hub-Signature' is missing.");
} elseif (!extension_loaded('hash')) {
throw new \Exception("Missing 'hash' extension to check the secret code validity.");
}
list($algo, $hash) = explode('=', $_SERVER['HTTP_X_HUB_SIGNATURE'], 2) + array('', '');
if (!in_array($algo, hash_algos(), TRUE)) {
throw new \Exception("Hash algorithm '$algo' is not supported.");
}
$rawPost = file_get_contents('php://input');
if ($hash !== hash_hmac($algo, $rawPost, $hookSecret)) {
throw new \Exception('Hook secret does not match.');
}
$contenttype = null;
//apache and nginx/fastcgi/phpfpm call this two different things.
if (!isset($_SERVER['HTTP_CONTENT_TYPE'])) {
if (!isset($_SERVER['CONTENT_TYPE']))
throw new \Exception("Missing HTTP 'Content-Type' header.");
else
$contenttype = $_SERVER['CONTENT_TYPE'];
} else {
$contenttype = $_SERVER['HTTP_CONTENT_TYPE'];
}
if (!isset($_SERVER['HTTP_X_GITHUB_EVENT'])) {
throw new \Exception("Missing HTTP 'X-Github-Event' header.");
}
switch ($contenttype) {
case 'application/json':
$json = $rawPost ?: file_get_contents('php://input');
break;
case 'application/x-www-form-urlencoded':
$json = $_POST['payload'];
break;
default:
throw new \Exception("Unsupported content type: $contenttype");
}
# Payload structure depends on triggered event
# https://developer.github.com/v3/activity/events/types/
$payload = json_decode($json, true);
switch (strtolower($_SERVER['HTTP_X_GITHUB_EVENT'])) {
case 'ping':
echo 'pong';
break;
case 'pull_request':
handle_pr($payload);
break;
default:
header('HTTP/1.0 404 Not Found');
echo "Event:$_SERVER[HTTP_X_GITHUB_EVENT] Payload:\n";
print_r($payload); # For debug only. Can be found in GitHub hook log.
die();
}
function apisend($url, $method = 'GET', $content = NULL) {
global $apiKey;
if (is_array($content))
$content = json_encode($content);
$scontext = array('http' => array(
'method' => $method,
'header' =>
"Content-type: application/json\r\n".
'Authorization: token ' . $apiKey,
'ignore_errors' => true,
'user_agent' => 'tgstation13.org-Github-Automation-Tools'
));
if ($content)
$scontext['http']['content'] = $content;
return file_get_contents($url, false, stream_context_create($scontext));
}
function validate_user($payload) {
global $validation, $validation_count;
$query = array();
if (empty($validation))
$validation = 'org';
switch (strtolower($validation)) {
case 'disable':
return TRUE;
case 'repo':
$query['repo'] = $payload['pull_request']['base']['repo']['full_name'];
break;
default:
$query['user'] = $payload['pull_request']['base']['repo']['owner']['login'];
break;
}
$query['author'] = $payload['pull_request']['user']['login'];
$query['is'] = 'merged';
$querystring = '';
foreach($query as $key => $value)
$querystring .= ($querystring == '' ? '' : '+') . urlencode($key) . ':' . urlencode($value);
$res = apisend('https://api.github.com/search/issues?q='.$querystring);
$res = json_decode($res, TRUE);
return $res['total_count'] >= (int)$validation_count;
}
//rip bs-12
function tag_pr($payload, $opened) {
//get the mergeable state
$url = $payload['pull_request']['url'];
$payload['pull_request'] = json_decode(apisend($url), TRUE);
if($payload['pull_request']['mergeable'] == null) {
//STILL not ready. Give it a bit, then try one more time
sleep(10);
$payload['pull_request'] = json_decode(apisend($url), TRUE);
}
$tags = array();
$title = $payload['pull_request']['title'];
if($opened) { //you only have one shot on these ones so as to not annoy maintainers
$tags = checkchangelog($payload, true, false);
if(strpos(strtolower($title), 'refactor') !== FALSE)
$tags[] = 'Refactor';
if(strpos(strtolower($title), 'revert') !== FALSE || strpos(strtolower($title), 'removes') !== FALSE)
$tags[] = 'Revert/Removal';
}
$remove = array();
$mergeable = $payload['pull_request']['mergeable'];
if($mergeable === TRUE) //only look for the false value
$remove[] = 'Merge Conflict';
else if ($mergable === FALSE)
$tags[] = 'Merge Conflict';
$treetags = array('_maps' => 'Map Edit', 'tools' => 'Tools', 'SQL' => 'SQL');
$addonlytags = array('icons' => 'Sprites', 'sounds' => 'Sound', 'config' => 'Config Update');
foreach($treetags as $tree => $tag)
if(has_tree_been_edited($payload, $tree))
$tags[] = $tag;
else
$remove[] = $tag;
foreach($addonlytags as $tree => $tag)
if(has_tree_been_edited($payload, $tree))
$tags[] = $tag;
//only maintners should be able to remove these
if(strpos(strtolower($title), '[dnm]') !== FALSE)
$tags[] = 'Do Not Merge';
if(strpos(strtolower($title), '[wip]') !== FALSE)
$tags[] = 'Work In Progress';
$url = $payload['pull_request']['issue_url'] . '/labels';
$existing_labels = json_decode(apisend($url), true);
$existing = array();
foreach($existing_labels as $label)
$existing[] = $label['name'];
$tags = array_merge($tags, $existing);
$tags = array_unique($tags);
$tags = array_diff($tags, $remove);
$final = array();
foreach($tags as $t)
$final[] = $t;
echo apisend($url, 'PUT', $final);
return $final;
}
function remove_ready_for_review($payload, $labels, $r4rlabel){
$index = array_search($r4rlabel, $labels);
if($index !== FALSE)
unset($labels[$index]);
$url = $payload['pull_request']['issue_url'] . '/labels';
apisend($url, 'PUT', $labels);
}
function check_ready_for_review($payload, $labels){
$r4rlabel = 'Ready for Review';
$has_label_already = false;
//if the label is already there we may need to remove it
foreach($labels as $L)
if($L == $r4rlabel){
$has_label_already = true;
break;
}
//find all reviews to see if changes were requested at some point
$reviews = json_decode(apisend($payload['pull_request']['url'] . '/reviews'), true);
$reviews_ids_with_changes_requested = array();
foreach($reviews as $R){
if($R['state'] == 'CHANGES_REQUESTED' && isset($R['author_association']) && ($R['author_association'] == 'MEMBER' || $R['author_association'] == 'CONTRIBUTOR' || $R['author_association'] == 'OWNER'))
$reviews_ids_with_changes_requested[] = $R['id'];
}
if(count($reviews_ids_with_changes_requested) == 0){
if($has_label_already)
remove_ready_for_review($payload, $labels, $r4rlabel);
return; //no need to be here
}
echo count($reviews_ids_with_changes_requested) . ' offending reviews';
//now get the review comments for the offending reviews
$review_comments = json_decode(apisend($payload['pull_request']['review_comments_url']), true);
foreach($review_comments as $C){
//make sure they are part of an offending review
if(!in_array($C['pull_request_review_id'], $reviews_ids_with_changes_requested))
continue;
//review comments which are outdated have a null position
if($C['position'] !== null){
if($has_label_already)
remove_ready_for_review($payload, $labels, $r4rlabel);
return; //no need to tag
}
}
$labels[] = $r4rlabel;
$url = $payload['pull_request']['issue_url'] . '/labels';
apisend($url, 'PUT', $labels);
}
function handle_pr($payload) {
$action = 'opened';
$validated = validate_user($payload);
switch ($payload["action"]) {
case 'opened':
tag_pr($payload, true);
if(get_pr_code_friendliness($payload) < 0){
$balances = pr_balances();
$author = $payload['pull_request']['user']['login'];
if(isset($balances[$author]) && $balances[$author] < 0)
create_comment($payload, 'You currently have a negative Fix/Feature pull request delta of ' . $balances[$author] . '. Maintainers may close this PR at will. Fixing issues or improving the codebase will improve this score.');
}
break;
case 'edited':
case 'synchronize':
$labels = tag_pr($payload, false);
check_ready_for_review($payload, $labels);
return;
case 'reopened':
$action = $payload['action'];
break;
case 'closed':
if (!$payload['pull_request']['merged']) {
$action = 'closed';
}
else {
$action = 'merged';
auto_update($payload);
checkchangelog($payload, true, true);
update_pr_balance($payload);
$validated = TRUE; //pr merged events always get announced.
}
break;
default:
return;
}
if (strpos(strtolower($payload['pull_request']['title']), '[s]') !== false) {
echo "PR Announcement Halted; Secret tag detected.\n";
return;
}
if (!$validated) {
echo "PR Announcement Halted; User not validated.\n";
return;
}
$msg = '['.$payload['pull_request']['base']['repo']['full_name'].'] Pull Request '.$action.' by '.htmlSpecialChars($payload['sender']['login']).': <a href="'.$payload['pull_request']['html_url'].'">'.htmlSpecialChars('#'.$payload['pull_request']['number'].' '.$payload['pull_request']['user']['login'].' - '.$payload['pull_request']['title']).'</a>';
sendtoallservers('?announce='.urlencode($msg), $payload);
}
//creates a comment on the payload issue
function create_comment($payload, $comment){
apisend($payload['pull_request']['comments_url'], 'POST', json_encode(array('body' => $comment)));
}
//returns the payload issue's labels as a flat array
function get_pr_labels_array($payload){
$url = $payload['pull_request']['issue_url'] . '/labels';
$issue = json_decode(apisend($url), true);
$result = array();
foreach($issue as $l)
$result[] = $l['name'];
return $result;
}
//helper for getting the path the the balance json file
function pr_balance_json_path(){
global $prBalanceJson;
return $prBalanceJson != '' ? $prBalanceJson : 'pr_balances.json';
}
//return the assoc array of login -> balance for prs
function pr_balances(){
$path = pr_balance_json_path();
if(file_exists($path))
return json_decode(file_get_contents($path), true);
else
return array();
}
//returns the difference in PR balance a pull request would cause
function get_pr_code_friendliness($payload, $oldbalance = null){
global $startingPRBalance;
if($oldbalance == null)
$oldbalance = $startingPRBalance;
$labels = get_pr_labels_array($payload);
//anything not in this list defaults to 0
$label_values = array(
'Fix' => 2,
'Refactor' => 2,
'Code Improvement' => 1,
'Priority: High' => 4,
'Priority: CRITICAL' => 5,
'Atmospherics' => 4,
'Logging' => 1,
'Feedback' => 1,
'Performance' => 3,
'Feature' => -1,
'Balance/Rebalance' => -1,
'Tweak' => -1,
'PRB: Reset' => $startingPRBalance - $oldbalance,
);
$affecting = 0;
$is_neutral = FALSE;
$found_something_positive = false;
foreach($labels as $l){
if($l == 'PRB: No Update') { //no effect on balance
$affecting = 0;
break;
}
else if(isset($label_values[$l])) {
$friendliness = $label_values[$l];
if($friendliness > 0)
$found_something_positive = true;
$affecting = $found_something_positive ? max($affecting, $friendliness) : $friendliness;
}
}
return $affecting;
}
function is_maintainer($payload, $author){
global $maintainer_team_id;
$repo_is_org = $payload['pull_request']['base']['repo']['owner']['type'] == 'Organization';
if($maintainer_team_id == null || !$repo_is_org) {
$collaburl = $payload['pull_request']['base']['repo']['collaborators_url'] . '/' . $author . '/permissions';
$perms = json_decode(apisend($collaburl), true);
$permlevel = $perms['permission'];
return $permlevel == 'admin' || $permlevel == 'write';
}
else {
$check_url = 'https://api.github.com/teams/' . $maintainer_team_id . '/memberships/' . $author;
$result = json_decode(apisend($check_url), true);
return isset($result['state']); //this field won't be here if they aren't a member
}
}
//payload is a merged pull request, updates the pr balances file with the correct positive or negative balance based on comments
function update_pr_balance($payload) {
global $startingPRBalance;
global $trackPRBalance;
if(!$trackPRBalance)
return;
$author = $payload['pull_request']['user']['login'];
if(is_maintainer($payload, $author)) //immune
return;
$balances = pr_balances();
if(!isset($balances[$author]))
$balances[$author] = $startingPRBalance;
$friendliness = get_pr_code_friendliness($payload, $balances[$author]);
$balances[$author] += $friendliness;
if($balances[$author] < 0 && $friendliness < 0)
create_comment($payload, 'Your Fix/Feature pull request delta is currently below zero (' . $balances[$author] . '). Maintainers may close future Feature/Tweak/Balance PRs. Fixing issues or helping to improve the codebase will raise this score.');
else if($balances[$author] >= 0 && ($balances[$author] - $friendliness) < 0)
create_comment($payload, 'Your Fix/Feature pull request delta is now above zero (' . $balances[$author] . '). Feel free to make Feature/Tweak/Balance PRs.');
$balances_file = fopen(pr_balance_json_path(), 'w');
fwrite($balances_file, json_encode($balances));
fclose($balances_file);
}
function auto_update($payload){
global $enable_live_tracking;
global $path_to_script;
global $repoOwnerAndName;
if(!$enable_live_tracking || !has_tree_been_edited($payload, $path_to_script))
return;
$content = file_get_contents('https://raw.githubusercontent.com/' . $repoOwnerAndName . '/master/'. $path_to_script);
create_comment($payload, "Edit detected. Self updating... Here is my new code:\n``" . "`HTML+PHP\n" . $content . "\n``" . '`');
$code_file = fopen(basename($path_to_script), 'w');
fwrite($code_file, $content);
fclose($code_file);
}
function has_tree_been_edited($payload, $tree){
//go to the diff url
$url = $payload['pull_request']['diff_url'];
$content = file_get_contents($url);
//find things in the _maps/map_files tree
//e.g. diff --git a/_maps/map_files/Cerestation/cerestation.dmm b/_maps/map_files/Cerestation/cerestation.dmm
return $content !== FALSE && strpos($content, 'diff --git a/' . $tree) !== FALSE;
}
function checkchangelog($payload, $merge = false, $compile = true) {
if (!$merge)
return;
if (!isset($payload['pull_request']) || !isset($payload['pull_request']['body'])) {
return;
}
if (!isset($payload['pull_request']['user']) || !isset($payload['pull_request']['user']['login'])) {
return;
}
$body = $payload['pull_request']['body'];
$tags = array();
if(preg_match('/(?i)(fix|fixes|fixed|resolve|resolves|resolved)\s*#[0-9]+/',$body)) //github autoclose syntax
$tags[] = 'Fix';
$body = str_replace("\r\n", "\n", $body);
$body = explode("\n", $body);
$username = $payload['pull_request']['user']['login'];
$incltag = false;
$changelogbody = array();
$currentchangelogblock = array();
$foundcltag = false;
foreach ($body as $line) {
$line = trim($line);
if (substr($line,0,4) == ':cl:' || substr($line,0,4) == '🆑') {
$incltag = true;
$foundcltag = true;
$pos = strpos($line, " ");
if ($pos) {
$tmp = substr($line, $pos+1);
if (trim($tmp) != 'optional name here')
$username = $tmp;
}
continue;
} else if (substr($line,0,5) == '/:cl:' || substr($line,0,6) == '/ :cl:' || substr($line,0,5) == ':/cl:' || substr($line,0,5) == '/🆑' || substr($line,0,6) == '/ 🆑' ) {
$incltag = false;
$changelogbody = array_merge($changelogbody, $currentchangelogblock);
continue;
}
if (!$incltag)
continue;
$firstword = explode(' ', $line)[0];
$pos = strpos($line, " ");
$item = '';
if ($pos) {
$firstword = trim(substr($line, 0, $pos));
$item = trim(substr($line, $pos+1));
} else {
$firstword = $line;
}
if (!strlen($firstword)) {
$currentchangelogblock[count($currentchangelogblock)-1]['body'] .= "\n";
continue;
}
//not a prefix line.
//so we add it to the last changelog entry as a separate line
if (!strlen($firstword) || $firstword[strlen($firstword)-1] != ':') {
if (count($currentchangelogblock) <= 0)
continue;
$currentchangelogblock[count($currentchangelogblock)-1]['body'] .= "\n".$line;
continue;
}
$cltype = strtolower(substr($firstword, 0, -1));
switch ($cltype) {
case 'fix':
case 'fixes':
case 'bugfix':
if($item != 'fixed a few things') {
$tags[] = 'Fix';
$currentchangelogblock[] = array('type' => 'bugfix', 'body' => $item);
}
break;
case 'wip':
if($item != 'added a few works in progress')
$currentchangelogblock[] = array('type' => 'wip', 'body' => $item);
break;
case 'rsctweak':
case 'tweaks':
case 'tweak':
if($item != 'tweaked a few things') {
$tags[] = 'Tweak';
$currentchangelogblock[] = array('type' => 'tweak', 'body' => $item);
}
break;
case 'soundadd':
if($item != 'added a new sound thingy') {
$tags[] = 'Sound';
$currentchangelogblock[] = array('type' => 'soundadd', 'body' => $item);
}
break;
case 'sounddel':
if($item != 'removed an old sound thingy') {
$tags[] = 'Sound';
$tags[] = 'Revert/Removal';
$currentchangelogblock[] = array('type' => 'sounddel', 'body' => $item);
}
break;
case 'add':
case 'adds':
case 'rscadd':
if($item != 'Added new things' && $item != 'Added more things') {
$tags[] = 'Feature';
$currentchangelogblock[] = array('type' => 'rscadd', 'body' => $item);
}
break;
case 'del':
case 'dels':
case 'rscdel':
if($item != 'Removed old things') {
$tags[] = 'Revert/Removal';
$currentchangelogblock[] = array('type' => 'rscdel', 'body' => $item);
}
break;
case 'imageadd':
if($item != 'added some icons and images') {
$tags[] = 'Sprites';
$currentchangelogblock[] = array('type' => 'imageadd', 'body' => $item);
}
break;
case 'imagedel':
if($item != 'deleted some icons and images') {
$tags[] = 'Sprites';
$tags[] = 'Revert/Removal';
$currentchangelogblock[] = array('type' => 'imagedel', 'body' => $item);
}
break;
case 'typo':
case 'spellcheck':
if($item != 'fixed a few typos') {
$tags[] = 'Grammar and Formatting';
$currentchangelogblock[] = array('type' => 'spellcheck', 'body' => $item);
}
break;
case 'experimental':
case 'experiment':
if($item != 'added an experimental thingy')
$currentchangelogblock[] = array('type' => 'experiment', 'body' => $item);
break;
case 'balance':
case 'rebalance':
if($item != 'rebalanced something'){
$tags[] = 'Balance/Rebalance';
$currentchangelogblock[] = array('type' => 'balance', 'body' => $item);
}
break;
case 'tgs':
$currentchangelogblock[] = array('type' => 'tgs', 'body' => $item);
break;
default:
//we add it to the last changelog entry as a separate line
if (count($currentchangelogblock) > 0)
$currentchangelogblock[count($currentchangelogblock)-1]['body'] .= "\n".$line;
break;
}
}
if (!count($changelogbody) || !$compile)
return $tags;
$file = 'author: "'.trim(str_replace(array("\\", '"'), array("\\\\", "\\\""), $username)).'"'."\n";
$file .= "delete-after: True\n";
$file .= "changes: \n";
foreach ($changelogbody as $changelogitem) {
$type = $changelogitem['type'];
$body = trim(str_replace(array("\\", '"'), array("\\\\", "\\\""), $changelogitem['body']));
$file .= ' - '.$type.': "'.$body.'"';
$file .= "\n";
}
$content = array (
'branch' => $payload['pull_request']['base']['ref'],
'message' => 'Automatic changelog generation for PR #'.$payload['pull_request']['number'].' [ci skip]',
'content' => base64_encode($file)
);
$filename = '/html/changelogs/AutoChangeLog-pr-'.$payload['pull_request']['number'].'.yml';
echo apisend($payload['pull_request']['base']['repo']['url'].'/contents'.$filename, 'PUT', $content);
}
function sendtoallservers($str, $payload = null) {
global $servers;
if (!empty($payload))
$str .= '&payload='.urlencode(json_encode($payload));
foreach ($servers as $serverid => $server) {
$msg = $str;
if (isset($server['comskey']))
$msg .= '&key='.urlencode($server['comskey']);
$rtn = export($server['address'], $server['port'], $msg);
echo "Server Number $serverid replied: $rtn\n";
}
}
function export($addr, $port, $str) {
// All queries must begin with a question mark (ie "?players")
if($str{0} != '?') $str = ('?' . $str);
/* --- Prepare a packet to send to the server (based on a reverse-engineered packet structure) --- */
$query = "\x00\x83" . pack('n', strlen($str) + 6) . "\x00\x00\x00\x00\x00" . $str . "\x00";
/* --- Create a socket and connect it to the server --- */
$server = socket_create(AF_INET,SOCK_STREAM,SOL_TCP) or exit("ERROR");
socket_set_option($server, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 2, 'usec' => 0)); //sets connect and send timeout to 2 seconds
if(!socket_connect($server,$addr,$port)) {
return "ERROR: Connection failed";
}
/* --- Send bytes to the server. Loop until all bytes have been sent --- */
$bytestosend = strlen($query);
$bytessent = 0;
while ($bytessent < $bytestosend) {
//echo $bytessent.'<br>';
$result = socket_write($server,substr($query,$bytessent),$bytestosend-$bytessent);
//echo 'Sent '.$result.' bytes<br>';
if ($result===FALSE)
return "ERROR: " . socket_strerror(socket_last_error());
$bytessent += $result;
}
/* --- Idle for a while until recieved bytes from game server --- */
$result = socket_read($server, 10000, PHP_BINARY_READ);
socket_close($server); // we don't need this anymore
if($result != "") {
if($result{0} == "\x00" || $result{1} == "\x83") { // make sure it's the right packet format
// Actually begin reading the output:
$sizebytes = unpack('n', $result{2} . $result{3}); // array size of the type identifier and content
$size = $sizebytes[1] - 1; // size of the string/floating-point (minus the size of the identifier byte)
if($result{4} == "\x2a") { // 4-byte big-endian floating-point
$unpackint = unpack('f', $result{5} . $result{6} . $result{7} . $result{8}); // 4 possible bytes: add them up together, unpack them as a floating-point
return $unpackint[1];
}
else if($result{4} == "\x06") { // ASCII string
$unpackstr = ""; // result string
$index = 5; // string index
while($size > 0) { // loop through the entire ASCII string
$size--;
$unpackstr .= $result{$index}; // add the string position to return string
$index++;
}
return $unpackstr;
}
}
}
return "";
}
?>
|
MrStonedOne/-tg-station
|
tools/WebhookProcessor/github_webhook_processor.php
|
PHP
|
agpl-3.0
| 24,718
|
class IndexMembershipsAndTypes < ActiveRecord::Migration
def change
add_index :membership_types, :organization_id
add_index :memberships, :membership_type_id
end
end
|
andrewkrug/artfully_ose
|
db/migrate/20140125183606_index_memberships_and_types.rb
|
Ruby
|
agpl-3.0
| 185
|
import classNames from 'classnames'
import ReactSwitch from 'react-switch'
type Props = {
ariaLabel: string
checked?: boolean
onChange: any
}
export const Switch = ({ ariaLabel, checked, onChange }: Props) => {
const switchClass = classNames(checked ? 'is-on' : 'is-off')
return (
<div className='switch'>
<ReactSwitch
aria-label={ariaLabel}
checked={checked}
checkedIcon={false}
className={switchClass}
height={22}
onChange={onChange}
uncheckedIcon={false}
width={37}
/>
</div>
)
}
|
podverse/podverse-web
|
src/components/Switch/Switch.tsx
|
TypeScript
|
agpl-3.0
| 581
|
/*
* Copyright 2015 BrewPi/Elco Jacobs.
* Copyright 2015 Matthew McGowan.
*
* This file is part of BrewPi.
*
* BrewPi 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.
*
* BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "Platform.h"
#include "ActuatorInterfaces.h"
class ActuatorPin final: public ActuatorDigital, public ActuatorPinMixin
{
private:
bool invert;
uint8_t pin;
public:
ActuatorPin(uint8_t pin,
bool invert);
~ActuatorPin() = default;
void accept(VisitorBase & v) final {
v.visit(*this);
}
void setState(State state, int8_t priority = 127) override final
{
digitalWrite(pin, ((state == State::Active) ^ invert) ? HIGH : LOW);
}
State getState() const override final
{
return ((digitalRead(pin) != LOW) ^ invert) ? State::Active : State::Inactive;
}
void update() override final {} // do nothing on periodic update
void fastUpdate() override final {} // do nothing on fast update
friend class ActuatorPinMixin;
};
|
BrewPi/firmware
|
platform/wiring/ActuatorPin.h
|
C
|
agpl-3.0
| 1,669
|
# This file is part of Mconf-Web, a web application that provides access
# to the Mconf webconferencing system. Copyright (C) 2010-2012 Mconf
#
# This file is licensed under the Affero General Public License version
# 3 or later. See the LICENSE file.
require "spec_helper"
describe AdminMailer do
describe '.new_user_waiting_for_approval' do
let(:admin) { FactoryGirl.create(:user, superuser: true) }
let(:user) { FactoryGirl.create(:user) }
let(:mail) { AdminMailer.new_user_waiting_for_approval(admin.id, user.id) }
context "in the standard case" do
it("sets 'to'") { mail.to.should eql([admin.email]) }
it("sets 'subject'") {
text = I18n.t('admin_mailer.new_user_waiting_for_approval.subject')
text = "[#{Site.current.name}] #{text}"
mail.subject.should eql(text)
}
it("sets 'from'") { mail.from.should eql([Site.current.smtp_sender]) }
it("sets 'headers'") { mail.headers.should eql({}) }
it("sets 'reply_to'") { mail.reply_to.should eql([Site.current.smtp_sender]) }
it("assigns @user_name") {
mail.body.encoded.should match(user.name)
}
end
context "uses the receiver's locale" do
before {
Site.current.update_attributes(:locale => "en")
admin.update_attribute(:locale, "pt-br")
user.update_attribute(:locale, "en")
}
it {
content = I18n.t('admin_mailer.new_user_waiting_for_approval.click_here', url: manage_users_url(host: Site.current.domain, q: user.email), locale: "pt-br")
mail.body.encoded.should match(Regexp.escape(content))
}
end
context "uses the current site's locale if the receiver has no locale set" do
before {
Site.current.update_attributes(:locale => "pt-br")
admin.update_attribute(:locale, nil)
user.update_attribute(:locale, "en")
}
it {
content = I18n.t('admin_mailer.new_user_waiting_for_approval.click_here', url: manage_users_url(host: Site.current.domain, q: user.email), locale: "pt-br")
mail.body.encoded.should match(Regexp.escape(content))
}
end
context "uses the default locale if the site has no locale set" do
before {
Site.current.update_attributes(:locale => nil)
I18n.default_locale = "pt-br"
admin.update_attribute(:locale, nil)
user.update_attribute(:locale, "en")
}
it {
content = I18n.t('admin_mailer.new_user_waiting_for_approval.click_here', url: manage_users_url(host: Site.current.domain, q: user.email), locale: "pt-br")
mail.body.encoded.should match(Regexp.escape(content))
}
end
end
describe '.new_user_approved' do
let(:user) { FactoryGirl.create(:user) }
let(:mail) { AdminMailer.new_user_approved(user.id) }
context "in the standard case" do
it("sets 'to'") { mail.to.should eql([user.email]) }
it("sets 'subject'") {
text = I18n.t('admin_mailer.new_user_approved.subject')
text = "[#{Site.current.name}] #{text}"
mail.subject.should eql(text)
}
it("sets 'from'") { mail.from.should eql([Site.current.smtp_sender]) }
it("sets 'headers'") { mail.headers.should eql({}) }
it("sets 'reply_to'") { mail.reply_to.should eql([Site.current.smtp_sender]) }
it("assigns @user_name") {
mail.body.encoded.should match(user.name)
}
end
context "uses the receiver's locale" do
before {
Site.current.update_attributes(:locale => "en")
user.update_attribute(:locale, "pt-br")
}
it {
content = I18n.t('admin_mailer.new_user_approved.click_here', url: my_home_url(host: Site.current.domain), locale: "pt-br")
mail.body.encoded.should match(content)
}
end
context "uses the current site's locale if the receiver has no locale set" do
before {
Site.current.update_attributes(:locale => "pt-br")
user.update_attribute(:locale, nil)
}
it {
content = I18n.t('admin_mailer.new_user_approved.click_here', url: my_home_url(host: Site.current.domain), locale: "pt-br")
mail.body.encoded.should match(content)
}
end
context "uses the default locale if the site has no locale set" do
before {
Site.current.update_attributes(:locale => nil)
I18n.default_locale = "pt-br"
user.update_attribute(:locale, nil)
}
it {
content = I18n.t('admin_mailer.new_user_approved.click_here', url: my_home_url(host: Site.current.domain), locale: "pt-br")
mail.body.encoded.should match(content)
}
end
end
context "calls the error handler on exceptions" do
let(:exception) { Exception.new("test exception") }
it {
with_resque do
BaseMailer.any_instance.stub(:render) { raise exception }
Mconf::MailerErrorHandler.should_receive(:handle).with(AdminMailer, nil, exception, "new_user_waiting_for_approval", anything)
AdminMailer.new_user_waiting_for_approval(1, 1).deliver
end
}
end
end
|
mconftec/mconf-web-ufpe
|
spec/mailers/admin_mailer_spec.rb
|
Ruby
|
agpl-3.0
| 5,089
|
**Merge checklist:**
- [ ] Any new requirements are in the right place (do **not** manually modify the `requirements/*.txt` files)
- `base.in` if needed in production but edx-platform doesn't install it
- `test-master.in` if edx-platform pins it, with a matching version
- `make upgrade && make requirements` have been run to regenerate requirements
- [ ] `make static` has been run to update webpack bundling if any static content was updated
- [ ] `./manage.py makemigrations` has been run
- Checkout the [Database Migration](https://openedx.atlassian.net/wiki/spaces/AC/pages/23003228/Everything+About+Database+Migrations) Confluence page for helpful tips on creating migrations.
- *Note*: This **must** be run if you modified any models.
- It may or may not make a migration depending on exactly what you modified, but it should still be run.
- This should be run from either a venv with all the lms/edx-enterprise requirements installed or if you checked out edx-enterprise into the src directory used by lms, you can run this command through an lms shell.
- It would be `./manage.py lms makemigrations` in the shell.
- [ ] [Version](https://github.com/edx/edx-enterprise/blob/master/enterprise/__init__.py) bumped
- [ ] [Changelog](https://github.com/edx/edx-enterprise/blob/master/CHANGELOG.rst) record added
- [ ] Translations updated (see docs/internationalization.rst but also this isn't blocking for merge atm)
**Post merge:**
- [ ] Tag pushed and a new [version](https://github.com/edx/edx-enterprise/releases) released
- *Note*: Assets will be added automatically. You just need to provide a tag (should match your version number) and title and description.
- [ ] After versioned build finishes in [GitHub Actions](https://github.com/edx/edx-enterprise/actions), verify version has been pushed to [PyPI](https://pypi.org/project/edx-enterprise/)
- Each step in the release build has a condition flag that checks if the rest of the steps are done and if so will deploy to PyPi.
(so basically once your build finishes, after maybe a minute you should see the new version in PyPi automatically (on refresh))
- [ ] PR created in [edx-platform](https://github.com/edx/edx-platform) to upgrade dependencies (including edx-enterprise)
- This **must** be done after the version is visible in PyPi as `make upgrade` in edx-platform will look for the latest version in PyPi.
- Note: the edx-enterprise constraint in edx-platform **must** also be bumped to the latest version in PyPi.
|
edx/edx-enterprise
|
.github/PULL_REQUEST_TEMPLATE.md
|
Markdown
|
agpl-3.0
| 2,546
|
<?php
/**
*
* Gestion de la saisie, de la modification d'un login
* Gestion du changement du mot de passe (en mode BDD)
*/
require_once 'framework/identification/loginGestion.class.php';
$dataClass = new LoginGestion($bdd_gacl, $ObjetBDDParam);
$dataClass->setKeys($privateKey, $pubKey);
$id = $_REQUEST["id"];
if (!$APPLI_passwordMinLength > 0) {
$APPLI_passwordMinLength = 12;
}
switch ($t_module["param"]) {
case "list":
/*
* Display the list of all records of the table
*/
$vue->set($dataClass->getListeTriee(), "liste");
$vue->set("framework/ident/loginliste.tpl", "corps");
break;
case "change":
try {
$data = $dataClass->lire($id);
$vue->set("framework/ident/loginsaisie.tpl", "corps");
$vue->set($APPLI_passwordMinLength, "passwordMinLength");
unset($data["password"]);
/**
* Add dbconnect_provisional_nb
*/
if (strlen($data["login"]) > 0) {
$data["dbconnect_provisional_nb"] = $dataClass->getDbconnectProvisionalNb($data["login"]);
}
$vue->set($data, "data");
} catch (FrameworkException | ObjetBDDException | PDOException $e) {
$message->set($e->getMessage(), true);
$module_coderetour = -1;
}
break;
case "write":
/*
* write record in database
*/
$id = dataWrite($dataClass, $_REQUEST);
if ($id > 0) {
/*
* Ecriture du compte dans la table acllogin
*/
try {
include_once "framework/droits/acllogin.class.php";
$acllogin = new Acllogin($bdd_gacl, $ObjetBDDParam);
if (!empty($_REQUEST["nom"])) {
$nom = $_REQUEST["nom"] . " " . $_REQUEST["prenom"];
} else {
$nom = $_REQUEST["login"];
}
$acllogin->addLoginByLoginAndName($_REQUEST["login"], $nom);
} catch (FrameworkException | ObjetBDDException | PDOException $e) {
$message->set(_("Problème rencontré lors de l'écriture du login pour la gestion des droits"), true);
$message->setSyslog($e->getMessage());
}
}
break;
case "delete":
/*
* delete record
*/
dataDelete($dataClass, $id);
break;
case "changePassword":
if ($log->getLastConnexionType($_SESSION["login"]) == "db") {
$vue->set("framework/ident/loginChangePassword.tpl", "corps");
$vue->set($APPLI_passwordMinLength, "passwordMinLength");
} else {
$message->set(_("Le mode d'identification utilisé pour votre compte n'autorise pas la modification du mot de passe depuis cette application"), true);
$vue->set("main.tpl");
}
break;
case 'changePasswordExec':
if ($dataClass->changePassword($_REQUEST["oldPassword"], $_REQUEST["pass1"], $_REQUEST["pass2"]) < 1) {
$module_coderetour = -1;
foreach ($dataClass->getErrorData(1) as $messageError) {
$message->set($messageError, true);
}
} else {
$module_coderetour = 1;
/**
* Send mail to the user
*/
$data = $dataClass->lireByLogin($_SESSION["login"]);
if (!empty($data["mail"]) && $MAIL_enabled == 1) {
include_once 'framework/identification/mail.class.php';
$subject = $_SESSION["APPLI_title"] . " - " . _("Modification du mot de passe");
$contents = "<html><body>" .
_("Vous venez de modifier votre mot de passe. Si vous n'êtes pas à l'origine de cette opération, contactez l'administrateur de l'application, et activez également la double authentification pour mieux protéger votre compte.") . "<br>" .
_("Ne répondez pas à ce message, il ne sera pas relevé") .
'</body></html>';
$MAIL_param = array(
"replyTo" => "$APPLI_mail",
"subject" => "$subject",
"from" => "$APPLI_mail",
"contents" => $contents,
);
$mail = new Mail($MAIL_param);
if ($mail->sendMail($dataLogin["mail"], array())) {
$log->setLog($_SESSION["login"], "password mail confirm", "ok");
} else {
$log->setLog($_SESSION["login"], "password mail confirm", "ko");
}
}
}
break;
}
|
Irstea/collec
|
framework/identification/login.php
|
PHP
|
agpl-3.0
| 4,164
|
class TreeView {
constructor($dom, store, adapter) {
this.store = store;
this.adapter = adapter;
this.$view = $dom.find('.octotree_treeview');
this.$tree = this.$view
.find('.octotree_view_body')
.on('click.jstree', '.jstree-open>a', ({target}) => {
setTimeout(() => {
this.$jstree.close_node(target)
}, 0);
})
.on('click.jstree', '.jstree-closed>a', ({target}) => {
setTimeout(() => {
this.$jstree.open_node(target)
}, 0);
})
.on('click', this._onItemClick.bind(this))
.jstree({
core: {multiple: false, worker: false, themes: {responsive: false}},
plugins: ['wholerow']
});
}
get $jstree() {
return this.$tree.jstree(true);
}
show(repo, token) {
const $jstree = this.$jstree;
$jstree.settings.core.data = (node, cb) => {
const prMode = this.store.get(STORE.PR) && repo.pullNumber;
const loadAll = this.adapter.canLoadEntireTree(repo) && (prMode || this.store.get(STORE.LOADALL));
node = !loadAll && (node.id === '#' ? {path: ''} : node.original);
this.adapter.loadCodeTree({repo, token, node}, (err, treeData) => {
if (err) {
if (err.status === 206 && loadAll) { // The repo is too big to load all, need to retry
$jstree.refresh(true);
} else {
$(this).trigger(EVENT.FETCH_ERROR, [err]);
}
} else {
treeData = this._sort(treeData);
if (loadAll) {
treeData = this._collapse(treeData);
}
cb(treeData);
}
});
};
this.$tree.one('refresh.jstree', () => {
this.syncSelection(repo);
$(this).trigger(EVENT.VIEW_READY);
});
this._showHeader(repo);
$jstree.refresh(true);
}
_showHeader(repo) {
const adapter = this.adapter;
this.$view
.find('.octotree_view_header')
.html(
`<div class="octotree_header_repo">
<a href="/${repo.username}">${repo.username}</a>
/
<a data-pjax href="/${repo.username}/${repo.reponame}">${repo.reponame}</a>
</div>
<div class="octotree_header_branch">
${this._deXss(repo.branch.toString())}
</div>`
)
.on('click', 'a[data-pjax]', function(event) {
event.preventDefault();
// A.href always return absolute URL, don't want that
const href = $(this).attr('href');
const newTab = event.shiftKey || event.ctrlKey || event.metaKey;
newTab ? adapter.openInNewTab(href) : adapter.selectFile(href);
});
}
_deXss(str) {
return str && str.replace(/[<>'"&]/g, '-');
}
_sort(folder) {
folder.sort((a, b) => {
if (a.type === b.type) return a.text === b.text ? 0 : a.text < b.text ? -1 : 1;
return a.type === 'blob' ? 1 : -1;
});
folder.forEach((item) => {
if (item.type === 'tree' && item.children !== true && item.children.length > 0) {
this._sort(item.children);
}
});
return folder;
}
_collapse(folder) {
return folder.map((item) => {
if (item.type === 'tree') {
item.children = this._collapse(item.children);
if (item.children.length === 1 && item.children[0].type === 'tree') {
const onlyChild = item.children[0];
onlyChild.text = item.text + '/' + onlyChild.text;
return onlyChild;
}
}
return item;
});
}
_onItemClick(event) {
let $target = $(event.target);
let download = false;
// Handle middle click
if (event.which === 2) return;
// Handle icon click, fix #122
if ($target.is('i.jstree-icon')) {
$target = $target.parent();
download = true;
}
if (!$target.is('a.jstree-anchor')) return;
// Refocus after complete so that keyboard navigation works, fix #158
const refocusAfterCompletion = () => {
$(document).one('pjax:success page:load', () => {
this.$jstree.get_container().focus();
});
};
const adapter = this.adapter;
const newTab = event.shiftKey || event.ctrlKey || event.metaKey;
const href = $target.attr('href');
// The 2nd path is for submodule child links
const $icon = $target.children().length ? $target.children(':first') : $target.siblings(':first');
if ($icon.hasClass('commit')) {
refocusAfterCompletion();
newTab ? adapter.openInNewTab(href) : adapter.selectSubmodule(href);
} else if ($icon.hasClass('blob')) {
if (download) {
const downloadUrl = $target.attr('data-download-url');
const downloadFileName = $target.attr('data-download-filename');
adapter.downloadFile(downloadUrl, downloadFileName);
} else {
refocusAfterCompletion();
newTab ? adapter.openInNewTab(href) : adapter.selectFile(href);
}
}
}
syncSelection(repo) {
const $jstree = this.$jstree;
if (!$jstree) return;
// Convert /username/reponame/object_type/branch/path to path
const path = decodeURIComponent(location.pathname);
const match = path.match(/(?:[^\/]+\/){4}(.*)/);
if (!match) return;
const currentPath = match[1];
const loadAll = this.adapter.canLoadEntireTree(repo) && this.store.get(STORE.LOADALL);
selectPath(loadAll ? [currentPath] : breakPath(currentPath));
// Convert ['a/b'] to ['a', 'a/b']
function breakPath(fullPath) {
return fullPath.split('/').reduce((res, path, idx) => {
res.push(idx === 0 ? path : `${res[idx - 1]}/${path}`);
return res;
}, []);
}
function selectPath(paths, index = 0) {
const nodeId = NODE_PREFIX + paths[index];
if ($jstree.get_node(nodeId)) {
$jstree.deselect_all();
$jstree.select_node(nodeId);
$jstree.open_node(nodeId, () => {
if (++index < paths.length) {
selectPath(paths, index);
}
});
}
}
}
}
|
crashbell/octotree
|
src/view.tree.js
|
JavaScript
|
agpl-3.0
| 5,983
|
# This file is part of Rails PowerDNS Admin
#
# Copyright (C) 2014-2015 Dennis <allspark> Börm
#
# Rails PowerDNS Admin 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.
#
# Rails PowerDNS Admin 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 Rails PowerDNS Admin. If not, see <http://www.gnu.org/licenses/>.
class UserRolePowerdnsDomain < ActiveRecord::Base
belongs_to :user
belongs_to :role
belongs_to :domain, class_name: PowerDns::Domain
end
|
allspark/rails_pdns_admin
|
app/models/user_role_powerdns_domain.rb
|
Ruby
|
agpl-3.0
| 941
|
/*
* Copyright (C) 2012-2022 Online-Go.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import * as React from "react";
import * as data from "data";
import { ai_socket } from "sockets";
import { MoveTree } from "goban";
import { IdType } from "src/lib/types";
const analysis_requests_made: { [id: string]: boolean } = {};
interface AIReviewStreamProperties {
uuid?: string;
game_id?: IdType;
ai_review_id?: IdType;
callback: (data: any) => any;
}
export function AIReviewStream(props: AIReviewStreamProperties): JSX.Element {
const uuid = props.uuid;
const game_id = props.game_id;
const ai_review_id = props.ai_review_id;
React.useEffect(() => {
if (!props.uuid) {
console.log("No UUID for review stream");
return;
} else {
ai_socket.on("connect", onConnect);
ai_socket.on(uuid, onMessage);
if (ai_socket.connected) {
onConnect();
}
}
function onJwtChange() {
const user = data.get("config.user");
const user_jwt = data.get("config.user_jwt");
if (!user.anonymous && user_jwt) {
ai_socket.send("authenticate", { jwt: user_jwt });
}
}
function watch_jwt() {
data.watch("config.user_jwt", onJwtChange);
}
function unwatch_jwt() {
data.unwatch("config.user_jwt", onJwtChange);
}
function onConnect() {
ai_socket.send("ai-review-connect", { uuid, game_id, ai_review_id });
watch_jwt();
}
function onMessage(data: any) {
props.callback(data);
}
return () => {
if (ai_socket.connected) {
ai_socket.send("ai-review-disconnect", { uuid });
}
ai_socket.off("connect", onConnect);
ai_socket.off(uuid, onMessage);
unwatch_jwt();
};
}, [uuid]);
return null;
}
export function ai_request_variation_analysis(
uuid,
game_id,
ai_review_id,
cur_move: MoveTree,
trunk_move: MoveTree,
): void {
if (!ai_socket.connected) {
console.warn(
"Not sending request for variation analysis since we wern't connected to the AI server",
);
return;
}
const trunk_move_string = trunk_move.getMoveStringToThisPoint();
const cur_move_string = cur_move.getMoveStringToThisPoint();
const variation = cur_move_string.slice(trunk_move_string.length);
const key = `${uuid}-${game_id}-${ai_review_id}-${trunk_move.move_number}-${variation}`;
if (key in analysis_requests_made) {
return;
}
analysis_requests_made[key] = true;
const req = {
uuid: uuid,
game_id: game_id,
ai_review_id: ai_review_id,
from: trunk_move.move_number,
variation: variation,
};
ai_socket.send("ai-analyze-variation", req);
}
|
online-go/online-go.com
|
src/components/AIReviewStream/AIReviewStream.tsx
|
TypeScript
|
agpl-3.0
| 3,607
|
#Generate install, uninstall and detect .PS1 scripts for Choco-managed software
$appFriendlyName = "Paint.Net (managed)" #e.g. "Adobe Reader (managed)"
$appChocoName = "Paint.Net" #e.g. "AdobeReader"
$installedAppFileForDetection = "${env:ProgramFiles}\Paint.Net\PaintDotNet.exe" #e.g. "${env:ProgramFiles(x86)}\Adobe\Acrobat Reader DC"
#$test = Start-Process -FilePath "$env:ProgramData\chocolatey\choco.exe" -ArgumentList "list $appChocoName" -PassThru
#$test = &(choco list $appChocoName)
#region Create Files
if(!(Test-Path "$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\$appChocoName")){
New-Item -Path "$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\" -Name $appChocoName -ItemType Directory
}
if(Test-Path "$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\$appChocoName"){
if(Test-Path "$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\$appChocoName\install.ps1"){Remove-Item "$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\$appChocoName\install.ps1" -Force}
Add-Content -Path "$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\$appChocoName\install.ps1" -Value "`$thisApp = `"$appChocoName`""
Get-Content -Path "$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\_example\install.ps1" | Add-Content "$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\$appChocoName\install.ps1"
if(Test-Path "$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\$appChocoName\uninstall.ps1"){Remove-Item "$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\$appChocoName\uninstall.ps1" -Force}
Add-Content -Path "$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\$appChocoName\uninstall.ps1" -Value "`$thisApp = `"$appChocoName`""
Get-Content -Path "$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\_example\uninstall.ps1" | Add-Content "$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\$appChocoName\uninstall.ps1"
if(Test-Path "$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\$appChocoName\detect.ps1"){Remove-Item "$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\$appChocoName\detect.ps1" -Force}
Add-Content -Path "$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\$appChocoName\detect.ps1" -Value "`$thisApp = `"$appChocoName`""
Add-Content -Path "$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\$appChocoName\detect.ps1" -Value "`$filePathToTest = `"$installedAppFileForDetection`""
Get-Content -Path "$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\_example\detect.ps1" | Add-Content "$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\$appChocoName\detect.ps1"
Start-Process -NoNewWindow -FilePath "$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\IntuneWinAppUtil.exe" -ArgumentList "-c `"$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\$appChocoName`"","-s install.ps1","-o `"$env:USERPROFILE\OneDrive - Anthesis LLC\Documents\WindowsPowerShell\Modules\Intune-WinApp\$appChocoName`"","-q"
}
#endregion
#region Create Security Group
$tokenResponseTeamBot = get-graphTokenResponse -aadAppCreds $(get-graphAppClientCredentials -appName TeamsBot) -grant_type client_credentials
$newSG = new-graphGroup -tokenResponse $tokenResponseTeamBot -groupDisplayName "Software - $appFriendlyName" -groupDescription "Security Group for deploying Choco-managed app [$appChocoName]" -groupType Security -membershipType Assigned
#endregion
#region Create Intune Win32 App
$tokenResponseIntuneBot = get-graphTokenResponse -aadAppCreds $(get-graphAppClientCredentials -appName IntuneBot) -grant_type client_credentials
Write-Host -ForegroundColor Yellow "Manually create a Win32 app here: `r`n`thttps://endpoint.microsoft.com/#blade/Microsoft_Intune_DeviceSettings/AppsWindowsMenu/windowsApps"
<#The managedApp endpoint doesn't (as of 2020-10-19) let you create these via Graph (https://docs.microsoft.com/en-us/graph/api/resources/intune-apps-managedapp?view=graph-rest-1.0) but an object looks like this:
{
"@odata.type": "#microsoft.graph.win32LobApp",
"id": "c5ade2d4-2f6a-47df-b0ef-1b8da11b8089",
"displayName": "GitHub Desktop (managed)",
"description": "Code management tool",
"publisher": "Git",
"largeIcon": null,
"createdDateTime": "2020-10-15T13:00:21.9877002Z",
"lastModifiedDateTime": "2020-10-15T13:00:21.9877002Z",
"isFeatured": false,
"privacyInformationUrl": "",
"informationUrl": "https://desktop.github.com/",
"owner": "Anthesis",
"developer": "",
"notes": "",
"publishingState": "published",
"committedContentVersion": "1",
"fileName": "install.intunewin",
"size": 1376,
"installCommandLine": "powershell.exe -executionpolicy bypass .\\install.ps1",
"uninstallCommandLine": "powershell.exe -executionpolicy bypass .\\uninstall.ps1",
"applicableArchitectures": "x86,x64",
"minimumFreeDiskSpaceInMB": null,
"minimumMemoryInMB": null,
"minimumNumberOfProcessors": null,
"minimumCpuSpeedInMHz": null,
"msiInformation": null,
"setupFilePath": "install.ps1",
"minimumSupportedWindowsRelease": "1803",
"rules": [
{
"@odata.type": "#microsoft.graph.win32LobAppPowerShellScriptRule",
"ruleType": "detection",
"displayName": null,
"enforceSignatureCheck": false,
"runAs32Bit": false,
"runAsAccount": null,
"scriptContent": "77u/JHRoaXNBcHAgPSAiR2l0SHViLURlc2t0b3AiDQokZmlsZVBhdGhUb1Rlc3QgPSAiJGVudjpMT0NBTEFQUERBVEFcR2l0SHViRGVza3RvcFxHaXRIdWJEZXNrdG9wLmV4ZSINCiRzY2hlZHVsZWRUYXNrVG9UZXN0ID0gIkFudGhlc2lzIElUIC0gQ2hvY28gSW50YWxsT3JVcGdyYWRlICR0aGlzQXBwIg0KDQppZihUZXN0LV
BhdGggJGZpbGVQYXRoVG9UZXN0KXsNCiAgICBpZihHZXQtU2NoZWR1bGVkVGFzayAtVGFza05hbWUgJHNjaGVkdWxlZFRhc2tUb1Rlc3Qpew0KICAgICAgICBXcml0ZS1Ib3N0ICJQYXRoIFskKCRmaWxlUGF0aFRvVGVzdCldIGFuZCBUYXNrIFskKCRzY2hlZHVsZWRUYXNrVG9UZXN0KV0gYm90aCBleGlzdCEiDQogICAgICAgIH0NCiAgICB9DQplbHNlew0KICAgIFRocm93ICJQY
XRoIFskKCRmaWxlUGF0aFRvVGVzdCldIG5vdCBmb3VuZCAtIFskKCR0aGlzQXBwKV0gaXMgbm90IGluc3RhbGxlZCINCiAgICB9",
"operationType": "notConfigured",
"operator": "notConfigured",
"comparisonValue": null
}
],
"installExperience": {
"runAsAccount": "system",
"deviceRestartBehavior": "allow"
},
"returnCodes": [
{
"returnCode": 0,
"type": "success"
},
{
"returnCode": 1707,
"type": "success"
},
{
"returnCode": 3010,
"type": "softReboot"
},
{
"returnCode": 1641,
"type": "hardReboot"
},
{
"returnCode": 1618,
"type": "retry"
}
]
} #>
#endregion
|
kevmaitland/PoshAnt
|
Intune-WinApp/_example/redeploy.ps1
|
PowerShell
|
agpl-3.0
| 8,126
|
#include <iostream>
#include <string>
#include <cstdlib>
#include "TextUtil.h"
#include "util.h"
void Usage() {
std::cerr << "Usage: " << ::progname << " utf8_text\n";
std::exit(EXIT_FAILURE);
}
int main(int argc, char *argv[]) {
::progname = argv[0];
if (argc != 2)
Usage();
std::string s(argv[1]);
if (not TextUtil::TrimLastCharFromUTF8Sequence(&s)) {
std::cerr << "Rats!\n";
return EXIT_FAILURE;
} else
std::cout << s << '\n';
}
|
ubtue/ub_tools
|
cpp/test/TrimLastCharFromUTF8Sequence_test.cc
|
C++
|
agpl-3.0
| 498
|
require 'rails_spec_helper'
include Toolkits::S3Manager::EncryptionToolkit
RSpec.describe S3Manager::ObjectSummary do
let(:s3_manager) { S3Manager::Manager.new }
let(:object_summary) { S3Manager::Manager::ObjectSummary.new("waffles", s3_manager) }
describe "an ObjectSummary instance" do
subject { object_summary }
describe "#initialize" do
it "sets the object key" do
expect(subject.instance_variable_get(:@object_key)).to eq("waffles")
end
it "sets the s3_manager" do
expect(subject.instance_variable_get(:@s3_manager)).to eq(s3_manager)
end
end
describe "readers" do
it "can read the object_key" do
expect(object_summary.object_key).to eq("waffles")
end
it "can read the s3_manager" do
expect(object_summary.s3_manager).to eq(s3_manager)
end
end
end
describe "#summary_client" do
subject { object_summary.summary_client }
it "creates a new ObjectSummary client from the attributes" do
expect(Aws::S3::ObjectSummary).to receive(:new).with(object_summary.summary_client_attributes)
subject
end
it "returns an Aws::S3::ObjectSummary instance" do
expect(subject.class).to eq(Aws::S3::ObjectSummary)
end
it "caches the summary client" do
subject
expect(Aws::S3::ObjectSummary).not_to receive(:new)
subject
end
end
describe "#summary_client_attributes" do
subject { object_summary.summary_client_attributes }
it "contains the bucket_name" do
expect(subject[:bucket_name]).to eq(s3_manager.bucket_name)
end
it "contains the key for the target object" do
expect(subject[:key]).to eq(object_summary.object_key)
end
it "contains the AWS client from the s3_manager" do
expect(subject[:client]).to eq(object_summary.s3_manager.client)
end
end
describe "summary client wrapper methods" do
subject { object_summary.summary_client }
let(:aws_waiter) { Aws::Waiters::Waiter.new(delay: 0.1, max_attempts: 1) }
describe "#exists?" do
it "calls #exists? on the summary client" do
expect(subject).to receive(:exists?)
object_summary.exists?
end
end
describe "#wait_until_exists" do
it "calls #wait_until_exists on the summary client" do
expect(subject).to receive(:wait_until_exists)
object_summary.wait_until_exists {|aws_waiter|}
end
end
describe "#wait_until_not_exists" do
it "calls #wait_until_not_exists on the summary client" do
expect(subject).to receive(:wait_until_not_exists)
object_summary.wait_until_not_exists {|aws_waiter|}
end
end
end
end
|
mkoon/gradecraft-development
|
spec/lib/s3_manager/object_summary_spec.rb
|
Ruby
|
agpl-3.0
| 2,703
|
<?php
namespace GeditLab\Module;
class React extends \GeditLab\Web\Controller {
function get() {
if(! local_channel())
return;
$postid = $_REQUEST['postid'];
if(! $postid)
return;
$emoji = $_REQUEST['emoji'];
if($_REQUEST['emoji']) {
$i = q("select * from item where id = %d and uid = %d",
intval($postid),
intval(local_channel())
);
if(! $i)
return;
$channel = \App::get_channel();
$n = array();
$n['aid'] = $channel['channel_account_id'];
$n['uid'] = $channel['channel_id'];
$n['item_origin'] = true;
$n['parent'] = $postid;
$n['parent_mid'] = $i[0]['mid'];
$n['mid'] = item_message_id();
$n['verb'] = ACTIVITY_REACT . '#' . $emoji;
$n['body'] = "\n\n[zmg=32x32]" . z_root() . '/images/emoji/' . $emoji . '.png[/zmg]' . "\n\n";
$n['author_xchan'] = $channel['channel_hash'];
$x = item_store($n);
if($x['success']) {
$nid = $x['item_id'];
\GeditLab\Daemon\Master::Summon(array('Notifier','like',$nid));
}
}
}
}
|
BlaBlaNet/BlaBlaNet
|
GeditLab/Module/React.php
|
PHP
|
agpl-3.0
| 1,019
|
/*
Copyright (C) 2015-2016 Claude SIMON (http://q37.info/contact/).
This file is part of 'orgnzq' software.
'orgnzq' 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.
'orgnzq' 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 'orgnzq'. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PROLOG_INC_
# define PROLOG_INC_
# include "base.h"
namespace prolog {
BASE_ACD( SwitchProjectType );
BASE_ACD( DisplayProjectFilename );
BASE_ACD( LoadProject );
inline void Register( void )
{
BASE_ACR( SwitchProjectType );
BASE_ACR( DisplayProjectFilename );
BASE_ACR( LoadProject );
};
void SetLayout( core::rSession & Session );
void SetCasting( core::rSession & Session );
void Display( core::rSession &Session);
}
#endif
|
epeios-q37/epeios
|
apps/orgnzq/frontend/XDHTML/prolog.h
|
C
|
agpl-3.0
| 1,233
|
class BlacklistWord < ActiveRecord::Base
validates :word,
:presence => true,
:uniqueness => true
validates :kind,
:presence => true
end
|
dukedorje/dreamcatcher
|
app/models/blacklist_word.rb
|
Ruby
|
agpl-3.0
| 184
|
<?php
require_once 'propel/util/BasePeer.php';
// The object class -- needed for instanceof checks in this class.
// actual class may be a subclass -- as returned by RoutePeer::getOMClass()
include_once 'classes/model/Route.php';
/**
* Base static class for performing query and update operations on the 'ROUTE' table.
*
*
*
* @package workflow.classes.model.om
*/
abstract class BaseRoutePeer
{
/** the default database name for this class */
const DATABASE_NAME = 'workflow';
/** the table name for this class */
const TABLE_NAME = 'ROUTE';
/** A class that can be returned by this peer. */
const CLASS_DEFAULT = 'classes.model.Route';
/** The total number of columns. */
const NUM_COLUMNS = 17;
/** The number of lazy-loaded columns. */
const NUM_LAZY_LOAD_COLUMNS = 0;
/** the column name for the ROU_UID field */
const ROU_UID = 'ROUTE.ROU_UID';
/** the column name for the ROU_PARENT field */
const ROU_PARENT = 'ROUTE.ROU_PARENT';
/** the column name for the PRO_UID field */
const PRO_UID = 'ROUTE.PRO_UID';
/** the column name for the TAS_UID field */
const TAS_UID = 'ROUTE.TAS_UID';
/** the column name for the ROU_NEXT_TASK field */
const ROU_NEXT_TASK = 'ROUTE.ROU_NEXT_TASK';
/** the column name for the ROU_CASE field */
const ROU_CASE = 'ROUTE.ROU_CASE';
/** the column name for the ROU_TYPE field */
const ROU_TYPE = 'ROUTE.ROU_TYPE';
/** the column name for the ROU_CONDITION field */
const ROU_CONDITION = 'ROUTE.ROU_CONDITION';
/** the column name for the ROU_TO_LAST_USER field */
const ROU_TO_LAST_USER = 'ROUTE.ROU_TO_LAST_USER';
/** the column name for the ROU_OPTIONAL field */
const ROU_OPTIONAL = 'ROUTE.ROU_OPTIONAL';
/** the column name for the ROU_SEND_EMAIL field */
const ROU_SEND_EMAIL = 'ROUTE.ROU_SEND_EMAIL';
/** the column name for the ROU_SOURCEANCHOR field */
const ROU_SOURCEANCHOR = 'ROUTE.ROU_SOURCEANCHOR';
/** the column name for the ROU_TARGETANCHOR field */
const ROU_TARGETANCHOR = 'ROUTE.ROU_TARGETANCHOR';
/** the column name for the ROU_TO_PORT field */
const ROU_TO_PORT = 'ROUTE.ROU_TO_PORT';
/** the column name for the ROU_FROM_PORT field */
const ROU_FROM_PORT = 'ROUTE.ROU_FROM_PORT';
/** the column name for the ROU_EVN_UID field */
const ROU_EVN_UID = 'ROUTE.ROU_EVN_UID';
/** the column name for the GAT_UID field */
const GAT_UID = 'ROUTE.GAT_UID';
/** The PHP to DB Name Mapping */
private static $phpNameMap = null;
/**
* holds an array of fieldnames
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
*/
private static $fieldNames = array (
BasePeer::TYPE_PHPNAME => array ('RouUid', 'RouParent', 'ProUid', 'TasUid', 'RouNextTask', 'RouCase', 'RouType', 'RouCondition', 'RouToLastUser', 'RouOptional', 'RouSendEmail', 'RouSourceanchor', 'RouTargetanchor', 'RouToPort', 'RouFromPort', 'RouEvnUid', 'GatUid', ),
BasePeer::TYPE_COLNAME => array (RoutePeer::ROU_UID, RoutePeer::ROU_PARENT, RoutePeer::PRO_UID, RoutePeer::TAS_UID, RoutePeer::ROU_NEXT_TASK, RoutePeer::ROU_CASE, RoutePeer::ROU_TYPE, RoutePeer::ROU_CONDITION, RoutePeer::ROU_TO_LAST_USER, RoutePeer::ROU_OPTIONAL, RoutePeer::ROU_SEND_EMAIL, RoutePeer::ROU_SOURCEANCHOR, RoutePeer::ROU_TARGETANCHOR, RoutePeer::ROU_TO_PORT, RoutePeer::ROU_FROM_PORT, RoutePeer::ROU_EVN_UID, RoutePeer::GAT_UID, ),
BasePeer::TYPE_FIELDNAME => array ('ROU_UID', 'ROU_PARENT', 'PRO_UID', 'TAS_UID', 'ROU_NEXT_TASK', 'ROU_CASE', 'ROU_TYPE', 'ROU_CONDITION', 'ROU_TO_LAST_USER', 'ROU_OPTIONAL', 'ROU_SEND_EMAIL', 'ROU_SOURCEANCHOR', 'ROU_TARGETANCHOR', 'ROU_TO_PORT', 'ROU_FROM_PORT', 'ROU_EVN_UID', 'GAT_UID', ),
BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, )
);
/**
* holds an array of keys for quick access to the fieldnames array
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0
*/
private static $fieldKeys = array (
BasePeer::TYPE_PHPNAME => array ('RouUid' => 0, 'RouParent' => 1, 'ProUid' => 2, 'TasUid' => 3, 'RouNextTask' => 4, 'RouCase' => 5, 'RouType' => 6, 'RouCondition' => 7, 'RouToLastUser' => 8, 'RouOptional' => 9, 'RouSendEmail' => 10, 'RouSourceanchor' => 11, 'RouTargetanchor' => 12, 'RouToPort' => 13, 'RouFromPort' => 14, 'RouEvnUid' => 15, 'GatUid' => 16, ),
BasePeer::TYPE_COLNAME => array (RoutePeer::ROU_UID => 0, RoutePeer::ROU_PARENT => 1, RoutePeer::PRO_UID => 2, RoutePeer::TAS_UID => 3, RoutePeer::ROU_NEXT_TASK => 4, RoutePeer::ROU_CASE => 5, RoutePeer::ROU_TYPE => 6, RoutePeer::ROU_CONDITION => 7, RoutePeer::ROU_TO_LAST_USER => 8, RoutePeer::ROU_OPTIONAL => 9, RoutePeer::ROU_SEND_EMAIL => 10, RoutePeer::ROU_SOURCEANCHOR => 11, RoutePeer::ROU_TARGETANCHOR => 12, RoutePeer::ROU_TO_PORT => 13, RoutePeer::ROU_FROM_PORT => 14, RoutePeer::ROU_EVN_UID => 15, RoutePeer::GAT_UID => 16, ),
BasePeer::TYPE_FIELDNAME => array ('ROU_UID' => 0, 'ROU_PARENT' => 1, 'PRO_UID' => 2, 'TAS_UID' => 3, 'ROU_NEXT_TASK' => 4, 'ROU_CASE' => 5, 'ROU_TYPE' => 6, 'ROU_CONDITION' => 7, 'ROU_TO_LAST_USER' => 8, 'ROU_OPTIONAL' => 9, 'ROU_SEND_EMAIL' => 10, 'ROU_SOURCEANCHOR' => 11, 'ROU_TARGETANCHOR' => 12, 'ROU_TO_PORT' => 13, 'ROU_FROM_PORT' => 14, 'ROU_EVN_UID' => 15, 'GAT_UID' => 16, ),
BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, )
);
/**
* @return MapBuilder the map builder for this peer
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getMapBuilder()
{
include_once 'classes/model/map/RouteMapBuilder.php';
return BasePeer::getMapBuilder('classes.model.map.RouteMapBuilder');
}
/**
* Gets a map (hash) of PHP names to DB column names.
*
* @return array The PHP to DB name map for this peer
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @deprecated Use the getFieldNames() and translateFieldName() methods instead of this.
*/
public static function getPhpNameMap()
{
if (self::$phpNameMap === null) {
$map = RoutePeer::getTableMap();
$columns = $map->getColumns();
$nameMap = array();
foreach ($columns as $column) {
$nameMap[$column->getPhpName()] = $column->getColumnName();
}
self::$phpNameMap = $nameMap;
}
return self::$phpNameMap;
}
/**
* Translates a fieldname to another type
*
* @param string $name field name
* @param string $fromType One of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @param string $toType One of the class type constants
* @return string translated name of the field.
*/
static public function translateFieldName($name, $fromType, $toType)
{
$toNames = self::getFieldNames($toType);
$key = isset(self::$fieldKeys[$fromType][$name]) ? self::$fieldKeys[$fromType][$name] : null;
if ($key === null) {
throw new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r(self::$fieldKeys[$fromType], true));
}
return $toNames[$key];
}
/**
* Returns an array of of field names.
*
* @param string $type The type of fieldnames to return:
* One of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @return array A list of field names
*/
static public function getFieldNames($type = BasePeer::TYPE_PHPNAME)
{
if (!array_key_exists($type, self::$fieldNames)) {
throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM. ' . $type . ' was given.');
}
return self::$fieldNames[$type];
}
/**
* Convenience method which changes table.column to alias.column.
*
* Using this method you can maintain SQL abstraction while using column aliases.
* <code>
* $c->addAlias("alias1", TablePeer::TABLE_NAME);
* $c->addJoin(TablePeer::alias("alias1", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN);
* </code>
* @param string $alias The alias for the current table.
* @param string $column The column name for current table. (i.e. RoutePeer::COLUMN_NAME).
* @return string
*/
public static function alias($alias, $column)
{
return str_replace(RoutePeer::TABLE_NAME.'.', $alias.'.', $column);
}
/**
* Add all the columns needed to create a new object.
*
* Note: any columns that were marked with lazyLoad="true" in the
* XML schema will not be added to the select list and only loaded
* on demand.
*
* @param criteria object containing the columns to add.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function addSelectColumns(Criteria $criteria)
{
$criteria->addSelectColumn(RoutePeer::ROU_UID);
$criteria->addSelectColumn(RoutePeer::ROU_PARENT);
$criteria->addSelectColumn(RoutePeer::PRO_UID);
$criteria->addSelectColumn(RoutePeer::TAS_UID);
$criteria->addSelectColumn(RoutePeer::ROU_NEXT_TASK);
$criteria->addSelectColumn(RoutePeer::ROU_CASE);
$criteria->addSelectColumn(RoutePeer::ROU_TYPE);
$criteria->addSelectColumn(RoutePeer::ROU_CONDITION);
$criteria->addSelectColumn(RoutePeer::ROU_TO_LAST_USER);
$criteria->addSelectColumn(RoutePeer::ROU_OPTIONAL);
$criteria->addSelectColumn(RoutePeer::ROU_SEND_EMAIL);
$criteria->addSelectColumn(RoutePeer::ROU_SOURCEANCHOR);
$criteria->addSelectColumn(RoutePeer::ROU_TARGETANCHOR);
$criteria->addSelectColumn(RoutePeer::ROU_TO_PORT);
$criteria->addSelectColumn(RoutePeer::ROU_FROM_PORT);
$criteria->addSelectColumn(RoutePeer::ROU_EVN_UID);
$criteria->addSelectColumn(RoutePeer::GAT_UID);
}
const COUNT = 'COUNT(ROUTE.ROU_UID)';
const COUNT_DISTINCT = 'COUNT(DISTINCT ROUTE.ROU_UID)';
/**
* Returns the number of rows matching criteria.
*
* @param Criteria $criteria
* @param boolean $distinct Whether to select only distinct columns (You can also set DISTINCT modifier in Criteria).
* @param Connection $con
* @return int Number of matching rows.
*/
public static function doCount(Criteria $criteria, $distinct = false, $con = null)
{
// we're going to modify criteria, so copy it first
$criteria = clone $criteria;
// clear out anything that might confuse the ORDER BY clause
$criteria->clearSelectColumns()->clearOrderByColumns();
if ($distinct || in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
$criteria->addSelectColumn(RoutePeer::COUNT_DISTINCT);
} else {
$criteria->addSelectColumn(RoutePeer::COUNT);
}
// just in case we're grouping: add those columns to the select statement
foreach ($criteria->getGroupByColumns() as $column) {
$criteria->addSelectColumn($column);
}
$rs = RoutePeer::doSelectRS($criteria, $con);
if ($rs->next()) {
return $rs->getInt(1);
} else {
// no rows returned; we infer that means 0 matches.
return 0;
}
}
/**
* Method to select one object from the DB.
*
* @param Criteria $criteria object used to create the SELECT statement.
* @param Connection $con
* @return Route
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelectOne(Criteria $criteria, $con = null)
{
$critcopy = clone $criteria;
$critcopy->setLimit(1);
$objects = RoutePeer::doSelect($critcopy, $con);
if ($objects) {
return $objects[0];
}
return null;
}
/**
* Method to do selects.
*
* @param Criteria $criteria The Criteria object used to build the SELECT statement.
* @param Connection $con
* @return array Array of selected Objects
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelect(Criteria $criteria, $con = null)
{
return RoutePeer::populateObjects(RoutePeer::doSelectRS($criteria, $con));
}
/**
* Prepares the Criteria object and uses the parent doSelect()
* method to get a ResultSet.
*
* Use this method directly if you want to just get the resultset
* (instead of an array of objects).
*
* @param Criteria $criteria The Criteria object used to build the SELECT statement.
* @param Connection $con the connection to use
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @return ResultSet The resultset object with numerically-indexed fields.
* @see BasePeer::doSelect()
*/
public static function doSelectRS(Criteria $criteria, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
if (!$criteria->getSelectColumns()) {
$criteria = clone $criteria;
RoutePeer::addSelectColumns($criteria);
}
// Set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
// BasePeer returns a Creole ResultSet, set to return
// rows indexed numerically.
return BasePeer::doSelect($criteria, $con);
}
/**
* The returned array will contain objects of the default type or
* objects that inherit from the default.
*
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function populateObjects(ResultSet $rs)
{
$results = array();
// set the class once to avoid overhead in the loop
$cls = RoutePeer::getOMClass();
$cls = Propel::import($cls);
// populate the object(s)
while ($rs->next()) {
$obj = new $cls();
$obj->hydrate($rs);
$results[] = $obj;
}
return $results;
}
/**
* Returns the TableMap related to this peer.
* This method is not needed for general use but a specific application could have a need.
* @return TableMap
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getTableMap()
{
return Propel::getDatabaseMap(self::DATABASE_NAME)->getTable(self::TABLE_NAME);
}
/**
* The class that the Peer will make instances of.
*
* This uses a dot-path notation which is tranalted into a path
* relative to a location on the PHP include_path.
* (e.g. path.to.MyClass -> 'path/to/MyClass.php')
*
* @return string path.to.ClassName
*/
public static function getOMClass()
{
return RoutePeer::CLASS_DEFAULT;
}
/**
* Method perform an INSERT on the database, given a Route or Criteria object.
*
* @param mixed $values Criteria or Route object containing data that is used to create the INSERT statement.
* @param Connection $con the connection to use
* @return mixed The new primary key.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doInsert($values, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} else {
$criteria = $values->buildCriteria(); // build Criteria from Route object
}
// Set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
try {
// use transaction because $criteria could contain info
// for more than one table (I guess, conceivably)
$con->begin();
$pk = BasePeer::doInsert($criteria, $con);
$con->commit();
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
return $pk;
}
/**
* Method perform an UPDATE on the database, given a Route or Criteria object.
*
* @param mixed $values Criteria or Route object containing data create the UPDATE statement.
* @param Connection $con The connection to use (specify Connection exert more control over transactions).
* @return int The number of affected rows (if supported by underlying database driver).
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doUpdate($values, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$selectCriteria = new Criteria(self::DATABASE_NAME);
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
$comparison = $criteria->getComparison(RoutePeer::ROU_UID);
$selectCriteria->add(RoutePeer::ROU_UID, $criteria->remove(RoutePeer::ROU_UID), $comparison);
} else {
$criteria = $values->buildCriteria(); // gets full criteria
$selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s)
}
// set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
return BasePeer::doUpdate($selectCriteria, $criteria, $con);
}
/**
* Method to DELETE all rows from the ROUTE table.
*
* @return int The number of affected rows (if supported by underlying database driver).
*/
public static function doDeleteAll($con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->begin();
$affectedRows += BasePeer::doDeleteAll(RoutePeer::TABLE_NAME, $con);
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Method perform a DELETE on the database, given a Route or Criteria object OR a primary key value.
*
* @param mixed $values Criteria or Route object or primary key or array of primary keys
* which is used to create the DELETE statement
* @param Connection $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver).
* This includes CASCADE-related rows
* if supported by native driver or if emulated using Propel.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doDelete($values, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(RoutePeer::DATABASE_NAME);
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} elseif ($values instanceof Route) {
$criteria = $values->buildPkeyCriteria();
} else {
// it must be the primary key
$criteria = new Criteria(self::DATABASE_NAME);
$criteria->add(RoutePeer::ROU_UID, (array) $values, Criteria::IN);
}
// Set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->begin();
$affectedRows += BasePeer::doDelete($criteria, $con);
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Validates all modified columns of given Route object.
* If parameter $columns is either a single column name or an array of column names
* than only those columns are validated.
*
* NOTICE: This does not apply to primary or foreign keys for now.
*
* @param Route $obj The object to validate.
* @param mixed $cols Column name or array of column names.
*
* @return mixed TRUE if all columns are valid or the error message of the first invalid column.
*/
public static function doValidate(Route $obj, $cols = null)
{
$columns = array();
if ($cols) {
$dbMap = Propel::getDatabaseMap(RoutePeer::DATABASE_NAME);
$tableMap = $dbMap->getTable(RoutePeer::TABLE_NAME);
if (! is_array($cols)) {
$cols = array($cols);
}
foreach ($cols as $colName) {
if ($tableMap->containsColumn($colName)) {
$get = 'get' . $tableMap->getColumn($colName)->getPhpName();
$columns[$colName] = $obj->$get();
}
}
} else {
if ($obj->isNew() || $obj->isColumnModified(RoutePeer::ROU_UID))
$columns[RoutePeer::ROU_UID] = $obj->getRouUid();
if ($obj->isNew() || $obj->isColumnModified(RoutePeer::PRO_UID))
$columns[RoutePeer::PRO_UID] = $obj->getProUid();
if ($obj->isNew() || $obj->isColumnModified(RoutePeer::TAS_UID))
$columns[RoutePeer::TAS_UID] = $obj->getTasUid();
if ($obj->isNew() || $obj->isColumnModified(RoutePeer::ROU_NEXT_TASK))
$columns[RoutePeer::ROU_NEXT_TASK] = $obj->getRouNextTask();
if ($obj->isNew() || $obj->isColumnModified(RoutePeer::ROU_TYPE))
$columns[RoutePeer::ROU_TYPE] = $obj->getRouType();
if ($obj->isNew() || $obj->isColumnModified(RoutePeer::ROU_TO_LAST_USER))
$columns[RoutePeer::ROU_TO_LAST_USER] = $obj->getRouToLastUser();
if ($obj->isNew() || $obj->isColumnModified(RoutePeer::ROU_OPTIONAL))
$columns[RoutePeer::ROU_OPTIONAL] = $obj->getRouOptional();
if ($obj->isNew() || $obj->isColumnModified(RoutePeer::ROU_SEND_EMAIL))
$columns[RoutePeer::ROU_SEND_EMAIL] = $obj->getRouSendEmail();
}
return BasePeer::doValidate(RoutePeer::DATABASE_NAME, RoutePeer::TABLE_NAME, $columns);
}
/**
* Retrieve a single object by pkey.
*
* @param mixed $pk the primary key.
* @param Connection $con the connection to use
* @return Route
*/
public static function retrieveByPK($pk, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$criteria = new Criteria(RoutePeer::DATABASE_NAME);
$criteria->add(RoutePeer::ROU_UID, $pk);
$v = RoutePeer::doSelect($criteria, $con);
return !empty($v) > 0 ? $v[0] : null;
}
/**
* Retrieve multiple objects by pkey.
*
* @param array $pks List of primary keys
* @param Connection $con the connection to use
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function retrieveByPKs($pks, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$objs = null;
if (empty($pks)) {
$objs = array();
} else {
$criteria = new Criteria();
$criteria->add(RoutePeer::ROU_UID, $pks, Criteria::IN);
$objs = RoutePeer::doSelect($criteria, $con);
}
return $objs;
}
}
// static code to register the map builder for this Peer with the main Propel class
if (Propel::isInit()) {
// the MapBuilder classes register themselves with Propel during initialization
// so we need to load them here.
try {
BaseRoutePeer::getMapBuilder();
} catch (Exception $e) {
Propel::log('Could not initialize Peer: ' . $e->getMessage(), Propel::LOG_ERR);
}
} else {
// even if Propel is not yet initialized, the map builder class can be registered
// now and then it will be loaded when Propel initializes.
require_once 'classes/model/map/RouteMapBuilder.php';
Propel::registerMapBuilder('classes.model.map.RouteMapBuilder');
}
|
maestrano/processmaker
|
workflow/engine/classes/model/om/BaseRoutePeer.php
|
PHP
|
agpl-3.0
| 26,113
|
#!/bin/sh
# pythonInstall.sh
#
#
# Created by Ron Yadgar on 25/09/2016.
#
SOURCE_DIRECTORY="/opt/kaltura/liveController/latest"
HOME_DIRECTORY=`grep recording_base_dir $SOURCE_DIRECTORY/liveRecorder/Config/config.ini | awk '{ print $3 }'`
HOSTNAME=$(hostname)
HOSTNAME_DIRECTORY="$HOME_DIRECTORY/$HOSTNAME"
echo "home directory $HOME_DIRECTORY"
if [ ! -d $HOME_DIRECTORY ]; then
echo "ERROR: can't find recording path"
exit 1
fi
if ! [[ $(python --version 2>&1) == *2\.7\.* ]]; then
echo "Python version >= 2.7.0 is required";
exit 2
fi
pip install poster
pip install psutil
pip install m3u8
pip install schedule
pip install pycrypto
mkdir -p $HOME_DIRECTORY
mkdir -p "$HOME_DIRECTORY/recordings"
mkdir -p "$HOME_DIRECTORY/recordings/newSession"
mkdir -p "$HOME_DIRECTORY/recordings/append"
mkdir -p "$HOME_DIRECTORY/error"
mkdir -p "$HOME_DIRECTORY/incoming"
mkdir -p $HOSTNAME_DIRECTORY
UPLOAD_TASK_DIRECTORY="$HOSTNAME_DIRECTORY/UploadTask"
CONCATINATION_TASK_DIRECTORY="$HOSTNAME_DIRECTORY/ConcatenationTask"
mkdir -p $CONCATINATION_TASK_DIRECTORY
ln -s "$HOME_DIRECTORY/incoming" "$CONCATINATION_TASK_DIRECTORY/incoming"
mkdir -p "$CONCATINATION_TASK_DIRECTORY/failed"
mkdir -p "$CONCATINATION_TASK_DIRECTORY/processing"
mkdir -p $UPLOAD_TASK_DIRECTORY
mkdir -p "$UPLOAD_TASK_DIRECTORY/failed"
mkdir -p "$UPLOAD_TASK_DIRECTORY/incoming"
mkdir -p "$UPLOAD_TASK_DIRECTORY/processing"
cp $SOURCE_DIRECTORY/recordingUploader/liveRecorder.sh /etc/init.d/liveRecorder
/etc/init.d/liveRecorder.sh restart
|
kaltura/liveDVR
|
liveRecorder/install.sh
|
Shell
|
agpl-3.0
| 1,530
|
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package api_test
import (
"strings"
"github.com/juju/utils/set"
gc "gopkg.in/check.v1"
"github.com/juju/juju/api"
"github.com/juju/juju/apiserver/common"
"github.com/juju/juju/feature"
coretesting "github.com/juju/juju/testing"
)
type facadeVersionSuite struct {
coretesting.BaseSuite
}
var _ = gc.Suite(&facadeVersionSuite{})
func (s *facadeVersionSuite) TestFacadeVersionsMatchServerVersions(c *gc.C) {
// Enable feature flags so we can see them all.
devFeatures := []string{feature.MESS, feature.Storage}
s.SetFeatureFlags(strings.Join(devFeatures, ","))
// The client side code doesn't want to directly import the server side
// code just to list out what versions are available. However, we do
// want to make sure that the two sides are kept in sync.
clientFacadeNames := set.NewStrings()
for name := range *api.FacadeVersions {
clientFacadeNames.Add(name)
}
allServerFacades := common.Facades.List()
serverFacadeNames := set.NewStrings()
serverFacadeBestVersions := make(map[string]int, len(allServerFacades))
for _, facade := range allServerFacades {
serverFacadeNames.Add(facade.Name)
serverFacadeBestVersions[facade.Name] = facade.Versions[len(facade.Versions)-1]
}
// First check that both sides know about all the same versions
c.Check(serverFacadeNames.Difference(clientFacadeNames).SortedValues(), gc.HasLen, 0)
c.Check(clientFacadeNames.Difference(serverFacadeNames).SortedValues(), gc.HasLen, 0)
// Next check that the best versions match
c.Check(*api.FacadeVersions, gc.DeepEquals, serverFacadeBestVersions)
}
func checkBestVersion(c *gc.C, desiredVersion int, versions []int, expectedVersion int) {
resultVersion := api.BestVersion(desiredVersion, versions)
c.Check(resultVersion, gc.Equals, expectedVersion)
}
func (*facadeVersionSuite) TestBestVersionDesiredAvailable(c *gc.C) {
checkBestVersion(c, 0, []int{0, 1, 2}, 0)
checkBestVersion(c, 1, []int{0, 1, 2}, 1)
checkBestVersion(c, 2, []int{0, 1, 2}, 2)
}
func (*facadeVersionSuite) TestBestVersionDesiredNewer(c *gc.C) {
checkBestVersion(c, 3, []int{0}, 0)
checkBestVersion(c, 3, []int{0, 1, 2}, 2)
}
func (*facadeVersionSuite) TestBestVersionDesiredGap(c *gc.C) {
checkBestVersion(c, 1, []int{0, 2}, 0)
}
func (*facadeVersionSuite) TestBestVersionNoVersions(c *gc.C) {
checkBestVersion(c, 0, []int{}, 0)
checkBestVersion(c, 1, []int{}, 0)
checkBestVersion(c, 0, []int(nil), 0)
checkBestVersion(c, 1, []int(nil), 0)
}
func (*facadeVersionSuite) TestBestVersionNotSorted(c *gc.C) {
checkBestVersion(c, 0, []int{0, 3, 1, 2}, 0)
checkBestVersion(c, 3, []int{0, 3, 1, 2}, 3)
checkBestVersion(c, 1, []int{0, 3, 1, 2}, 1)
checkBestVersion(c, 2, []int{0, 3, 1, 2}, 2)
}
func (s *facadeVersionSuite) TestBestFacadeVersionExactMatch(c *gc.C) {
s.PatchValue(api.FacadeVersions, map[string]int{"Client": 1})
st := api.NewTestingState(api.TestingStateParams{
FacadeVersions: map[string][]int{
"Client": {0, 1},
}})
c.Check(st.BestFacadeVersion("Client"), gc.Equals, 1)
}
func (s *facadeVersionSuite) TestBestFacadeVersionNewerServer(c *gc.C) {
s.PatchValue(api.FacadeVersions, map[string]int{"Client": 1})
st := api.NewTestingState(api.TestingStateParams{
FacadeVersions: map[string][]int{
"Client": {0, 1, 2},
}})
c.Check(st.BestFacadeVersion("Client"), gc.Equals, 1)
}
func (s *facadeVersionSuite) TestBestFacadeVersionNewerClient(c *gc.C) {
s.PatchValue(api.FacadeVersions, map[string]int{"Client": 2})
st := api.NewTestingState(api.TestingStateParams{
FacadeVersions: map[string][]int{
"Client": {0, 1},
}})
c.Check(st.BestFacadeVersion("Client"), gc.Equals, 1)
}
func (s *facadeVersionSuite) TestBestFacadeVersionServerUnknown(c *gc.C) {
s.PatchValue(api.FacadeVersions, map[string]int{"TestingAPI": 2})
st := api.NewTestingState(api.TestingStateParams{
FacadeVersions: map[string][]int{
"Client": {0, 1},
}})
c.Check(st.BestFacadeVersion("TestingAPI"), gc.Equals, 0)
}
|
Altoros/juju-vmware
|
api/facadeversions_test.go
|
GO
|
agpl-3.0
| 4,034
|
# Gentoo Recruiters Web App - to help Gentoo recruiters do their job better
# Copyright (C) 2010 Joachim Filip Bartosik
#
# 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, version 3 of the License
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
require 'permissions/set.rb'
class ProjectAcceptance < ActiveRecord::Base
hobo_model # Don't put anything above this
fields do
accepting_nick :string, :null => false, :null => false
accepted :boolean, :default => false
timestamps
end
belongs_to :user, :null => false
attr_readonly :user
validates_presence_of :user, :accepting_nick
validates_uniqueness_of :accepting_nick, :scope => :user_id
named_scope :find_by_user_name_and_accepting_nick, lambda { |user_name, accepting_nick| {
:joins => :user, :conditions => ['users.name = ? AND accepting_nick = ?', user_name, accepting_nick] } }
def create_permitted?
# Recruiters can create project_acceptances
# Project leads can create project_acceptances they should approve
return true if acting_user.role.is_recruiter?
return true if acting_user.project_lead && accepting_nick == acting_user.nick
false
end
multi_permission :update, :destroy, :edit do
# Allow admins everything
return true if acting_user.administrator?
# Allow recruiters changing pending acceptances
return true if acting_user.role.is_recruiter? && !accepted && !accepted_changed?
# Allow user with nick accepting_nick to change :accepted
return true if (acting_user.nick == accepting_nick) && only_changed?(:accepted)
# Allow CRU new records to recruiters and project leads
return true if new_record? && acting_user.role.is_recruiter?
return true if new_record? && acting_user.project_lead
false
end
def view_permitted?(field)
# Allow user(relation), mentor of user and recruiters to view
return true if user_is?(acting_user)
return true if acting_user.role.is_recruiter?
return true if user.mentor_is?(acting_user)
return true if accepting_nick == acting_user.nick
false
end
# Returns new project acceptance with user = recruit, accepting_nick = lead.nick
# if lead is marked as project_lead AND there isn't such a project acceptance yet
def self.new_for_users(recruit, lead)
return nil unless lead.project_lead
return nil unless recruit.signed_up?
return nil unless ProjectAcceptance.first(:conditions => { :accepting_nick => lead.nick, :user_id => recruit.id}).nil?
ProjectAcceptance.new :accepting_nick => lead.nick, :user => recruit
end
end
|
ahenobarbi/Gentoo-Recruiters-App
|
app/models/project_acceptance.rb
|
Ruby
|
agpl-3.0
| 3,092
|
<?php
/**
* This file is part of the login-cidadao project or it's bundles.
*
* (c) Guilherme Donato <guilhermednt on github>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PROCERGS\LoginCidadao\NfgBundle\Exception;
class EmailInUseException extends \RuntimeException
{
/**
* EmailInUseException constructor.
* @param string $message
* @param int $code
* @param \Exception $previous
*/
public function __construct($message = "", $code = 0, \Exception $previous = null)
{
parent::__construct($message, $code, $previous);
}
}
|
PROCERGS/login-cidadao
|
src/PROCERGS/LoginCidadao/NfgBundle/Exception/EmailInUseException.php
|
PHP
|
agpl-3.0
| 675
|
/*!
* jquery.fancytree.persist.js
*
* Persist tree status in cookiesRemove or highlight tree nodes, based on a filter.
* (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
*
* @depends: js-cookie or jquery-cookie
*
* Copyright (c) 2008-2020, Martin Wendt (https://wwWendt.de)
*
* Released under the MIT license
* https://github.com/mar10/fancytree/wiki/LicenseInfo
*
* @version 2.36.0
* @date 2020-07-15T20:15:15Z
*/
(function(factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["jquery", "./jquery.fancytree"], factory);
} else if (typeof module === "object" && module.exports) {
// Node/CommonJS
require("./jquery.fancytree");
module.exports = factory(require("jquery"));
} else {
// Browser globals
factory(jQuery);
}
})(function($) {
"use strict";
/* global Cookies:false */
/*******************************************************************************
* Private functions and variables
*/
var cookieStore = null,
localStorageStore = window.localStorage
? {
get: function(key) {
return window.localStorage.getItem(key);
},
set: function(key, value) {
window.localStorage.setItem(key, value);
},
remove: function(key) {
window.localStorage.removeItem(key);
},
}
: null,
sessionStorageStore = window.sessionStorage
? {
get: function(key) {
return window.sessionStorage.getItem(key);
},
set: function(key, value) {
window.sessionStorage.setItem(key, value);
},
remove: function(key) {
window.sessionStorage.removeItem(key);
},
}
: null,
_assert = $.ui.fancytree.assert,
ACTIVE = "active",
EXPANDED = "expanded",
FOCUS = "focus",
SELECTED = "selected";
if (typeof Cookies === "function") {
// Assume https://github.com/js-cookie/js-cookie
cookieStore = {
get: Cookies.get,
set: function(key, value) {
Cookies.set(key, value, this.options.persist.cookie);
},
remove: Cookies.remove,
};
} else if ($ && typeof $.cookie === "function") {
// Fall back to https://github.com/carhartl/jquery-cookie
cookieStore = {
get: $.cookie,
set: function(key, value) {
$.cookie.set(key, value, this.options.persist.cookie);
},
remove: $.removeCookie,
};
}
/* Recursively load lazy nodes
* @param {string} mode 'load', 'expand', false
*/
function _loadLazyNodes(tree, local, keyList, mode, dfd) {
var i,
key,
l,
node,
foundOne = false,
expandOpts = tree.options.persist.expandOpts,
deferredList = [],
missingKeyList = [];
keyList = keyList || [];
dfd = dfd || $.Deferred();
for (i = 0, l = keyList.length; i < l; i++) {
key = keyList[i];
node = tree.getNodeByKey(key);
if (node) {
if (mode && node.isUndefined()) {
foundOne = true;
tree.debug(
"_loadLazyNodes: " + node + " is lazy: loading..."
);
if (mode === "expand") {
deferredList.push(node.setExpanded(true, expandOpts));
} else {
deferredList.push(node.load());
}
} else {
tree.debug("_loadLazyNodes: " + node + " already loaded.");
node.setExpanded(true, expandOpts);
}
} else {
missingKeyList.push(key);
tree.debug("_loadLazyNodes: " + node + " was not yet found.");
}
}
$.when.apply($, deferredList).always(function() {
// All lazy-expands have finished
if (foundOne && missingKeyList.length > 0) {
// If we read new nodes from server, try to resolve yet-missing keys
_loadLazyNodes(tree, local, missingKeyList, mode, dfd);
} else {
if (missingKeyList.length) {
tree.warn(
"_loadLazyNodes: could not load those keys: ",
missingKeyList
);
for (i = 0, l = missingKeyList.length; i < l; i++) {
key = keyList[i];
local._appendKey(EXPANDED, keyList[i], false);
}
}
dfd.resolve();
}
});
return dfd;
}
/**
* [ext-persist] Remove persistence data of the given type(s).
* Called like
* $.ui.fancytree.getTree("#tree").clearCookies("active expanded focus selected");
*
* @alias Fancytree#clearPersistData
* @requires jquery.fancytree.persist.js
*/
$.ui.fancytree._FancytreeClass.prototype.clearPersistData = function(
types
) {
var local = this.ext.persist,
prefix = local.cookiePrefix;
types = types || "active expanded focus selected";
if (types.indexOf(ACTIVE) >= 0) {
local._data(prefix + ACTIVE, null);
}
if (types.indexOf(EXPANDED) >= 0) {
local._data(prefix + EXPANDED, null);
}
if (types.indexOf(FOCUS) >= 0) {
local._data(prefix + FOCUS, null);
}
if (types.indexOf(SELECTED) >= 0) {
local._data(prefix + SELECTED, null);
}
};
$.ui.fancytree._FancytreeClass.prototype.clearCookies = function(types) {
this.warn(
"'tree.clearCookies()' is deprecated since v2.27.0: use 'clearPersistData()' instead."
);
return this.clearPersistData(types);
};
/**
* [ext-persist] Return persistence information from cookies
*
* Called like
* $.ui.fancytree.getTree("#tree").getPersistData();
*
* @alias Fancytree#getPersistData
* @requires jquery.fancytree.persist.js
*/
$.ui.fancytree._FancytreeClass.prototype.getPersistData = function() {
var local = this.ext.persist,
prefix = local.cookiePrefix,
delim = local.cookieDelimiter,
res = {};
res[ACTIVE] = local._data(prefix + ACTIVE);
res[EXPANDED] = (local._data(prefix + EXPANDED) || "").split(delim);
res[SELECTED] = (local._data(prefix + SELECTED) || "").split(delim);
res[FOCUS] = local._data(prefix + FOCUS);
return res;
};
/******************************************************************************
* Extension code
*/
$.ui.fancytree.registerExtension({
name: "persist",
version: "2.36.0",
// Default options for this extension.
options: {
cookieDelimiter: "~",
cookiePrefix: undefined, // 'fancytree-<treeId>-' by default
cookie: {
raw: false,
expires: "",
path: "",
domain: "",
secure: false,
},
expandLazy: false, // true: recursively expand and load lazy nodes
expandOpts: undefined, // optional `opts` argument passed to setExpanded()
fireActivate: true, // false: suppress `activate` event after active node was restored
overrideSource: true, // true: cookie takes precedence over `source` data attributes.
store: "auto", // 'cookie': force cookie, 'local': force localStore, 'session': force sessionStore
types: "active expanded focus selected",
},
/* Generic read/write string data to cookie, sessionStorage or localStorage. */
_data: function(key, value) {
var store = this._local.store;
if (value === undefined) {
return store.get.call(this, key);
} else if (value === null) {
store.remove.call(this, key);
} else {
store.set.call(this, key, value);
}
},
/* Append `key` to a cookie. */
_appendKey: function(type, key, flag) {
key = "" + key; // #90
var local = this._local,
instOpts = this.options.persist,
delim = instOpts.cookieDelimiter,
cookieName = local.cookiePrefix + type,
data = local._data(cookieName),
keyList = data ? data.split(delim) : [],
idx = $.inArray(key, keyList);
// Remove, even if we add a key, so the key is always the last entry
if (idx >= 0) {
keyList.splice(idx, 1);
}
// Append key to cookie
if (flag) {
keyList.push(key);
}
local._data(cookieName, keyList.join(delim));
},
treeInit: function(ctx) {
var tree = ctx.tree,
opts = ctx.options,
local = this._local,
instOpts = this.options.persist;
// // For 'auto' or 'cookie' mode, the cookie plugin must be available
// _assert((instOpts.store !== "auto" && instOpts.store !== "cookie") || cookieStore,
// "Missing required plugin for 'persist' extension: js.cookie.js or jquery.cookie.js");
local.cookiePrefix =
instOpts.cookiePrefix || "fancytree-" + tree._id + "-";
local.storeActive = instOpts.types.indexOf(ACTIVE) >= 0;
local.storeExpanded = instOpts.types.indexOf(EXPANDED) >= 0;
local.storeSelected = instOpts.types.indexOf(SELECTED) >= 0;
local.storeFocus = instOpts.types.indexOf(FOCUS) >= 0;
local.store = null;
if (instOpts.store === "auto") {
instOpts.store = localStorageStore ? "local" : "cookie";
}
if ($.isPlainObject(instOpts.store)) {
local.store = instOpts.store;
} else if (instOpts.store === "cookie") {
local.store = cookieStore;
} else if (instOpts.store === "local") {
local.store =
instOpts.store === "local"
? localStorageStore
: sessionStorageStore;
} else if (instOpts.store === "session") {
local.store =
instOpts.store === "local"
? localStorageStore
: sessionStorageStore;
}
_assert(local.store, "Need a valid store.");
// Bind init-handler to apply cookie state
tree.$div.on("fancytreeinit", function(event) {
if (
tree._triggerTreeEvent("beforeRestore", null, {}) === false
) {
return;
}
var cookie,
dfd,
i,
keyList,
node,
prevFocus = local._data(local.cookiePrefix + FOCUS), // record this before node.setActive() overrides it;
noEvents = instOpts.fireActivate === false;
// tree.debug("document.cookie:", document.cookie);
cookie = local._data(local.cookiePrefix + EXPANDED);
keyList = cookie && cookie.split(instOpts.cookieDelimiter);
if (local.storeExpanded) {
// Recursively load nested lazy nodes if expandLazy is 'expand' or 'load'
// Also remove expand-cookies for unmatched nodes
dfd = _loadLazyNodes(
tree,
local,
keyList,
instOpts.expandLazy ? "expand" : false,
null
);
} else {
// nothing to do
dfd = new $.Deferred().resolve();
}
dfd.done(function() {
if (local.storeSelected) {
cookie = local._data(local.cookiePrefix + SELECTED);
if (cookie) {
keyList = cookie.split(instOpts.cookieDelimiter);
for (i = 0; i < keyList.length; i++) {
node = tree.getNodeByKey(keyList[i]);
if (node) {
if (
node.selected === undefined ||
(instOpts.overrideSource &&
node.selected === false)
) {
// node.setSelected();
node.selected = true;
node.renderStatus();
}
} else {
// node is no longer member of the tree: remove from cookie also
local._appendKey(
SELECTED,
keyList[i],
false
);
}
}
}
// In selectMode 3 we have to fix the child nodes, since we
// only stored the selected *top* nodes
if (tree.options.selectMode === 3) {
tree.visit(function(n) {
if (n.selected) {
n.fixSelection3AfterClick();
return "skip";
}
});
}
}
if (local.storeActive) {
cookie = local._data(local.cookiePrefix + ACTIVE);
if (
cookie &&
(opts.persist.overrideSource || !tree.activeNode)
) {
node = tree.getNodeByKey(cookie);
if (node) {
node.debug("persist: set active", cookie);
// We only want to set the focus if the container
// had the keyboard focus before
node.setActive(true, {
noFocus: true,
noEvents: noEvents,
});
}
}
}
if (local.storeFocus && prevFocus) {
node = tree.getNodeByKey(prevFocus);
if (node) {
// node.debug("persist: set focus", cookie);
if (tree.options.titlesTabbable) {
$(node.span)
.find(".fancytree-title")
.focus();
} else {
$(tree.$container).focus();
}
// node.setFocus();
}
}
tree._triggerTreeEvent("restore", null, {});
});
});
// Init the tree
return this._superApply(arguments);
},
nodeSetActive: function(ctx, flag, callOpts) {
var res,
local = this._local;
flag = flag !== false;
res = this._superApply(arguments);
if (local.storeActive) {
local._data(
local.cookiePrefix + ACTIVE,
this.activeNode ? this.activeNode.key : null
);
}
return res;
},
nodeSetExpanded: function(ctx, flag, callOpts) {
var res,
node = ctx.node,
local = this._local;
flag = flag !== false;
res = this._superApply(arguments);
if (local.storeExpanded) {
local._appendKey(EXPANDED, node.key, flag);
}
return res;
},
nodeSetFocus: function(ctx, flag) {
var res,
local = this._local;
flag = flag !== false;
res = this._superApply(arguments);
if (local.storeFocus) {
local._data(
local.cookiePrefix + FOCUS,
this.focusNode ? this.focusNode.key : null
);
}
return res;
},
nodeSetSelected: function(ctx, flag, callOpts) {
var res,
selNodes,
tree = ctx.tree,
node = ctx.node,
local = this._local;
flag = flag !== false;
res = this._superApply(arguments);
if (local.storeSelected) {
if (tree.options.selectMode === 3) {
// In selectMode 3 we only store the the selected *top* nodes.
// De-selecting a node may also de-select some parents, so we
// calculate the current status again
selNodes = $.map(tree.getSelectedNodes(true), function(n) {
return n.key;
});
selNodes = selNodes.join(
ctx.options.persist.cookieDelimiter
);
local._data(local.cookiePrefix + SELECTED, selNodes);
} else {
// beforeSelect can prevent the change - flag doesn't reflect the node.selected state
local._appendKey(SELECTED, node.key, node.selected);
}
}
return res;
},
});
// Value returned by `require('jquery.fancytree..')`
return $.ui.fancytree;
}); // End of closure
|
isard-vdi/isard
|
webapp/webapp/webapp/static/vendor/fancytree/dist/modules/jquery.fancytree.persist.js
|
JavaScript
|
agpl-3.0
| 13,835
|
# streamer-wrapper
[/statusIcon)](http://ci.gtaun.net/project.html?projectId=Shoebill_Wrappers_Streamer)
This project serves as a Wrapper between Shoebill and Incognito's Streamer Plugin.
# Requirement
You will need Incognito's Streamer Plugin (http://forum.sa-mp.com/showthread.php?t=102865)
|
Shoebill/streamer-wrapper
|
README.md
|
Markdown
|
agpl-3.0
| 397
|
/* This file is part of VoltDB.
* Copyright (C) 2008-2013 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
#include "common/RecoveryProtoMessage.h"
#include "common/FatalException.hpp"
#include "common/types.h"
#include "common/Pool.hpp"
namespace voltdb {
/*
* Prepare a recovery message for reading.
*/
RecoveryProtoMsg::RecoveryProtoMsg(ReferenceSerializeInput *in) :
m_in(in), m_type(static_cast<RecoveryMsgType>(in->readByte())),
m_tableId(in->readInt()) {
assert(m_in);
assert(m_type != RECOVERY_MSG_TYPE_SCAN_COMPLETE);
int32_t totalTupleCount = in->readInt();
m_totalTupleCount = *reinterpret_cast<uint32_t*>(&totalTupleCount);
if (m_type == RECOVERY_MSG_TYPE_COMPLETE)
m_exportStreamSeqNo = in->readLong();
}
/*
* Retrieve the type of this recovery message.
*/
RecoveryMsgType RecoveryProtoMsg::msgType() {
return m_type;
}
/*
* Retrieve the type of this recovery message.
*/
CatalogId RecoveryProtoMsg::tableId() {
return m_tableId;
}
uint32_t RecoveryProtoMsg::totalTupleCount() {
return m_totalTupleCount;
}
ReferenceSerializeInput* RecoveryProtoMsg::stream() {
return m_in;
}
}
|
kobronson/cs-voltdb
|
src/ee/common/RecoveryProtoMessage.cpp
|
C++
|
agpl-3.0
| 1,797
|
<%! from django.utils.translation import ugettext as _ %>
<%! from django.utils.translation import ugettext as _ %>
<%inherit file="../main.html" />
<%block name="pagetitle">${_("Vision")}</%block>
<section class="container about">
<h1>${_("Vision")}</h1>
<p>${_("This page left intentionally blank. It is not used by edx.org but is left here for possible use by installations of Open edX.")}</p>
</section>
|
LICEF/edx-platform
|
lms/templates/static_templates/remerciements.html
|
HTML
|
agpl-3.0
| 410
|
<html>
<head>
<meta charset="utf-8" />
<title>1 iframe of the node test by Sembiki Interactive</title>
</head>
<body>
<p id="send">
id: <input id="id" type="number" value="0" />
message: <input id="message" type="text" value="moo" />
<input id="send" type="submit" onclick="sendMessageParent(); return false;" value="send to parent" />
<input id="send" type="submit" onclick="sendMessageSib(); return false;" value="send to sib" />
<input id="send" type="submit" onclick="sendChainParent(); return false;" value="chain to parent" />
<input id="send" type="submit" onclick="sendChainSib(); return false;" value="chain to sib" />
</p>
<p id="status">
this page should be loaded in iframe-node<strong>s</strong>.html
</p>
<script>
(function() {
var parentWindow = window.opener ? window.opener : window.parent ? window.parent : void 0;
var postMessageToParent = function(message) {
// parentWindow.postMessage(message, window.location.protocol + "//" + window.location.host);
parentWindow.postMessage(message, "*");
};
var recieveMessage = function(e) {
var message = e.data.split("/");
switch (message[1]) {
case "name":
break;
case "chain":
document.getElementById("id").value = parseInt(message[2])+1;
document.getElementById("message").value = message[3];
sendChainSib();
break;
case "chainparent":
document.getElementById("id").value = parseInt(message[2])+1;
document.getElementById("message").value = message[3];
sendChainParent();
break;
}
document.getElementById("status").innerHTML = e.data;
var sentTime = parseInt(message[4]);
if (sentTime==sentTime){
document.getElementById("status").innerHTML += " ("+ (new Date().getTime() - sentTime) + "ms)";
}
};
window.addEventListener("message", recieveMessage, false);
// Post on loaded
postMessageToParent("/loaded");
window.sendMessageParent = function() {
var windowIndex = parseInt(document.getElementById("id").value);
postMessageToParent("/forward/"+windowIndex+"/"+document.getElementById("message").value);
};
window.sendMessageSib = function() {
var windowIndex = parseInt(document.getElementById("id").value);
var sib = parentWindow.frames[windowIndex];
if (sib) {
sib.postMessage(document.getElementById("message").value, "*")
}
};
window.sendChainParent = function() {
var time = new Date().getTime();
var windowIndex = parseInt(document.getElementById("id").value);
var message = "/chainparent/"+windowIndex+"/"+document.getElementById("message").value+"/"+time;
postMessageToParent("/forward/"+windowIndex+"/"+encodeURIComponent(message));
};
window.sendChainSib = function() {
var time = new Date().getTime();
var windowIndex = parseInt(document.getElementById("id").value);
var sib = parentWindow.frames[windowIndex];
if (sib) {
sib.postMessage("/chain/"+windowIndex+"/"+document.getElementById("message").value+"/"+time, "*")
}
};
}).call(this);
</script>
</body>
</html>
|
forresto/meemoo-videosequencer
|
test/iframe-node.html
|
HTML
|
agpl-3.0
| 3,506
|
# Copyright 2009-2010 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
__metaclass__ = type
__all__ = [
'BranchRevision',
]
from storm.locals import (
Int,
Reference,
Storm,
)
from zope.interface import implements
from lp.code.interfaces.branchrevision import IBranchRevision
class BranchRevision(Storm):
"""See `IBranchRevision`."""
__storm_table__ = 'BranchRevision'
__storm_primary__ = ("branch_id", "revision_id")
implements(IBranchRevision)
branch_id = Int(name='branch', allow_none=False)
branch = Reference(branch_id, 'Branch.id')
revision_id = Int(name='revision', allow_none=False)
revision = Reference(revision_id, 'Revision.id')
sequence = Int(name='sequence', allow_none=True)
def __init__(self, branch, revision, sequence=None):
self.branch = branch
self.revision = revision
self.sequence = sequence
|
abramhindle/UnnaturalCodeFork
|
python/testdata/launchpad/lib/lp/code/model/branchrevision.py
|
Python
|
agpl-3.0
| 984
|
from gavel import app
from gavel.models import *
from gavel.constants import *
import gavel.settings as settings
import gavel.utils as utils
from flask import (
redirect,
render_template,
request,
url_for,
)
import urllib.parse
@app.route('/admin/')
@utils.requires_auth
def admin():
annotators = Annotator.query.order_by(Annotator.id).all()
items = Item.query.order_by(Item.id).all()
decisions = Decision.query.all()
counts = {}
item_counts = {}
for d in decisions:
a = d.annotator_id
w = d.winner_id
l = d.loser_id
counts[a] = counts.get(a, 0) + 1
item_counts[w] = item_counts.get(w, 0) + 1
item_counts[l] = item_counts.get(l, 0) + 1
viewed = {i.id: {a.id for a in i.viewed} for i in items}
skipped = {}
for a in annotators:
for i in a.ignore:
if a.id not in viewed[i.id]:
skipped[i.id] = skipped.get(i.id, 0) + 1
# settings
setting_closed = Setting.value_of(SETTING_CLOSED) == SETTING_TRUE
return render_template(
'admin.html',
annotators=annotators,
counts=counts,
item_counts=item_counts,
skipped=skipped,
items=items,
votes=len(decisions),
setting_closed=setting_closed,
)
@app.route('/admin/item', methods=['POST'])
@utils.requires_auth
def item():
action = request.form['action']
if action == 'Submit':
csv = request.form['data']
data = utils.data_from_csv_string(csv)
for row in data:
_item = Item(*row)
db.session.add(_item)
db.session.commit()
elif action == 'Prioritize' or action == 'Cancel':
item_id = request.form['item_id']
target_state = action == 'Prioritize'
Item.by_id(item_id).prioritized = target_state
db.session.commit()
elif action == 'Disable' or action == 'Enable':
item_id = request.form['item_id']
target_state = action == 'Enable'
Item.by_id(item_id).active = target_state
db.session.commit()
elif action == 'Delete':
item_id = request.form['item_id']
try:
db.session.execute(ignore_table.delete(ignore_table.c.item_id == item_id))
Item.query.filter_by(id=item_id).delete()
db.session.commit()
except IntegrityError as e:
return render_template('error.html', message=str(e))
return redirect(url_for('admin'))
@app.route('/admin/item_patch', methods=['POST'])
@utils.requires_auth
def item_patch():
item = Item.by_id(request.form['item_id'])
if not item:
return render_template('error.html', message='Item not found.')
if 'location' in request.form:
item.location = request.form['location']
if 'name' in request.form:
item.name = request.form['name']
if 'description' in request.form:
item.description = request.form['description']
db.session.commit()
return redirect(url_for('item_detail', item_id=item.id))
@app.route('/admin/annotator', methods=['POST'])
@utils.requires_auth
def annotator():
action = request.form['action']
if action == 'Submit':
csv = request.form['data']
data = utils.data_from_csv_string(csv)
added = []
for row in data:
annotator = Annotator(*row)
added.append(annotator)
db.session.add(annotator)
db.session.commit()
try:
email_invite_links(added)
except Exception as e:
return render_template('error.html', message=str(e))
elif action == 'Email':
annotator_id = request.form['annotator_id']
try:
email_invite_links(Annotator.by_id(annotator_id))
except Exception as e:
return render_template('error.html', message=str(e))
elif action == 'Disable' or action == 'Enable':
annotator_id = request.form['annotator_id']
target_state = action == 'Enable'
Annotator.by_id(annotator_id).active = target_state
db.session.commit()
elif action == 'Delete':
annotator_id = request.form['annotator_id']
try:
db.session.execute(ignore_table.delete(ignore_table.c.annotator_id == annotator_id))
Annotator.query.filter_by(id=annotator_id).delete()
db.session.commit()
except IntegrityError as e:
return render_template('error.html', message=str(e))
return redirect(url_for('admin'))
@app.route('/admin/setting', methods=['POST'])
@utils.requires_auth
def setting():
key = request.form['key']
if key == 'closed':
action = request.form['action']
new_value = SETTING_TRUE if action == 'Close' else SETTING_FALSE
Setting.set(SETTING_CLOSED, new_value)
db.session.commit()
return redirect(url_for('admin'))
@app.route('/admin/item/<item_id>/')
@utils.requires_auth
def item_detail(item_id):
item = Item.by_id(item_id)
if not item:
return render_template('error.html', message='Item not found.')
else:
assigned = Annotator.query.filter(Annotator.next == item).all()
viewed_ids = {i.id for i in item.viewed}
if viewed_ids:
skipped = Annotator.query.filter(
Annotator.ignore.contains(item) & ~Annotator.id.in_(viewed_ids)
)
else:
skipped = Annotator.query.filter(Annotator.ignore.contains(item))
return render_template(
'admin_item.html',
item=item,
assigned=assigned,
skipped=skipped
)
@app.route('/admin/annotator/<annotator_id>/')
@utils.requires_auth
def annotator_detail(annotator_id):
annotator = Annotator.by_id(annotator_id)
if not annotator:
return render_template('error.html', message='Annotator not found.')
else:
seen = Item.query.filter(Item.viewed.contains(annotator)).all()
ignored_ids = {i.id for i in annotator.ignore}
if ignored_ids:
skipped = Item.query.filter(
Item.id.in_(ignored_ids) & ~Item.viewed.contains(annotator)
)
else:
skipped = []
return render_template(
'admin_annotator.html',
annotator=annotator,
seen=seen,
skipped=skipped
)
def email_invite_links(annotators):
if settings.DISABLE_EMAIL or annotators is None:
return
if not isinstance(annotators, list):
annotators = [annotators]
emails = []
for annotator in annotators:
link = urllib.parse.urljoin(settings.BASE_URL, '/login/%s' % annotator.secret)
raw_body = settings.EMAIL_BODY.format(name=annotator.name, link=link)
body = '\n\n'.join(utils.get_paragraphs(raw_body))
emails.append((annotator.email, settings.EMAIL_SUBJECT, body))
utils.send_emails(emails)
|
atagh/gavel-clone
|
gavel/controllers/admin.py
|
Python
|
agpl-3.0
| 6,919
|
[](https://app.shippable.com/projects/58b08461067893070065aab3)
# Online-Go.com source code
This repository contains the source code for web client used by [Online-Go.com](https://online-go.com).
# Bugs, Suggestions, and Discussions
Online-Go.com has a very active community of Go players, however only a
relatively small portion of the community actively develops the code base and
regularly visits this github page and the issue tracker. As such:
* https://forums.online-go.com should be used to discuss any proposed functional changes or any new notable features, allowing non developers to chime in with their thoughts and ideas.
* The [github issue tracker](https://github.com/online-go/online-go.com/issues) should be used to track all bugs, minor "obvious" enhancements, and accepted major enhancements. Any enhancements (and ideally bugs) posted need to be articulated in a way that it is obvious what needs to be done, partial thoughts will be closed and should be moved back to the forums for futher discussion.
# Development Environment
Getting setup is easy, you'll need to have [node.js](https://nodejs.org/) installed,
then simply clone the repository and within the working directory run the following:
```
# You only need to run this the first time
npm install
# Run this to start the development server and build system
npm run dev
```
If you're on linux, you can simply type `make` and it will do all this for you as well.
Once running, you can then navigate to [http://dev.beta.online-go.com:8080/](http://dev.beta.online-go.com:8080/)
which loads the interface from your local server that you just started with gulp, and
connects to the beta server for testing.
|
DmitriyKirakosyan/online-go.com
|
README.md
|
Markdown
|
agpl-3.0
| 1,788
|
/*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2019 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.rgaa32016;
import org.asqatasun.entity.audit.TestSolution;
import org.asqatasun.entity.audit.ProcessResult;
import org.asqatasun.rules.rgaa32016.test.Rgaa32016RuleImplementationTestCase;
/**
* Unit test class for the implementation of the rule 1.3.8 of the referential RGAA 3.2016
*
* @author
*/
public class Rgaa32016Rule010308Test extends Rgaa32016RuleImplementationTestCase {
/**
* Default constructor
* @param testName
*/
public Rgaa32016Rule010308Test (String testName){
super(testName);
}
@Override
protected void setUpRuleImplementationClassName() {
setRuleImplementationClassName(
"org.asqatasun.rules.rgaa32016.Rgaa32016Rule010308");
}
@Override
protected void setUpWebResourceMap() {
// addWebResource("Rgaa32016.Test.1.3.8-1Passed-01");
// addWebResource("Rgaa32016.Test.1.3.8-2Failed-01");
addWebResource("Rgaa32016.Test.1.3.8-3NMI-01");
// addWebResource("Rgaa32016.Test.1.3.8-4NA-01");
}
@Override
protected void setProcess() {
//----------------------------------------------------------------------
//------------------------------1Passed-01------------------------------
//----------------------------------------------------------------------
// checkResultIsPassed(processPageTest("Rgaa32016.Test.1.3.8-1Passed-01"), 1);
//----------------------------------------------------------------------
//------------------------------2Failed-01------------------------------
//----------------------------------------------------------------------
// ProcessResult processResult = processPageTest("Rgaa32016.Test.1.3.8-2Failed-01");
// checkResultIsFailed(processResult, 1, 1);
// checkRemarkIsPresent(
// processResult,
// TestSolution.FAILED,
// "#MessageHere",
// "#CurrentElementHere",
// 1,
// new ImmutablePair("#ExtractedAttributeAsEvidence", "#ExtractedAttributeValue"));
//----------------------------------------------------------------------
//------------------------------3NMI-01---------------------------------
//----------------------------------------------------------------------
ProcessResult processResult = processPageTest("Rgaa32016.Test.1.3.8-3NMI-01");
checkResultIsNotTested(processResult); // temporary result to make the result buildable before implementation
// checkResultIsPreQualified(processResult, 2, 1);
// checkRemarkIsPresent(
// processResult,
// TestSolution.NEED_MORE_INFO,
// "#MessageHere",
// "#CurrentElementHere",
// 1,
// new ImmutablePair("#ExtractedAttributeAsEvidence", "#ExtractedAttributeValue"));
//----------------------------------------------------------------------
//------------------------------4NA-01------------------------------
//----------------------------------------------------------------------
// checkResultIsNotApplicable(processPageTest("Rgaa32016.Test.1.3.8-4NA-01"));
}
@Override
protected void setConsolidate() {
// The consolidate method can be removed when real implementation is done.
// The assertions are automatically tested regarding the file names by
// the abstract parent class
assertEquals(TestSolution.NOT_TESTED,
consolidate("Rgaa32016.Test.1.3.8-3NMI-01").getValue());
}
}
|
dzc34/Asqatasun
|
rules/rules-rgaa3.2016/src/test/java/org/asqatasun/rules/rgaa32016/Rgaa32016Rule010308Test.java
|
Java
|
agpl-3.0
| 4,461
|
/*
* eyeos - The Open Source Cloud's Web Desktop
* Version 2.0
* Copyright (C) 2007 - 2010 eyeos Team
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* version 3 along with this program in the file "LICENSE". If not, see
* <http://www.gnu.org/licenses/agpl-3.0.txt>.
*
* See www.eyeos.org for more details. All requests should be sent to licensing@eyeos.org
*
* 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
* eyeos" logo and retain the original copyright notice. If the display of the
* logo is not reasonably feasible for technical reasons, the Appropriate Legal Notices
* must display the words "Powered by eyeos" and retain the original copyright notice.
*/
/**
* eyeos.dashboard.Widget
*
* Our Widget object
*/
qx.Class.define('eyeos.dashboard.Widget', {
'extend': qx.ui.core.Widget,
'construct': function (title, id, application, blocked, checknum) {
arguments.callee.base.apply(this, arguments);
//this.setFont(new qx.bom.Font(12, ["Lucida Grande", "Verdana"]));
this.setApplication(application);
this.setChecknum(checknum);
this.setTitle(title);
this.setId(id);
this.setBlocked(blocked);
this._buildLayout(title);
this._addListeners();
},
'properties': {
application: {
check: 'String'
},
checknum: {
check: 'Number'
},
executeFullAppParameters: {
init: null
},
icon: {
init: 'eyeos/extern/images/widgetIcon.png',
nullable: false,
check: 'String',
apply: '_applyIcon'
},
blocked: {
check: 'Boolean',
init: false
},
savedBounds: {
check: 'Object'
},
title: {
init: null
},
id: {
init: null
}
},
'members': {
'_currentContainer': false,
'_isMinimized': false,
'_lastWidgetOver': false,
/**
* Widget Layout items
*/
'_widgetCaption': false,
'_widgetContent': false,
'_widgetMenu': false,
'_widgetMain': false,
'_widgetMenuButtonSettings': false,
'_widgetMenuButtonFullApp': false,
'_widgetMenuButtonBackground': false,
'_widgetSettingsPanel': false,
'_widgetSettingsPanelForm': false,
'_widgetSettingsPanelButtonCancel': false,
'_widgetSettingsPanelButtonSave': false,
'_widgetTitlebar': false,
'_widgetTitlebarButtons': false,
'_widgetTitlebarButtonMenu': false,
'_widgetTitlebarButtonMinimize': false,
'_widgetTitlebarButtonClose': false,
'_widgetBackground': false,
'_widgetBorderActive': new qx.ui.decoration.Single(2, 'solid', '#9DC1E1'),
'_widgetBorderInactive': new qx.ui.decoration.Single(2, 'solid', '#E6E6E6'),
'_widgetBorderInactiveBackground': new qx.ui.decoration.Single(2, 'solid', '#F4F4F4'),
'_addListeners': function () {
var self = this;
// Caption Listener
if (this.getBlocked() != true) {
this._widgetCaption.addListener('mouseover', function (e) {
this.setDraggable(true);
this.setCursor('move');
}, this);
this._widgetCaption.addListener('mouseout', function (e) {
if (!qx.ui.core.Widget.contains(this._widgetCaption, e.getRelatedTarget())) {
this.setDraggable(false);
this.setCursor('default');
}
}, this);
// Titlebar Listeners
this._widgetTitlebar.addListener('mouseover', function (e) {
this.setVisibleTitlebarButtons(true);
this._widgetTitlebar.setBackgroundColor('#ebebeb');
}, this);
this._widgetTitlebar.addListener('mouseout', function (e) {
if (!qx.ui.core.Widget.contains(this._widgetTitlebar, e.getRelatedTarget())) {
this.setVisibleTitlebarButtons(false);
this._widgetTitlebar.setBackgroundColor('#ffffff');
}
}, this);
this._widgetTitlebarButtonMenu.addListener('mouseover', function (e) {
if (!self._widgetMenu.isVisible()) {
this.set({'icon': 'eyeos/extern/images/Arrow.png'});
}
});
this._widgetTitlebarButtonMenu.addListener('mouseout', function (e) {
if (!qx.ui.core.Widget.contains(this._widgetitlebarButtonMenu, e.getRelatedTarget())) {
if (!self._widgetMenu.isVisible()) {
this.set({
'icon': 'eyeos/extern/images/Arrow50.png'
});
}
}
});
this._widgetTitlebarButtonMenu.addListener('click', function (e) {
this.set({'icon': 'eyeos/extern/images/ArrowPush.png'});
});
this._widgetTitlebarButtonMinimize.addListener('mouseover', function (e) {
if (self._isMinimized) {
this.set({'icon': 'eyeos/extern/images/Max.png'});
} else {
this.set({'icon': 'eyeos/extern/images/Min.png'});
}
});
this._widgetTitlebarButtonMinimize.addListener('mouseout', function (e) {
if (!qx.ui.core.Widget.contains(this._widgetTitlebarButtonMinimize, e.getRelatedTarget())) {
if (self._isMinimized) {
this.set({
'icon': 'eyeos/extern/images/Max50.png'
});
} else {
this.set({
'icon': 'eyeos/extern/images/Min50.png'
});
}
}
});
this._widgetTitlebarButtonMinimize.addListener('execute', function (e) {
this.toggleMinimize();
}, this);
this._widgetTitlebarButtonClose.addListener('mouseover', function (e) {
this.set({'icon': 'eyeos/extern/images/Close.png'});
});
this._widgetTitlebarButtonClose.addListener('mouseout', function (e) {
if (!qx.ui.core.Widget.contains(this._widgetTitlebarButtonClose, e.getRelatedTarget())) {
this.set({'icon': 'eyeos/extern/images/Close50.png'});
}
});
this._widgetTitlebarButtonClose.addListener('execute', function (e) {
//HERE
this.close();
}, this);
// Menu Listeners
this._widgetMenu.addListener('mouseover', function (e) {
this.setVisibleTitlebarButtons(true);
}, this);
this._widgetMenu.addListener('disappear', function (e) {
this.setVisibleTitlebarButtons(false);
}, this);
this._widgetMenuButtonSettings.addListener('execute', function (e) {
this.setVisibleSettingsPanel(true);
this.setVisibleTitlebarButtons(false);
}, this);
this._widgetSettingsPanelButtonCancel.addListener('execute', function (e) {
this.setVisibleSettingsPanel(false);
}, this);
this._widgetSettingsPanelButtonSave.addListener('execute', function (e) {
this.setVisibleSettingsPanel(false);
}, this);
this._widgetMenuButtonBackground.addListener('execute', function (e) {
this.toggleBackground();
}, this);
this._widgetMenu.addListener('disappear', function (e) {
if (!this._widgetBackground) {
var borderDecorator = new qx.ui.decoration.Single(2, 'solid', '#E6E6E6');
this.setDecorator(borderDecorator);
}
this._widgetTitlebarButtonMenu.set({'icon': 'eyeos/extern/images/Arrow50.png'});
}, this);
if(this.getApplication() != '') {
this._widgetMenuButtonFullApp.addListener('execute', function (e) {
if(this.getExecuteFullAppParameters()) {
eyeos.execute(this.getApplication(), this.getChecknum(), this.getExecuteFullAppParameters());
} else {
eyeos.execute(this.getApplication(), this.getChecknum());
}
}, this);
}
}
},
'_applyIcon': function(value, old) {
if (this._widgetCaption != false) {
this._widgetCaption.setIcon(value);
}
},
'_buildLayout': function (title) {
/**
* Main Layout
*/
var borderDecorator = new qx.ui.decoration.Single(2, 'solid', '#E6E6E6');
this._setLayout(new qx.ui.layout.VBox(0));
this.set({
'backgroundColor': '#FFFFFF',
'droppable': true,
decorator: null
});
this._widgetMain = new qx.ui.container.Composite(new qx.ui.layout.VBox(0));
if (!this.getBlocked()) {
this.set({'decorator': borderDecorator});
/**
* Widget Titlebar
*/
this._widgetTitlebar = new qx.ui.container.Composite(new qx.ui.layout.HBox(5));
this._widgetTitlebar.set({'height': 23, 'padding': 2, 'paddingLeft': 5, 'paddingRight': 6});
this._widgetCaption = new qx.ui.basic.Atom(title, this.getIcon());
this._widgetCaption.set({
'paddingTop': 0,
'gap': 5,
'height': 14
});
this._widgetTitlebar.add(this._widgetCaption, {flex: 1});
this._add(this._widgetTitlebar);
/**
* Widget Menu
*/
this._widgetMenu = new qx.ui.menu.Menu();
this._decoratorWidgetMenu = new qx.ui.decoration.Single(1, 'solid', '#9EB6DB');
this._widgetMenu.set({
'backgroundColor': '#F3F7FF',
'padding': 0,
'decorator': this._decoratorWidgetMenu,
'shadow': null
});
this._widgetMenuButtonSettings = new qx.ui.menu.Button('Settings', 'eyeos/extern//images/16x16/actions/configure.png');
this._applyMenuButtonDecoration(this._widgetMenuButtonSettings);
if(this.getApplication() != '') {
this._widgetMenuButtonFullApp = new qx.ui.menu.Button('Open full app', 'eyeos/extern//images/16x16/actions/window-duplicate.png');
this._applyMenuButtonDecoration(this._widgetMenuButtonFullApp);
this._widgetMenu.add(this._widgetMenuButtonFullApp);
}
this._widgetMenuButtonBackground = new qx.ui.menu.Button('Background', 'eyeos/extern//images/16x16/actions/games-config-background.png');
this._applyMenuButtonDecoration(this._widgetMenuButtonBackground);
this._widgetMenu.add(this._widgetMenuButtonSettings);
this._widgetMenu.add(this._widgetMenuButtonBackground);
/**
* Widget Titlebar buttons
*/
this._widgetTitlebarButtons = new qx.ui.container.Composite(new qx.ui.layout.HBox(0));
this._widgetTitlebarButtonMenu = new qx.ui.form.MenuButton(null, 'eyeos/extern/images/Arrow50.png', this._widgetMenu);
this._widgetTitlebarButtonMenu.set({'decorator': null, 'width': 16, 'margin': 0, 'padding': 0, 'marginRight': 3});
this._widgetTitlebarButtonMinimize = new qx.ui.form.Button(null, 'eyeos/extern/images/Min50.png');
this._widgetTitlebarButtonMinimize.set({'decorator': null, 'width': 16, 'margin': 0, 'padding': 0, 'marginRight': 3});
this._widgetTitlebarButtonClose = new qx.ui.form.Button(null, 'eyeos/extern/images/Close50.png');
this._widgetTitlebarButtonClose.set({'decorator': null, 'width': 16, 'margin': 0, 'padding': 0});
this._widgetTitlebarButtons._add(this._widgetTitlebarButtonMenu);
this._widgetTitlebarButtons._add(this._widgetTitlebarButtonMinimize);
this._widgetTitlebarButtons._add(this._widgetTitlebarButtonClose);
this._widgetTitlebar.add(this._widgetTitlebarButtons);
this.setVisibleTitlebarButtons(false);
this._widgetSettingsPanel = new qx.ui.container.Composite(new qx.ui.layout.VBox(5));
var borderAll = new qx.ui.decoration.RoundBorderBeveled().set({
'leftTopR': 3,
'rightTopR': 3,
'leftBottomR': 3,
'rightBottomR': 3
});
this._widgetSettingsPanel.set({
'height': 50,
'padding': 5,
'backgroundColor': '#e6e6e6',
'decorator': borderAll
});
var grid = new qx.ui.layout.Grid();
grid.setSpacing(5);
grid.setColumnAlign(0, "left", "middle")
this._widgetSettingsPanelForm = new qx.ui.container.Composite(grid);
var settingsPanelButtons = new qx.ui.container.Composite(new qx.ui.layout.HBox(0, 'right'));
this._widgetSettingsPanelButtonCancel = new qx.ui.form.Button('Cancel');
this._widgetSettingsPanelButtonSave = new qx.ui.form.Button('Save');
settingsPanelButtons.add(this._widgetSettingsPanelButtonCancel);
settingsPanelButtons.add(this._widgetSettingsPanelButtonSave);
this._widgetSettingsPanel.add(this._widgetSettingsPanelForm);
this._widgetSettingsPanel.add(settingsPanelButtons);
this._widgetMain.add(this._widgetSettingsPanel);
this.setVisibleSettingsPanel(false);
}
// MAIN INNER LAYOUT (Includes widget content and Settings)
/**
* Settings Panel
* BUG: Qooxdoo says that "qx.ui.form.Form()" it's not a constructor though it's listed on the API
* - this is a serious problem due to most windows should work with forms and we shouldn't care about layouting -
*/
/**
* Content
*/
this._widgetContent = new qx.ui.container.Composite(new qx.ui.layout.VBox(0));
this._widgetMain.add(this._widgetContent);
this._add(this._widgetMain);
},
'_applyMenuButtonDecoration': function (element) {
element.set({
'padding': 2,
'textColor': '#535758',
'backgroundColor': '#F3F7FF'
})
element.addListener('mouseover', function (e) {
this.set({
'decorator': null,
'textColor': '#535758',
'backgroundColor': '#CDE0ED'
});
});
element.addListener('mouseout', function (e) {
if (!qx.ui.core.Widget.contains(element, e.getRelatedTarget())) {
this.set({
'decorator': null,
'backgroundColor': '#F3F7FF'
});
}
});
},
'setBorderActive': function (value) {
if (!this.getBlocked()) {
if (value) {
this.setDecorator(this._widgetBorderActive);
} else {
if (this._widgetBackground) {
this.setDecorator(this._widgetBorderInactiveBackground);
} else {
this.setDecorator(this._widgetBorderInactive);
}
}
}
},
'setVisibleTitlebarButtons': function (value) {
if (value) {
this._widgetTitlebarButtons.show();
} else {
this._widgetTitlebarButtons.hide();
}
},
'setVisibleSettingsPanel': function (value) {
if (value) {
this._widgetSettingsPanel.setVisibility('visible');
} else {
this._widgetSettingsPanel.setVisibility('excluded');
}
},
'addSettings': function (element) {
this._widgetSettingsPanelForm.add(element);
},
'addContent': function (element) {
this._widgetContent.add(element);
},
'minimize': function () {
this._widgetMain.setVisibility('excluded');
},
'restore': function () {
this._widgetMain.setVisibility('visible');
},
'close': function () {
this.destroy();
},
'setCurrentContainer': function (element) {
this._currentContainer = element;
},
'getCurrentContainer': function (element) {
return this._currentContainer;
},
'getTitle': function () {
if (this._widgetCaption != false) {
return this._widgetCaption.getLabel();
}
},
'setTitle': function (title) {
if (this._widgetCaption != false) {
this._widgetCaption.setLabel(title);
}
},
'toggleBackground': function () {
if (this._widgetBackground) {
this.set({
'backgroundColor': '#FFFFFF'
});
this._widgetBackground = false;
} else {
this.set({
'backgroundColor': null
});
this._widgetBackground = true;
this.setBorderActive(false);
}
},
'toggleMinimize': function () {
if (this._isMinimized) {
this._widgetTitlebarButtonMinimize.set({'icon': 'eyeos/extern/images/Min.png'});
this.restore();
this._isMinimized = false;
} else {
this._widgetTitlebarButtonMinimize.set({'icon': 'eyeos/extern/images/Max.png'});
this.minimize();
this._isMinimized = true;
}
var positions = document.eyeDashBoard.getAllWidgetsPositions();
eyeos.callMessage(this.getChecknum(), 'savePositionsWidget', positions);
},
'openAndPlace': function (container, position) {
var container = container;
if (container == undefined) {
container = document.eyeDashBoard.getLastContainer();
}
container.addWidget(this, position);
}
}
});
|
Seldaiendil/meyeOS
|
eyeos/extern/js/eyeos.dashboard.Widget.js
|
JavaScript
|
agpl-3.0
| 16,044
|
DELETE FROM `weenie` WHERE `class_Id` = 49547;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (49547, 'ace49547-lightningphyntoswaspessence100', 70, '2019-02-10 00:00:00') /* PetDevice */;
INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`)
VALUES (49547, 1, 128) /* ItemType - Misc */
, (49547, 5, 50) /* EncumbranceVal */
, (49547, 16, 8) /* ItemUseable - Contained */
, (49547, 18, 64) /* UiEffects - Lightning */
, (49547, 19, 6000) /* Value */
, (49547, 33, 0) /* Bonded - Normal */
, (49547, 91, 50) /* MaxStructure */
, (49547, 92, 50) /* Structure */
, (49547, 93, 1044) /* PhysicsState - Ethereal, IgnoreCollisions, Gravity */
, (49547, 94, 16) /* TargetType - Creature */
, (49547, 105, 7) /* ItemWorkmanship */
, (49547, 114, 0) /* Attuned - Normal */
, (49547, 280, 213) /* SharedCooldown */
, (49547, 366, 54) /* UseRequiresSkill */
, (49547, 367, 400) /* UseRequiresSkillLevel */
, (49547, 369, 90) /* UseRequiresLevel */
, (49547, 370, 8) /* GearDamage */
, (49547, 371, 13) /* GearDamageResist */
, (49547, 8041, 101) /* PCAPRecordedPlacement - Resting */;
INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`)
VALUES (49547, 22, True ) /* Inscribable */
, (49547, 69, True ) /* IsSellable */;
INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`)
VALUES (49547, 39, 0.4) /* DefaultScale */
, (49547, 167, 45) /* CooldownDuration */;
INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`)
VALUES (49547, 1, 'Lightning Phyntos Wasp Essence (100)') /* Name */
, (49547, 14, 'Use this essence to summon or dismiss your Lightning Phyntos Wasp.') /* Use */;
INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`)
VALUES (49547, 1, 33554817) /* Setup */
, (49547, 3, 536870932) /* SoundTable */
, (49547, 6, 67111919) /* PaletteBase */
, (49547, 8, 100667450) /* Icon */
, (49547, 22, 872415275) /* PhysicsEffectTable */
, (49547, 50, 100693028) /* IconOverlay */
, (49547, 52, 100693024) /* IconUnderlay */
, (49547, 8001, 1076382872) /* PCAPRecordedWeenieHeader - Value, Usable, UiEffects, Structure, MaxStructure, Container, TargetType, Burden, IconOverlay */
, (49547, 8002, 7) /* PCAPRecordedWeenieHeader2 - IconUnderlay, Cooldown, CooldownDuration */
, (49547, 8003, 67108882) /* PCAPRecordedObjectDesc - Inscribable, Attackable, IncludesSecondHeader */
, (49547, 8005, 137345) /* PCAPRecordedPhysicsDesc - CSetup, ObjScale, STable, PeTable, AnimationFrame */;
INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`)
VALUES (49547, 8000, 3705346101) /* PCAPRecordedObjectIID */;
INSERT INTO `weenie_properties_palette` (`object_Id`, `sub_Palette_Id`, `offset`, `length`)
VALUES (49547, 67111921, 0, 0);
INSERT INTO `weenie_properties_texture_map` (`object_Id`, `index`, `old_Id`, `new_Id`)
VALUES (49547, 0, 83890064, 83890069);
INSERT INTO `weenie_properties_anim_part` (`object_Id`, `index`, `animation_Id`)
VALUES (49547, 0, 16777882);
|
LtRipley36706/ACE-World
|
Database/3-Core/9 WeenieDefaults/SQL/PetDevice/Misc/49547 Lightning Phyntos Wasp Essence (100).sql
|
SQL
|
agpl-3.0
| 3,350
|
default: libmupdf_java.so libmupdf.jar
MUPDF_CORE = ../../build/java/libmupdf.a ../../build/java/libmupdfthird.a
LIBRARY_JAVA_SOURCES := $(sort $(wildcard com/artifex/mupdf/fitz/*.java))
LIBRARY_JAVA_OBJECTS := $(LIBRARY_JAVA_SOURCES:%.java=%.class)
LIBRARY_JAVA_CLASSES := $(subst com/artifex/mupdf/fitz/,com.artifex.mupdf.fitz.,$(LIBRARY_JAVA_SOURCES:%.java=%))
VIEWER_JAVA_SOURCES := $(sort $(wildcard *.java))
VIEWER_JAVA_OBJECTS := $(VIEWER_JAVA_SOURCES:%.java=%.class)
$(MUPDF_CORE) :
$(MAKE) -C ../.. OUT=build/java XCFLAGS=-fPIC build=release libs
$(LIBRARY_JAVA_OBJECTS) : $(LIBRARY_JAVA_SOURCES)
javac $^
libmupdf.jar : $(LIBRARY_JAVA_OBJECTS)
rm -f $@
jar cf $@ $^
mupdf_native.h : $(LIBRARY_JAVA_OBJECTS)
rm -f $@
javah -o $@ $(LIBRARY_JAVA_CLASSES)
mupdf_native.o : mupdf_native.c mupdf_native.h
$(CC) -g -fPIC -Wall -Wextra -Wno-unused-parameter \
-I /usr/lib/jvm/java-7-openjdk-i386/include \
-I /usr/lib/jvm/java-7-openjdk-i386/include/linux \
-I /usr/lib/jvm/java-7-openjdk-amd64/include \
-I /usr/lib/jvm/java-7-openjdk-amd64/include/linux \
-I ../../include \
-o $@ -c $<
libmupdf_java.so : mupdf_native.o $(MUPDF_CORE)
$(CC) -shared -o $@ $^
$(VIEWER_JAVA_OBJECTS) : $(VIEWER_JAVA_SOURCES)
javac $^
viewer: libmupdf_java.so $(LIBRARY_JAVA_OBJECTS) $(VIEWER_JAVA_OBJECTS)
LD_LIBRARY_PATH=. java Viewer
clean:
rm -f com/artifex/mupdf/fitz/*.class
rm -f *.class
rm -f mupdf_native.o
rm -f libmupdf_java.so
nuke: clean
$(MAKE) -C ../.. OUT=build/java clean
.NOTPARALLEL : # disable -j option (it breaks since javac compiles all class files in one command)
|
asbloomf/mupdf
|
platform/java/Makefile
|
Makefile
|
agpl-3.0
| 1,613
|
DELETE FROM `weenie` WHERE `class_Id` = 31647;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (31647, 'ace31647-moina', 10, '2019-02-10 00:00:00') /* Creature */;
INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`)
VALUES (31647, 1, 16) /* ItemType - Creature */
, (31647, 2, 31) /* CreatureType - Human */
, (31647, 6, -1) /* ItemsCapacity */
, (31647, 7, -1) /* ContainersCapacity */
, (31647, 16, 32) /* ItemUseable - Remote */
, (31647, 25, 135) /* Level */
, (31647, 93, 6292504) /* PhysicsState - ReportCollisions, IgnoreCollisions, Gravity, ReportCollisionsAsEnvironment, EdgeSlide */
, (31647, 95, 8) /* RadarBlipColor - Yellow */
, (31647, 113, 2) /* Gender - Female */
, (31647, 133, 4) /* ShowableOnRadar - ShowAlways */
, (31647, 134, 16) /* PlayerKillerStatus - RubberGlue */
, (31647, 188, 1) /* HeritageGroup - Aluvian */
, (31647, 8007, 0) /* PCAPRecordedAutonomousMovement */;
INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`)
VALUES (31647, 1, True ) /* Stuck */
, (31647, 19, False) /* Attackable */;
INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`)
VALUES (31647, 54, 3) /* UseRadius */;
INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`)
VALUES (31647, 1, 'Moina') /* Name */
, (31647, 5, 'Violator Grievver Vetoer') /* Template */
, (31647, 8006, 'AAA9AAAAAAA=') /* PCAPRecordedCurrentMotionState */;
INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`)
VALUES (31647, 1, 33554510) /* Setup */
, (31647, 2, 150994945) /* MotionTable */
, (31647, 3, 536870914) /* SoundTable */
, (31647, 6, 67108990) /* PaletteBase */
, (31647, 8, 100667377) /* Icon */
, (31647, 9, 83890283) /* EyesTexture */
, (31647, 10, 83890315) /* NoseTexture */
, (31647, 11, 83890355) /* MouthTexture */
, (31647, 15, 67117078) /* HairPalette */
, (31647, 16, 67110062) /* EyesPalette */
, (31647, 17, 67109562) /* SkinPalette */
, (31647, 8001, 9437238) /* PCAPRecordedWeenieHeader - ItemsCapacity, ContainersCapacity, Usable, UseRadius, RadarBlipColor, RadarBehavior */
, (31647, 8003, 4) /* PCAPRecordedObjectDesc - Stuck */
, (31647, 8005, 100355) /* PCAPRecordedPhysicsDesc - CSetup, MTable, STable, Position, Movement */;
INSERT INTO `weenie_properties_position` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`)
VALUES (31647, 8040, 1240465444, 100.839, 87.4448, 170.005, 0.587867, 0, 0, 0.808958) /* PCAPRecordedLocation */
/* @teleloc 0x49F00024 [100.839000 87.444800 170.005000] 0.587867 0.000000 0.000000 0.808958 */;
INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`)
VALUES (31647, 8000, 3690989780) /* PCAPRecordedObjectIID */;
INSERT INTO `weenie_properties_attribute` (`object_Id`, `type`, `init_Level`, `level_From_C_P`, `c_P_Spent`)
VALUES (31647, 1, 60, 0, 0) /* Strength */
, (31647, 2, 70, 0, 0) /* Endurance */
, (31647, 3, 80, 0, 0) /* Quickness */
, (31647, 4, 50, 0, 0) /* Coordination */
, (31647, 5, 120, 0, 0) /* Focus */
, (31647, 6, 130, 0, 0) /* Self */;
INSERT INTO `weenie_properties_attribute_2nd` (`object_Id`, `type`, `init_Level`, `level_From_C_P`, `c_P_Spent`, `current_Level`)
VALUES (31647, 1, 10, 0, 0, 45) /* MaxHealth */
, (31647, 3, 10, 0, 0, 80) /* MaxStamina */
, (31647, 5, 10, 0, 0, 140) /* MaxMana */;
INSERT INTO `weenie_properties_palette` (`object_Id`, `sub_Palette_Id`, `offset`, `length`)
VALUES (31647, 67109562, 0, 24)
, (31647, 67110062, 32, 8)
, (31647, 67110539, 92, 4)
, (31647, 67113079, 40, 24)
, (31647, 67113079, 64, 8)
, (31647, 67113079, 72, 8)
, (31647, 67113079, 108, 8)
, (31647, 67113079, 128, 8)
, (31647, 67117078, 24, 8);
INSERT INTO `weenie_properties_texture_map` (`object_Id`, `index`, `old_Id`, `new_Id`)
VALUES (31647, 0, 83892345, 83886685)
, (31647, 0, 83892344, 83889386)
, (31647, 1, 83892352, 83886241)
, (31647, 2, 83892351, 83887055)
, (31647, 5, 83892352, 83886241)
, (31647, 6, 83892351, 83887055)
, (31647, 9, 83891974, 83886781)
, (31647, 9, 83891968, 83886686)
, (31647, 10, 83892347, 83886782)
, (31647, 11, 83892346, 83891213)
, (31647, 13, 83892347, 83886782)
, (31647, 14, 83892346, 83891213)
, (31647, 16, 83886232, 83890685)
, (31647, 16, 83886668, 83890283)
, (31647, 16, 83886837, 83890315)
, (31647, 16, 83886684, 83890355);
INSERT INTO `weenie_properties_anim_part` (`object_Id`, `index`, `animation_Id`)
VALUES (31647, 0, 16783897)
, (31647, 1, 16783885)
, (31647, 2, 16783878)
, (31647, 3, 16777708)
, (31647, 4, 16777708)
, (31647, 5, 16783889)
, (31647, 6, 16783881)
, (31647, 7, 16777708)
, (31647, 8, 16777708)
, (31647, 9, 16783714)
, (31647, 10, 16783863)
, (31647, 11, 16783853)
, (31647, 12, 16778423)
, (31647, 13, 16783871)
, (31647, 14, 16783855)
, (31647, 15, 16778435)
, (31647, 16, 16795662);
|
LtRipley36706/ACE-World
|
Database/3-Core/9 WeenieDefaults/SQL/Creature/Human/31647 Moina.sql
|
SQL
|
agpl-3.0
| 5,420
|
/*
* Copyright (C) 2013-2022 The enviroCar project
*
* 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.envirocar.server.rest.encoding.rdf.linker;
import javax.ws.rs.core.UriBuilder;
import org.envirocar.server.core.entities.Phenomenon;
import org.envirocar.server.rest.encoding.rdf.vocab.DUL;
import org.envirocar.server.rest.encoding.rdf.vocab.SSN;
import org.envirocar.server.rest.resources.PhenomenonsResource;
import org.envirocar.server.rest.resources.RootResource;
import org.envirocar.server.rest.rights.AccessRights;
import com.google.inject.Provider;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.vocabulary.RDF;
import org.apache.jena.vocabulary.RDFS;
/**
* TODO JavaDoc
*
* @author Christian Autermann <autermann@uni-muenster.de>
*/
public class PhenomenonSSNLinker extends AbstractSSNLinker<Phenomenon> {
@Override
protected void linkInternal(Model m, Phenomenon t, AccessRights rights,
Resource uri, Provider<UriBuilder> uriBuilder) {
Resource phenomenon = m.createResource(uriBuilder.get()
.path(RootResource.class).path(RootResource.PHENOMENONS)
.path(PhenomenonsResource.PHENOMENON).build(t.getName())
.toASCIIString());
phenomenon.addProperty(RDF.type, SSN.Property);
Resource unit = m.createResource(fragment(phenomenon,
MeasurementSSNLinker.UNIT_FRAGMENT));
unit.addProperty(RDF.type, DUL.UnitOfMeasure);
unit.addLiteral(RDFS.comment, t.getUnit());
}
}
|
enviroCar/enviroCar-server
|
rest/src/main/java/org/envirocar/server/rest/encoding/rdf/linker/PhenomenonSSNLinker.java
|
Java
|
agpl-3.0
| 2,204
|
/*
* 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.io.file;
/**
* A processor of a {@link SilverpeasFile} instance. It performs some peculiar
* tasks according to a file path in order to apply some additional business or technical rules
* on the asked file.
* @author mmoquillon
*/
public interface SilverpeasFileProcessor extends Comparable<SilverpeasFileProcessor> {
/**
* The value of the maximum priority
*/
int MAX_PRIORITY = 100;
enum ProcessingContext {
/**
* The processing is about the getting of a file.
*/
GETTING,
/**
* The processing is about the writing of the content into a file.
*/
WRITING,
/**
* The processing is about the deletion of a file.
*/
DELETION,
/**
* The processing is about the copy of a file.
*/
COPY,
/**
* The processing is about the moving of a file.
*/
MOVING
}
/**
* Gets the priority that permits to sort the processor list to execute.<br>
* The more the value of the priority is high, the more the processor is executed first.<br>
* The chained execution of processors that have the same priority could be known.<br>
* By default, the priority is set to 50.
* @return the priority value.
*/
int getPriority();
/**
* Processes the specified path and returns the new path of the SilverpeasFile to get. This method
* is triggered before retrieving the SilverpeasFile matching a given file path. If nothing
* should be done with the path, then just returns the path passed as argument.
* @param path the path of the asked file.
* @param context the processing context.
* @return either the specified path or a new path of the asked file.
*/
String processBefore(String path, ProcessingContext context);
/**
* Processes the specified SilverpeasFile and returns the new one. This method is triggered after
* retrieving the SilverpeasFile. If nothing should be done with the path, then just returns the
* SilverpeasFile instance passed as argument.
* @param file the SilverpeasFile to process.
* @param context the processing context.
* @return either the specified one or a new one.
*/
SilverpeasFile processAfter(SilverpeasFile file, ProcessingContext context);
}
|
SilverDav/Silverpeas-Core
|
core-library/src/main/java/org/silverpeas/core/io/file/SilverpeasFileProcessor.java
|
Java
|
agpl-3.0
| 3,396
|
class AutomaticCorrection::Result < ApplicationRecord
include CourseLock
belongs_to :test_run, foreign_key: :automatic_correction_test_run_id
has_many :issues, foreign_key: :automatic_correction_result_id, class_name: "AutomaticCorrection::Issue"
end
|
the-loom/dashboard
|
app/models/automatic_correction/result.rb
|
Ruby
|
agpl-3.0
| 258
|
<div id="application" class="page">
<div class="divided title">
Application
</div>
<div class="ui stackable page grid">
<div class="column">
<div class="ui form"
ng-class="{'loading': loading}">
<div class="divided title">Basic Information</div>
<fieldset ng-disabled="regIsClosed">
<div class="field">
<label> Email </label>
<input type="email"
name="email"
disabled="disabled"
ng-model="user.email">
</div>
<div class="field">
<label> Full Name </label>
<input type="text"
name="name"
ng-model="user.profile.name">
</div>
<div class="field" ng-show="autoFilledSchool">
<label> School </label>
<input class="ui input"
disabled="disabled"
ng-show="autoFilledSchool"
ng-model="user.profile.school">
</div>
<div class="field" ng-show="!autoFilledSchool">
<label> School </label>
<div id="school" class="ui search">
<div class="ui input">
<input class="prompt" type="text" placeholder="School" name="school" ng-model="user.profile.school">
</div>
<div class="results"></div>
</div>
</div>
<div class="field">
<label>Graduation Year</label>
<select
name="year"
ng-model="user.profile.graduationYear">
<option value="">Graduation Year</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
</select>
</div>
<div class="field">
<label>Gender</label>
<select
name="gender"
ng-model="user.profile.gender">
<option value="">Gender</option>
<option value="M">Male</option>
<option value="F">Female</option>
<option value="O">Other</option>
<option value="N">I prefer not to answer.</option>
</select>
</div>
<div class="field">
<label>I would describe myself as a...</label>
<input type="text"
placeholder="Designer, Data Scientist, iOS Wizard, Hacker Extraordinaire"
ng-model="user.profile.description">
</div>
<div class="field">
<label>
What would you like to learn or get out of HackMIT? (optional)
</label>
<textarea ng-model="user.profile.essay">
</textarea>
</div>
<div class="field"
ng-hide="isMitStudent">
<p>
Because of limitations imposed by MIT, we are not legally allowed to host
non-MIT minors (those under 18) for HackMIT 2015. Checking the box below affirms that you are or will be 18 years or older by September 19th, 2015.
</p>
<p>
<strong>
We will be checking ID. If you are a non-MIT minor, you will be turned away at the door.
</strong>
</p>
<div class="ui checkbox">
<input type="checkbox" id="adult" ng-model="user.profile.adult">
<label for="adult">I am 18 or older.</label>
</div>
</div>
<br>
<div class="field" ng-hide="regIsClosed">
<button type="submit"
class="fluid ui purple button"
ng-click="submitForm()">
Submit
</button>
</div>
</fieldset>
</div>
</div>
</div>
</div>
|
techx/quill
|
app/client/views/application/application.html
|
HTML
|
agpl-3.0
| 3,790
|
/*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2014 The Kuali Foundation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.module.ld.document.authorization;
import java.util.Set;
import org.kuali.kfs.module.ld.LaborConstants;
import org.kuali.kfs.module.ld.batch.LaborEnterpriseFeedStep;
import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
import org.kuali.rice.coreservice.framework.parameter.ParameterService;
import org.kuali.rice.kns.document.authorization.MaintenanceDocumentPresentationControllerBase;
import org.kuali.rice.kns.inquiry.InquiryPresentationController;
import org.kuali.rice.krad.bo.BusinessObject;
public class BenefitsCalculationMaintenanceDocumentPresentationController extends MaintenanceDocumentPresentationControllerBase implements InquiryPresentationController {
private ParameterService parameterService;
/**
* @see org.kuali.rice.kns.document.authorization.MaintenanceDocumentPresentationControllerBase#getConditionallyHiddenPropertyNames(org.kuali.rice.kns.bo.BusinessObject)
*/
@Override
public Set<String> getConditionallyHiddenPropertyNames(BusinessObject businessObject) {
Set<String> fields = super.getConditionallyHiddenPropertyNames(businessObject);
String offsetParmValue = getParameterService().getParameterValueAsString(LaborEnterpriseFeedStep.class, LaborConstants.BenefitCalculation.LABOR_BENEFIT_CALCULATION_OFFSET_IND);
if(offsetParmValue.equalsIgnoreCase("n")) {
fields.add(LaborConstants.BenefitCalculation.ACCOUNT_CODE_OFFSET_PROPERTY_NAME);
fields.add(LaborConstants.BenefitCalculation.OBJECT_CODE_OFFSET_PROPERTY_NAME);
} else {
fields.remove(LaborConstants.BenefitCalculation.ACCOUNT_CODE_OFFSET_PROPERTY_NAME);
fields.remove(LaborConstants.BenefitCalculation.OBJECT_CODE_OFFSET_PROPERTY_NAME);
}
return fields;
}
/**
* Gets the parameterService attribute.
* @return Returns the parameterService.
*/
public ParameterService getParameterService() {
if(parameterService == null){
parameterService = (ParameterService)GlobalResourceLoader.getService( "parameterService" );
}
return parameterService;
}
}
|
ua-eas/ua-kfs-5.3
|
work/src/org/kuali/kfs/module/ld/document/authorization/BenefitsCalculationMaintenanceDocumentPresentationController.java
|
Java
|
agpl-3.0
| 3,083
|
# frozen_string_literal: true
module Decidim
# Attachment can be any type of document or images related to a partcipatory
# process.
class Attachment < ApplicationRecord
belongs_to :attached_to, polymorphic: true
validates :file, :content_type, presence: true
validates :file, file_size: { less_than_or_equal_to: ->(_attachment) { Decidim.maximum_attachment_size } }
mount_uploader :file, Decidim::AttachmentUploader
# Whether this attachment is a photo or not.
#
# Returns Boolean.
def photo?
@photo ||= content_type.start_with? "image"
end
# Whether this attachment is a document or not.
#
# Returns Boolean.
def document?
!photo?
end
# Which kind of file this is.
#
# Returns String.
def file_type
file.url&.split(".")&.last&.downcase
end
# The URL to download the file.
#
# Returns String.
delegate :url, to: :file
# The URL to download the thumbnail of the file. Only works with images.
#
# Returns String.
def thumbnail_url
return unless photo?
file.thumbnail.url
end
# The URL to download the a big version of the file. Only works with images.
#
# Returns String.
def big_url
return unless photo?
file.big.url
end
end
end
|
Hilfe/decidim
|
decidim-core/app/models/decidim/attachment.rb
|
Ruby
|
agpl-3.0
| 1,319
|
<section class="oe_container oe_dark">
<div class="oe_row">
<h2 class="oe_slogan">Easily start creating your new modules</h2>
<h3 class="oe_slogan">One module to rule them all.</h3>
<div class="oe_span6">
<p class='oe_mt32'>
Tired of starting your module from scratch? Spending time coping snippets of code or searching for view and model data references?
Unable to graphically design your models and fields and how they relationate?
All this common tasks are eased when designing your module with our Module Builder.
You can extend models and views, create new views and even create your own themes and snippets in an easy way.
</p>
<p>
Creating a new module has never been this easy. Fill all module information using common Odoo form and edit description page using the amazing web designer.
</p>
</div>
<div class="oe_span6">
<div class="oe_bg_img oe_centered">
<img class="oe_picture oe_screenshot" width="400" height="200" src="module_info.png">
</div>
</div>
</div>
</section>
<section class="oe_container">
<div class="oe_row oe_spaced">
<div class="oe_span12">
<h2 class="oe_slogan">Design your database models using the diagram!</h2>
<h3 class="oe_slogan">Create your models, fields and relations in one place.</h3>
</div>
<div class="oe_span6">
<div class="oe_bg_img oe_centered">
<img class="oe_picture oe_screenshot" width="400" height="200" src="designer.png">
</div>
</div>
<div class="oe_span6">
<p class='oe_mt32'>
You can design your models relations in an easy way or even see how system models relates then you'll love the Module Builder's UML Designer.
Import and extend system models easily and add your own fields to extend those models. Module dependencies are managed automatically!
</p>
<p class='oe_mt8'>
You can export and import your working module and share with your coworkers easily.
Local modules can be imported for review of info, models and views. Try importing the Module Builder
module with the Module Builder and then open the UML Designer. Give it a try!
</p>
</div>
</div>
</section>
<section class="oe_container">
<div class="oe_row oe_spaced">
<div class="oe_span12">
<h2 class="oe_slogan">Generate all view types easily.</h2>
<h3 class="oe_slogan">Wizards will help you create a view in no time!</h3>
</div>
<div class="oe_span6">
<p class='oe_mt32'>
Model views can be generated for all view types following simple customization wizards. Simply choose the fields to show and
set up their options like widgets and visibility or even arrange their order.
You can preview the generated architecture (arch) and customize it manually if you want.
</p>
</div>
<div class="oe_span6">
<div class="oe_bg_img oe_centered">
<img class="oe_picture oe_screenshot" width="400" height="200" src="view_wizards.png">
</div>
</div>
</div>
</section>
<section class="oe_container">
<div class="oe_row oe_spaced">
<div class="oe_span12">
<h2 class="oe_slogan">Great odoo backend integration!</h2>
<h3 class="oe_slogan">Create backend menus, actions, views and manage security.</h3>
</div>
<div class="oe_span6">
<div class="oe_bg_img oe_centered">
<img class="oe_picture oe_screenshot" width="400" height="200" src="backend.png">
</div>
</div>
<div class="oe_span6">
<p class='oe_mt32'>
Focusing on odoo administration, Module Builder delivers an easy to use interface to configure most
backend elements such as models, views, menus, actions, record rules and groups.
</p>
</div>
</div>
</section>
<section class="oe_container">
<div class="oe_row oe_spaced">
<div class="oe_span12">
<h2 class="oe_slogan">Website features out of the box!</h2>
<h3 class="oe_slogan">Create website menus, pages, themes or snippets in no time!</h3>
</div>
<div class="oe_span6">
<div class="oe_bg_img oe_centered">
<img class="oe_picture oe_screenshot" width="400" height="200" src="website.png">
</div>
</div>
<div class="oe_span6">
<p class='oe_mt32'>
Module Builder allow you to create all these website features easing the development process.
Tweaks like odoo version differences are been take into account.
Create snippets as easy as dragging a bookmarklet and clicking on a page to select the page portion that interests.
Also website WYSIWYG is available for creating snippets and pages.
</p>
</div>
</div>
</section>
|
smartforceplus/SmartForceplus
|
.local/share/Odoo/addons/8.0/builder/static/description/index.html
|
HTML
|
agpl-3.0
| 5,285
|
/**
* Class responsible for display and drop patients to the pedigree tree nodes
*
* @class PatientDropLegend
* @constructor
*/
define([
"pedigree/model/helpers"
], function(
Helpers
){
var PatientDropLegend = Class.create( {
initialize: function() {
if (editor.isReadOnlyMode()) {
return;
}
this.assignNewPatientId = null;
this._notLinkedPatients = {};
this._legendInfo = new Element('div', {'class' : 'legend-box legend-info', id: 'legend-info'}).insert(
new Element('div', {'class' : 'infomessage no-word-wrap'}).insert(
"Drag and drop onto the pedigree")
);
this.closeButton = new Element('span', {'class' : 'close-button'}).update('x');
this.closeButton.observe('click', this.hideDragHint.bindAsEventListener(this));
this._legendInfo.insert({'top': this.closeButton});
this._legendInfo.hide();
this.legendContainer = new Element('div', {'class' : 'patient-assign-legend', id: 'patient-assign'}).insert(this._legendInfo);
this.legendContainer.hide();
this._list_new = new Element('ul', {'class' : 'patient-list new'});
this._list_unlinked = new Element('ul', {'class' : 'patient-list unlinked'});
var l_box = new Element('div', {'class' : 'legend-box', 'id' : 'list_new'});
l_box.insert(new Element('h2', {'class' : 'legend-title'}).update("New patient: "));
l_box.insert(this._list_new);
this.legendContainer.insert(l_box);
var lg_box = new Element('div', {'class' : 'legend-box', 'id' : 'list_unlinked'});
lg_box.insert(new Element('h2', {'class' : 'legend-title'}).update("Unlinked patients: "));
lg_box.insert(this._list_unlinked);
this.legendContainer.insert(lg_box);
editor.getWorkspace().getWorkArea().insert(this.legendContainer);
$('list_new').hide();
$('list_unlinked').hide();
Droppables.add(editor.getWorkspace().canvas, {accept: 'drop-patient',
onDrop: this._onDropWrapper.bind(this),
onHover: this._onHoverWrapper.bind(this)});
//add patient to a legend on unlink patient from node event
document.observe('pedigree:patient:unlinked', function (event) {
if ( event.memo.phenotipsID == this.assignNewPatientId) {
this.addCase(event.memo.phenotipsID, 'new', event.memo.gender, event.memo.firstName, event.memo.lastName, event.memo.externalID);
} else {
this.addCase(event.memo.phenotipsID, 'unlinked', event.memo.gender, event.memo.firstName, event.memo.lastName, event.memo.externalID);
}
}.bind(this));
//remove patient from a legend on link patient to node event
document.observe('pedigree:patient:linked', function (event){
if (this._notLinkedPatients.hasOwnProperty(event.memo.phenotipsID)) {
this._deletePatientElement(event.memo.phenotipsID, this._notLinkedPatients[event.memo.phenotipsID].type);
delete this._notLinkedPatients[event.memo.phenotipsID];
}
}.bind(this));
},
hideDragHint: function() {
editor.getPreferencesManager().setConfigurationOption("user", "hideDraggingHint", true);
this._legendInfo.hide();
},
hide: function() {
this.legendContainer.hide();
},
show: function() {
if (!this._hasPatients()) {
this.legendContainer.show();
}
},
/**
* Add patient to a legend
*
* @method addCase
**/
addCase: function(patientID, type, gender, firstName, lastName, externalID) {
if (!this._notLinkedPatients.hasOwnProperty(patientID)) {
// if data about this patient is not available need ot load it
if (gender === undefined) {
this._loadPatientInfoAndAddToLegend(patientID, type);
return;
}
var name = firstName + " " + lastName;
if (!editor.getPreferencesManager().getConfigurationOption("hideDraggingHint")) {
this._legendInfo && this._legendInfo.show();
}
this._notLinkedPatients[patientID] = {"type" : type, "phenotipsID": patientID, "gender": gender, "name": name, "externalID": externalID};
var listElement = this._generateElement(this._notLinkedPatients[patientID]);
if (type == 'new') {
this._list_new.insert(listElement);
this.assignNewPatientId = patientID;
$('list_new').show();
} else {
this._list_unlinked.insert(listElement);
$('list_unlinked').show();
}
}
// show legend in any case when addCase() is invoked
this.legendContainer.show();
},
_loadPatientInfoAndAddToLegend: function(patientID, type) {
var _this = this;
var patientDataJsonURL = editor.getExternalEndpoint().getLoadPatientDataJSONURL([patientID]);
new Ajax.Request(patientDataJsonURL, {
method: "GET",
onSuccess: function (response) {
if (response.responseJSON) {
var patient = response.responseJSON[patientID];
var firstName = patient.hasOwnProperty('patient_name') && patient.patient_name.hasOwnProperty("first_name")
? patient.patient_name.first_name.trim() : "";
var lastName = patient.hasOwnProperty('patient_name') && patient.patient_name.hasOwnProperty("last_name")
? patient.patient_name.last_name.trim() : "";
_this.addCase(patientID, type, patient.sex, firstName, lastName, patient.external_id);
}
}
});
},
/**
* Returns the list of unassigned patients that are in the in the patient legend
*
* @method getListOfPatientsInTheLegend
* @return {patientList} List of patients in the legend
*/
getListOfPatientsInTheLegend: function() {
var patientList = [];
for (var patient in this._notLinkedPatients) {
if (this._notLinkedPatients.hasOwnProperty(patient)) {
patientList.push(patient);
}
}
return patientList;
},
/**
* Generate the element that will display information about the given patient in the patient legend
*
* @method _generateElement
* @return {HTMLLIElement} List element to be insert in the legend
* @private
*/
_generateElement: function(patientElement) {
var shape = 'circle';
if (patientElement.gender == "M"){
shape = 'square';
}
if (patientElement.gender == "U" || patientElement.gender == "O"){
shape = 'diamond';
}
var p_label = patientElement.phenotipsID;
var hasName = patientElement.name && patientElement.name != ' ';
var hasExternalID = patientElement.externalID && patientElement.externalID != ' ';
if (hasName || hasExternalID) {
p_label += " (";
if (hasName) {
var displayName = patientElement.name;
if (displayName.length > 25) {
// to make sure patient legend is not too wide
displayName = displayName.substring(0, 24) + "...";
}
p_label+= "name: " + displayName;
}
if (hasExternalID) {
p_label += (hasName ? ", " : "") + "identifier: " + patientElement.externalID;
}
p_label += ")";
}
var item = new Element('li', {'class' : 'abnormality drop-patient', 'id' : patientElement.phenotipsID}).insert(new Element('span', {'class' : shape})).insert(new Element('span', {'class' : 'patient-name no-word-wrap'}).update(p_label));
item.insert(new Element('input', {'type' : 'hidden', 'value' : patientElement.phenotipsID}));
var _this = this;
Element.observe(item, 'mouseover', function() {
item.down('.patient-name').setStyle({'background': '#DDD'});
// TODO: only highlight on start drag
_this._highlightDropTargets(patientElement, true);
});
Element.observe(item, 'mouseout', function() {
// item.setStyle({'text-decoration':'none'});
item.down('.patient-name').setStyle({'background':''});
_this._highlightDropTargets(patientElement, false);
});
new Draggable(item, {
revert: true,
reverteffect: function(segment) {
// Reset the in-line style.
segment.setStyle({
height: '',
left: '',
position: '',
top: '',
zIndex: '',
width: ''
});
},
ghosting: true
});
return item;
},
_highlightDropTargets: function(patient, isOn) {
if (editor.getView().getCurrentDraggable() != null) {
return;
}
//console.log("null");
this.validTargets = editor.getGraph().getPossiblePatientIDTarget(patient.gender);
this.validTargets.forEach(function(nodeID) {
var node = editor.getNode(nodeID);
if (node) {
if (isOn) {
node.getGraphics().highlight();
} else {
node.getGraphics().unHighlight()
}
}
});
},
/**
* Callback for moving around/hovering an object from the legend over nodes. Converts canvas coordinates
* to nodeID and calls the actual drop holder once the grunt UI work is done.
*
* @method _onHoverWrapper
* @param {HTMLElement} [label]
* @param {HTMLElement} [target]
* @param {int} [the percentage of overlapping]
* @private
*/
_onHoverWrapper: function(label, target, overlap, event) {
if (editor.isReadOnlyMode()) {
return;
}
editor.getView().setCurrentDraggable(-1); // in drag mode but with no target
var divPos = editor.getWorkspace().viewportToDiv(event.pointerX(), event.pointerY());
var pos = editor.getWorkspace().divToCanvas(divPos.x,divPos.y);
var node = editor.getView().getPersonNodeNear(pos.x, pos.y);
if (node) {
node.getGraphics().getHoverBox().animateHideHoverZone();
node.getGraphics().getHoverBox().setHighlighted(true);
this._previousHighightedNode = node;
} else {
this._unhighlightAfterDrag();
}
},
_unhighlightAfterDrag: function() {
if (this._previousHighightedNode) {
this._previousHighightedNode.getGraphics().getHoverBox().setHighlighted(false);
this._previousHighightedNode = null;
}
},
/**
* Callback for dragging an object from the legend onto nodes. Converts canvas coordinates
* to nodeID and calls the actual drop holder once the grunt UI work is done.
*
* @method _onDropWrapper
* @param {HTMLElement} [label]
* @param {HTMLElement} [target]
* @param {Event} [event]
* @private
*/
_onDropWrapper: function(label, target, event) {
if (editor.isReadOnlyMode()) {
return;
}
editor.getView().setCurrentDraggable(null);
var id = label.select('input')[0].value;
var patient = this._notLinkedPatients[id];
this._highlightDropTargets(patient, false);
this._unhighlightAfterDrag();
var divPos = editor.getWorkspace().viewportToDiv(event.pointerX(), event.pointerY());
var pos = editor.getWorkspace().divToCanvas(divPos.x,divPos.y);
var node = editor.getView().getPersonNodeNear(pos.x, pos.y);
if (node) {
if (node.getGender() != patient.gender && node.getGender() != 'U' && patient.gender != 'U') {
editor.getOkCancelDialogue().showCustomized("Can not drag the patient to a different gender","Can't assign", "OK", null);
return;
}
if (node.getPhenotipsPatientId() != "") {
editor.getOkCancelDialogue().showCustomized("This individual is already linked to another patient","Can't assign", "OK", null);
return;
}
this._onDropObject(node, patient);
}
},
/**
* Callback for dragging an object from the legend onto nodes
*
* @method _onDropGeneric
* @param {Person} Person node
* @param {String|Number} id ID of the object
*/
_onDropObject: function(node, patient) {
if (node.isPersonGroup()) {
return;
}
editor.getView().unmarkAll();
var properties = { "setPhenotipsPatientId": patient.phenotipsID };
document.fire("pedigree:node:modify", {'nodeID': node.getID(), 'modifications': {'trySetPhenotipsPatientId': patient.phenotipsID}});
},
/**
* Remove patient from legend
*
* @method _deletePatientElement
* @param {patientId} Person patient id
* @param {type} Person patient's type
* @private
*/
_deletePatientElement: function(patientId, type) {
$(patientId).remove();
delete this._notLinkedPatients[patientId];
// hide legend if empty
if (!this._hasPatients()) {
this.legendContainer.hide();
}
// independently, hide new section, if empty
if (!this._list_new.down('li')) {
$('list_new').hide();
}
// independently, hide unlinked section, if empty
if (!this._list_unlinked.down('li')) {
$('list_unlinked').hide();
}
},
_hasPatients: function() {
if (!this.legendContainer.down('li')) {
return false;
}
return true;
}
});
return PatientDropLegend;
});
|
alexhenrie/phenotips
|
components/pedigree/resources/src/main/resources/pedigree/view/patientDropLegend.js
|
JavaScript
|
agpl-3.0
| 15,438
|
/*****************************************************************************
@(#) File: src/util/slstatsd.c
-----------------------------------------------------------------------------
Copyright (c) 2008-2015 Monavacon Limited <http://www.monavacon.com/>
Copyright (c) 2001-2008 OpenSS7 Corporation <http://www.openss7.com/>
Copyright (c) 1997-2001 Brian F. G. Bidulock <bidulock@openss7.org>
All Rights Reserved.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, version 3 of the license.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>, or
write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA
02139, USA.
-----------------------------------------------------------------------------
U.S. GOVERNMENT RESTRICTED RIGHTS. If you are licensing this Software on
behalf of the U.S. Government ("Government"), the following provisions apply
to you. If the Software is supplied by the Department of Defense ("DoD"), it
is classified as "Commercial Computer Software" under paragraph 252.227-7014
of the DoD Supplement to the Federal Acquisition Regulations ("DFARS") (or any
successor regulations) and the Government is acquiring only the license rights
granted herein (the license rights customarily provided to non-Government
users). If the Software is supplied to any unit or agency of the Government
other than DoD, it is classified as "Restricted Computer Software" and the
Government's rights in the Software are defined in paragraph 52.227-19 of the
Federal Acquisition Regulations ("FAR") (or any successor regulations) or, in
the cases of NASA, in paragraph 18.52.227-86 of the NASA Supplement to the FAR
(or any successor regulations).
-----------------------------------------------------------------------------
Commercial licensing and support of this software is available from OpenSS7
Corporation at a fee. See http://www.openss7.com/
*****************************************************************************/
static char const ident[] = "src/util/slstatsd.c (" PACKAGE_ENVR ") " PACKAGE_DATE;
/*
* This is slstatsd(8). The purpose of this program is to open a connection
* to the signalling link mutiplexing driver, redirect standard output to an
* output file and standard error to a log file, close standard input, and
* place itself in the background as a deamon process. Every interval
* (usually 5 to 30 minutes) the daemon wakes up, collects statistics for
* each signalling link and outputs the statistics to the log file. THe
* daemon can also be sent a SIG_USR signal to cause it to collect statistics
* immediately, or a SIG_HUP signal to cause it to rotate its log files (for
* logrotate).
*/
int verbose = 1;
int debug = 0;
int nomead = 1;
#ifndef MAX_PATH_LENGTH
#define MAX_PATH_LENGTH 256
#endif /* MAX_PATH_LENGTH */
#ifndef SLSTATS_DEFAULT_OUTPDIR
#define SLSTATS_DEFAULT_OUTPDIR "/var/log"
#endif /* SLSTATS_DEFAULT_OUTPDIR */
#ifndef SLSTATS_DEFAULT_OUTFILE
#define SLSTATS_DEFAULT_OUTFILE "slstats.out"
#endif /* SLSTATS_DEFAULT_OUTFILE */
#ifndef SLSTATS_DEFAULT_ERRFILE
#define SLSTATS_DEFAULT_ERRFILE "slstats.err"
#endif /* SLSTATS_DEFAULT_ERRFILE */
#ifndef SLSTATS_DEFAULT_CFGFILE
#define SLSTATS_DEFAULT_CFGFILE "/etc/sysconfig/slstats.conf"
#endif /* SLSTATS_DEFAULT_CFGFILE */
#ifndef SLSTATS_DEFAULT_DEVICE
#define SLSTATS_DEFAULT_DEVICE "/dev/streams/sl-mux/stats"
#endif /* SLSTATS_DEFAULT_DEVICE */
char *outpdir[MAX_PATH_LENGTH] = SLSTATS_DEFAULT_OUTPDIR;
char *outfile[MAX_PATH_LENGTH] = SLSTATS_DEFAULT_OUTFILE;
char *errfile[MAX_PATH_LENGTH] = SLSTATS_DEFAULT_ERRFILE;
char *cfgfile[MAX_PATH_LENGTH] = SLSTATS_DEFAULT_CFGFILE;
char *device[MAX_PATH_LENGTH] = SLSTATS_DEFAULT_DEVICE;
static void
copying(int argc, char *argv[])
{
if (!verbose)
return;
(void) fprintf(stdout, "\
--------------------------------------------------------------------------------\n\
%1$s\n\
--------------------------------------------------------------------------------\n\
Copyright (c) 2008-2015 Monavacon Limited <http://www.monavacon.com/>\n\
Copyright (c) 2001-2008 OpenSS7 Corporation <http://www.openss7.com/>\n\
Copyright (c) 1997-2001 Brian F. G. Bidulock <bidulock@openss7.org>\n\
\n\
All Rights Reserved.\n\
--------------------------------------------------------------------------------\n\
This program is free software: you can redistribute it and/or modify it under\n\
the terms of the GNU Affero General Public License as published by the Free\n\
Software Foundation, version 3 of the license.\n\
\n\
This program is distributed in the hope that it will be useful, but WITHOUT ANY\n\
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n\
PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\n\
\n\
You should have received a copy of the GNU Affero General Public License along\n\
with this program. If not, see <http://www.gnu.org/licenses/>, or write to the\n\
Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\
--------------------------------------------------------------------------------\n\
U.S. GOVERNMENT RESTRICTED RIGHTS. If you are licensing this Software on behalf\n\
of the U.S. Government (\"Government\"), the following provisions apply to you. If\n\
the Software is supplied by the Department of Defense (\"DoD\"), it is classified\n\
as \"Commercial Computer Software\" under paragraph 252.227-7014 of the DoD\n\
Supplement to the Federal Acquisition Regulations (\"DFARS\") (or any successor\n\
regulations) and the Government is acquiring only the license rights granted\n\
herein (the license rights customarily provided to non-Government users). If the\n\
Software is supplied to any unit or agency of the Government other than DoD, it\n\
is classified as \"Restricted Computer Software\" and the Government's rights in\n\
the Software are defined in paragraph 52.227-19 of the Federal Acquisition\n\
Regulations (\"FAR\") (or any successor regulations) or, in the cases of NASA, in\n\
paragraph 18.52.227-86 of the NASA Supplement to the FAR (or any successor\n\
regulations).\n\
--------------------------------------------------------------------------------\n\
Commercial licensing and support of this software is available from OpenSS7\n\
Corporation at a fee. See http://www.openss7.com/\n\
--------------------------------------------------------------------------------\n\
", ident);
}
static void
version(int argc, char *argv[])
{
if (!verbose)
return;
(void) fprintf(stdout, "\
%1$s (OpenSS7 %2$s) %3$s (%4$s)\n\
Written by Brian Bidulock.\n\
\n\
Copyright (c) 2008, 2009, 2010, 2015 Monavacon Limited.\n\
Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 OpenSS7 Corporation.\n\
Copyright (c) 1997, 1998, 1999, 2000, 2001 Brian F. G. Bidulock.\n\
This is free software; see the source for copying conditions. There is NO\n\
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
\n\
Distributed by OpenSS7 under GNU Affero General Public License Version 3,\n\
with conditions, incorporated herein by reference.\n\
\n\
See `%1$s --copying' for copying permissions.\n\
", NAME, PACKAGE, VERSION, PACKAGE_ENVR " " PACKAGE_DATE);
}
static void
usage(int argc, char *argv[])
{
if (!verbose)
return;
(void) fprintf(stderr, "\
Usage:\n\
%1$s [options] [{-o,--outfile}=OUTFILE] [{-l,--logfile}=ERRFILE]\n\
%1$s {-h|--help}\n\
%1$s {-V|--version}\n\
%1$s {-C|--copying}\n\
", argv[0]);
}
static void
help(int argc, char *argv[])
{
if (!verbose)
return;
(void) fprintf(stdout, "\
Usage:\n\
%1$s [options] [{-o,--outfile}=OUTFILE] [{-l,--logfile}=ERRFILE]\n\
%1$s {-h|--help}\n\
%1$s {-V|--version}\n\
%1$s {-C|--copying}\n\
Arguments:\n\
None.\n\
Options:\n\
Output Options:\n\
-i, --interval SECONDS (default: %2$d)\n\
specifies interval between collection\n\
-O, --outpdir DIRECTORY (default: %3$s)\n\
specifies the output directory\n\
-o, --outfile FILENAME (default: %4$s)\n\
specifies the output file name\n\
-l, --logfile LOGFILE (default: %5$s)\n\
specifies the log file name\n\
-c, --cfgfile CFGFILE (default: %6$s)\n\
specifies the configuration file name\n\
-e, --device DEVICE (default: %7$s)\n\
specifies the device name\n\
Command Options:\n\
-h, --help, -?, --?\n\
print this usage information and exit\n\
-V, --version\n\
print version and exit\n\
-C, --copying\n\
print copying permission and exit\n\
General Options:\n\
-q, --quiet\n\
suppress normal output (equivalent to --verbose=0)\n\
-D, --debug [LEVEL]\n\
increment or set debug LEVEL [default: 0]\n\
-v, --verbose [LEVEL]\n\
increment or set output verbosity LEVEL [default: 1]\n\
this option may be repeated.\n\
", name, interval, outpdir, outfile, errfile, cfgfile, device);
}
int alm_signal = 0;
int hup_signal = 0;
int usr_signal = 0;
int trm_signal = 0;
void
sig_handler(int signum)
{
switch (signum) {
case SIGALRM:
alm_signal = 1;
break;
case SIGHUP:
hup_signal = 1;
break;
case SIGUSR1:
usr_signal = 1;
break;
case SIGTERM:
trm_signal = 1;
break;
}
return;
}
int
sig_register(int signum, void (*handler) (int))
{
sigset_t mask;
struct sigaction act;
act.sa_handler = handler ? handler : SIG_DFL;
act.sa_flags = handler ? SA_RESTART : 0;
act.sa_restorer = NULL;
sigemptyset(&act.sa_mask);
if (sigaction(signum, &act, NULL))
return (-1);
sigemptyset(&mask);
sigaddset(&mask, signum);
sigprocmask(handler ? SIG_UNBLOCK : SIG_BLOCK, &mask, NULL);
return (0);
}
void
slstats_catch(void)
{
sig_register(SIGALRM, sig_handler);
sig_register(SIGHUP, sig_handler);
sig_register(SIGUSR1, sig_handler);
sig_register(SIGTERM, sig_handler);
}
void
slstats_block(void)
{
sig_register(SIGALRM, NULL);
sig_register(SIGHUP, NULL);
sig_register(SIGUSR1, NULL);
sig_register(SIGTERM, NULL);
}
int
start_timer(long duration)
{
struct itimerval setting = {
{0, 0},
{duration / 1000, (duration % 1000) * 1000}
};
if (sig_register(SIGALRM, sig_handler))
return (-1);
if (setitimer(ITIMER_REAL, &setting, NULL))
return (-1);
alm_signal = 0;
return (0);
}
int
stop_timer(void)
{
return sig_register(SIGALRM, NULL);
}
void slstats_exit(int retval);
static struct timeval tv;
void
fprint_time(FILE * stream)
{
if (0 > tv.tv_usec || tv.tv_usec > 1000000) {
tv.tv_usec += (tv.tv_usec / 1000000);
tv.tv_usec %= 1000000;
}
fprintf(stream, "%012ld.%06ld", tv.tv_sec, tv.tv_usec);
}
int
ftimestamp(void)
{
while (gettimeofday(&tv, NULL) < 0)
if (errno == EAGAIN || errno = EINTR || errno = ERESTART) {
syslog(LOG_ERR, "%m");
syslog(LOG_ERR, "Could not read timestamp: winging it %s", outpath);
break;
}
return (0);
}
/* generate output header */
void
slstats_header(void)
{
unsigned char buf[128] = "";
struct utsname uts;
ftimestamp();
fprint_time(stdout);
fprintf(stdout, " # SLSTATSD src/util/slstatsd.c (" PACKAGE_ENVR " " PACKAGE_DATE ") Output Header\n");
uname(&uts);
fprint_time(stdout);
fprintf(stdout, " # machine: %s %s %s %s %s\n", uts.sysname, uts.nodename, uts.release,
uts.version, uts.machine);
fprint_time(stdout);
if (outpath[0] != '\0')
snprintf(buf, sizeof(buf), outpath);
else
snprintf(buf, sizeof(buf), "(stdout)");
fprintf(stdout, " # original file name: %s\n", buf);
fprint_time(stdout);
gethostname(buf, sizeof(buf));
fprintf(stdout, " # host: %s\n", buf);
fprint_time(stdout);
fprintf(stdout, " # date: %s\n", ctime(&tv.tv_sec));
}
/* periodic collection of statistics */
int
collect_stats(void)
{
if (all) {
struct slmux_ppa_list *slm;
struct slmux_ppa *p;
struct strioctl ic;
int n, len;
/* normal case is we collect statistics for all signalling links */
/* first, find out how many links there are */
while ((n = ioctl(fd, SLM_IOCLPPA, NULL)) == -1)
if (errno != EAGAIN && errno != EINTR && errno != ERESTART) {
syslog(LOG_ERR, "%m");
syslog(LOG_ERR, "Could not obtain number of links.");
slstats_exit(1);
return (-1);
}
len = sizeof(*slm) + n * sizeof(slm->slm_list_array[0]);
if ((slm = malloc(len)) == NULL) {
syslog(LOG_ERR, "%m");
syslog(LOG_ERR, "Could not allocate memory.");
slstats_exit(1);
return (-1);
}
slm->slm_list_num = n;
ic.ic_cmd = SLM_IOCLPPA;
ic.ic_timout = -1;
ic.ic_len = len;
ic.ic_dp = (char *)slm;
while (ioctl(fd, I_STR, &ic) == -1)
if (errno != EAGAIN && errno != EINTR && errno != ERESTART) {
syslog(LOG_ERR, "%m");
syslog(LOG_ERR, "Could not list links.");
free(slm);
slstats_exit(1);
return (-1);
}
for (n = 0, p = &slm->slm_list_array[0]; n < slm->slm_list_num; n++, p++)
collect_stats_one(p);
} else {
struct slmux_ppa slm = ppa, *p = &slm;
struct strioctl ic;
ic.ic_cmd = SLM_IOCGPPA;
ic.ic_timout = -1;
ic.ic_len = sizeof(*p);
ic.Ic_dp = (char *)p;
while (ioctl(fd, I_STR, &ic) == -1)
if (errno != EAGAIN && errno != EINTR && errno != ERESTART) {
syslog(LOG_ERR, "%m");
syslog(LOG_ERR, "Could not get PPA.");
slsats_exit(1);
return (-1);
}
}
}
/* interrim reporting of statistics */
int
report_stats(void)
{
if (all) {
/* normal case is we report statistics for all signalling links */
} else {
}
}
/* ultimate signal actions */
void
trm_action(void)
{
syslog(LOG_WARNING, "Caught SIGTERM, shutting down");
slstats_exit(0);
}
void
hup_action(void)
{
syslog(LOG_WARNING, "Caught SIGHUP, reopening files");
if (verbose > 1)
syslog(LOG_NOTICE, "Reopening output file %s", outpath);
if (outpath[0] != '\0') {
fflush(stdout);
fclose(stdout);
if (freopen(outpath, "a", stdout) == NULL) {
syslog(LOG_ERR, "%m");
syslog(LOG_ERR, "Could not reopen stdout file %s", outpath);
}
slstats_header();
}
if (verbose > 1)
syslog(LOG_NOTICE, "Reopening error file %s", errpath);
if (errpath[0] != '\0') {
fflush(stderr);
fclose(stderr);
if (freopen(errpath, "a", stderr) == NULL) {
syslog(LOG_ERR, "%m");
syslog(LOG_ERR, "Could not reopen stderr file %s", errpath);
}
slstats_header();
}
return (0);
}
void
alm_action(void)
{
start_timer(interval);
collect_stats();
return (0);
}
void
usr_action(void)
{
report_stats();
return (0);
}
int fd = -1;
int
slstats_open(void)
{
if (verbose > 1)
syslog(LOG_NOTICE, "opening %s", devname);
if ((fd = open(devname, O_NONBLOCK | O_RDWR)) < 0) {
syslog(LOG_ERR, "%s: %m", __FUNCTION__);
syslog(LOG_ERR, "%s: couldn't open devname: %s", __FUNCTION__, devname);
slstats_exit(1);
return (-1);
}
return (0);
}
int
slstats_close(void)
{
if (verbose > 1)
syslog(LOG_NOTICE, "closing %s", devname);
close(fd);
return (0);
}
void
slstats_exit(int retval)
{
stop_timer();
slstats_block();
slstats_close();
syslog(LOG_NOTICE, "Exiting %d", retval);
fflush(stdout);
fflush(stderr);
closelog();
exit(retval);
}
int
wait_event(void)
{
for (;;) {
struct pollfd pfd[] = {
{fd, POLLIN | POLLPRI | POLLERR | POLLHUP, 0}
};
if (trm_signal) {
trm_signal = 0;
trm_action();
}
if (alm_signal) {
alm_signal = 0;
alm_action();
}
if (hup_signal) {
hup_signal = 0;
hup_action();
}
if (usr_signal) {
usr_signal = 0;
usr_action();
}
if (verbose > 2)
fprintf(stderr, "entering poll loop\n");
switch (poll(pfd, 1, -1)) {
case -1:
if (errno == EAGAIN || errno == EINTR || errno == ERESTART)
continue;
syslog(LOG_ERR, "%s: %m", __FUNCTION__);
syslog(LOG_ERR, "%s: poll error", __FUNCTION__);
slstats_exit(1);
return (-1);
case 0:
return (0);
case 1:
if (pfd[0].revents & (POLLIN | POLLPRI)) {
syslog(LOG_ERR, "%s: device output", __FUNCTION__);
slstats_exit(1);
return (-1);
}
if (pfd[0].revents & POLLNVAL) {
syslog(LOG_ERR, "%s: device invalid", __FUNCTION__);
slstats_exit(1);
return (-1);
}
if (pfd[0].revents & POLLHUP) {
syslog(LOG_ERR, "%s: device hangup", __FUNCTION__);
slstats_exit(1);
return (-1);
}
if (pfd[0].revents & POLLERR) {
syslog(LOG_ERR, "%s: device error", __FUNCTION__);
slstats_exit(1);
return (-1);
}
break;
default:
syslog(LOG_ERR, "%s: poll error", __FUNCTION__);
slstats_exit(1);
return (-1);
}
}
}
void
slstats_enter(const char *name)
{
if (nomead) {
pid_t pid;
if ((pid = fork()) < 0) {
perror(name);
exit(2);
} else if (pid != 0) {
/* parent exits */
exit(0);
}
/* child continues */
setsid(); /* become a session leader */
/* fork once more for SVR4 */
if ((pid = fork()) < 0) {
perror(name);
exit(2);
} else if (pid != 0) {
/* parent exits */
exit(0);
}
chdir("/"); /* release current directory */
umask(0); /* clear file creation mask */
/* rearrange file streams */
fclose(stdin);
}
/* continue in foreground or background */
openlog(name, LOG_CONS | LOG_NDELAY | LOG_PERROR | LOG_PID, LOG_DAEMON);
if (lnkname[0] == '\0')
snprintf(lnkname, sizeof(lnkname), "%s%d", name, getpid());
if (nomead || outfile[0] != '\0') {
/* initialize default filename */
if (outfile[0] == '\0')
snprintf(outfile, sizeof(outfile), "%s.out", getpid());
snprintf(outpath, sizeof(outpath), "%s/%s", outpdir, outfile);
if (verbose > 1)
syslog(LOG_NOTICE, "Redirecting stdout to file %s", outpath);
fflush(stdout);
if (freopen(outpath, "a", stdout) == NULL) {
syslog(LOG_ERR, "%m");
syslog(LOG_ERR, "Could not redirect stdout to %s", outpath);
slstats_exit(2);
}
}
if (nomead || errfile[0] != '\0') {
/* initialize default filename */
if (errfile[0] = '\0')
snprintf(errfile, sizeof(errfile), "%s.err", lnkname);
snprintf(errpath, sizeof(errpath), "%s/%s", outpdir, errfile);
if (output > 1)
syslog(LOG_NOTICE, "Redirecting stderr to file %s", errpath);
fflush(stderr);
if (freopen(errpath, "a", stderr) == NULL) {
syslog(LOG_ERR, "%m");
syslog(LOG_ERR, "Could not redirect stderr to %s", errpath);
slstats_exit(2);
}
}
slstats_catch();
slstats_header();
syslog(LOG_NOTICE, "Startup complete.");
}
void
slstats(const char *name)
{
slstats_enter(name);
if (slstats_open() == 0) {
start_timer(interval);
while (wait_event() != -1) ;
}
stop_timer();
slstats_close();
slstats_exit(1);
}
int
main(int argc, char *argv[])
{
int c;
int val;
char *optstr;
while (1) {
int option_index = 0;
/* *INDENT-OFF* */
static struct option long_options[] = {
{"interval", required_argument, NULL, 'i'},
{"daemon", no_argument, NULL, 'd'},
{"outpdir", required_argument, NULL, 'O'},
{"outfile", required_argument, NULL, 'o'},
{"logfile", required_argument, NULL, 'l'},
{"cfgfile", required_argument, NULL, 'f'},
{"device", optional_argument, NULL, 'e'},
{"clci", required_argument, NULL, 'c'},
{"gppa", required_argument, NULL, 'g'},
{"quiet", no_argument, NULL, 'q'},
{"debug", optional_argument, NULL, 'D'},
{"verbose", optional_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{"?", no_argument, NULL, 'h'},
{"version", no_argument, NULL, 'V'},
{"copying", no_argument, NULL, 'C'},
{NULL, 0 NULL, 0}
};
/* *INDENT-ON* */
c = getopt_long(argc, argv, ":W:dO:o:l:f:c:g:qD::v::hVC?", long_options,
&option_index);
if (c == -1)
break;
switch (c) {
case 0:
usage(argc, argv);
exit(2);
case 'd': /* -d, --daemon */
nomead = 1;
break;
case 'O': /* -O, --outpdir DIRECTORY */
if (optarg == NULL)
goto bad_option;
strncpy(outpdir, optarg, sizeof(outpdir));
break;
case 'o': /* -o, --outfile OUTFILE */
if (optarg == NULL)
goto bad_option;
strncpy(outfile, optarg, sizeof(outfile));
break;
case 'l': /* -l, --logfile LOGFILE */
if (optarg == NULL)
goto bad_option;
strncpy(errfile, optarg, sizeof(errfile));
break;
case 'f': /* -f, --cfgfile CFGFILE */
if (optarg == NULL)
goto bad_option;
strncpy(cfgfile, optarg, sizeof(cfgfile));
break;
case 'e': /* -e, --device DEVICENAME */
if (optarg == NULL)
goto bad_option;
strncpy(device, optarg, sizeof(device));
break;
case 'c': /* -c, --clei, --clci CLEI|CLCI */
case 'g': /* -g, --gppa GLOBAL-PPA */
case 'q': /* -q, --quiet */
verbose -= verbose > 1 ? 1 : verbose;
break;
case 'D': /* -D, --debug [LEVEL] */
if (optarg == NULL) {
debug++;
break;
}
val = strtol(optarg, &optstr, 0);
if (optstr == optarg || *optstr != '\0' || val < 0)
goto bad_option;
debug = val;
break;
case 'v': /* -v, --verbose [LEVEL] */
if (optarg == NULL) {
verbose++;
break;
}
val = strtol(optarg, &optstr, 0);
if (optstr == optarg || *optstr != '\0' || val < 0)
goto bad_option;
verbose = val;
break;
case 'h': /* -h, --help */
help(argc, argv);
exit(0);
break;
case 'C': /* -C, --copying */
copying(argc, argv);
exit(0);
break;
case 'V': /* -V, --version */
version(argc, argv);
exit(0);
break;
case ':': /* missing requiried argument */
fprintf(stderr, "%s: missing argument --", argv[0]);
while (optind < optarg)
fprintf(stderr, " %s", argv[optind++]);
fprintf(stderr, "\n");
usage(argv[0]);
exit(2);
case '?':
bad_option:
default:
optind--;
syntax_error:
fprintf(stderr, "%s: illegal syntax --", argv[0]);
while (optind < optarg)
fprintf(stderr, " %s", argv[optind++]);
fprintf(stderr, "\n");
usage(argv[0]);
exit(2);
}
}
}
|
kerr-huang/openss7
|
src/util/slstatsd.c
|
C
|
agpl-3.0
| 22,113
|
declare
li_count number;
begin
select count(role_perm_id)
into li_count
from KRIM_ROLE_PERM_T
where role_id = (select ROLE_ID from KRIM_ROLE_T where trim(upper(ROLE_NM)) = trim(upper('Longitudinal Survey Catalyst')))
and PERM_ID = (select PERM_ID from KRIM_PERM_T where nm = 'GENERATE_NEGOT_SURVEY_NOTIF');
if li_count = 0 then
INSERT INTO KRIM_ROLE_PERM_T(
ROLE_PERM_ID,
OBJ_ID,
VER_NBR,
ROLE_ID,
PERM_ID,
ACTV_IND
)
VALUES(
KRIM_ROLE_PERM_ID_S.nextval,
sys_guid(),
1,
(select ROLE_ID from KRIM_ROLE_T where trim(upper(ROLE_NM)) = trim(upper('Longitudinal Survey Catalyst'))),
(select PERM_ID from KRIM_PERM_T where nm = 'GENERATE_NEGOT_SURVEY_NOTIF'),
'Y'
);
end if;
end;
/
|
geothomasp/kcmit
|
coeus-db/coeus-db-sql/src/main/resources/edu/mit/kc/sql/migration/DML_MITKC-189_03182015.sql
|
SQL
|
agpl-3.0
| 884
|
/*
fTelnet: An HTML5 WebSocket client
Copyright (C) Rick Parrish, R&M Software
This file is part of fTelnet.
fTelnet 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 any later version.
fTelnet 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 fTelnet. If not, see <http://www.gnu.org/licenses/>.
*/
class FileRecord {
private _Data: ByteArray = new ByteArray();
private _Name: string = '';
private _Size: number = 0;
constructor(name: string, size: number) {
this._Name = name;
this._Size = size;
}
public get data(): ByteArray {
return this._Data;
}
public get name(): string {
return this._Name;
}
public get size(): number {
return this._Size;
}
}
|
rickparrish/fTelnet
|
source/filetransfer/FileRecord.ts
|
TypeScript
|
agpl-3.0
| 1,181
|
##
# Donate Your Account (donateyouraccount.com)
# Copyright (C) 2011 Kyle Shank (kyle.shank@gmail.com)
# http://www.gnu.org/licenses/agpl.html
#
# 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/>.
##
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module Dya
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
config.assets.enabled = true
config.assets.version = '1.0'
config.generators do |g|
g.test_framework :rspec
g.fixture_replacement :factory_girl, :dir => 'spec/factories'
end
end
end
|
kyleshank/donateyouraccount
|
config/application.rb
|
Ruby
|
agpl-3.0
| 3,069
|
namespace MusicStore.Test
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Mocks;
using Models;
using MyTested.AspNetCore.Mvc;
public class TestStartup : Startup
{
public TestStartup(IWebHostEnvironment env)
: base(env)
{
}
public void ConfigureTestServices(IServiceCollection services)
{
base.ConfigureServices(services);
services.ReplaceSingleton<SignInManager<ApplicationUser>, SignInManagerMock>();
}
}
}
|
ivaylokenov/MyTested.Mvc
|
samples/MusicStore/MusicStore.Test/TestStartup.cs
|
C#
|
agpl-3.0
| 627
|
export * from "./msg";
export * from "./msg-repo";
export * from "./imsg-repo";
export * from "./msg-repo-mock";
|
kgtkr/anontown-server
|
src/models/msg/index.ts
|
TypeScript
|
agpl-3.0
| 113
|
#include <stdio.h>
void f(int x){
if(x>2){
}
}
int main(){
int a = 3, b = 2;
if(a>b){f(a);}
else{f(b);}
return 0;
}
|
aureooms-ulb-2010-2015/2013-2014-infof403-project
|
2/more/tools/c/add.c
|
C
|
agpl-3.0
| 131
|
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
/*********************************************************************************
* Description: TODO To be written.
* Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
* All Rights Reserved.
* Contributor(s): ______________________________________..
********************************************************************************/
global $mod_strings,$app_strings;
if(ACLController::checkAccess('Meetings', 'edit', true))$module_menu[]=Array("index.php?module=Meetings&action=EditView&return_module=Meetings&return_action=DetailView", $mod_strings['LNK_NEW_MEETING'],"CreateMeetings");
if(ACLController::checkAccess('Meetings', 'list', true))$module_menu[]=Array("index.php?module=Meetings&action=index&return_module=Meetings&return_action=DetailView", $mod_strings['LNK_MEETING_LIST'],"Meetings");
if(ACLController::checkAccess('Meetings', 'import', true))$module_menu[]=Array("index.php?module=Import&action=Step1&import_module=Meetings&return_module=Meetings&return_action=index", $mod_strings['LNK_IMPORT_MEETINGS'],"Import", 'Meetings');
$module_menu[] = array(
'index.php?module=Calendar&action=reporteActividades',
isset($mod_strings['LNK_RENTABILIDAD_PROYECTOS']) ? $mod_strings['LNK_RENTABILIDAD_PROYECTOS'] : 'Informe de Actividades',
'Project'
);
$module_menu[] = array(
'index.php?module=Calendar&action=reporteDias',
isset($mod_strings['LNK_RENTABILIDAD_PROYECTOS']) ? $mod_strings['LNK_RENTABILIDAD_PROYECTOS'] : 'Informe de Actividades Global',
'Project'
);
?>
|
dev-pnt/gers-pruebas
|
modules/Meetings/Menu.php
|
PHP
|
agpl-3.0
| 3,655
|
package ch.openech.test.ui.resources;
import java.io.IOException;
import org.junit.Ignore;
import org.junit.Test;
public class ResourcesAvailableTest {
@Test
@Ignore
public void testClasses() throws IOException {
// AnnotationDB db = new AnnotationDB();
//
// ClasspathUrlFinder finder = new ClasspathUrlFinder();
// for (URL url : finder.findClassPaths()) {
// System.out.println(url);
// db.scanArchives(url);
// }
// URL url = ResourceHelper.class.getClassLoader().getResource("../../OpenEchSwing/bin/");
// DirectoryIteratorFactory directoryIteratorFactory = new Dir
// db.scanArchives(url);
}
}
|
BrunoEberhard/open-ech
|
src/old/test/ui/resources/ResourcesAvailableTest.java
|
Java
|
agpl-3.0
| 621
|
/*
* Copyright 2013-2018 Emmanuel BRUN (contact@amapj.fr)
*
* This file is part of AmapJ.
*
* AmapJ 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.
* AmapJ 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 AmapJ. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package fr.amapj.service.services.listeproducteurreferent;
import java.util.List;
import fr.amapj.service.services.producteur.ProdUtilisateurDTO;
/**
* Informations sur les contrats d'un utilisateur
*
*/
public class DetailProducteurDTO
{
//
public String nom;
public String description;
//
public List<ProdUtilisateurDTO> referents;
//
public List<ProdUtilisateurDTO> utilisateurs;
}
|
amapj/amapj
|
amapj/src/fr/amapj/service/services/listeproducteurreferent/DetailProducteurDTO.java
|
Java
|
agpl-3.0
| 1,231
|
// Tradity.de Server
// Copyright (C) 2016 Tradity.de Tech Team <tech@tradity.de>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
"use strict";
/**
* Provides the {@link module:access~Access} object.
*
* @public
* @module access
*/
/**
* Represents the access levels in which server code gets executed.
*
* Access levels are identified by simple strings, but #242 is
* basically about throwing them all out and introducing new ones.
* After that, there should be a list of the new levels with
* associated documentation.
*
* @public
* @constructor module:access~Access
*/
class Access {
constructor() {
this.areas = [];
this.hasAnyAccess = false;
// above code is equiv to this.dropAll();
}
/**
* Returns a copy of this access object.
*
* @return {module:access~Access} An access object with identical access levels.
*
* @function module:access~Access#clone
*/
clone() {
const a = new Access();
a.areas = this.areas.slice();
a.hasAnyAccess = this.hasAnyAccess;
return a;
}
toString() { return this.toJSON(); }
/**
* Serializes the access levels associated with this access object
* into a JSON string that can be passed to {@link module:access~Access.fromJSON}.
*
* @return {string} A short machine-readable description of the access
* levels associated with this access object.
*
* @function module:access~Access#toJSON
*/
toJSON() {
if (this.hasAnyAccess) {
return '["*"]';
}
return JSON.stringify(this.areas);
}
/**
* Serializes the access levels associated with this access object
* into an array of access levels.
*
* @return {string[]} A list of the access levels associated with
* this access object, possibly including <code>"*"</code>.
*
* @function module:access~Access#toJSON
*/
toArray() {
if (this.hasAnyAccess) {
return ['*'];
}
return this.areas;
}
/**
* Checks for privileges to a certain access level.
*
* @param {string} area The access level identifier.
*
* @return {boolean} Indicates whether access is present.
*
* @function module:access~Access#has
*/
has(area) {
return this.hasAnyAccess || (this.areas.indexOf(area) !== -1);
}
/**
* Grants all access levels held by another access object.
*
* @param {module:access~Access} otherAccess Another access object.
*
* @function module:access~Access#update
*/
update(otherAccess) {
if (otherAccess.hasAnyAccess) {
this.grant('*');
}
for (let i = 0; i < otherAccess.areas.length; ++i) {
this.grant(otherAccess.areas[i]);
}
}
/**
* Grants access to a specified access level.
*
* @param {string} area The access level to grant access to, or
* <code>"*"</code> to indicate full access.
*
* @function module:access~Access#grant
*/
grant(area) {
area = area.trim();
if (!area) {
return;
}
if (area === '*') {
return this.grantAny();
}
if (this.areas.indexOf(area) === -1) {
this.areas.push(area);
}
}
/**
* Grants full access to all access levels.
*
* @function module:access~Access#grantAny
*/
grantAny() {
this.hasAnyAccess = true;
}
/**
* Removes access to a specified access level.
*
* @param {string} area The access level to remove access from, or
* <code>"*"</code> to indicate removing full access.
*
* @function module:access~Access#drop
*/
drop(area) {
area = area.trim();
if (!area) {
return;
}
if (area === '*') {
return this.dropAny();
}
let index;
while ((index = this.areas.indexOf(area)) !== -1) {
this.areas.splice(index, 1);
}
}
/**
* Drop full access, if previously held.
* Access levels that have been granted explicitly
* are not affected.
*
* @function module:access~Access#dropAny
*/
dropAny() {
this.hasAnyAccess = false;
}
/**
* Drop all access levels held by this objects,
* possibly including full access.
*
* @function module:access~Access#dropAall
*/
dropAll() {
this.dropAny();
this.areas = [];
}
}
/**
* Creates a new access object from a JSON specification.
* See also {@link module:access~Access#toJSON}.
*
* @param {string} j A string describing the access levels.
*
* @return {module:access~Access} An access object with the access levels
* speicified in <code>j</code>.
*
* @function module:access~Access.fromJSON
*/
Access.fromJSON = function(j) {
const a = new Access();
if (!j) {
return a;
}
if (j.trim() === '*') {
a.grant('*');
} else {
const p = JSON.parse(j);
// note that this can handle both an array and the "*" string!
for (let i = 0; i < p.length; ++i) {
a.grant(p[i]);
}
}
return a;
};
exports.Access = Access;
|
tradity/tradity-server
|
access.js
|
JavaScript
|
agpl-3.0
| 5,699
|
package org.chronos.common.builder;
import static com.google.common.base.Preconditions.*;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import org.apache.commons.configuration.BaseConfiguration;
import org.apache.commons.configuration.Configuration;
import org.chronos.common.exceptions.ChronosException;
import com.google.common.collect.Maps;
public class AbstractChronoBuilder<SELF extends ChronoBuilder<?>> implements ChronoBuilder<SELF> {
protected final Map<String, String> properties;
public AbstractChronoBuilder() {
this.properties = Maps.newHashMap();
}
@Override
@SuppressWarnings("unchecked")
public SELF withProperty(final String key, final String value) {
checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!");
checkNotNull(value, "Precondition violation - argument 'value' must not be NULL!");
this.properties.put(key, value);
return (SELF) this;
}
protected String getProperty(final String key) {
return this.properties.get(key);
}
protected Map<String, String> getProperties() {
return Collections.unmodifiableMap(Maps.newHashMap(this.properties));
}
protected Configuration getPropertiesAsConfiguration() {
Map<String, String> properties = this.getProperties();
Configuration config = new BaseConfiguration();
for (Entry<String, String> entry : properties.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
config.setProperty(key, value);
}
return config;
}
@Override
@SuppressWarnings("unchecked")
public SELF withPropertiesFile(final File file) {
checkNotNull(file, "Precondition violation - argument 'file' must not be NULL!");
checkArgument(file.isFile(), "Precondition violation - argument 'file' must be a file (not a directory)!");
checkArgument(file.exists(), "Precondition violation - argument 'file' must refer to an existing file!");
checkArgument(file.getName().endsWith(".properties"),
"Precondition violation - argument 'file' must specify a file name that ends with '.properties'!");
Properties properties = new Properties();
try {
FileReader reader = new FileReader(file);
properties.load(reader);
for (Entry<Object, Object> entry : properties.entrySet()) {
String key = String.valueOf(entry.getKey());
String value = String.valueOf(entry.getValue());
this.properties.put(key, value);
}
reader.close();
} catch (IOException ioe) {
throw new ChronosException("Failed to read properties file '" + file.getAbsolutePath() + "'!", ioe);
}
return (SELF) this;
}
@Override
public SELF withPropertiesFile(final String filePath) {
checkNotNull(filePath, "Precondition violation - argument 'filePath' must not be NULL!");
File propertiesFile = new File(filePath);
return this.withPropertiesFile(propertiesFile);
}
}
|
MartinHaeusler/chronos
|
org.chronos.common/src/main/java/org/chronos/common/builder/AbstractChronoBuilder.java
|
Java
|
agpl-3.0
| 2,952
|
/*
* Created on 18/set/2011
* Copyright 2011 by Andrea Vacondio (andrea.vacondio@gmail.com).
*
* This file is part of the Sejda source code
*
* 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.sejda.model.image;
import java.awt.image.BufferedImage;
import org.sejda.common.FriendlyNamed;
/**
* The color type for an image.
*
* @author Andrea Vacondio
*
*/
public enum ImageColorType implements FriendlyNamed {
BLACK_AND_WHITE("black_and_white", BufferedImage.TYPE_BYTE_BINARY),
GRAY_SCALE("gray_scale", BufferedImage.TYPE_BYTE_GRAY),
COLOR_RGB("color_rgb", BufferedImage.TYPE_INT_RGB);
private int bufferedImageType;
private String displayName;
private ImageColorType(String displayName, int bufferedImageType) {
this.displayName = displayName;
this.bufferedImageType = bufferedImageType;
}
@Override
public String getFriendlyName() {
return displayName;
}
/**
* @return the corresponding {@link BufferedImage} color type.
*/
public int getBufferedImageType() {
return bufferedImageType;
}
/**
* @param width
* @param height
* @return a {@link BufferedImage} for this color type with the given width and height.
*/
public BufferedImage createBufferedImage(int width, int height) {
return new BufferedImage(width, height, getBufferedImageType());
}
}
|
torakiki/sejda
|
sejda-model/src/main/java/org/sejda/model/image/ImageColorType.java
|
Java
|
agpl-3.0
| 2,037
|
import os
import subprocess
import shutil
karma = os.path.join(os.path.dirname(__file__), '../node_modules/.bin/karma')
def javascript_tests():
if not shutil.which('nodejs'):
print("W: nodejs not available, skipping javascript tests")
return 0
elif os.path.exists(karma):
chrome_exec = shutil.which('chromium') or shutil.which('chromium-browser')
if chrome_exec:
os.environ["CHROME_BIN"] = chrome_exec
else:
print("Please install a chromium browser package in order"
"to run javascript unit tests.")
return 2
return subprocess.call(
[karma, "start", "test/karma.conf.js", "--single-run"]
)
else:
print("I: skipping javascript test (karma not available)")
return 0
if __name__ == "__main__":
import sys
sys.exit(javascript_tests())
|
Linaro/squad
|
test/javascript.py
|
Python
|
agpl-3.0
| 895
|
# coding: utf-8
# Copyright (C) 2017 Jaime Bemarás
# See LICENSE.txt
from IPy import IP
import re
ASN = re.compile(r'AS\d+', re.IGNORECASE)
def validate(resources):
outcome = True
for resource in resources:
if ASN.match(resource):
continue
else:
try:
IP(resource)
except ValueError as error:
outcome = False
print('\t~ ERROR:', error.args[0])
return outcome
|
synte/ec-ripe-api
|
resource_validator/validator.py
|
Python
|
agpl-3.0
| 479
|
/**
* Module dependencies.
*/
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
/**
* Support request Schema
*
* This collection serves as a backup for sent support requests
*/
const SupportRequestSchema = new Schema({
user: {
type: Schema.ObjectId,
ref: 'User',
},
sent: {
type: Date,
default: Date.now,
},
email: {
type: String,
trim: true,
lowercase: true,
},
username: {
type: String,
},
message: {
type: String,
required: true,
},
userAgent: {
type: String,
},
reportMember: {
type: String,
},
});
mongoose.model('SupportRequest', SupportRequestSchema);
|
Trustroots/trustroots
|
modules/support/server/models/support.server.model.js
|
JavaScript
|
agpl-3.0
| 663
|
package org.cmdbuild.data.store.email;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.cmdbuild.data.store.Storable;
public class EmailAccount implements Storable {
public static class Builder implements org.cmdbuild.common.Builder<EmailAccount> {
private Long id;
private String name;
private boolean isDefault;
private String username;
private String password;
private String address;
private String smtpServer;
private Integer smtpPort;
private boolean smtpSsl;
private String imapServer;
private Integer imapPort;
private boolean imapSsl;
private String inputFolder;
private String processedFolder;
private String rejectedFolder;
private boolean rejectNotMatching;
private Builder() {
// use static method
}
@Override
public EmailAccount build() {
validate();
return new EmailAccount(this);
}
private void validate() {
Validate.isTrue(isNotBlank(name), "invalid name");
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
public Builder withId(final Long id) {
this.id = id;
return this;
}
public Builder withName(final String name) {
this.name = name;
return this;
}
public Builder withDefaultStatus(final boolean isDefault) {
this.isDefault = isDefault;
return this;
}
public Builder withUsername(final String username) {
this.username = username;
return this;
}
public Builder withPassword(final String password) {
this.password = password;
return this;
}
public Builder withAddress(final String address) {
this.address = address;
return this;
}
public Builder withSmtpServer(final String smtpServer) {
this.smtpServer = smtpServer;
return this;
}
public Builder withSmtpPort(final Integer smtpPort) {
this.smtpPort = smtpPort;
return this;
}
public Builder withSmtpSsl(final boolean smtpSsl) {
this.smtpSsl = smtpSsl;
return this;
}
public Builder withImapServer(final String imapServer) {
this.imapServer = imapServer;
return this;
}
public Builder withImapPort(final Integer imapPort) {
this.imapPort = imapPort;
return this;
}
public Builder withImapSsl(final boolean imapSsl) {
this.imapSsl = imapSsl;
return this;
}
public Builder withInputFolder(final String inputFolder) {
this.inputFolder = inputFolder;
return this;
}
public Builder withProcessedFolder(final String processedFolder) {
this.processedFolder = processedFolder;
return this;
}
public Builder withRejectedFolder(final String rejectedFolder) {
this.rejectedFolder = rejectedFolder;
return this;
}
public Builder withRejectNotMatchingStatus(final boolean rejectNotMatching) {
this.rejectNotMatching = rejectNotMatching;
return this;
}
}
public static Builder newInstance() {
return new Builder();
}
private final Long id;
private final String name;
private final boolean isDefault;
private final String username;
private final String password;
private final String address;
private final String smtpServer;
private final Integer smtpPort;
private final boolean smtpSsl;
private final String imapServer;
private final Integer imapPort;
private final boolean imapSsl;
private final String inputFolder;
private final String processedFolder;
private final String rejectedFolder;
private final boolean rejectNotMatching;
private EmailAccount(final Builder builder) {
this.id = builder.id;
this.name = builder.name;
this.isDefault = builder.isDefault;
this.username = builder.username;
this.password = builder.password;
this.address = builder.address;
this.smtpServer = builder.smtpServer;
this.smtpPort = builder.smtpPort;
this.smtpSsl = builder.smtpSsl;
this.imapServer = builder.imapServer;
this.imapPort = builder.imapPort;
this.imapSsl = builder.imapSsl;
this.inputFolder = builder.inputFolder;
this.processedFolder = builder.processedFolder;
this.rejectedFolder = builder.rejectedFolder;
this.rejectNotMatching = builder.rejectNotMatching;
}
@Override
public String getIdentifier() {
return name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public boolean isDefault() {
return isDefault;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getAddress() {
return address;
}
public String getSmtpServer() {
return smtpServer;
}
public Integer getSmtpPort() {
return smtpPort;
}
public boolean isSmtpSsl() {
return smtpSsl;
}
public String getImapServer() {
return imapServer;
}
public Integer getImapPort() {
return imapPort;
}
public boolean isImapSsl() {
return imapSsl;
}
public String getInputFolder() {
return inputFolder;
}
public String getProcessedFolder() {
return processedFolder;
}
public String getRejectedFolder() {
return rejectedFolder;
}
public boolean isRejectNotMatching() {
return rejectNotMatching;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
}
|
jzinedine/CMDBuild
|
core/src/main/java/org/cmdbuild/data/store/email/EmailAccount.java
|
Java
|
agpl-3.0
| 5,373
|
<?php
/**
* zCorrecteurs.fr est le logiciel qui fait fonctionner www.zcorrecteurs.fr
*
* Copyright (C) 2012-2018 Corrigraphie
*
* 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/>.
*/
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Zco\Bundle\DicteesBundle\Domain\Dictation;
use Zco\Bundle\DicteesBundle\Domain\DictationDAO;
/**
* Lecture d'une dictée.
*
* @author mwsaz <mwsaz@zcorrecteurs.fr>
*/
class DicteeAction extends Controller
{
public function execute()
{
$Dictee = $_GET['id'] ? DictationDAO::Dictee($_GET['id']) : null;
if(!$Dictee)
throw new NotFoundHttpException();
zCorrecteurs::VerifierFormatageUrl($Dictee->titre, true);
$Tags = DictationDAO::DicteeTags($Dictee);
Page::$titre = htmlspecialchars($Dictee->titre);
fil_ariane(Page::$titre);
$this->get('zco_core.resource_manager')->requireResources(array(
'@ZcoCoreBundle/Resources/public/css/zcode.css',
'@ZcoDicteesBundle/Resources/public/css/dictees.css',
));
return render_to_response('ZcoDicteesBundle::dictee.html.php', [
'Dictee' => $Dictee,
'Tags' => $Tags,
'DicteeDifficultes' => Dictation::LEVELS,
'DicteeEtats' => Dictation::STATUSES,
]);
}
}
|
zcorrecteurs/zcorrecteurs.fr
|
src/Zco/Bundle/DicteesBundle/Controller/DicteeAction.class.php
|
PHP
|
agpl-3.0
| 1,921
|
<?php
namespace Civix\ApiBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files.
*
* To learn more see
* {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('civix_api');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
|
austinpapp/powerline-server
|
backend/src/Civix/ApiBundle/DependencyInjection/Configuration.php
|
PHP
|
agpl-3.0
| 876
|
"""
Studio editing view for OpenAssessment XBlock.
"""
import copy
import logging
from uuid import uuid4
from django.template.loader import get_template
from django.utils.translation import ugettext_lazy
from voluptuous import MultipleInvalid
from xblock.fields import List, Scope
from xblock.core import XBlock
from web_fragments.fragment import Fragment
from openassessment.xblock.data_conversion import (
create_rubric_dict,
make_django_template_key,
update_assessments_format
)
from openassessment.xblock.defaults import DEFAULT_EDITOR_ASSESSMENTS_ORDER, DEFAULT_RUBRIC_FEEDBACK_TEXT
from openassessment.xblock.resolve_dates import resolve_dates, parse_date_value, DateValidationError, InvalidDateFormat
from openassessment.xblock.schema import EDITOR_UPDATE_SCHEMA
from openassessment.xblock.validation import validator
from openassessment.xblock.editor_config import AVAILABLE_EDITORS
from openassessment.xblock.load_static import LoadStatic
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
class StudioMixin:
"""
Studio editing view for OpenAssessment XBlock.
"""
DEFAULT_CRITERIA = [
{
'label': '',
'options': [
{
'label': ''
},
]
}
]
NECESSITY_OPTIONS = {
"required": ugettext_lazy("Required"),
"optional": ugettext_lazy("Optional"),
"": ugettext_lazy("None")
}
# Build editor options from AVAILABLE_EDITORS
AVAILABLE_EDITOR_OPTIONS = {
key: val.get('display_name', key) for key, val in AVAILABLE_EDITORS.items()
}
STUDIO_EDITING_TEMPLATE = 'openassessmentblock/edit/oa_edit.html'
BASE_EDITOR_ASSESSMENTS_ORDER = copy.deepcopy(DEFAULT_EDITOR_ASSESSMENTS_ORDER)
# Since the XBlock problem definition contains only assessment
# modules that are enabled, we need to keep track of the order
# that the user left assessments in the editor, including
# the ones that were disabled. This allows us to keep the order
# that the user specified.
editor_assessments_order = List(
default=DEFAULT_EDITOR_ASSESSMENTS_ORDER,
scope=Scope.content,
help="The order to display assessments in the editor."
)
def studio_view(self, context=None): # pylint: disable=unused-argument
"""
Render the OpenAssessment XBlock for editing in Studio.
Args:
context: Not actively used for this view.
Returns:
(Fragment): An HTML fragment for editing the configuration of this XBlock.
"""
rendered_template = get_template(
self.STUDIO_EDITING_TEMPLATE
).render(self.editor_context())
fragment = Fragment(rendered_template)
fragment.add_javascript_url(LoadStatic.get_url('openassessment-studio.js'))
js_context_dict = {
"ALLOWED_IMAGE_EXTENSIONS": self.ALLOWED_IMAGE_EXTENSIONS,
"ALLOWED_FILE_EXTENSIONS": self.ALLOWED_FILE_EXTENSIONS,
"FILE_EXT_BLACK_LIST": self.FILE_EXT_BLACK_LIST,
}
fragment.initialize_js('OpenAssessmentEditor', js_context_dict)
return fragment
def editor_context(self):
"""
Update the XBlock's XML.
Returns:
dict with keys
'rubric' (unicode), 'prompt' (unicode), 'title' (unicode),
'submission_start' (unicode), 'submission_due' (unicode),
'assessments (dict)
"""
# In the authoring GUI, date and time fields should never be null.
# Therefore, we need to resolve all "default" dates to datetime objects
# before displaying them in the editor.
try:
__, __, date_ranges = resolve_dates( # pylint: disable=redeclared-assigned-name
self.start, self.due,
[
(self.submission_start, self.submission_due)
] + [
(asmnt.get('start'), asmnt.get('due'))
for asmnt in self.valid_assessments
],
self._
)
except (DateValidationError, InvalidDateFormat):
# If the dates are somehow invalid, we still want users to be able to edit the ORA,
# so just present the dates as they are.
def _parse_date_safe(date):
try:
return parse_date_value(date, self._)
except InvalidDateFormat:
return ''
date_ranges = [
(_parse_date_safe(self.submission_start), _parse_date_safe(self.submission_due))
] + [
(_parse_date_safe(asmnt.get('start')), _parse_date_safe(asmnt.get('due')))
for asmnt in self.valid_assessments
]
submission_start, submission_due = date_ranges[0]
assessments = self._assessments_editor_context(date_ranges[1:])
self.editor_assessments_order = self._editor_assessments_order_context()
# Every rubric requires one criterion. If there is no criteria
# configured for the XBlock, return one empty default criterion, with
# an empty default option.
criteria = copy.deepcopy(self.rubric_criteria_with_labels)
if not criteria:
criteria = self.DEFAULT_CRITERIA
# To maintain backwards compatibility, if there is no
# feedback_default_text configured for the xblock, use the default text
feedback_default_text = copy.deepcopy(self.rubric_feedback_default_text)
if not feedback_default_text:
feedback_default_text = DEFAULT_RUBRIC_FEEDBACK_TEXT
course_id = self.location.course_key if hasattr(self, 'location') else None
# If allowed file types haven't been explicitly set, load from a preset
white_listed_file_types = self.get_allowed_file_types_or_preset()
white_listed_file_types_string = ','.join(white_listed_file_types) if white_listed_file_types else ''
# If rubric reuse is enabled, include information about the other ORAs in this course
rubric_reuse_data = {}
if self.is_rubric_reuse_enabled:
rubric_reuse_data = self.get_other_ora_blocks_for_rubric_editor_context()
return {
'prompts': self.prompts,
'prompts_type': self.prompts_type,
'title': self.title,
'submission_due': submission_due,
'submission_start': submission_start,
'assessments': assessments,
'criteria': criteria,
'feedbackprompt': self.rubric_feedback_prompt,
'feedback_default_text': feedback_default_text,
'text_response': self.text_response if self.text_response else '',
'text_response_editor': self.text_response_editor if self.text_response_editor else 'text',
'file_upload_response': self.file_upload_response if self.file_upload_response else '',
'necessity_options': self.NECESSITY_OPTIONS,
'available_editor_options': self.AVAILABLE_EDITOR_OPTIONS,
'file_upload_type': self.file_upload_type,
'allow_multiple_files': self.allow_multiple_files,
'white_listed_file_types': white_listed_file_types_string,
'allow_latex': self.allow_latex,
'leaderboard_show': self.leaderboard_show,
'editor_assessments_order': [
make_django_template_key(asmnt)
for asmnt in self.editor_assessments_order
],
'teams_feature_enabled': self.team_submissions_enabled,
'teams_enabled': self.teams_enabled,
'base_asset_url': self._get_base_url_path_for_course_assets(course_id),
'is_released': self.is_released(),
'teamsets': self.get_teamsets(course_id),
'selected_teamset_id': self.selected_teamset_id,
'show_rubric_during_response': self.show_rubric_during_response,
'rubric_reuse_enabled': self.is_rubric_reuse_enabled,
'rubric_reuse_data': rubric_reuse_data,
'block_location': str(self.location),
}
@XBlock.json_handler
def update_editor_context(self, data, suffix=''): # pylint: disable=unused-argument
"""
Update the XBlock's configuration.
Args:
data (dict): Data from the request; should have the format described
in the editor schema.
Keyword Arguments:
suffix (str): Not used
Returns:
dict with keys 'success' (bool) and 'msg' (str)
"""
# Validate and sanitize the data using a schema
# If the data is invalid, this means something is wrong with
# our JavaScript, so we log an exception.
try:
data = EDITOR_UPDATE_SCHEMA(data)
except MultipleInvalid:
logger.exception('Editor context is invalid')
return {'success': False, 'msg': self._('Error updating XBlock configuration')}
# Check that the editor assessment order contains all the assessments.
current_order = set(data['editor_assessments_order'])
if set(DEFAULT_EDITOR_ASSESSMENTS_ORDER) != current_order:
# Backwards compatibility: "staff-assessment" may not be present.
# If that is the only problem with this data, just add it manually and continue.
if set(DEFAULT_EDITOR_ASSESSMENTS_ORDER) == current_order | {'staff-assessment'}:
data['editor_assessments_order'].append('staff-assessment')
logger.info('Backwards compatibility: editor_assessments_order now contains staff-assessment')
else:
logger.exception('editor_assessments_order does not contain all expected assessment types')
return {'success': False, 'msg': self._('Error updating XBlock configuration')}
if not data['text_response'] and not data['file_upload_response']:
return {
'success': False,
'msg': self._("Error: Text Response and File Upload Response cannot both be disabled")
}
if not data['text_response'] and data['file_upload_response'] == 'optional':
return {'success': False,
'msg': self._("Error: When Text Response is disabled, File Upload Response must be Required")}
if not data['file_upload_response'] and data['text_response'] == 'optional':
return {'success': False,
'msg': self._("Error: When File Upload Response is disabled, Text Response must be Required")}
# Backwards compatibility: We used to treat "name" as both a user-facing label
# and a unique identifier for criteria and options.
# Now we treat "name" as a unique identifier, and we've added an additional "label"
# field that we display to the user.
# If the JavaScript editor sends us a criterion or option without a "name"
# field, we should assign it a unique identifier.
for criterion in data['criteria']:
if 'name' not in criterion:
criterion['name'] = uuid4().hex
for option in criterion['options']:
if 'name' not in option:
option['name'] = uuid4().hex
xblock_validator = validator(self, self._)
success, msg = xblock_validator(
create_rubric_dict(data['prompts'], data['criteria']),
data['assessments'],
submission_start=data['submission_start'],
submission_due=data['submission_due'],
leaderboard_show=data['leaderboard_show']
)
if not success:
return {'success': False, 'msg': self._('Validation error: {error}').format(error=msg)}
# At this point, all the input data has been validated,
# so we can safely modify the XBlock fields.
self.title = data['title']
self.display_name = data['title']
self.prompts = data['prompts']
self.prompts_type = data['prompts_type']
self.rubric_criteria = data['criteria']
self.rubric_assessments = data['assessments']
self.editor_assessments_order = data['editor_assessments_order']
self.rubric_feedback_prompt = data['feedback_prompt']
self.rubric_feedback_default_text = data['feedback_default_text']
self.submission_start = data['submission_start']
self.submission_due = data['submission_due']
self.text_response = data['text_response']
self.text_response_editor = data['text_response_editor']
self.file_upload_response = data['file_upload_response']
if data['file_upload_response']:
self.file_upload_type = data['file_upload_type']
self.white_listed_file_types_string = data['white_listed_file_types']
else:
self.file_upload_type = None
self.white_listed_file_types_string = None
self.allow_multiple_files = bool(data['allow_multiple_files'])
self.allow_latex = bool(data['allow_latex'])
self.leaderboard_show = data['leaderboard_show']
self.teams_enabled = bool(data.get('teams_enabled', False))
self.selected_teamset_id = data.get('selected_teamset_id', '')
self.show_rubric_during_response = data.get('show_rubric_during_response', False)
return {'success': True, 'msg': self._('Successfully updated OpenAssessment XBlock')}
@XBlock.json_handler
def check_released(self, data, suffix=''): # pylint: disable=unused-argument
"""
Check whether the problem has been released.
Args:
data (dict): Not used
Keyword Arguments:
suffix (str): Not used
Returns:
dict with keys 'success' (bool), 'message' (unicode), and 'is_released' (bool)
"""
# There aren't currently any server-side error conditions we report to the client,
# but we send success/msg values anyway for consistency with other handlers.
return {
'success': True, 'msg': '',
'is_released': self.is_released()
}
def _assessments_editor_context(self, assessment_dates):
"""
Transform the rubric assessments list into the context
we will pass to the Django template.
Args:
assessment_dates: List of assessment date ranges (tuples of start/end datetimes).
Returns:
dict
"""
assessments = {}
for asmnt, date_range in zip(self.rubric_assessments, assessment_dates):
# Django Templates cannot handle dict keys with dashes, so we'll convert
# the dashes to underscores.
template_name = make_django_template_key(asmnt['name'])
assessments[template_name] = copy.deepcopy(asmnt)
assessments[template_name]['start'] = date_range[0]
assessments[template_name]['due'] = date_range[1]
# In addition to the data in the student training assessment, we need to include two additional
# pieces of information: a blank context to render the empty template with, and the criteria
# for each example (so we don't have any complicated logic within the template). Though this
# could be accomplished within the template, we are opting to remove logic from the template.
student_training_module = self.get_assessment_module('student-training')
student_training_template = {
'answer': {
'parts': [
{'text': ''} for _ in self.prompts
]
}
}
criteria_list = copy.deepcopy(self.rubric_criteria_with_labels)
for criterion in criteria_list:
criterion['option_selected'] = ""
student_training_template['criteria'] = criteria_list
if student_training_module:
student_training_module = update_assessments_format([student_training_module])[0]
example_list = []
# Adds each example to a modified version of the student training module dictionary.
for example in student_training_module['examples']:
criteria_list = copy.deepcopy(self.rubric_criteria_with_labels)
# Equivalent to a Join Query, this adds the selected option to the Criterion's dictionary, so that
# it can be easily referenced in the template without searching through the selected options.
for criterion in criteria_list:
for option_selected in example['options_selected']:
if option_selected['criterion'] == criterion['name']:
criterion['option_selected'] = option_selected['option']
example_list.append({
'answer': example['answer'],
'criteria': criteria_list,
})
assessments['training'] = {'examples': example_list, 'template': student_training_template}
# If we don't have student training enabled, we still need to render a single (empty, or default) example
else:
assessments['training'] = {'examples': [student_training_template], 'template': student_training_template}
return assessments
def _editor_assessments_order_context(self):
"""
Create a list of assessment names in the order
the user last set in the editor, including
assessments that are not currently enabled.
Returns:
list of assessment names
"""
# Start with the default order, to pick up any assessment types that have been added
# since the user last saved their ordering.
effective_order = copy.deepcopy(self.BASE_EDITOR_ASSESSMENTS_ORDER)
# Account for changes the user has made to the default order
user_order = copy.deepcopy(self.editor_assessments_order)
effective_order = self._subset_in_relative_order(effective_order, user_order)
# Account for inconsistencies between the user's order and the problems
# that are currently enabled in the problem (These cannot be changed)
enabled_assessments = [asmnt['name'] for asmnt in self.valid_assessments]
enabled_ordered_assessments = [
assessment for assessment in enabled_assessments if assessment in user_order
]
effective_order = self._subset_in_relative_order(effective_order, enabled_ordered_assessments)
return effective_order
def _subset_in_relative_order(self, superset, subset):
"""
Returns a copy of superset, with entries that appear in subset being reordered to match
their relative ordering in subset.
"""
superset_indices = [superset.index(item) for item in subset]
sorted_superset_indices = sorted(superset_indices)
if superset_indices != sorted_superset_indices:
for index, superset_index in enumerate(sorted_superset_indices):
superset[superset_index] = subset[index]
return superset
def _get_base_url_path_for_course_assets(self, course_key):
"""
Returns base url path for course assets
"""
if course_key is None:
return None
placeholder_id = uuid4().hex
# create a dummy asset location with a fake but unique name. strip off the name, and return it
url_path = str(course_key.make_asset_key('asset', placeholder_id).for_branch(None))
if not url_path.startswith('/'):
url_path = '/' + url_path
return url_path.replace(placeholder_id, '')
def get_team_configuration(self, course_id):
"""
Returns a dict with team configuration settings.
"""
configuration_service = self.runtime.service(self, 'teams_configuration')
team_configuration = configuration_service.get_teams_configuration(course_id)
if not team_configuration:
return None
return team_configuration
def get_teamsets(self, course_id):
"""
Wrapper around get_team_configuration that returns team names only for display
"""
team_configuration = self.get_team_configuration(course_id)
if not team_configuration:
return None
return team_configuration.teamsets
|
edx/edx-ora2
|
openassessment/xblock/studio_mixin.py
|
Python
|
agpl-3.0
| 20,504
|
# Copyright 2018 Silvio Gregorini (silviogregorini@openforce.it)
# Copyright (c) 2018 Openforce Srls Unipersonale (www.openforce.it)
# Copyright (c) 2019 Matteo Bilotta
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
def group_by_account_and_tax(self):
grouped_lines = {}
for line in self:
group_key = (line.account_id, line.tax_line_id)
if group_key not in grouped_lines:
grouped_lines.update({group_key: []})
grouped_lines[group_key].append(line)
return grouped_lines
|
OCA/l10n-italy
|
l10n_it_vat_statement_split_payment/models/account.py
|
Python
|
agpl-3.0
| 670
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HearthAnalyzer.Core.Cards.Spells
{
/// <summary>
/// Implements the Shield Block spell
///
/// Gain 5 Armor. Draw a card.
/// </summary>
/// <remarks>
/// TODO: NOT YET COMPLETELY IMPLEMENTED
/// </remarks>
public class ShieldBlock : BaseSpell
{
private const int MANA_COST = 3;
private const int MIN_SPELL_POWER = 0;
private const int MAX_SPELL_POWER = 0;
public ShieldBlock(int id = -1)
{
this.Id = id;
this.Name = "Shield Block";
this.OriginalManaCost = MANA_COST;
this.CurrentManaCost = MANA_COST;
}
public override void Activate(IDamageableEntity target = null, CardEffect cardEffect = CardEffect.NONE)
{
throw new NotImplementedException();
}
}
}
|
kwluo90/HearthAnalyzer
|
HearthAnalyzer.Core/Cards/Spells/ShieldBlock.cs
|
C#
|
agpl-3.0
| 961
|
package ru.hflabs.rcd.connector.files.dataset;
import com.google.common.collect.Lists;
import org.dbunit.dataset.Column;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITableMetaData;
import org.dbunit.dataset.stream.DataSetProducerAdapter;
import org.dbunit.dataset.stream.IDataSetConsumer;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* Класс <class>FilesConsumer</class> реализует формирование файлов на основе {@link org.dbunit.dataset.IDataSet таблиц}
*
* @param <W> сервис записи
* @author Nazin Alexander
*/
public abstract class FilesConsumer<W> implements IDataSetConsumer {
/** Целевая директория */
protected final File targetDirectory;
/** Текущий сервис записи */
protected String[] currentHeaders;
/** Текущий сервис записи */
protected W currentWriter;
/** Текущий файл */
protected File currentFile;
/** Коллекция целевых файлов */
protected final List<File> files;
/** Расширение файлов */
private final String extension;
public FilesConsumer(File targetDirectory, String extension) {
this.targetDirectory = targetDirectory;
this.extension = extension;
this.currentFile = null;
this.files = Lists.newArrayList();
}
public List<File> getFiles() {
return files;
}
/**
* Создает и возвращает текущий сервис записи
*
* @return Возвращает созданный сервис записи
*/
protected abstract W createWriter() throws IOException;
/**
* Выполняет закрытие сервиса записи
*
* @param writer текущий сервис записи
*/
protected abstract void closeWriter(W writer);
/**
* Выполняет запись колонок
*/
protected abstract void writeHeader() throws IOException;
@Override
public void startTable(ITableMetaData metaData) throws DataSetException {
// Формируем целевой файл
currentFile = new File(targetDirectory, String.format("%s.%s", metaData.getTableName(), extension));
try {
// Формируем сервис записи файла
currentWriter = createWriter();
// Формируем название колонок
Column[] columns = metaData.getColumns();
currentHeaders = new String[columns.length];
for (int i = 0; i < currentHeaders.length; i++) {
currentHeaders[i] = columns[i].getColumnName();
}
// Записываем название колонок
writeHeader();
} catch (IOException ex) {
throw new DataSetException(ex);
}
}
@Override
public void endTable() throws DataSetException {
currentHeaders = null;
closeWriter(currentWriter);
currentWriter = null;
files.add(currentFile);
currentFile = null;
}
@Override
public void startDataSet() throws DataSetException {
if (targetDirectory.exists()) {
if (targetDirectory.isFile()) {
throw new DataSetException(String.format("Can't store data set to existed file '%s'", targetDirectory.getPath()));
}
} else if (!targetDirectory.mkdirs()) {
throw new DataSetException("Can't create destination directory '" + targetDirectory.getPath() + "'");
}
}
@Override
public void endDataSet() throws DataSetException {
// do nothing
}
public List<File> write(IDataSet dataSet) throws DataSetException {
DataSetProducerAdapter provider = new DataSetProducerAdapter(dataSet);
provider.setConsumer(this);
provider.produce();
return files;
}
}
|
hflabs/perecoder
|
rcd-connector/files/src/main/java/ru/hflabs/rcd/connector/files/dataset/FilesConsumer.java
|
Java
|
agpl-3.0
| 4,085
|
<?php
require_once 'system.php';
require_once 'libs/cache_kit.php';
require_once 'libs/url.php';
require_once 'libs/helpers.php';
//require_once 'libs/rober.php';
require_once 'libs/'.$configuracion['conector'];
require_once 'libs/text.php';
require_once 'libs/functions.php';
require_once 'libs/dbconnect.php';
require_once 'libs/usuarios.php';
require_once 'libs/movil.php';
//require_once 'libs/movil.php';
$nombre = (int)$_GET['parada'];
$fecha = date('Y-m-d H:i:s');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" dir="ltr" lang="es">
<head>
<title><?=html_title("Reportar un error")?></title>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Last-Modified" content="0" />
<meta http-equiv="Cache-Control" content="no-cache, mustrevalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta name="Robots" content="noarchive" />
<meta name="rating" content="general" />
<meta name="description" content="Tubus facilita el acceso a toda la información relativa al sistema de transporte urbano granadino. Gracias a TuBus es muy sencillo conocer el tiempo estimado de llegada de cada autobús en cada parada, desde cualquier lugar y en cualquier momento." />
<meta name="keywords" content="bus urbano, rober, granada, tubus, autobus, urbano, granadino, tiempo real, paradas, linea 4, línea 3, estación de autobuses, metro ligero, ave, estación de trenes, fuente las batallas, marquesinas, paneles" />
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;"/>
<meta name="generator" content="Huruk Soluciones" />
<link rel="stylesheet" type="text/css" media="screen" href="<?=$configuracion['home_url']?>/style/style_<?=$configuracion['version']?>.css" />
<link rel="stylesheet" type="text/css" media="handheld" href="<?=$configuracion['home_url']?>/style/style_<?=$configuracion['version']?>.css" />
<!--[if IEMobile 7]>
<link rel="stylesheet" type="text/css" media="screen" href="<?=$configuracion['home_url']?>/style/wp7_style_<?=$configuracion['version']?>.css" />
<![endif]-->
<link rel="search" type="application/opensearchdescription+xml" title="Buscar en Tubus" href="<?=$configuracion['home_url']?>/opensearch.xml"/>
<link rel="apple-touch-icon" href="<?=$configuracion['home_url']?>/style/images/apple-touch-icon.png"/>
<link rel="shortcut icon" href="<?=$configuracion['home_url']?>/tubus_fav.png" type="image/png"/>
<script src="https://www.google.com/jsapi?key=ABQIAAAA4NrpBT8LijNsshLTHNpmLxR4mkvciC68xVMfDJ-G4kipE2SDyRSXqWnexajRtZVBdCCsD1K3Ntye6Q" type="text/javascript"></script>
<script language="Javascript" type="text/javascript">
//<![CDATA[
google.load("jquery", "1.4.2");
//]]>
</script>
<!-- <script src="<?=$configuracion['home_url']?>/js/jquery-1.4.2.min.js" type="text/javascript"></script> -->
<script src="<?=$configuracion['home_url']?>/js/menuhor.js"></script>
<script type="text/javascript">
jQuery(window).ready(function(){
toggle_menu();
});
</script>
</head>
<body>
<div id="contenedor">
<?php require_once 'header.php'; ?>
<div id="cuerpo">
<?php include_once 'menu-horizontal.php'; ?>
<div id="sub-cont">
<?php
if(isset($_POST['enviar'])){
$nombre = (int)$_POST['parada'];
$errortype = $_POST['errortype'];
$comentarios = $_POST['comentarios'];
$htmlform = '';
if(strlen($_POST['comentarios'])>5){
$sql = "Select * from paradas Where nombre = '".$nombre."'";
$res = mysql_query($sql);
$ip = get_real_ip();
$aviso="";
$logged_u = is_logged();
if($logged_u['logged'])
$user = $logged_u['id_usuario'];
else $user = get_userid();
switch($errortype){
case 'geo';
$tipo = "Error en la geolocalización de la parada";
break;
case 'lineas';
$tipo = "Error en las lineas de la parada";
break;
case 'nombre';
$tipo = "Error en el nombre de la parada";
break;
case 'otros';
$tipo = "Error en la parada";
break;
}
$sql_insert = "Insert into reportes (nombre, date_added, ip, userid, tipo, comentarios) values ('".$nombre."','".$fecha."','".$ip."','".$user."','".$errortype."','".$comentarios."')";
if(mysql_query($sql_insert)){
//no ha habido problema en la inserción del reporte en BD
//Mando mail y muestro mensaje de confirmación.
$ciudad = '';
$subdominio = '';
if(isset($_COOKIE['userciudad'])){
switch($_COOKIE['userciudad']){
case 'gr':
$ciudad = 'Granada';
$subdominio = 'gr.';
break;
case 'v':
$ciudad = 'Valencia';
$subdominio = 'v.';
break;
case 'z':
$ciudad = 'Zaragoza';
$subdominio = 'z.';
break;
case 'b':
$ciudad = 'Barcelona';
$subdominio = 'b.';
break;
case 'ma':
$ciudad = 'Malaga';
$subdominio = 'ma.';
break;
case 'do':
$ciudad = 'Donostia';
$subdominio = 'do.';
break;
}
}
$aviso = 'Se ha enviado el error al equipo técnico de Tubus. En breve será analizado y corregido';
$mensaje = '';
mail('info@huruk.net', $tipo.' '.$nombre.' '.$ciudad, 'Se ha reportado un error en la parada '.$nombre.' de '.$ciudad.' por el usuario '.$user. ' con ip '.$ip.' Puedes verla en http://'.$subdominio.'tubus.es/'.$nombre."\n\n\nError: ".$comentarios);
}
else $aviso = 'Error. No se ha podido enviar el reporte'; //se ha producido un error al insertar en base de datos;
}
else{
$aviso = 'Error. Debes especificar el fallo'; //se ha producido un error al insertar en base de datos;
$htmlform='
<form name="errorForm" id="register" action="report_error.php" method="POST">
<p><input type="hidden" name="parada" value="'.$nombre.'" /></p>
<p>
<label for="errortype"><span>Problema detectado *</span></label>
<select id="errortype" name="errortype">
<option value="geo" '.($errortype == "geo"? ' selected="selected"':'').'>Error en la geolocalización de la parada</option>
<option value="lineas" '.($errortype == "lineas"? ' selected="selected"':'').'>Error en las lineas de la parada</option>
<option value="nombre" '.($errortype == "nombre"? ' selected="selected"':'').'>Error en el nombre de la parada</option>
<option value="otros" '.($errortype == "otros"? ' selected="selected"':'').'>Otro error...</option>
</select>
</p>
<p>
<label for="comentarios"><span>Más detalles *</span></label>
<textarea id="comentarios" name="comentarios" cols="35"></textarea>
</p>
<div style="position:relative;margin:15px 0;">
<input type="submit" name="enviar" value="ENVIAR ERROR" />
<span class="btn-der"></span>
<span class="btn-izq"></span>
</div>
</form>';
}
?>
<h1><span>Error en parada: <?=$nombre?></span></h1>
<span class="liine"></span>
<p> </p>
<p><?=$aviso?></p>
<?= $htmlform ?>
<p class="info_general returner">Volver a la parada <a href="<?=$configuracion['home_url']?>/<?=$nombre?>" title="Volver a la parada <?=$nombre?>"><?=$nombre?></a></p>
<?php
}
else{
?>
<h1><span>Error en parada: <?=$nombre?></span></h1>
<span class="liine"></span>
<form name="errorForm" id="register" action="report_error.php" method="POST">
<p><input type="hidden" name="parada" value="<?=$nombre?>" /></p>
<p>
<label for="errortype"><span>Problema detectado *</span></label>
<select id="errortype" name="errortype">
<option value="geo">Error en la geolocalización de la parada</option>
<option value="lineas">Error en las lineas de la parada</option>
<option value="nombre">Error en el nombre de la parada</option>
<option value="otros">Otro error...</option>
</select>
</p>
<p>
<label for="comentarios"><span>Más detalles *</span></label>
<textarea id="comentarios" name="comentarios" cols="35"></textarea>
</p>
<div style="position:relative;margin:15px 0;">
<input type="submit" name="enviar" value="ENVIAR ERROR" />
<span class="btn-der"></span>
<span class="btn-izq"></span>
</div>
</form>
<p class="info_general returner">Volver a la parada <a href="<?=$configuracion['home_url']?>/<?=$nombre?>" title="Volver a la parada <?=$nombre?>"><?=$nombre?></a></p>
<?php
}
?>
</div>
</div>
<!-- Por aqui meto mano -->
<?php include 'caja-busqueda.php' ?>
<?php include 'footer.php';?>
|
miguelpedregosa/Tubus
|
report_error.php
|
PHP
|
agpl-3.0
| 8,636
|
# Amara, universalsubtitles.org
#
# Copyright (C) 2013 Participatory Culture Foundation
#
# 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/agpl-3.0.html.
from django.conf.urls.defaults import *
from videos.views import rpc_router
urlpatterns = patterns(
'videos.views',
url(r'^watch/$', 'watch_page', name='watch_page'),
url(r'^watch/featured/$', 'featured_videos', name='featured_videos'),
url(r'^watch/latest/$', 'latest_videos', name='latest_videos'),
url(r'^watch/popular/$', 'popular_videos', name='popular_videos'),
# temporarily commented: see https://www.pivotaltracker.com/story/show/17619883
# url(r'^volunteer/$', 'volunteer_page', name='volunteer_page'),
url(r'^volunteer/(?P<category>\w+)/$', 'volunteer_category', name='volunteer_category'),
url(r'^test_celery/$', 'test_celery'),
url(r'^test_celery_exception/$', 'test_celery_exception'),
url(r'^router/$', rpc_router, name='rpc_router'),
url(r'^router/api/$', rpc_router.api, name='rpc_api'),
url(r'^subscribe_to_updates/$', 'subscribe_to_updates', name='subscribe_to_updates'),
url(r'^feedback/$', 'feedback', name='feedback'),
url(r'^feedback/error/$', 'feedback', {'hide_captcha': True}, 'feedback_error'),
url(r'^upload_subtitles/$', 'upload_subtitles', name='upload_subtitles'),
url(r'^upload_transcription_file/$', 'upload_transcription_file', name='upload_transcription_file'),
url(r'^create/$', 'create', name='create'),
url(r'^create/feed/$', 'create_from_feed', name='create_from_feed'),
url(r'^email_friend/$', 'email_friend', name='email_friend'),
url(r'^activities/(?P<video_id>(\w|-)+)/$', 'actions_list', name='actions_list'),
url(r'^stop_notification/(?P<video_id>(\w|-)+)/$', 'stop_notification', name='stop_notification'),
url(r'^(?P<video_id>(\w|-)+/)?rollback/(?P<pk>\d+)/$', 'rollback', name='rollback'),
url(r'^(?P<video_id>(\w|-)+/)?diffing/(?P<pk>\d+)/(?P<second_pk>\d+)/$', 'diffing', name='diffing'),
url(r'^test/$', 'test_form_page', name='test_form_page'),
url(r'^video_url_make_primary/$', 'video_url_make_primary', name='video_url_make_primary'),
url(r'^video_url_create/$', 'video_url_create', name='video_url_create'),
url(r'^video_url_remove/$', 'video_url_remove', name='video_url_remove'),
url(r'^(?P<video_id>(\w|-)+)/debug/$', 'video_debug', name='video_debug'),
url(r'^(?P<video_id>(\w|-)+)/reset_metadata/$', 'reset_metadata', name='reset_metadata'),
url(r'^(?P<video_id>(\w|-)+)/set-original-language/$', 'set_original_language', name='set_original_language'),
url(r'^(?P<video_id>(\w|-)+)/$', 'redirect_to_video'),
url(r'^(?P<video_id>(\w|-)+)/info/$', 'video', name='video'),
url(r'^(?P<video_id>(\w|-)+)/info/(?P<title>[^/]+)/$', 'video', name='video_with_title'),
url(r'^(?P<video_id>(\w|-)+)/url/(?P<video_url>\d+)/$', 'video', name='video_url'),
url(r'^(?P<video_id>(\w|-)+)/(?P<lang>[\w\-]+)/(?P<lang_id>[\d]+)/$', 'language_subtitles', name='translation_history'),
url(r'^(?P<video_id>(\w|-)+)/(?P<lang>[\w\-]+)/(?P<lang_id>[\d]+)/(?P<version_id>[\d]+)/$', 'language_subtitles', name='subtitleversion_detail'),
url(r'^(?P<video_id>(\w|-)+)/(?P<lang>[\w\-]+)/$', 'legacy_history', name='translation_history_legacy'),
url(r'(?P<video_id>(\w|-)+)/staff/delete/$', 'video_staff_delete', name='video_staff_delete'),
)
|
ujdhesa/unisubs
|
apps/videos/urls.py
|
Python
|
agpl-3.0
| 3,989
|
<?php
namespace Plenty\Modules\Pim\SearchService\Filter;
use Illuminate\Contracts\Support\Arrayable;
use Plenty\Modules\Cloud\ElasticSearch\Lib\Query\Statement\Filter\MatchExactFilter;
use Plenty\Modules\Cloud\ElasticSearch\Lib\Query\Statement\Filter\MatchFuzzyFilter;
use Plenty\Modules\Cloud\ElasticSearch\Lib\Query\Statement\Filter\TermFilter;
use Plenty\Modules\Cloud\ElasticSearch\Lib\Query\Statement\StatementInterface;
use Plenty\Modules\Cloud\ElasticSearch\Lib\Query\Type\Filter\BoolMustFilter;
use Plenty\Modules\Cloud\ElasticSearch\Lib\Query\Type\TypeInterface;
/**
* Includes filters for barcodes
*/
abstract class BarcodeFilter implements TypeInterface
{
/**
* Restricts the result to have a specified code.
*/
abstract public function hasCode(
$code,
string $precision
):self;
/**
* Restricts the result to have a specified type. Not implemented.
*/
abstract public function hasType(
string $type
);
/**
* Restricts the result to have a specified id.
*/
abstract public function hasId(
int $id
):self;
abstract public function toArray(
):array;
abstract public function addStatement(
StatementInterface $statement
);
abstract public function addQuery(
$statement
);
}
|
plentymarkets/plugin-hack-api
|
Modules/Pim/SearchService/Filter/BarcodeFilter.php
|
PHP
|
agpl-3.0
| 1,234
|
<div style="position: absolute; top: 0; left: 0; width: 30%; height: 100%; overflow: auto; background: #cccccc">
<div class="Padding">
<h2>
Contents:
</h2>
<ol>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#gettingstarted">Getting started</a></li>
</ol>
<h2>
Command index:
</h2>
<ol>
<li><a href="#cmd_break">break</a></li>
<li><a href="#cmd_cd">cd</a></li>
<li><a href="#cmd_dir">dir</a></li>
<li><a href="#cmd_echo">echo</a></li>
<li><a href="#cmd_status">status</a></li>
</ol>
</div>
</div>
<div style="position: absolute; top: 0; left: 30%; width: 70%; height: 100%; overflow: auto">
<div class="Padding BorderBottom">
<h1>
Friend DOS
</h1>
</div>
<div class="Padding" style="text-align: justify">
<h2>
<a name="introduction"></a>
Introduction
</h2>
<p>
Every Workspace should allow you to use it using written language
alone. Not because you would prefer it, but because it gives everyone
options on how to use their system. Consider people with reduced
eyesight or other disabilities.
</p>
<p>
Friend DOS (Friend Disk Operating System), is inspired by many
similar systems. It allows you to navigate through your Workspace
using commands and arguments. Additionally, it allows you to
navigate through your applications. This way, you are able to
access more advanced features than ever before.
</p>
<p>
The DOS is often accessed through what we call a <strong>Shell</strong>.
It allows you to type in DOS commands that control the file system as
well as OS structures. In FriendUP, you can have as many Shell sessions
as you want, opening a CLI window on the Workspace. Additionally,
you can access the DOS commands through your applications, using
the Shell javascript class.
</p>
<p>
For advanced users, simple typed commands might not be enough.
Because of this, we have provided you with a powerful DOS scripting language.
With this scripting language, you can access most of the OS
structures using a shell, or using the Shell javascript class.
</p>
<h2>
<a name="gettingstarted"></a>
Getting started
</h2>
<p>
To get started, open a new Shell by either starting the application
using your dock, or by selecting "New shell" from the Workspace
menu. This will bring up a new Shell where you can enter your
first Friend DOS commands.
</p>
<p>
In a shell, you start out on the command prompt. This is where
you input your commands. When opening a new shell session, it will
look like this:
</p>
<p>
<strong>System:></strong>
</p>
<p>
This indicates that your current location is the root directory
of the System: volume. Here you can change directory. Normally,
in a standard FriendUP setup, you also have a Home: volume.
Start by changing to this location:
</p>
<p>
<strong>cd Home:</strong>
</p>
<p>
After writing this, you can hit enter. This will let you enter
the Home: volume. After this, change back to the System: volume.
</p>
<p>
<strong>cd System:</strong>
</p>
<p>
Now being back at the System: volume, you should do a directory
listing to show all the files and directories that are found
at the root directory.
</p>
<p>
<strong>dir</strong>
</p>
<p>
You will now have a directory listing. You will see the standard
directory output.
</p>
<p>
Settings/ Devices/ Documentation/<br>
Tools/ Libraries/ Functions/<br>
Modules/ Software/
</p>
<h2>
<a name="cmd_break"></a>
break
</h2>
<p>
The command "break" lets you terminate processes running in the
FriendUP Workspace. "break" requires a process number to function.
This process number is a acquired with "status".
</p>
<h2>
<a name="cmd_cd"></a>
cd
</h2>
<p>
"cd" stands for "change directory". It allows you to navigate
through the DOS environment, changing from volumes to directories.
</p>
</div>
</div>
|
FriendSoftwareLabs/friendup
|
interfaces/web_desktop/templates/sysdoc_FriendDOS.html
|
HTML
|
agpl-3.0
| 4,193
|
<?php
/**
* Smarty Method UnregisterFilter
*
* Smarty::unregisterFilter() method
*
* @package Smarty
* @subpackage PluginsInternal
* @author Uwe Tews
*/
class Smarty_Internal_Method_UnregisterFilter extends Smarty_Internal_Method_RegisterFilter
{
/**
* Unregisters a filter function
*
* @api Smarty::unregisterFilter()
*
* @link http://www.smarty.net/docs/en/api.unregister.filter.tpl
*
* @param \Smarty_Internal_TemplateBase|\Smarty_Internal_Template|\Smarty $obj
* @param string $type filter type
* @param callback|string $callback
*
* @return \Smarty|\Smarty_Internal_Template
*/
public function unregisterFilter(Smarty_Internal_TemplateBase $obj, $type, $callback)
{
$smarty = $obj->_getSmartyObj();
$this->_checkFilterType($type);
if (isset($smarty->registered_filters[ $type ])) {
$name = is_string($callback) ? $callback : $this->_getFilterName($callback);
if (isset($smarty->registered_filters[ $type ][ $name ])) {
unset($smarty->registered_filters[ $type ][ $name ]);
if (empty($smarty->registered_filters[ $type ])) {
unset($smarty->registered_filters[ $type ]);
}
}
}
return $obj;
}
}
|
oposso-team/oposso
|
classes/vendor/smarty/smarty/libs/sysplugins/smarty_internal_method_unregisterfilter.php
|
PHP
|
agpl-3.0
| 1,479
|
<?php /* Smarty version 2.6.11, created on 2015-11-27 12:06:34
compiled from cache/modules/AOW_WorkFlow/LeadsDetailViewdate_modified.tpl */ ?>
<?php if (strlen ( $this->_tpl_vars['fields']['aow_temp_date']['value'] ) <= 0): ?>
<?php $this->assign('value', $this->_tpl_vars['fields']['aow_temp_date']['default_value']); ?>
<?php else: ?>
<?php $this->assign('value', $this->_tpl_vars['fields']['aow_temp_date']['value']); ?>
<?php endif; ?>
<span class="sugar_field" id="<?php echo $this->_tpl_vars['fields']['aow_temp_date']['name']; ?>
"><?php echo $this->_tpl_vars['value']; ?>
</span>
|
caleboau2012/edusupport
|
cache/smarty/templates_c/%%83^833^8334053C%%LeadsDetailViewdate_modified.tpl.php
|
PHP
|
agpl-3.0
| 629
|
/*
* Copyright (c) 2017 Reto Inderbitzin (mail@indr.ch)
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
package ch.indr.threethreefive.libs;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import ch.indr.threethreefive.ThreeThreeFiveApp;
import ch.indr.threethreefive.libs.utils.BundleUtils;
public final class FragmentViewModelManager {
private static final String VIEW_MODEL_ID_KEY = "fragment_view_model_id";
private static final String VIEW_MODEL_STATE_KEY = "fragment_view_model_state";
private static final FragmentViewModelManager instance = new FragmentViewModelManager();
private Map<String, FragmentViewModel> viewModels = new HashMap<>();
public static @NonNull FragmentViewModelManager getInstance() {
return instance;
}
@SuppressWarnings("unchecked")
public <T extends FragmentViewModel> T fetch(final @NonNull Context context, final @NonNull Class<T> viewModelClass,
final @Nullable Bundle savedInstanceState) {
final String id = fetchId(savedInstanceState);
FragmentViewModel viewModel = viewModels.get(id);
if (viewModel == null) {
viewModel = create(context, viewModelClass, savedInstanceState, id);
}
return (T) viewModel;
}
public void destroy(final @NonNull FragmentViewModel viewModel) {
viewModel.onDestroy();
final Iterator<Map.Entry<String, FragmentViewModel>> iterator = viewModels.entrySet().iterator();
while (iterator.hasNext()) {
final Map.Entry<String, FragmentViewModel> entry = iterator.next();
if (viewModel.equals(entry.getValue())) {
iterator.remove();
}
}
}
public void save(final @NonNull FragmentViewModel viewModel, final @NonNull Bundle envelope) {
envelope.putString(VIEW_MODEL_ID_KEY, findIdForViewModel(viewModel));
final Bundle state = new Bundle();
envelope.putBundle(VIEW_MODEL_STATE_KEY, state);
}
private <T extends FragmentViewModel> FragmentViewModel create(final @NonNull Context context, final @NonNull Class<T> viewModelClass,
final @Nullable Bundle savedInstanceState, final @NonNull String id) {
final ThreeThreeFiveApp application = (ThreeThreeFiveApp) context.getApplicationContext();
final Environment environment = application.component().environment();
final FragmentViewModel viewModel;
try {
final Constructor constructor = viewModelClass.getConstructor(Environment.class);
viewModel = (FragmentViewModel) constructor.newInstance(environment);
// Need to catch these exceptions separately, otherwise the compiler turns them into `ReflectiveOperationException`.
// That exception is only available in API19+
} catch (IllegalAccessException exception) {
throw new RuntimeException(exception);
} catch (InvocationTargetException exception) {
throw new RuntimeException(exception);
} catch (InstantiationException exception) {
throw new RuntimeException(exception);
} catch (NoSuchMethodException exception) {
throw new RuntimeException(exception);
}
viewModels.put(id, viewModel);
viewModel.onCreate(context, BundleUtils.maybeGetBundle(savedInstanceState, VIEW_MODEL_STATE_KEY));
return viewModel;
}
private String fetchId(final @Nullable Bundle savedInstanceState) {
return savedInstanceState != null ?
savedInstanceState.getString(VIEW_MODEL_ID_KEY) :
UUID.randomUUID().toString();
}
private String findIdForViewModel(final @NonNull FragmentViewModel viewModel) {
for (final Map.Entry<String, FragmentViewModel> entry : viewModels.entrySet()) {
if (viewModel.equals(entry.getValue())) {
return entry.getKey();
}
}
throw new RuntimeException("Cannot find view model in map!");
}
}
|
indr/335
|
app/src/main/java/ch/indr/threethreefive/libs/FragmentViewModelManager.java
|
Java
|
agpl-3.0
| 4,109
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_51) on Tue Jun 25 15:27:12 EDT 2013 -->
<TITLE>
Uses of Class com.sleepycat.util.FastInputStream (Oracle - Berkeley DB Java API)
</TITLE>
<META NAME="date" CONTENT="2013-06-25">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../style.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.sleepycat.util.FastInputStream (Oracle - Berkeley DB Java API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../com/sleepycat/util/FastInputStream.html" title="class in com.sleepycat.util"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<b>Berkeley DB</b><br><font size="-1"> version 6.0.20</font></EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?com/sleepycat/util//class-useFastInputStream.html" target="_top"><B>FRAMES</B></A>
<A HREF="FastInputStream.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>com.sleepycat.util.FastInputStream</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../com/sleepycat/util/FastInputStream.html" title="class in com.sleepycat.util">FastInputStream</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#com.sleepycat.bind.tuple"><B>com.sleepycat.bind.tuple</B></A></TD>
<TD>Bindings that use sequences of primitive fields, or tuples. </TD>
</TR>
</TABLE>
<P>
<A NAME="com.sleepycat.bind.tuple"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../com/sleepycat/util/FastInputStream.html" title="class in com.sleepycat.util">FastInputStream</A> in <A HREF="../../../../com/sleepycat/bind/tuple/package-summary.html">com.sleepycat.bind.tuple</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../com/sleepycat/util/FastInputStream.html" title="class in com.sleepycat.util">FastInputStream</A> in <A HREF="../../../../com/sleepycat/bind/tuple/package-summary.html">com.sleepycat.bind.tuple</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../com/sleepycat/bind/tuple/TupleInput.html" title="class in com.sleepycat.bind.tuple">TupleInput</A></B></CODE>
<BR>
An <code>InputStream</code> with <code>DataInput</code>-like methods for
reading tuple fields.</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../com/sleepycat/util/FastInputStream.html" title="class in com.sleepycat.util"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<b>Berkeley DB</b><br><font size="-1"> version 6.0.20</font></EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?com/sleepycat/util//class-useFastInputStream.html" target="_top"><B>FRAMES</B></A>
<A HREF="FastInputStream.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<font size=1>Copyright (c) 1996, 2013 Oracle and/or its affiliates. All rights reserved.</font>
</BODY>
</HTML>
|
hyc/BerkeleyDB
|
docs/java/com/sleepycat/util/class-use/FastInputStream.html
|
HTML
|
agpl-3.0
| 7,952
|
$ComputerSystem = Get-WmiObject -ClassName Win32_ComputerSystem
$ComputerSystem.AutomaticManagedPagefile = $true
$ComputerSystem.Put()
|
kevmaitland/PoshAnt
|
enable-managePagingFileSizeAutomatically.ps1
|
PowerShell
|
agpl-3.0
| 137
|
package net.diaowen.dwsurvey.dao.impl;
import net.diaowen.dwsurvey.dao.QuestionBankDao;
import net.diaowen.dwsurvey.entity.QuestionBank;
import org.springframework.stereotype.Repository;
import net.diaowen.common.dao.BaseDaoImpl;
/**
* 题库 dao
* @author keyuan(keyuan258@gmail.com)
*
* https://github.com/wkeyuan/DWSurvey
* http://dwsurvey.net
*/
@Repository
public class QuestionBankDaoImpl extends BaseDaoImpl<QuestionBank, String> implements QuestionBankDao {
}
|
wkeyuan/DWSurvey
|
src/main/java/net/diaowen/dwsurvey/dao/impl/QuestionBankDaoImpl.java
|
Java
|
agpl-3.0
| 499
|
from django.conf.urls import patterns, include, url
from django.contrib import admin
from rest_framework import viewsets, routers
from voting_app.models import Topic
from voting_app.views import Vote
from voting_app.serializer import TopicSerializer
admin.autodiscover()
# ViewSets define the view behavior.
class TopicViewSet(viewsets.ModelViewSet):
model = Topic
serializer_class = TopicSerializer
queryset = Topic.objects.all().filter(hide=False)
router = routers.DefaultRouter()
router.register(r'topics', TopicViewSet)
urlpatterns = patterns('',
url(r'^$', 'voting_app.views.index', name='index'),
url(r'^', include(router.urls)),
url(r'^vote/$', Vote.as_view()),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^admin/', include(admin.site.urls)),
)
|
gc3-uzh-ch/django-simple-poll
|
voting/urls.py
|
Python
|
agpl-3.0
| 833
|
//Selectively disables the "Submit" button for student logged assignments, if the
//assignment has outcome levels and no outcome level is selected.
var SelfGradeOutcomesSelect = document.querySelector("#grade_raw_points");
if(!SelfGradeOutcomesSelect) SelfGradeOutcomesSelect = document.querySelector("#grade_pass_fail_status");
var SelfGradeOutcomesButton = document.querySelector(".self_grade_outcomes_button");
if(SelfGradeOutcomesSelect && SelfGradeOutcomesButton){
SelfGradeOutcomesSelect.addEventListener("change", function(){
if(SelfGradeOutcomesSelect.selectedIndex == 0)
SelfGradeOutcomesButton.disabled = true;
else
SelfGradeOutcomesButton.disabled = false;
});
}
|
UM-USElab/gradecraft-development
|
app/assets/javascripts/behaviors/self_grade_outcomes_select.js
|
JavaScript
|
agpl-3.0
| 726
|
<!DOCTYPE html>
<html lang="en"
>
<head>
<title>Search - CD期末考週 網頁 (虎尾科大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">
<style type="text/css">
/*some stuff for output/input prompts*/
div.cell{border:1px solid transparent;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;display:flex;flex-direction:column;align-items:stretch}div.cell.selected{border-radius:4px;border:thin #ababab solid}
div.cell.edit_mode{border-radius:4px;border:thin #008000 solid}
div.cell{width:100%;padding:5px 5px 5px 0;margin:0;outline:none}
div.prompt{min-width:11ex;padding:.4em;margin:0;font-family:monospace;text-align:right;line-height:1.21429em}
@media (max-width:480px){div.prompt{text-align:left}}div.inner_cell{display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;display:flex;flex-direction:column;align-items:stretch;-webkit-box-flex:1;-moz-box-flex:1;box-flex:1;flex:1}
div.input_area{border:1px solid #cfcfcf;border-radius:4px;background:#f7f7f7;line-height:1.21429em}
div.prompt:empty{padding-top:0;padding-bottom:0}
div.input{page-break-inside:avoid;display:-webkit-box;-webkit-box-orient:horizontal;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:horizontal;-moz-box-align:stretch;display:box;box-orient:horizontal;box-align:stretch;}
div.inner_cell{width:90%;}
div.input_area{border:1px solid #cfcfcf;border-radius:4px;background:#f7f7f7;}
div.input_prompt{color:navy;border-top:1px solid transparent;}
div.output_wrapper{margin-top:5px;position:relative;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;width:100%;}
div.output_scroll{height:24em;width:100%;overflow:auto;border-radius:4px;-webkit-box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);-moz-box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);}
div.output_collapsed{margin:0px;padding:0px;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;width:100%;}
div.out_prompt_overlay{height:100%;padding:0px 0.4em;position:absolute;border-radius:4px;}
div.out_prompt_overlay:hover{-webkit-box-shadow:inset 0 0 1px #000000;-moz-box-shadow:inset 0 0 1px #000000;box-shadow:inset 0 0 1px #000000;background:rgba(240, 240, 240, 0.5);}
div.output_prompt{color:darkred;}
a.anchor-link:link{text-decoration:none;padding:0px 20px;visibility:hidden;}
h1:hover .anchor-link,h2:hover .anchor-link,h3:hover .anchor-link,h4:hover .anchor-link,h5:hover .anchor-link,h6:hover .anchor-link{visibility:visible;}
/* end stuff for output/input prompts*/
.highlight-ipynb .hll { background-color: #ffffcc }
.highlight-ipynb { background: #f8f8f8; }
.highlight-ipynb .c { color: #408080; font-style: italic } /* Comment */
.highlight-ipynb .err { border: 1px solid #FF0000 } /* Error */
.highlight-ipynb .k { color: #008000; font-weight: bold } /* Keyword */
.highlight-ipynb .o { color: #666666 } /* Operator */
.highlight-ipynb .cm { color: #408080; font-style: italic } /* Comment.Multiline */
.highlight-ipynb .cp { color: #BC7A00 } /* Comment.Preproc */
.highlight-ipynb .c1 { color: #408080; font-style: italic } /* Comment.Single */
.highlight-ipynb .cs { color: #408080; font-style: italic } /* Comment.Special */
.highlight-ipynb .gd { color: #A00000 } /* Generic.Deleted */
.highlight-ipynb .ge { font-style: italic } /* Generic.Emph */
.highlight-ipynb .gr { color: #FF0000 } /* Generic.Error */
.highlight-ipynb .gh { color: #000080; font-weight: bold } /* Generic.Heading */
.highlight-ipynb .gi { color: #00A000 } /* Generic.Inserted */
.highlight-ipynb .go { color: #888888 } /* Generic.Output */
.highlight-ipynb .gp { color: #000080; font-weight: bold } /* Generic.Prompt */
.highlight-ipynb .gs { font-weight: bold } /* Generic.Strong */
.highlight-ipynb .gu { color: #800080; font-weight: bold } /* Generic.Subheading */
.highlight-ipynb .gt { color: #0044DD } /* Generic.Traceback */
.highlight-ipynb .kc { color: #008000; font-weight: bold } /* Keyword.Constant */
.highlight-ipynb .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */
.highlight-ipynb .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */
.highlight-ipynb .kp { color: #008000 } /* Keyword.Pseudo */
.highlight-ipynb .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */
.highlight-ipynb .kt { color: #B00040 } /* Keyword.Type */
.highlight-ipynb .m { color: #666666 } /* Literal.Number */
.highlight-ipynb .s { color: #BA2121 } /* Literal.String */
.highlight-ipynb .na { color: #7D9029 } /* Name.Attribute */
.highlight-ipynb .nb { color: #008000 } /* Name.Builtin */
.highlight-ipynb .nc { color: #0000FF; font-weight: bold } /* Name.Class */
.highlight-ipynb .no { color: #880000 } /* Name.Constant */
.highlight-ipynb .nd { color: #AA22FF } /* Name.Decorator */
.highlight-ipynb .ni { color: #999999; font-weight: bold } /* Name.Entity */
.highlight-ipynb .ne { color: #D2413A; font-weight: bold } /* Name.Exception */
.highlight-ipynb .nf { color: #0000FF } /* Name.Function */
.highlight-ipynb .nl { color: #A0A000 } /* Name.Label */
.highlight-ipynb .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */
.highlight-ipynb .nt { color: #008000; font-weight: bold } /* Name.Tag */
.highlight-ipynb .nv { color: #19177C } /* Name.Variable */
.highlight-ipynb .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */
.highlight-ipynb .w { color: #bbbbbb } /* Text.Whitespace */
.highlight-ipynb .mf { color: #666666 } /* Literal.Number.Float */
.highlight-ipynb .mh { color: #666666 } /* Literal.Number.Hex */
.highlight-ipynb .mi { color: #666666 } /* Literal.Number.Integer */
.highlight-ipynb .mo { color: #666666 } /* Literal.Number.Oct */
.highlight-ipynb .sb { color: #BA2121 } /* Literal.String.Backtick */
.highlight-ipynb .sc { color: #BA2121 } /* Literal.String.Char */
.highlight-ipynb .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */
.highlight-ipynb .s2 { color: #BA2121 } /* Literal.String.Double */
.highlight-ipynb .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */
.highlight-ipynb .sh { color: #BA2121 } /* Literal.String.Heredoc */
.highlight-ipynb .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */
.highlight-ipynb .sx { color: #008000 } /* Literal.String.Other */
.highlight-ipynb .sr { color: #BB6688 } /* Literal.String.Regex */
.highlight-ipynb .s1 { color: #BA2121 } /* Literal.String.Single */
.highlight-ipynb .ss { color: #19177C } /* Literal.String.Symbol */
.highlight-ipynb .bp { color: #008000 } /* Name.Builtin.Pseudo */
.highlight-ipynb .vc { color: #19177C } /* Name.Variable.Class */
.highlight-ipynb .vg { color: #19177C } /* Name.Variable.Global */
.highlight-ipynb .vi { color: #19177C } /* Name.Variable.Instance */
.highlight-ipynb .il { color: #666666 } /* Literal.Number.Integer.Long */
</style>
<style type="text/css">
/* Overrides of notebook CSS for static HTML export */
div.entry-content {
overflow: visible;
padding: 8px;
}
.input_area {
padding: 0.2em;
}
a.heading-anchor {
white-space: normal;
}
.rendered_html
code {
font-size: .8em;
}
pre.ipynb {
color: black;
background: #f7f7f7;
border: none;
box-shadow: none;
margin-bottom: 0;
padding: 0;
margin: 0px;
font-size: 13px;
}
/* remove the prompt div from text cells */
div.text_cell .prompt {
display: none;
}
/* remove horizontal padding from text cells, */
/* so it aligns with outer body text */
div.text_cell_render {
padding: 0.5em 0em;
}
img.anim_icon{padding:0; border:0; vertical-align:middle; -webkit-box-shadow:none; -box-shadow:none}
</style>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML" type="text/javascript"></script>
<script type="text/javascript">
init_mathjax = function() {
if (window.MathJax) {
// MathJax loaded
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ]
},
displayAlign: 'left', // Change this to 'center' to center equations.
"HTML-CSS": {
styles: {'.MathJax_Display': {"margin": 0}}
}
});
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
}
}
init_mathjax();
</script>
<meta name="author" content="kmol" />
<!-- Open Graph tags -->
<meta property="og:site_name" content="CD期末考週 網頁 (虎尾科大MDE)" />
<meta property="og:type" content="website"/>
<meta property="og:title" content="CD期末考週 網頁 (虎尾科大MDE)"/>
<meta property="og:url" content="."/>
<meta property="og:description" content="CD期末考週 網頁 (虎尾科大MDE)"/>
<!-- 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="CD期末考週 網頁 (虎尾科大MDE) ATOM Feed"/>
<script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shCore.js"></script>
<script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushJScript.js"></script>
<script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushJava.js"></script>
<script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushPython.js"></script>
<script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushSql.js"></script>
<script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushXml.js"></script>
<script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushPhp.js"></script>
<script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushCpp.js"></script>
<script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushCss.js"></script>
<script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushCSharp.js"></script>
<script type='text/javascript'>
(function(){
var corecss = document.createElement('link');
var themecss = document.createElement('link');
var corecssurl = "http://cad-lab.github.io/cadlab_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 = "http://cad-lab.github.io/cadlab_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">
CD期末考週 網頁 (虎尾科大MDE) </a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li >
<a href="./category/bg2.html">Bg2</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">
<div id="tipue_search_content"></div>
</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="./40123226-final-bao-gao.html">
40123226 final 報告
</a>
</li>
<li class="list-group-item">
<a href="./40123217-final-bao-gao.html">
40123217 final 報告
</a>
</li>
<li class="list-group-item">
<a href="./40123214-final-bao-gao.html">
40123214 final 報告
</a>
</li>
<li class="list-group-item">
<a href="./40123235-final-bao-gao.html">
40123235 final 報告
</a>
</li>
<li class="list-group-item">
<a href="./40123202-cdw18bao-gao.html">
40123202 cdw18報告
</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/bg2.html">
<i class="fa fa-folder-open fa-lg"></i> bg2
</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">© 2016 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>
<!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) -->
<script src="./theme/js/respond.min.js"></script>
<link href="./theme/tipuesearch/tipuesearch.css" rel="stylesheet">
<script type="text/javascript" src="./theme/tipuesearch/tipuesearch_set.js"></script>
<script type="text/javascript" src="./theme/tipuesearch/tipuesearch.min.js"></script>
<!-- 導入 local Tipue search 所需要的 tipuesearch_content.js -->
<script type="text/javascript" src="./tipuesearch_content.js"></script>
<script>
$(document).ready(function() {
$('#tipue_search_input').tipuesearch({
'mode' : 'static',
'show': 10,
'minimumLength': 2,
'newWindow': false
});
});
</script>
</body>
</html>
|
2014cdbg9/2016springcd_bG2
|
static/blog/search.html
|
HTML
|
agpl-3.0
| 19,165
|
/* 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/Layer.js
* @requires OpenLayers/Util.js
*/
/**
* Class: OpenLayers.Layer.EventPane
* Base class for 3rd party layers, providing a DOM element which isolates
* the 3rd-party layer from mouse events.
* Only used by Google layers.
*
* Automatically instantiated by the Google constructor, and not usually instantiated directly.
*
* Create a new event pane layer with the
* <OpenLayers.Layer.EventPane> constructor.
*
* Inherits from:
* - <OpenLayers.Layer>
*/
OpenLayers.Layer.EventPane = OpenLayers.Class(OpenLayers.Layer, {
/**
* APIProperty: smoothDragPan
* {Boolean} smoothDragPan determines whether non-public/internal API
* methods are used for better performance while dragging EventPane
* layers. When not in sphericalMercator mode, the smoother dragging
* doesn't actually move north/south directly with the number of
* pixels moved, resulting in a slight offset when you drag your mouse
* north south with this option on. If this visual disparity bothers
* you, you should turn this option off, or use spherical mercator.
* Default is on.
*/
smoothDragPan: true,
/**
* Property: isBaseLayer
* {Boolean} EventPaned layers are always base layers, by necessity.
*/
isBaseLayer: true,
/**
* APIProperty: isFixed
* {Boolean} EventPaned layers are fixed by default.
*/
isFixed: true,
/**
* Property: pane
* {DOMElement} A reference to the element that controls the events.
*/
pane: null,
/**
* Property: mapObject
* {Object} This is the object which will be used to load the 3rd party library
* in the case of the google layer, this will be of type GMap,
* in the case of the ve layer, this will be of type VEMap
*/
mapObject: null,
/**
* Constructor: OpenLayers.Layer.EventPane
* Create a new event pane layer
*
* Parameters:
* name - {String}
* options - {Object} Hashtable of extra options to tag onto the layer
*/
initialize: function(name, options) {
OpenLayers.Layer.prototype.initialize.apply(this, arguments);
if (this.pane == null) {
this.pane = OpenLayers.Util.createDiv(this.div.id + "_EventPane");
}
},
/**
* APIMethod: destroy
* Deconstruct this layer.
*/
destroy: function() {
this.mapObject = null;
this.pane = null;
OpenLayers.Layer.prototype.destroy.apply(this, arguments);
},
/**
* Method: setMap
* Set the map property for the layer. This is done through an accessor
* so that subclasses can override this and take special action once
* they have their map variable set.
*
* Parameters:
* map - {<OpenLayers.Map>}
*/
setMap: function(map) {
OpenLayers.Layer.prototype.setMap.apply(this, arguments);
this.pane.style.zIndex = parseInt(this.div.style.zIndex) + 1;
this.pane.style.display = this.div.style.display;
this.pane.style.width="100%";
this.pane.style.height="100%";
if (OpenLayers.BROWSER_NAME == "msie") {
this.pane.style.background =
"url(" + OpenLayers.Util.getImageLocation("blank.gif") + ")";
}
if (this.isFixed) {
this.map.viewPortDiv.appendChild(this.pane);
} else {
this.map.layerContainerDiv.appendChild(this.pane);
}
// once our layer has been added to the map, we can load it
this.loadMapObject();
// if map didn't load, display warning
if (this.mapObject == null) {
this.loadWarningMessage();
}
},
/**
* APIMethod: removeMap
* On being removed from the map, we'll like to remove the invisible 'pane'
* div that we added to it on creation.
*
* Parameters:
* map - {<OpenLayers.Map>}
*/
removeMap: function(map) {
if (this.pane && this.pane.parentNode) {
this.pane.parentNode.removeChild(this.pane);
}
OpenLayers.Layer.prototype.removeMap.apply(this, arguments);
},
/**
* Method: loadWarningMessage
* If we can't load the map lib, then display an error message to the
* user and tell them where to go for help.
*
* This function sets up the layout for the warning message. Each 3rd
* party layer must implement its own getWarningHTML() function to
* provide the actual warning message.
*/
loadWarningMessage:function() {
this.div.style.backgroundColor = "darkblue";
var viewSize = this.map.getSize();
var msgW = Math.min(viewSize.w, 300);
var msgH = Math.min(viewSize.h, 200);
var size = new OpenLayers.Size(msgW, msgH);
var centerPx = new OpenLayers.Pixel(viewSize.w/2, viewSize.h/2);
var topLeft = centerPx.add(-size.w/2, -size.h/2);
var div = OpenLayers.Util.createDiv(this.name + "_warning",
topLeft,
size,
null,
null,
null,
"auto");
div.style.padding = "7px";
div.style.backgroundColor = "yellow";
div.innerHTML = this.getWarningHTML();
this.div.appendChild(div);
},
/**
* Method: getWarningHTML
* To be implemented by subclasses.
*
* Returns:
* {String} String with information on why layer is broken, how to get
* it working.
*/
getWarningHTML:function() {
//should be implemented by subclasses
return "";
},
/**
* Method: display
* Set the display on the pane
*
* Parameters:
* display - {Boolean}
*/
display: function(display) {
OpenLayers.Layer.prototype.display.apply(this, arguments);
this.pane.style.display = this.div.style.display;
},
/**
* Method: setZIndex
* Set the z-index order for the pane.
*
* Parameters:
* zIndex - {int}
*/
setZIndex: function (zIndex) {
OpenLayers.Layer.prototype.setZIndex.apply(this, arguments);
this.pane.style.zIndex = parseInt(this.div.style.zIndex) + 1;
},
/**
* Method: moveByPx
* Move the layer based on pixel vector. To be implemented by subclasses.
*
* Parameters:
* dx - {Number} The x coord of the displacement vector.
* dy - {Number} The y coord of the displacement vector.
*/
moveByPx: function(dx, dy) {
OpenLayers.Layer.prototype.moveByPx.apply(this, arguments);
if (this.dragPanMapObject) {
this.dragPanMapObject(dx, -dy);
} else {
this.moveTo(this.map.getCachedCenter());
}
},
/**
* Method: moveTo
* Handle calls to move the layer.
*
* Parameters:
* bounds - {<OpenLayers.Bounds>}
* zoomChanged - {Boolean}
* dragging - {Boolean}
*/
moveTo:function(bounds, zoomChanged, dragging) {
OpenLayers.Layer.prototype.moveTo.apply(this, arguments);
if (this.mapObject != null) {
var newCenter = this.map.getCenter();
var newZoom = this.map.getZoom();
if (newCenter != null) {
var moOldCenter = this.getMapObjectCenter();
var oldCenter = this.getOLLonLatFromMapObjectLonLat(moOldCenter);
var moOldZoom = this.getMapObjectZoom();
var oldZoom= this.getOLZoomFromMapObjectZoom(moOldZoom);
if (!(newCenter.equals(oldCenter)) || newZoom != oldZoom) {
if (!zoomChanged && oldCenter && this.dragPanMapObject &&
this.smoothDragPan) {
var oldPx = this.map.getViewPortPxFromLonLat(oldCenter);
var newPx = this.map.getViewPortPxFromLonLat(newCenter);
this.dragPanMapObject(newPx.x-oldPx.x, oldPx.y-newPx.y);
} else {
var center = this.getMapObjectLonLatFromOLLonLat(newCenter);
var zoom = this.getMapObjectZoomFromOLZoom(newZoom);
this.setMapObjectCenter(center, zoom, dragging);
}
}
}
}
},
/********************************************************/
/* */
/* Baselayer Functions */
/* */
/********************************************************/
/**
* Method: getLonLatFromViewPortPx
* Get a map location from a pixel location
*
* Parameters:
* viewPortPx - {<OpenLayers.Pixel>}
*
* Returns:
* {<OpenLayers.LonLat>} An OpenLayers.LonLat which is the passed-in view
* port OpenLayers.Pixel, translated into lon/lat by map lib
* If the map lib is not loaded or not centered, returns null
*/
getLonLatFromViewPortPx: function (viewPortPx) {
var lonlat = null;
if ( (this.mapObject != null) &&
(this.getMapObjectCenter() != null) ) {
var moPixel = this.getMapObjectPixelFromOLPixel(viewPortPx);
var moLonLat = this.getMapObjectLonLatFromMapObjectPixel(moPixel);
lonlat = this.getOLLonLatFromMapObjectLonLat(moLonLat);
}
return lonlat;
},
/**
* Method: getViewPortPxFromLonLat
* Get a pixel location from a map location
*
* Parameters:
* lonlat - {<OpenLayers.LonLat>}
*
* Returns:
* {<OpenLayers.Pixel>} An OpenLayers.Pixel which is the passed-in
* OpenLayers.LonLat, translated into view port pixels by map lib
* If map lib is not loaded or not centered, returns null
*/
getViewPortPxFromLonLat: function (lonlat) {
var viewPortPx = null;
if ( (this.mapObject != null) &&
(this.getMapObjectCenter() != null) ) {
var moLonLat = this.getMapObjectLonLatFromOLLonLat(lonlat);
var moPixel = this.getMapObjectPixelFromMapObjectLonLat(moLonLat);
viewPortPx = this.getOLPixelFromMapObjectPixel(moPixel);
}
return viewPortPx;
},
/********************************************************/
/* */
/* Translation Functions */
/* */
/* The following functions translate Map Object and */
/* OL formats for Pixel, LonLat */
/* */
/********************************************************/
//
// TRANSLATION: MapObject LatLng <-> OpenLayers.LonLat
//
/**
* Method: getOLLonLatFromMapObjectLonLat
* Get an OL style map location from a 3rd party style map location
*
* Parameters
* moLonLat - {Object}
*
* Returns:
* {<OpenLayers.LonLat>} An OpenLayers.LonLat, translated from the passed in
* MapObject LonLat
* Returns null if null value is passed in
*/
getOLLonLatFromMapObjectLonLat: function(moLonLat) {
var olLonLat = null;
if (moLonLat != null) {
var lon = this.getLongitudeFromMapObjectLonLat(moLonLat);
var lat = this.getLatitudeFromMapObjectLonLat(moLonLat);
olLonLat = new OpenLayers.LonLat(lon, lat);
}
return olLonLat;
},
/**
* Method: getMapObjectLonLatFromOLLonLat
* Get a 3rd party map location from an OL map location.
*
* Parameters:
* olLonLat - {<OpenLayers.LonLat>}
*
* Returns:
* {Object} A MapObject LonLat, translated from the passed in
* OpenLayers.LonLat
* Returns null if null value is passed in
*/
getMapObjectLonLatFromOLLonLat: function(olLonLat) {
var moLatLng = null;
if (olLonLat != null) {
moLatLng = this.getMapObjectLonLatFromLonLat(olLonLat.lon,
olLonLat.lat);
}
return moLatLng;
},
//
// TRANSLATION: MapObject Pixel <-> OpenLayers.Pixel
//
/**
* Method: getOLPixelFromMapObjectPixel
* Get an OL pixel location from a 3rd party pixel location.
*
* Parameters:
* moPixel - {Object}
*
* Returns:
* {<OpenLayers.Pixel>} An OpenLayers.Pixel, translated from the passed in
* MapObject Pixel
* Returns null if null value is passed in
*/
getOLPixelFromMapObjectPixel: function(moPixel) {
var olPixel = null;
if (moPixel != null) {
var x = this.getXFromMapObjectPixel(moPixel);
var y = this.getYFromMapObjectPixel(moPixel);
olPixel = new OpenLayers.Pixel(x, y);
}
return olPixel;
},
/**
* Method: getMapObjectPixelFromOLPixel
* Get a 3rd party pixel location from an OL pixel location
*
* Parameters:
* olPixel - {<OpenLayers.Pixel>}
*
* Returns:
* {Object} A MapObject Pixel, translated from the passed in
* OpenLayers.Pixel
* Returns null if null value is passed in
*/
getMapObjectPixelFromOLPixel: function(olPixel) {
var moPixel = null;
if (olPixel != null) {
moPixel = this.getMapObjectPixelFromXY(olPixel.x, olPixel.y);
}
return moPixel;
},
CLASS_NAME: "OpenLayers.Layer.EventPane"
});
|
B3Partners/geo-ov
|
src/main/webapp/openlayers/lib/OpenLayers/Layer/EventPane.js
|
JavaScript
|
agpl-3.0
| 14,713
|
/* *********************************************************************
*
* This file is part of Full Metal Galaxy.
* http://www.fullmetalgalaxy.com
*
* Full Metal Galaxy 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.
*
* Full Metal Galaxy 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 Full Metal Galaxy.
* If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2010 to 2015 Vincent Legendre
*
* *********************************************************************/
package com.fullmetalgalaxy.client.creation;
import com.fullmetalgalaxy.client.game.GameEngine;
import com.fullmetalgalaxy.client.widget.WgtTokenQty;
import com.fullmetalgalaxy.model.TokenType;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* @author Vincent
*
*/
public class WgtEditReserve extends Composite
{
private VerticalPanel m_panel = new VerticalPanel();
private Grid m_grid = new Grid( 3, 5 );
public WgtEditReserve()
{
m_panel.add( new Label( MAppGameCreation.s_messages.tipReserve() ) );
Button btnReinit = new Button( MAppGameCreation.s_messages.defaultValue() );
btnReinit.addClickHandler( new ClickHandler()
{
@Override
public void onClick(ClickEvent p_event)
{
// reset to default value
GameEngine.model().getGame().setConstructReserve( null );
onTabSelected();
}
} );
m_panel.add( btnReinit );
m_panel.add( m_grid );
initWidget( m_panel );
}
private Widget createWgt(final TokenType p_tokenType)
{
WgtTokenQty wgt = new WgtTokenQty( p_tokenType, GameEngine.model().getGame()
.getConstructReserve().get( p_tokenType ) );
wgt.setEnabled( true );
wgt.addValueChangeHandler( new ValueChangeHandler<Integer>()
{
@Override
public void onValueChange(ValueChangeEvent<Integer> p_event)
{
GameEngine.model().getGame().setConstructQty( p_tokenType, p_event.getValue() );
}
} );
return wgt;
}
public void onTabSelected()
{
m_grid.clear();
m_grid.setWidget( 0, 0, createWgt( TokenType.Pontoon ) );
m_grid.setWidget( 0, 1, createWgt( TokenType.Sluice ) );
m_grid.setWidget( 0, 2, createWgt( TokenType.Teleporter ) );
m_grid.setWidget( 1, 0, createWgt( TokenType.Crab ) );
m_grid.setWidget( 1, 1, createWgt( TokenType.Crayfish ) );
m_grid.setWidget( 1, 2, createWgt( TokenType.Barge ) );
m_grid.setWidget( 1, 3, createWgt( TokenType.WeatherHen ) );
m_grid.setWidget( 1, 4, createWgt( TokenType.Destroyer ) );
m_grid.setWidget( 2, 0, createWgt( TokenType.Tank ) );
m_grid.setWidget( 2, 1, createWgt( TokenType.Hovertank ) );
m_grid.setWidget( 2, 2, createWgt( TokenType.Speedboat ) );
m_grid.setWidget( 2, 3, createWgt( TokenType.Heap ) );
m_grid.setWidget( 2, 4, createWgt( TokenType.Tarask ) );
}
}
|
kroc702/fullmetalgalaxy
|
src/com/fullmetalgalaxy/client/creation/WgtEditReserve.java
|
Java
|
agpl-3.0
| 3,784
|
/*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2017 Tanaguru.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: tanaguru AT tanaguru DOT org
*/
package org.tanaguru.rules.rgaa32017;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.tanaguru.entity.audit.TestSolution;
import org.tanaguru.ruleimplementation.AbstractPageRuleWithSelectorAndCheckerImplementation;
import org.tanaguru.rules.elementchecker.element.ElementPresenceChecker;
import org.tanaguru.rules.elementselector.SimpleElementSelector;
import static org.tanaguru.rules.keystore.CssLikeQueryStore.FORM_BUTTON_CSS_LIKE_QUERY;
import static org.tanaguru.rules.keystore.RemarkMessageStore.CHECK_INPUT_IMG_ARIA_MSG;
/**
* Implementation of the rule 1.6.5 of the referential Rgaa 3-2017.
*
* For more details about the implementation, refer to <a href="http://tanaguru-rules-rgaa3.readthedocs.org/en/latest/Rule-1-6-5">the rule 1.6.5 design page.</a>
* @see <a href="http://references.modernisation.gouv.fr/referentiel-technique-0#test-1-6-5"> 1.6.5 rule specification</a>
*/
public class Rgaa32017Rule010605 extends AbstractPageRuleWithSelectorAndCheckerImplementation {
/**
* Default constructor
*/
public Rgaa32017Rule010605 () {
super(new SimpleElementSelector(FORM_BUTTON_CSS_LIKE_QUERY ),
new ElementPresenceChecker(
new ImmutablePair(TestSolution.NEED_MORE_INFO,CHECK_INPUT_IMG_ARIA_MSG),
new ImmutablePair(TestSolution.NOT_APPLICABLE, "")
));
}
}
|
Tanaguru/Tanaguru
|
rules/rgaa3-2017/src/main/java/org/tanaguru/rules/rgaa32017/Rgaa32017Rule010605.java
|
Java
|
agpl-3.0
| 2,200
|
# This file is part of rinohtype, the Python document preparation system.
#
# Copyright (c) Brecht Machiels.
#
# Use of this source code is subject to the terms of the GNU Affero General
# Public License v3. See the LICENSE file or http://www.gnu.org/licenses/.
import pytest
from io import BytesIO
from rinoh.backend.pdf import cos
from rinoh.backend.pdf.reader import PDFObjectReader
def test_read_boolean():
def test_boolean(bytes_boolean, boolean):
reader = PDFObjectReader(BytesIO(bytes_boolean))
result = reader.next_item()
assert isinstance(result, cos.Boolean) and bool(result) == boolean
test_boolean(b'true', True)
test_boolean(b'false', False)
def test_read_integer():
def test_integer(bytes_integer, integer):
reader = PDFObjectReader(BytesIO(bytes_integer))
result = reader.next_item()
assert isinstance(result, cos.Integer) and result == integer
test_integer(b'123', 123)
test_integer(b'43445', 43445)
test_integer(b'+17', 17)
test_integer(b'-98', -98)
test_integer(b'0', 0)
def test_read_real():
def test_real(bytes_real, real):
reader = PDFObjectReader(BytesIO(bytes_real))
result = reader.next_item()
assert isinstance(result, cos.Real) and result == real
test_real(b'34.5', 34.5)
test_real(b'-3.62', -3.62)
test_real(b'+123.6', 123.6)
test_real(b'4.', 4.0)
test_real(b'-.002', -.002)
test_real(b'0.0', 0.0)
def test_read_name():
def test_name(bytes_name, unicode_name):
reader = PDFObjectReader(BytesIO(bytes_name))
result = reader.next_item()
assert isinstance(result, cos.Name) and str(result) == unicode_name
test_name(b'/Adobe#20Green', 'Adobe Green')
test_name(b'/PANTONE#205757#20CV', 'PANTONE 5757 CV')
test_name(b'/paired#28#29parentheses', 'paired()parentheses')
test_name(b'/The_Key_of_F#23_Minor', 'The_Key_of_F#_Minor')
test_name(b'/A#42', 'AB')
def test_read_dictionary():
input = b"""
<< /Type /Example
/Subtype /DictionaryExample
/Version 0.01
/IntegerItem 12
/StringItem (a string)
/Subdictionary << /Item1 0.4
/Item2 true
/LastItem (not!)
/VeryLastItem (OK)
>>
>>"""
reader = PDFObjectReader(BytesIO(input))
result = reader.next_item()
expected = cos.Dictionary([('Type', cos.Name('Example')),
('Subtype', cos.Name('DictionaryExample')),
('Version', cos.Real(0.01)),
('IntegerItem', cos.Integer(12)),
('StringItem', cos.String('a string')),
('Subdictionary', cos.Dictionary(
[('Item1', cos.Real(0.4)),
('Item2', cos.Boolean(True)),
('LastItem', cos.String('not!')),
('VeryLastItem', cos.String('OK'))]))])
assert isinstance(result, cos.Dictionary)
assert dict(result) == dict(expected)
|
brechtm/rinohtype
|
tests/test_pdf_reader.py
|
Python
|
agpl-3.0
| 3,238
|
<?php
declare(strict_types=1);
namespace unit;
use app\plugins\openslides\AutoupdateSyncService;
use app\plugins\openslides\controllers\AutoupdateController;
use app\plugins\openslides\DTO\LoginResponse;
use app\plugins\openslides\OpenslidesClient;
use app\plugins\openslides\SiteSettings;
use GuzzleHttp\{Client, Handler\MockHandler, HandlerStack, Middleware, Psr7\Request, Psr7\Response};
class OpenslidesClientTest extends TestBase
{
/** @var array */
protected $osApiHistory;
/** @var MockHandler */
protected $mockHandler;
private function getClient(): OpenslidesClient
{
$this->osApiHistory = [];
$history = Middleware::history($this->osApiHistory);
$this->mockHandler = new MockHandler();
$handlerStack = HandlerStack::create($this->mockHandler);
$handlerStack->push($history);
$guzzleClient = new Client(['handler' => $handlerStack]);
$siteSettings = new SiteSettings([]);
$siteSettings->osBaseUri = 'https://os.test/';
return new OpenslidesClient($siteSettings, $guzzleClient);
}
private function getRequestNo(int $no): Request
{
return $this->osApiHistory[$no]['request'];
}
public function testLoginResponse_Success()
{
$client = $this->getClient();
// This is the JSON returned by Openslides
$successJson = '{
"user_id":2,
"guest_enabled":false,
"user":{
"vote_weight":"1.000000",
"vote_delegated_from_users_id":[],
"is_active":true,
"number":"",
"last_email_send":null,
"is_committee":false,
"is_present":true,
"first_name":"Max",
"vote_delegated_to_id":null,
"gender":"",
"title":"",
"last_name":"Mustermann",
"email":"",
"groups_id":[2],
"comment":"",
"about_me":"",
"id":2,
"username":"demo",
"default_password":"demo",
"structure_level":"",
"auth_type":"default"
},
"auth_type":"default",
"permissions":[]
}';
$this->mockHandler->append(new Response(200, ['Content-Type' => 'application/json'], $successJson));
$loginResponse = $client->login('username', 'password');
$this->assertFalse($loginResponse->isGuestEnabled());
$this->assertSame(2, $loginResponse->getUserId());
$this->assertSame([2], $loginResponse->getUser()->getGroupsId());
$this->assertSame(2, $loginResponse->getUser()->getId());
$this->assertSame('demo', $loginResponse->getUser()->getUsername());
$this->assertSame('Max', $loginResponse->getUser()->getFirstName());
$this->assertSame('Mustermann', $loginResponse->getUser()->getLastName());
$this->assertSame([], $loginResponse->getUser()->getVoteDelegatedFromUsersId());
// This is the request we made to Openslides
$request = $this->getRequestNo(0);
$this->assertSame('apps/users/login/', $request->getUri()->getPath());
$this->assertJsonStringEqualsJsonString('{"username":"username","password":"password"}', $request->getBody()->getContents());
}
public function testParseAutoupdaterCallbackParsing()
{
$json = file_get_contents(__DIR__ . '/../_data/openslides-autoupdate-fullload.json');
$service = new AutoupdateSyncService();
$data = $service->parseRequest($json);
$this->assertCount(44, $data->getChanged()->getUsersUsers());
$this->assertCount(5, $data->getChanged()->getUsersGroups());
$this->assertSame(2, $data->getChanged()->getUsersGroups()[1]->getId());
$this->assertSame('Admin', $data->getChanged()->getUsersGroups()[1]->getName());
$this->assertSame([], $data->getChanged()->getUsersGroups()[1]->getPermissions());
$this->assertSame([5], $data->getChanged()->getUsersUsers()[43]->getGroupsId());
$this->assertSame('Vorstand', $data->getChanged()->getUsersUsers()[43]->getUsername());
$this->assertSame(43, $data->getChanged()->getUsersUsers()[43]->getId());
}
}
|
CatoTH/antragsgruen
|
tests/unit/OpenslidesClientTest.php
|
PHP
|
agpl-3.0
| 4,318
|
<?php
if (!defined('sugarEntry') || !sugarEntry) {
die('Not A Valid Entry Point');
}
/**
*
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
*
* SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd.
* Copyright (C) 2011 - 2018 SalesAgility Ltd.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
*/
global $mod_strings,$app_strings;
if(ACLController::checkAccess('Tasks', 'edit', true))$module_menu[]=Array("index.php?module=Tasks&action=EditView&return_module=Tasks&return_action=DetailView", $mod_strings['LNK_NEW_TASK'],"Create");
if(ACLController::checkAccess('Tasks', 'list', true))$module_menu[]=Array("index.php?module=Tasks&action=index&return_module=Tasks&return_action=DetailView", $mod_strings['LNK_TASK_LIST'],"List");
if(ACLController::checkAccess('Tasks', 'import', true))$module_menu[] =Array("index.php?module=Import&action=Step1&import_module=Tasks&return_module=Tasks&return_action=index", $mod_strings['LNK_IMPORT_TASKS'],"Import", 'Contacts');
|
willrennie/SuiteCRM
|
modules/Tasks/Menu.php
|
PHP
|
agpl-3.0
| 2,816
|
package nl.wietmazairac.bimql.get.attribute;
/******************************************************************************
* Copyright (C) 2009-2017 BIMserver.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 {@literal<http://www.gnu.org/licenses/>}.
*****************************************************************************/
import java.util.ArrayList;
import org.bimserver.models.ifc2x3tc1.IfcDraughtingPreDefinedCurveFont;
public class GetAttributeSubIfcDraughtingPreDefinedCurveFont {
// fields
private Object object;
private String string;
// constructors
public GetAttributeSubIfcDraughtingPreDefinedCurveFont(Object object, String string) {
this.object = object;
this.string = string;
}
// methods
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public ArrayList<Object> getResult() {
ArrayList<Object> resultList = new ArrayList<Object>();
if (string.equals("Name")) {
resultList.add(((IfcDraughtingPreDefinedCurveFont) object).getName());
//3String
}
else {
}
return resultList;
}
}
|
opensourceBIM/bimql
|
BimQL/src/nl/wietmazairac/bimql/get/attribute/GetAttributeSubIfcDraughtingPreDefinedCurveFont.java
|
Java
|
agpl-3.0
| 1,864
|
/**
* Copyright (C) 2015 3D Repo Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cstdlib>
#include <gtest/gtest.h>
#include <repo/core/model/bson/repo_node_revision.h>
#include <repo/core/model/bson/repo_bson_builder.h>
#include <repo/core/model/bson/repo_bson_factory.h>
#include "../../../../repo_test_utils.h"
using namespace repo::core::model;
/**
* Construct from mongo builder and mongo bson should give me the same bson
*/
TEST(RevisionNodeTest, Constructor)
{
RevisionNode empty;
EXPECT_TRUE(empty.isEmpty());
EXPECT_EQ(NodeType::REVISION, empty.getTypeAsEnum());
auto repoBson = RepoBSON(BSON("test" << "blah" << "test2" << 2));
auto fromRepoBSON = RevisionNode(repoBson);
EXPECT_EQ(NodeType::REVISION, fromRepoBSON.getTypeAsEnum());
EXPECT_EQ(fromRepoBSON.nFields(), repoBson.nFields());
EXPECT_EQ(0, fromRepoBSON.getFileList().size());
}
TEST(RevisionNodeTest, TypeTest)
{
RevisionNode node;
EXPECT_EQ(REPO_NODE_TYPE_REVISION, node.getType());
EXPECT_EQ(NodeType::REVISION, node.getTypeAsEnum());
}
TEST(RevisionNodeTest, PositionDependantTest)
{
RevisionNode node;
EXPECT_FALSE(node.positionDependant());
}
TEST(RevisionNodeTest, CloneAndUpdateStatusTest)
{
RevisionNode empty;
auto updatedEmpty = empty.cloneAndUpdateStatus(RevisionNode::UploadStatus::GEN_DEFAULT);
EXPECT_EQ(updatedEmpty.getUploadStatus(), RevisionNode::UploadStatus::GEN_DEFAULT);
auto updatedEmpty2 = updatedEmpty.cloneAndUpdateStatus(RevisionNode::UploadStatus::GEN_SEL_TREE);
EXPECT_EQ(updatedEmpty2.getUploadStatus(), RevisionNode::UploadStatus::GEN_SEL_TREE);
}
TEST(RevisionNodeTest, GetterTest)
{
RevisionNode empty;
EXPECT_TRUE(empty.getAuthor().empty());
auto offset = empty.getCoordOffset();
EXPECT_EQ(3, offset.size());
for (const auto &v : offset)
EXPECT_EQ(0, v);
EXPECT_EQ(0, empty.getCurrentIDs().size());
EXPECT_TRUE(empty.getMessage().empty());
EXPECT_TRUE(empty.getTag().empty());
EXPECT_EQ(RevisionNode::UploadStatus::COMPLETE, empty.getUploadStatus());
EXPECT_EQ(0, empty.getOrgFiles().size());
EXPECT_EQ(-1, empty.getTimestampInt64());
auto user = getRandomString(rand() % 10 + 1);
auto branch = repo::lib::RepoUUID::createUUID();
std::vector<repo::lib::RepoUUID> currentNodes, parents;
for (int i = 0; i < rand() % 10 + 1; ++i)
{
currentNodes.push_back(repo::lib::RepoUUID::createUUID());
parents.push_back(repo::lib::RepoUUID::createUUID());
}
std::vector<std::string> files = { getRandomString(rand() % 10 + 1), getRandomString(rand() % 10 + 1) };
std::vector<double> offsetIn = { rand() / 100.f, rand() / 100.f, rand() / 100.f };
auto message = getRandomString(rand() % 10 + 1);
auto tag = getRandomString(rand() % 10 + 1);
auto rId = repo::lib::RepoUUID::createUUID();
auto revisionNode = RepoBSONFactory::makeRevisionNode(user, branch, rId, currentNodes, files, parents, offsetIn, message, tag);
EXPECT_EQ(user, revisionNode.getAuthor());
auto offset2 = revisionNode.getCoordOffset();
EXPECT_EQ(offsetIn.size(), offset2.size());
for (uint32_t i = 0; i < offset2.size(); ++i)
EXPECT_EQ(offsetIn[i], offset2[i]);
auto currentNodesOut = revisionNode.getCurrentIDs();
EXPECT_EQ(currentNodes.size(), currentNodesOut.size());
EXPECT_EQ(message, revisionNode.getMessage());
EXPECT_EQ(tag, revisionNode.getTag());
EXPECT_EQ(RevisionNode::UploadStatus::COMPLETE, revisionNode.getUploadStatus());
auto filesOut = revisionNode.getOrgFiles();
EXPECT_EQ(files.size(), filesOut.size());
EXPECT_NE(-1, revisionNode.getTimestampInt64());
}
|
3drepo/3drepobouncer
|
test/src/unit/repo/core/model/bson/ut_repo_node_revision.cpp
|
C++
|
agpl-3.0
| 4,156
|
class AddDonorEmailToProjectDonations < ActiveRecord::Migration
def self.up
add_column :project_donations, :donor_email, :string
end
def self.down
remove_column :project_donations, :donor_email
end
end
|
PowerToChange/pat
|
db/migrate/20150521193039_add_donor_email_to_project_donations.rb
|
Ruby
|
agpl-3.0
| 219
|
---
"layout": contract
"datum podpisu": 2018-12-01
"datum účinnosti": 0000-00-00
"datum ukončení": 0000-00-00
"title": "NDA Petr Springfield"
"použité smluvní typy":
- NDA
"předmět": "Ochrana důvěrných informací"
"stav": v plnění
"náklady": 0
"místo uložení": Archiv strany
"smluvní strany":
-
"jméno": "Petr Springfield"
"bydliště": Moutnice
"narozen": 1998
"zástupce": Jana Koláříková
"funkce": Vedoucí Personálního odboru
"soubory":
-
"podepsaná verze": ndaspringinsfeld.pdf
"strojově čitelná verze": ndaspringinsfeld_anonymizováno.pdf
---
|
pirati-web/smlouvy.pirati.cz
|
smlouvy/2018/12/01/NDA-Springfield/index.html
|
HTML
|
agpl-3.0
| 597
|
{% extends 'base.html' %}
{% load i18n %}
{% load bootstrap_toolkit %}
{% load django_bootstrap_breadcrumbs %}
{% load tags %}
{% load static %}
{% block title %}{% trans "Edit your astrophotography gear" %}{% endblock %}
{% block breadcrumbs %}
{{ block.super }}
{% breadcrumb_safe 'Users' None %}
{% breadcrumb request.user.userprofile.get_display_name 'user_page' request.user.username %}
{% breadcrumb 'Settings' None %}
{% breadcrumb 'Gear' None %}
{% endblock %}
{% block content %}
<div class="row-fluid">
{% include 'user/profile/edit/navigation.html' %}
<div class="span9">
{% if READONLY_MODE %}
{% include 'readonly_mode.html' %}
{% else %}
{% for label, gear_items in prefill.items %}
{% list_gear label gear_items.0 gear_items.1 request.user %}
{% endfor %}
{% endif %} {# READONLY #}
</div> <!-- span9 -->
</div> <!-- row -->
{% endblock %}
{% block modals %}
<div class="modal hide fade" id="edit-gear-modal">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>{% trans "Edit gear item" %}</h3>
</div>
<div class="modal-body">
<div class="alert alert-warning">
<button class="close" data-dismiss="alert">×</button>
<h4 class="alert-heading">{% trans "Please note!" %}</h4>
{% blocktrans %}When you add or edit the make, the name, and the properties of this product, the data is global and shared between all AstroBin users. Do not write any information in there that refers to your personal copy of this product, like "modded", "sold", "broken", "a present from my aunt" and so on. {% endblocktrans %}
</div>
<form class="form-inline global" action="{% url 'save_gear_details' %}" method="post">{% csrf_token %}
<div class="form-content">
<div class="loading">
<img src="{% static 'astrobin/images/ajax-loader.gif' %}" alt=""/>
</div>
</div>
<input type="hidden" name="gear_id" value="" />
<div class="form-actions hidden">
<input type="submit" class="btn btn-primary" value="{% trans "Save" %}"/>
<input type="button" class="btn close-modal" value="{% trans "Close" %}"/>
</div>
</form>
<div class="well">
{% blocktrans %}The following information, instead, is personal, and may refer to your copy of this product.{% endblocktrans %}
</div>
<form class="form-inline custom" action="{% url 'save_gear_user_info' %}" method="post">{% csrf_token %}
<div class="form-content">
<div class="loading">
<img src="{% static 'astrobin/images/ajax-loader.gif' %}" alt=""/>
</div>
</div>
<input type="hidden" name="gear_id" value="" />
<div class="form-actions hidden">
<input type="submit" class="btn btn-primary" value="{% trans "Save" %}"/>
<input type="button" class="btn close-modal" value="{% trans "Close" %}"/>
</div>
</form>
</div>
</div>
<div class="modal hide fade" id="add-gear-modal">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>{% trans "Add gear item" %}</h3>
</div>
<div class="modal-body">
<div class="alert alert-warning">
<button class="close" data-dismiss="alert">×</button>
<h4 class="alert-heading">{% trans "Please note!" %}</h4>
{% blocktrans %}When you add or edit the make, the name, and the properties of this product, the data is global and shared between all AstroBin users. Do not write any information in there that refers to your personal copy of this product, like "modded", "sold", "broken", "a present from my aunt" and so on. {% endblocktrans %}
</div>
<form class="form-inline ajax" action="{% url 'save_gear_details' %}" method="post">{% csrf_token %}
<div class="form-content">
<div class="loading">
<img src="{% static 'astrobin/images/ajax-loader.gif' %}" alt=""/>
</div>
</div>
<div class="form-actions hidden">
<input type="submit" name="save" class="btn btn-primary" value="{% trans "Save" %}" />
</div>
</form>
</div>
</div>
{% endblock %}
{% block extra_js %}
<script language="javascript">
$(document).ready(function() {
$('.btn-gear .remove').live('click', function(event) {
event.preventDefault();
var $link = $(this);
var $btn = $link.closest('.btn-gear');
var id = $btn.attr('id');
$.ajax({
url: '/profile/edit/gear/remove/' + id + '/',
dataType: 'json',
timeout: 10000,
cache: false,
type: 'POST',
success: function() {
$link.tooltip('hide');
$btn.remove();
}
});
});
$('#add-gear-modal, #edit-gear-modal').on('hidden', function() {
$(this).find('.form-content').html('\
<div class="loading">\
<img src="{% static 'astrobin/images/ajax-loader.gif' %}" alt=""/>\
</div>'
);
$(this).find('.form-actions').addClass('hidden');
});
$('.btn-gear .edit').live('click', function(event) {
event.preventDefault();
var $btn_gear = $(this).closest('.btn-gear');
var id = $btn_gear.attr('id');
setTimeout(function() {
$.ajax({
url: '/get_edit_gear_form/' + id + '/',
dataType: 'json',
timeout: 10000,
cache: false,
success: function(data, textStatus, XMLHttpRequest) {
var $dlg = $('#edit-gear-modal');
var $form = $dlg.find('form.global');
$form.find('.form-content').html(data['form']);
$form.find('.btn-primary').removeClass('disabled');
$form.find('.btn-primary').removeAttr('disabled');
$form.find('.btn-primary').val("{% trans "Save" %}");
$form.find('input[name=gear_id]').val(id);
$form.find('.form-actions').removeClass('hidden');
$form.find('input, select').bind('change keyup', function(event) {
var $btn = $form.find('.btn-primary')
$btn.removeClass('disabled');
$btn.removeAttr('disabled');
$btn.val("{% trans "Save" %}");
});
$form.find('.close-modal').click(function(event) {
$dlg.modal('hide');
});
var ajaxFormOptions = {
dataType: 'json',
timeout: 10000,
beforeSubmit: function(formData, $form, options) {
var $btn = $form.find('.btn-primary')
$btn.addClass('disabled');
$btn.val("...");
},
success: function(responseJson, statusText, xhr, $form) {
var $btn = $form.find('.btn-primary')
$btn.removeClass('disabled');
$btn.removeAttr('disabled');
if (responseJson['success']) {
$btn.val("{% trans "Form saved. Thank you!" %}");
$btn_gear.find('.make').text($form.find('input[name=make]').val());
$btn_gear.find('.name').text($form.find('input[name=name]').val());
$.ajax({
url: '/get_is_gear_complete/' + id + '/',
dataType: 'json',
timeout: 10000,
cache: false,
success: function(data, textStatus, XMLHttpRequest) {
if (data['complete'])
$btn_gear.removeClass('incomplete');
else
$btn_gear.addClass('incomplete');
}
});
} else {
$form.find('.form-content').html(responseJson['form']);
$btn.removeClass('disabled');
$btn.removeAttr('disabled');
$btn.val("{% trans "Save" %}");
}
},
error: function(responseText, statusText, xhr, $form) {
var $btn = $form.find('.btn-primary')
$btn.removeClass('disabled');
$btn.removeAttr('disabled');
$btn.val("{% trans "Save" %}");
}
};
$form.ajaxForm(ajaxFormOptions);
},
error: function(XmlHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus);
}
});
}, 250);
setTimeout(function() {
$.ajax({
url: '/get_gear_user_info_form/' + id + '/',
dataType: 'json',
timeout: 10000,
cache: false,
success: function(data, textStatus, XMLHttpRequest) {
var $dlg = $('#edit-gear-modal');
var $form = $dlg.find('form.custom');
$form.find('.form-content').html(data['form']);
$form.find('input[name=gear_id]').val(id);
$form.find('.form-actions').removeClass('hidden');
$form.find('input, select').bind('change keyup', function(event) {
var $btn = $form.find('.btn-primary')
$btn.removeClass('disabled');
$btn.removeAttr('disabled');
$btn.val("{% trans "Save" %}");
});
$form.find('.close-modal').click(function(event) {
$dlg.modal('hide');
});
var ajaxFormOptions = {
dataType: 'json',
timeout: 10000,
cache: false,
beforeSubmit: function(formData, $form, options) {
var $btn = $form.find('.btn-primary')
$btn.addClass('disabled');
$btn.val("...");
},
success: function(responseJson, statusText, xhr, $form) {
var $btn = $form.find('.btn-primary')
$btn.removeClass('disabled');
$btn.removeAttr('disabled');
$btn.val("{% trans "Form saved. Thank you!" %}");
if (responseJson['success']) {
var alias = $form.find('input[name=alias]').val();
if (alias !== '')
$btn_gear.find('.alias').text('(' + alias + ')');
} else {
$form.find('.form-content').html(responseJson['form']);
}
},
error: function(responseText, statusText, xhr, $form) {
var $btn = $form.find('.btn-primary')
$btn.removeClass('disabled');
$btn.removeAttr('disabled');
$btn.val("{% trans "Save" %}");
}
};
$form.ajaxForm(ajaxFormOptions);
},
error: function(XmlHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus);
}
});
}, 500);
return false;
});
$('.add-gear').click(function(event) {
var $add_btn = $(this);
var gear_type = $add_btn.attr('data-klass');
setTimeout(function() {
$.ajax({
url: '/get_empty_edit_gear_form/' + gear_type + '/',
dataType: 'json',
timeout: 10000,
cache: false,
success: function(data, textStatus, XMLHttpRequest) {
var $dlg = $('#add-gear-modal'),
$form = $dlg.find('form');
$form.find('.form-content').html(data['form']);
$form.find('.btn-primary').removeClass('disabled');
$form.find('.btn-primary').removeAttr('disabled');
$form.find('.btn-primary').val("{% trans "Save" %}");
$form.find('.form-actions').removeClass('hidden');
var $make = $form.find('input[name=make]'),
$name = $form.find('input[name=name]');
$form.find('.form-content').append(
'<input type="hidden" name="gear_type" value="' + gear_type + '" />');
$make.attr('data-provide', 'typeahead');
$make.attr('autocomplete', 'off');
$name.attr('data-provide', 'typeahead');
$name.attr('autocomplete', 'off');
// Init autocomplete for appropriate gear type
$.ajax({
url: '/get-makes-by-type/' + gear_type + '/',
dataType: 'json',
timeout: 10000,
cache: false,
success: function(data, textStatus, XMLHttpRequest) {
var typeahead = $make.typeahead();
typeahead.data('typeahead').source = data.makes;
}
});
$name.focus(function(e) {
var make = $.trim($make.val());
if (make !== '') {
$.ajax({
url: '/gear/by-make/' + make + '/?klass=' + gear_type,
dataType: 'json',
timeout: 10000,
cache: false,
success: function(response, textStatus, XMLHttpRequest) {
$make.val(response.make);
var typeahead = $name.typeahead();
var gear_names = [];
for (var i = 0; i < response.gear.length; i++) {
gear_names.push(response.gear[i].name);
}
typeahead.data('typeahead').source = gear_names;
}
});
}
});
var ajaxFormOptions = {
dataType: 'json',
timeout: 10000,
cache: false,
beforeSubmit: function(formData, $form, options) {
var $btn = $form.find('input[name=save]')
$btn.addClass('disabled');
$btn.val("...");
},
success: function(responseJson, statusText, xhr, $form) {
var $btn = $form.find('input[name=save]')
$btn.removeClass('disabled');
$btn.removeAttr('disabled');
$btn.val("{% trans "Save" %}");
if (responseJson['success']) {
$dlg.modal('hide');
var template = '\
<div class="btn btn-gear">\
<div class="labels">\
<div class="make"></div>\
<div class="name"></div>\
<div class="alias"></div>\
</div>\
<div class="actions">\
<a href="#" class="remove" rel="tooltip" title="{% trans "Remove" %}">\
<i class="icon-trash"></i>\
</a>\
<a href="#edit-gear-modal" class="edit" data-toggle="modal" rel="tooltip" title="{% trans "Edit" %}">\
<i class="icon-pencil"></i>\
</a>\
</div>\
</div>'
var $new_button = $(template);
$new_button.attr('id', responseJson['id']);
$new_button.find('.make').text(responseJson['make']);
$new_button.find('.name').text(responseJson['name']);
$new_button.find('.alias').text('(' + responseJson['alias'] + ')');
if(responseJson['complete'] === false) {
$new_button.addClass('incomplete');
}
var $content = $add_btn.closest('.list-gear').find('.content');
$content.find('.no-gear').remove();
$content.append($new_button);
} else {
$form.find('.form-content').html(responseJson['form']);
$form.find('.form-content').append(
'<input type="hidden" name="gear_type" value="' + gear_type + '" />');
$form.find('input[name=make]').attr('data-provide', 'typeahead');
$form.find('input[name=make]').attr('data-source', '{{all_gear_makes|safe|addslashes}}');
$form.find('input[name=name]').attr('data-provide', 'typeahead');
$form.find('input[name=name]').attr('data-source', '{{all_gear_names|safe|addslashes}}');
if (responseJson.gear_id) {
$form.find('.form-content').append(
'<input type="hidden" name="gear_id" value="' + responseJson.gear_id + '" />');
}
if (responseJson.type === 'gear_type_missing') {
alert(responseJson.error);
}
}
},
error: function(responseText, statusText, xhr, $form) {
var $btn = $form.find('input[name=save]')
$btn.removeClass('disabled');
$btn.removeAttr('disabled');
$btn.val("{% trans "Save" %}");
}
};
$form.ajaxForm(ajaxFormOptions);
},
error: function(XmlHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus);
}
});
}, 250);
});
});
</script>
{% endblock %}
|
astrobin/astrobin
|
astrobin/templates/user/profile/edit/gear.html
|
HTML
|
agpl-3.0
| 21,863
|
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Enklave</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<!-- jQuery CDN -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<!-- jQuery local fallback -->
<script>
window.jQuery || document.write('<script src="/static/rest_framework/js/jquery-1.8.1-min.js"><\/script>')
</script>
<!-- Bootstrap JS CDN -->
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
<!-- Bootstrap JS local fallback -->
<script>
$.fn.modal || document.write('<script src="/static/rest_framework/js/bootstrap.min.js">\x3C/script>')
</script>
</head>
<body>
<div class="center-block row" style="padding-top:20px">
<div class="col-sm-4">
<h3 class="text-danger">You don't have a token!</h3>
</div>
</div>
</body>
</html>
|
TudorRosca/enklave
|
server/templates/no_token.html
|
HTML
|
agpl-3.0
| 966
|
<?php
/**
* Add default templates including default system template
*/
/**
* Define template contents
*/
$systemTemplate = <<<EOD
<div style="margin:0; text-align:center; width:100%; background:#EEE;min-width:240px;height:100%;"><br />
<div style="width:96%;margin:0 auto; border-top:6px solid #369;border-bottom: 6px solid #369;background:#DEF;" >
<h3 style="margin-top:5px;background-color:#69C; font-weight:normal; color:#FFF; text-align:center; margin-bottom:5px; padding:10px; line-height:1.2; font-size:21px; text-transform:capitalize;">[SUBJECT]</h3>
<div style="text-align:justify;background:#FFF;padding:20px; border-top:2px solid #369;min-height:200px;font-size:13px; border-bottom:2px solid #369;">[CONTENT]<div style="clear:both"></div></div>
<div style="clear:both;background:#69C;font-weight:normal; padding:10px;color:#FFF;text-align:center;font-size:11px;margin:5px 0px">[FOOTER]<br/>[SIGNATURE]</div>
</div>
<br /></div>
EOD;
/**
* Really Simple Free Responsive HTML Email Template
* @author Lee Munroe
* @author Angel Gonzalez
* @link https://github.com/algzb/responsive-html-email-template-for-PHPLIST
* @link https://github.com/leemunroe/responsive-html-email-template
* @license
*
* The MIT License (MIT)
*
* Copyright (c) [2013] [Lee Munroe]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
$simpleResponsiveTemplate = <<<EOD
<!doctype html>
<html>
<head><meta name="viewport" content="width=device-width" /><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>[SUBJECT]</title>
<style type="text/css">/* -------------------------------------
GLOBAL RESETS
------------------------------------- */
/*All the styling goes here*/
img {
border: none;
-ms-interpolation-mode: bicubic;
max-width: 100%;
}
/* -------------------------------------
BODY & CONTAINER
------------------------------------- */
.body {
background-color: #f6f6f6;
width: 100%;
}
/* Set a max-width, and make it display as block so it will automatically stretch to that width, but will also shrink down on a phone or something */
.templatecontainer {
display: block;
margin: 0 auto !important;
/* makes it centered */
max-width: 580px;
padding: 10px;
width: 580px;
}
.logo {
padding-bottom: 10px;
}
/* This should also be a block element, so that it will fill 100% of the .container */
.templatecontent {
box-sizing: border-box;
display: block;
margin: 0 auto;
max-width: 580px;
padding: 10px;
}
/* -------------------------------------
HEADER, FOOTER, MAIN
------------------------------------- */
.main {
background: #ffffff;
border-radius: 3px;
width: 100%;
}
.wrapper {
box-sizing: border-box;
padding: 20px;
}
.templatecontent-block {
padding-bottom: 10px;
padding-top: 10px;
}
.footer {
clear: both;
margin-top: 10px;
text-align: center;
width: 100%;
}
.footer td,
.footer p,
.footer span,
.footer a {
color: #999999;
font-size: 12px;
text-align: center;
}
/* -------------------------------------
TYPOGRAPHY
------------------------------------- */
h1,
h2,
h3,
h4 {
color: #000000;
font-family: sans-serif;
font-weight: 400;
line-height: 1.4;
margin: 0;
margin-bottom: 30px;
}
h1 {
font-size: 35px;
font-weight: 300;
text-align: center;
text-transform: capitalize;
}
p,
ul,
ol {
font-family: sans-serif;
font-size: 14px;
font-weight: normal;
margin: 0;
margin-bottom: 15px;
}
p li,
ul li,
ol li {
list-style-position: inside;
margin-left: 5px;
}
/* -------------------------------------
BUTTONS
------------------------------------- */
.templatebtn {
box-sizing: border-box;
width: 100%; }
.templatebtn > tbody > tr > td {
padding-bottom: 15px; }
.templatebtn table {
width: auto;
}
.templatebtn table td {
background-color: #ffffff;
border-radius: 5px;
text-align: center;
}
.templatebtn a {
background-color: #ffffff;
border: solid 1px #3498db;
border-radius: 5px;
box-sizing: border-box;
color: #3498db;
cursor: pointer;
display: inline-block;
font-size: 14px;
font-weight: bold;
margin: 0;
padding: 12px 25px;
text-decoration: none;
text-transform: capitalize;
}
.templatebtn-primary table td {
background-color: #3498db;
}
.templatebtn-primary a {
background-color: #3498db;
border-color: #3498db;
color: #ffffff;
}
/* -------------------------------------
OTHER STYLES THAT MIGHT BE USEFUL
------------------------------------- */
.last {
margin-bottom: 0;
}
.first {
margin-top: 0;
}
.align-center {
text-align: center;
}
.align-right {
text-align: right;
}
.align-left {
text-align: left;
}
.clear {
clear: both;
}
.mt0 {
margin-top: 0;
}
.mb0 {
margin-bottom: 0;
}
.preheader {
color: transparent;
display: none;
height: 0;
max-height: 0;
max-width: 0;
opacity: 0;
overflow: hidden;
mso-hide: all;
visibility: hidden;
width: 0;
}
.powered-by a {
text-decoration: none;
}
hr {
border: 0;
border-bottom: 1px solid #f6f6f6;
margin: 20px 0;
}
/* -------------------------------------
RESPONSIVE AND MOBILE FRIENDLY STYLES
------------------------------------- */
@media only screen and (max-width: 620px) {
table[class=body] h1 {
font-size: 28px !important;
margin-bottom: 10px !important;
}
table[class=body] p,
table[class=body] ul,
table[class=body] ol,
table[class=body] td,
table[class=body] span,
table[class=body] a {
font-size: 16px !important;
}
table[class=body] .wrapper,
table[class=body] .article {
padding: 10px !important;
}
table[class=body] .templatecontent {
padding: 0 !important;
}
table[class=body] .templatecontainer {
padding: 0 !important;
width: 100% !important;
}
table[class=body] .main {
border-left-width: 0 !important;
border-radius: 0 !important;
border-right-width: 0 !important;
}
table[class=body] .templatebtn table {
width: 100% !important;
}
table[class=body] .templatebtn a {
width: 100% !important;
}
table[class=body] .img-responsive {
height: auto !important;
max-width: 100% !important;
width: auto !important;
}
}
/* -------------------------------------
PRESERVE THESE STYLES IN THE HEAD
------------------------------------- */
@media all {
.ExternalClass {
width: 100%;
}
.ExternalClass,
.ExternalClass p,
.ExternalClass span,
.ExternalClass font,
.ExternalClass td,
.ExternalClass div {
line-height: 100%;
}
.apple-link a {
font-family: inherit !important;
font-size: inherit !important;
font-weight: bold !important;
line-height: inherit !important;
}
.templatebtn-primary table td:hover {
background-color: #34495e !important;
}
.templatebtn-primary a:hover {
background-color: #34495e !important;
border-color: #34495e !important;
}
}
</style>
</head>
<body style=" background-color: #f6f6f6;font-family: sans-serif;-webkit-font-smoothing: antialiased;font-size: 14px;line-height: 1.4;margin: 0;padding: 0;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<p> </p>
<table border="0" cellpadding="0" cellspacing="0" class="body" role="presentation" style="border-collapse: separate;mso-table-lspace: 0pt;mso-table-rspace: 0pt;width: 100%;">
<tbody>
<tr>
<td style="font-family: sans-serif;font-size: 14px;vertical-align: top;"> </td>
<td class="container" style="font-family: sans-serif;font-size: 14px;vertical-align: top;">
<div class="templatecontent">
<div class="logo">
<center><img src="[LOGO]" /></center>
</div>
<!-- START CENTERED WHITE CONTAINER -->
<table class="main" role="presentation" style="border-collapse: separate;mso-table-lspace: 0pt;mso-table-rspace: 0pt;width: 100%;"><!-- START MAIN CONTENT AREA -->
<tbody>
<tr>
<td class="wrapper" style="font-family: sans-serif;font-size: 14px;vertical-align: top;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="border-collapse: separate;mso-table-lspace: 0pt;mso-table-rspace: 0pt;width: 100%;">
<tbody>
<tr>
<td style="font-family: sans-serif;font-size: 14px;vertical-align: top;">
<span class="preheader">This is preheader text. Some clients will show this text as a preview.</span>
[CONTENT]
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<!-- END MAIN CONTENT AREA -->
</tbody>
</table>
<!-- START FOOTER -->
<div class="footer">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="border-collapse: separate;mso-table-lspace: 0pt;mso-table-rspace: 0pt;width: 100%;">
<tbody>
<tr>
<td class="templatecontent-block" style="font-family: sans-serif;font-size: 13px;vertical-align: top;">
<span class="apple-link">[FOOTER]</span>
<div>
<div style="color: #3498db; text-decoration: underline;">[CONTACT]</div>|<div>
<a href="[FORWARDURL]" style="color: #3498db; text-decoration: underline;">Forward this message</a></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- END FOOTER --><!-- END CENTERED WHITE CONTAINER --></div>
</td>
<td> </td>
</tr>
</tbody>
</table>
</body>
</html>
EOD;
/**
* Handle requests to add template
*/
if (isset($_POST['Submit'])) {
$radioVal = $_POST['template'];
switch ($radioVal) {
case 'systemTemplate':
$title = "System template";
$content = $systemTemplate;
break;
case 'simpleResponsiveTemplate':
$title = "Simple responsive template";
$content = $simpleResponsiveTemplate;
break;
}
$exists = Sql_Fetch_Row_Query(sprintf('
select
*
from
%s
where
title = "%s"'
, $GLOBALS['tables']['template']
, $title
));
if ($exists[0]) {
$messages = '<div class="actionresult alert alert-warning">';
$messages .= s('This default template already exists');
$messages .= '</div>';
echo $messages;
echo '<p>';
echo PageLinkButton('templates', s('Go back to templates'));
echo '</p>';
} else {
Sql_Query(sprintf('insert into %s (title,template,listorder) values("%s","%s",0)',
$GLOBALS['tables']['template'], $title, addslashes($content)));
$newid = Sql_Insert_Id();
if ($title === 'System template') {
saveConfig('systemmessagetemplate', $newid);
}
$messages = '<div class="actionresult alert alert-success">';
$messages .= s('The selected default template has been added as template with ID') . ' ' . $newid . ' ';
$messages .= '</div>';
echo $messages;
echo '<p>';
echo '' . PageLinkButton('templates', s('Go back to templates')) . '';
echo '' . PageLinkButton('template&id=' . $newid, s('Edit the added template')) . '';
echo '</p>';
}
}
/**
* Print page contents
*/
echo '<h2>'.s('Default templates suite').'</h2>';
echo formStart();
echo '
<div>
<input type="radio" name="template" value="systemTemplate" checked>System template<br>
<input type="radio" name="template" value="simpleResponsiveTemplate">Simple responsive template<br>
<input type="submit" value="Select" name="Submit">
</form>
</div>';
|
bramley/phplist3
|
public_html/lists/admin/defaultsystemtemplate.php
|
PHP
|
agpl-3.0
| 15,628
|
/*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2019 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.rgaa32017;
import org.asqatasun.ruleimplementation.AbstractNotTestedRuleImplementation;
/**
* Implementation of the rule 1.3.11 of the referential RGAA 3.2017
*
* For more details about the implementation, refer to <a href="https://doc.asqatasun.org/en/90_Rules/rgaa3.2017/01.Images/Rule-1-3-11.html">the rule 1.3.11 design page.</a>
* @see <a href="http://references.modernisation.gouv.fr/rgaa-accessibilite/criteres.html#test-1-3-11">1.3.11 rule specification</a>
*
* @author
*/
public class Rgaa32017Rule010311 extends AbstractNotTestedRuleImplementation {
/**
* Default constructor
*/
public Rgaa32017Rule010311 () {
super();
}
}
|
dzc34/Asqatasun
|
rules/rules-rgaa3.2017/src/main/java/org/asqatasun/rules/rgaa32017/Rgaa32017Rule010311.java
|
Java
|
agpl-3.0
| 1,523
|
package Moose::Exporter;
use strict;
use warnings;
our $VERSION = '0.79';
$VERSION = eval $VERSION;
our $AUTHORITY = 'cpan:STEVAN';
use Class::MOP;
use List::MoreUtils qw( first_index uniq );
use Moose::Util::MetaRole;
use Sub::Exporter;
use Sub::Name qw(subname);
my %EXPORT_SPEC;
sub setup_import_methods {
my ( $class, %args ) = @_;
my $exporting_package = $args{exporting_package} ||= caller();
my ( $import, $unimport ) = $class->build_import_methods(%args);
no strict 'refs';
*{ $exporting_package . '::import' } = $import;
*{ $exporting_package . '::unimport' } = $unimport;
}
sub build_import_methods {
my ( $class, %args ) = @_;
my $exporting_package = $args{exporting_package} ||= caller();
$EXPORT_SPEC{$exporting_package} = \%args;
my @exports_from = $class->_follow_also( $exporting_package );
my $export_recorder = {};
my ( $exports, $is_removable )
= $class->_make_sub_exporter_params(
[ @exports_from, $exporting_package ], $export_recorder );
my $exporter = Sub::Exporter::build_exporter(
{
exports => $exports,
groups => { default => [':all'] }
}
);
# $args{_export_to_main} exists for backwards compat, because
# Moose::Util::TypeConstraints did export to main (unlike Moose &
# Moose::Role).
my $import = $class->_make_import_sub( $exporting_package, $exporter,
\@exports_from, $args{_export_to_main} );
my $unimport = $class->_make_unimport_sub( $exporting_package, $exports,
$is_removable, $export_recorder );
return ( $import, $unimport )
}
{
my $seen = {};
sub _follow_also {
my $class = shift;
my $exporting_package = shift;
local %$seen = ( $exporting_package => 1 );
return uniq( _follow_also_real($exporting_package) );
}
sub _follow_also_real {
my $exporting_package = shift;
die "Package in also ($exporting_package) does not seem to use Moose::Exporter"
unless exists $EXPORT_SPEC{$exporting_package};
my $also = $EXPORT_SPEC{$exporting_package}{also};
return unless defined $also;
my @also = ref $also ? @{$also} : $also;
for my $package (@also)
{
die "Circular reference in also parameter to Moose::Exporter between $exporting_package and $package"
if $seen->{$package};
$seen->{$package} = 1;
}
return @also, map { _follow_also_real($_) } @also;
}
}
sub _make_sub_exporter_params {
my $class = shift;
my $packages = shift;
my $export_recorder = shift;
my %exports;
my %is_removable;
for my $package ( @{$packages} ) {
my $args = $EXPORT_SPEC{$package}
or die "The $package package does not use Moose::Exporter\n";
for my $name ( @{ $args->{with_caller} } ) {
my $sub = do {
no strict 'refs';
\&{ $package . '::' . $name };
};
my $fq_name = $package . '::' . $name;
$exports{$name} = $class->_make_wrapped_sub(
$fq_name,
$sub,
$export_recorder,
);
$is_removable{$name} = 1;
}
for my $name ( @{ $args->{as_is} } ) {
my $sub;
if ( ref $name ) {
$sub = $name;
# Even though Moose re-exports things from Carp &
# Scalar::Util, we don't want to remove those at
# unimport time, because the importing package may
# have imported them explicitly ala
#
# use Carp qw( confess );
#
# This is a hack. Since we can't know whether they
# really want to keep these subs or not, we err on the
# safe side and leave them in.
my $coderef_pkg;
( $coderef_pkg, $name ) = Class::MOP::get_code_info($name);
$is_removable{$name} = $coderef_pkg eq $package ? 1 : 0;
}
else {
$sub = do {
no strict 'refs';
\&{ $package . '::' . $name };
};
$is_removable{$name} = 1;
}
$export_recorder->{$sub} = 1;
$exports{$name} = sub {$sub};
}
}
return ( \%exports, \%is_removable );
}
our $CALLER;
sub _make_wrapped_sub {
my $self = shift;
my $fq_name = shift;
my $sub = shift;
my $export_recorder = shift;
# We need to set the package at import time, so that when
# package Foo imports has(), we capture "Foo" as the
# package. This lets other packages call Foo::has() and get
# the right package. This is done for backwards compatibility
# with existing production code, not because this is a good
# idea ;)
return sub {
my $caller = $CALLER;
my $wrapper = $self->_make_wrapper($caller, $sub, $fq_name);
my $sub = subname($fq_name => $wrapper);
$export_recorder->{$sub} = 1;
return $sub;
};
}
sub _make_wrapper {
my $class = shift;
my $caller = shift;
my $sub = shift;
my $fq_name = shift;
my $wrapper = sub { $sub->($caller, @_) };
if (my $proto = prototype $sub) {
# XXX - Perl's prototype sucks. Use & to make set_prototype
# ignore the fact that we're passing a "provate variable"
&Scalar::Util::set_prototype($wrapper, $proto);
}
return $wrapper;
}
sub _make_import_sub {
shift;
my $exporting_package = shift;
my $exporter = shift;
my $exports_from = shift;
my $export_to_main = shift;
return sub {
# I think we could use Sub::Exporter's collector feature
# to do this, but that would be rather gross, since that
# feature isn't really designed to return a value to the
# caller of the exporter sub.
#
# Also, this makes sure we preserve backwards compat for
# _get_caller, so it always sees the arguments in the
# expected order.
my $traits;
( $traits, @_ ) = _strip_traits(@_);
my $metaclass;
( $metaclass, @_ ) = _strip_metaclass(@_);
# Normally we could look at $_[0], but in some weird cases
# (involving goto &Moose::import), $_[0] ends as something
# else (like Squirrel).
my $class = $exporting_package;
$CALLER = _get_caller(@_);
# this works because both pragmas set $^H (see perldoc
# perlvar) which affects the current compilation -
# i.e. the file who use'd us - which is why we don't need
# to do anything special to make it affect that file
# rather than this one (which is already compiled)
strict->import;
warnings->import;
# we should never export to main
if ( $CALLER eq 'main' && !$export_to_main ) {
warn
qq{$class does not export its sugar to the 'main' package.\n};
return;
}
my $did_init_meta;
for my $c ( grep { $_->can('init_meta') } $class, @{$exports_from} ) {
# init_meta can apply a role, which when loaded uses
# Moose::Exporter, which in turn sets $CALLER, so we need
# to protect against that.
local $CALLER = $CALLER;
$c->init_meta( for_class => $CALLER, metaclass => $metaclass );
$did_init_meta = 1;
}
if ( $did_init_meta && @{$traits} ) {
# The traits will use Moose::Role, which in turn uses
# Moose::Exporter, which in turn sets $CALLER, so we need
# to protect against that.
local $CALLER = $CALLER;
_apply_meta_traits( $CALLER, $traits );
}
elsif ( @{$traits} ) {
require Moose;
Moose->throw_error(
"Cannot provide traits when $class does not have an init_meta() method"
);
}
goto $exporter;
};
}
sub _strip_traits {
my $idx = first_index { $_ eq '-traits' } @_;
return ( [], @_ ) unless $idx >= 0 && $#_ >= $idx + 1;
my $traits = $_[ $idx + 1 ];
splice @_, $idx, 2;
$traits = [ $traits ] unless ref $traits;
return ( $traits, @_ );
}
sub _strip_metaclass {
my $idx = first_index { $_ eq '-metaclass' } @_;
return ( undef, @_ ) unless $idx >= 0 && $#_ >= $idx + 1;
my $metaclass = $_[ $idx + 1 ];
splice @_, $idx, 2;
return ( $metaclass, @_ );
}
sub _apply_meta_traits {
my ( $class, $traits ) = @_;
return unless @{$traits};
my $meta = Class::MOP::class_of($class);
my $type = ( split /::/, ref $meta )[-1]
or Moose->throw_error(
'Cannot determine metaclass type for trait application . Meta isa '
. ref $meta );
my @resolved_traits
= map { Moose::Util::resolve_metatrait_alias( $type => $_ ) }
@$traits;
return unless @resolved_traits;
Moose::Util::MetaRole::apply_metaclass_roles(
for_class => $class,
metaclass_roles => \@resolved_traits,
);
}
sub _get_caller {
# 1 extra level because it's called by import so there's a layer
# of indirection
my $offset = 1;
return
( ref $_[1] && defined $_[1]->{into} ) ? $_[1]->{into}
: ( ref $_[1] && defined $_[1]->{into_level} )
? caller( $offset + $_[1]->{into_level} )
: caller($offset);
}
sub _make_unimport_sub {
shift;
my $exporting_package = shift;
my $exports = shift;
my $is_removable = shift;
my $export_recorder = shift;
return sub {
my $caller = scalar caller();
Moose::Exporter->_remove_keywords(
$caller,
[ keys %{$exports} ],
$is_removable,
$export_recorder,
);
};
}
sub _remove_keywords {
shift;
my $package = shift;
my $keywords = shift;
my $is_removable = shift;
my $recorded_exports = shift;
no strict 'refs';
foreach my $name ( @{ $keywords } ) {
next unless $is_removable->{$name};
if ( defined &{ $package . '::' . $name } ) {
my $sub = \&{ $package . '::' . $name };
# make sure it is from us
next unless $recorded_exports->{$sub};
# and if it is from us, then undef the slot
delete ${ $package . '::' }{$name};
}
}
}
sub import {
strict->import;
warnings->import;
}
1;
__END__
=head1 NAME
Moose::Exporter - make an import() and unimport() just like Moose.pm
=head1 SYNOPSIS
package MyApp::Moose;
use Moose ();
use Moose::Exporter;
Moose::Exporter->setup_import_methods(
with_caller => [ 'has_rw', 'sugar2' ],
as_is => [ 'sugar3', \&Some::Random::thing ],
also => 'Moose',
);
sub has_rw {
my ($caller, $name, %options) = @_;
Class::MOP::Class->initialize($caller)->add_attribute($name,
is => 'rw',
%options,
);
}
# then later ...
package MyApp::User;
use MyApp::Moose;
has 'name';
has_rw 'size';
thing;
no MyApp::Moose;
=head1 DESCRIPTION
This module encapsulates the exporting of sugar functions in a
C<Moose.pm>-like manner. It does this by building custom C<import> and
C<unimport> methods for your module, based on a spec you provide.
It also lets you "stack" Moose-alike modules so you can export
Moose's sugar as well as your own, along with sugar from any random
C<MooseX> module, as long as they all use C<Moose::Exporter>.
To simplify writing exporter modules, C<Moose::Exporter> also imports
C<strict> and C<warnings> into your exporter module, as well as into
modules that use it.
=head1 METHODS
This module provides two public methods:
=over 4
=item B<< Moose::Exporter->setup_import_methods(...) >>
When you call this method, C<Moose::Exporter> build custom C<import>
and C<unimport> methods for your module. The import method will export
the functions you specify, and you can also tell it to export
functions exported by some other module (like C<Moose.pm>).
The C<unimport> method cleans the callers namespace of all the
exported functions.
This method accepts the following parameters:
=over 8
=item * with_caller => [ ... ]
This a list of function I<names only> to be exported wrapped and then
exported. The wrapper will pass the name of the calling package as the
first argument to the function. Many sugar functions need to know
their caller so they can get the calling package's metaclass object.
=item * as_is => [ ... ]
This a list of function names or sub references to be exported
as-is. You can identify a subroutine by reference, which is handy to
re-export some other module's functions directly by reference
(C<\&Some::Package::function>).
If you do export some other packages function, this function will
never be removed by the C<unimport> method. The reason for this is we
cannot know if the caller I<also> explicitly imported the sub
themselves, and therefore wants to keep it.
=item * also => $name or \@names
This is a list of modules which contain functions that the caller
wants to export. These modules must also use C<Moose::Exporter>. The
most common use case will be to export the functions from C<Moose.pm>.
Functions specified by C<with_caller> or C<as_is> take precedence over
functions exported by modules specified by C<also>, so that a module
can selectively override functions exported by another module.
C<Moose::Exporter> also makes sure all these functions get removed
when C<unimport> is called.
=back
=item B<< Moose::Exporter->build_import_methods(...) >>
Returns two code refs, one for import and one for unimport.
Used by C<setup_import_methods>.
=back
=head1 IMPORTING AND init_meta
If you want to set an alternative base object class or metaclass
class, simply define an C<init_meta> method in your class. The
C<import> method that C<Moose::Exporter> generates for you will call
this method (if it exists). It will always pass the caller to this
method via the C<for_class> parameter.
Most of the time, your C<init_meta> method will probably just call C<<
Moose->init_meta >> to do the real work:
sub init_meta {
shift; # our class name
return Moose->init_meta( @_, metaclass => 'My::Metaclass' );
}
=head1 METACLASS TRAITS
The C<import> method generated by C<Moose::Exporter> will allow the
user of your module to specify metaclass traits in a C<-traits>
parameter passed as part of the import:
use Moose -traits => 'My::Meta::Trait';
use Moose -traits => [ 'My::Meta::Trait', 'My::Other::Trait' ];
These traits will be applied to the caller's metaclass
instance. Providing traits for an exporting class that does not create
a metaclass for the caller is an error.
=head1 AUTHOR
Dave Rolsky E<lt>autarch@urth.orgE<gt>
This is largely a reworking of code in Moose.pm originally written by
Stevan Little and others.
=head1 COPYRIGHT AND LICENSE
Copyright 2009 by Infinity Interactive, Inc.
L<http://www.iinteractive.com>
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
|
pombredanne/paperpile
|
catalyst/perl5/linux64/cpan/Moose/Exporter.pm
|
Perl
|
agpl-3.0
| 15,454
|
define(function(require) {
'use strict';
var _ = require('underscore');
var Backbone = require('backbone');
var PrismBreakSimulation = require('models/simulation/prism-break');
var BendingLightSimView = require('views/sim');
var MediumControlsView = require('views/medium-controls');
var PrismBreakSceneView = require('views/scene/prism-break');
var PrismsPanelView = require('views/prisms-panel');
var PrismBreakControlsView = require('views/prism-break-controls');
var simHtml = require('text!templates/sim/prism-break.html');
/**
*
*/
var PrismBreakSimView = BendingLightSimView.extend({
template: _.template(simHtml),
events: _.extend(BendingLightSimView.prototype.events, {
}),
initialize: function(options) {
options = _.extend({
title: 'Prism Break',
name: 'prism-break'
}, options);
BendingLightSimView.prototype.initialize.apply(this, [ options ]);
this.initEnvironmentMediumControls();
},
/**
* Initializes the Simulation.
*/
initSimulation: function() {
this.simulation = new PrismBreakSimulation();
},
/**
* Initializes the SceneView.
*/
initSceneView: function() {
this.sceneView = new PrismBreakSceneView({
simulation: this.simulation
});
},
initEnvironmentMediumControls: function() {
this.environmentMediumControlsView = new MediumControlsView({
model: this.simulation.environment,
simulation: this.simulation,
name: 'environment',
label: 'Environment'
});
},
initPrismsPanel: function() {
this.prismsPanelView = new PrismsPanelView({
simulation: this.simulation,
prismImages: this.sceneView.getPrismIcons()
});
},
initPrismBreakControls: function() {
this.prismBreakControlsView = new PrismBreakControlsView({
simulation: this.simulation,
sceneView: this.sceneView
});
},
/**
* Resets the sim and options
*/
reset: function() {
BendingLightSimView.prototype.reset.apply(this);
this.prismBreakControlsView.reset();
},
render: function() {
BendingLightSimView.prototype.render.apply(this);
this.initPrismsPanel();
this.initPrismBreakControls();
this.prismsPanelView.render();
this.prismBreakControlsView.render();
this.environmentMediumControlsView.render();
this.$el.append(this.prismsPanelView.el);
this.$el.append(this.prismBreakControlsView.el);
this.$el.append(this.environmentMediumControlsView.el);
return this;
},
postRender: function() {
BendingLightSimView.prototype.postRender.apply(this);
this.prismBreakControlsView.postRender();
}
});
return PrismBreakSimView;
});
|
Connexions/simulations
|
bending-light/src/js/views/sim/prism-break.js
|
JavaScript
|
agpl-3.0
| 3,295
|
pub use rust_sodium::crypto::box_::curve25519xsalsa20poly1305 as crypto_box;
pub use rust_sodium::crypto::hash::sha256;
pub use rust_sodium::crypto::scalarmult::curve25519 as scalarmult;
pub use self::crypto_box::{PrecomputedKey, PublicKey, SecretKey};
use auth_failure::AuthFailure;
/// Number of bytes in a password digest.
pub const PASSWORD_DIGEST_BYTES: usize = sha256::DIGESTBYTES;
/// Implements the fancy password hashing used by the FCP, decribed in paragraph 4
/// of https://github.com/fc00/spec/blob/10b349ab11/cryptoauth.md#hello-repeathello
pub fn shared_secret_from_password(
password: &[u8],
my_perm_sk: &SecretKey,
their_perm_pk: &PublicKey,
) -> PrecomputedKey {
assert_eq!(scalarmult::SCALARBYTES, crypto_box::PUBLICKEYBYTES);
assert_eq!(scalarmult::GROUPELEMENTBYTES, crypto_box::SECRETKEYBYTES);
let product = scalarmult::scalarmult(
&scalarmult::Scalar::from_slice(&my_perm_sk.0).unwrap(),
&scalarmult::GroupElement::from_slice(&their_perm_pk.0).unwrap(),
)
.expect("their_perm_pk should not be zeroed");
let mut shared_secret_preimage = product.0.to_vec();
shared_secret_preimage.extend(&sha256::hash(password).0);
let shared_secret = sha256::hash(&shared_secret_preimage).0;
PrecomputedKey::from_slice(&shared_secret).unwrap()
}
/// AuthNone Hello packets: my_sk and their_pk are permanent keys
/// Key packets: my_sk is permanent, their_pk is temporary
/// data packets: my_sk and their_pk are temporary keys
pub fn shared_secret_from_keys(my_sk: &SecretKey, their_pk: &PublicKey) -> PrecomputedKey {
crypto_box::precompute(their_pk, my_sk)
}
/// unseals the concatenation of fields msg_auth_code, sender_encrypted_temp_pk, and
/// encrypted_data of a packet.
/// If authentication was successful, returns the sender's temp_pk and the
/// data, unencrypted.
pub fn open_packet_end(
packet_end: &[u8],
shared_secret: &PrecomputedKey,
nonce: &crypto_box::Nonce,
) -> Result<(PublicKey, Vec<u8>), AuthFailure> {
if packet_end.len() < crypto_box::MACBYTES {
return Err(AuthFailure::PacketTooShort(format!(
"Packet end: {}",
packet_end.len()
)));
}
match crypto_box::open_precomputed(packet_end, nonce, &shared_secret) {
Err(_) => Err(AuthFailure::CorruptedPacket(
"Could not decrypt handshake packet end.".to_owned(),
)),
Ok(buf) => {
let mut pk = [0u8; crypto_box::PUBLICKEYBYTES];
pk.copy_from_slice(&buf[0..crypto_box::PUBLICKEYBYTES]);
let their_temp_pk = PublicKey::from_slice(&pk).unwrap();
let data = buf[crypto_box::PUBLICKEYBYTES..].to_vec();
Ok((their_temp_pk, data))
}
}
}
/// Randomly generates a secret key and a corresponding public key.
///
/// THREAD SAFETY: `gen_keypair()` is thread-safe provided that you
/// have called `fcp_cryptoauth::init()` (or `rust_sodium::init()`)
/// once before using any other function from `fcp_cryptoauth` or
/// `rust_sodium`.
pub fn gen_keypair() -> (PublicKey, SecretKey) {
crypto_box::gen_keypair()
}
|
rust-fcp/rust-fcp-cryptoauth
|
src/cryptography.rs
|
Rust
|
agpl-3.0
| 3,126
|
<?php
/*!
* This file is part of {@link https://github.com/MovLib MovLib}.
*
* Copyright © 2013-present {@link https://movlib.org/ MovLib}.
*
* MovLib 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.
*
* MovLib 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 MovLib.
* If not, see {@link http://www.gnu.org/licenses/ gnu.org/licenses}.
*/
namespace MovLib\Presentation\Award;
/**
* Random Award
*
* @author Richard Fussenegger <richard@fussenegger.info>
* @copyright © 2013 MovLib
* @license http://www.gnu.org/licenses/agpl.html AGPL-3.0
* @link https://movlib.org/
* @since 0.0.1-dev
*/
final class Random extends \MovLib\Presentation\AbstractRandomPresenter {
// @codingStandardsIgnoreStart
/**
* Short class name.
*
* @var string
*/
const name = "Random";
// @codingStandardsIgnoreEnd
}
|
MovLib/www
|
src/MovLib/Presentation/Award/Random.php
|
PHP
|
agpl-3.0
| 1,297
|
local ObjectManager = require("managers.object.object_manager")
local mapStringName = { "pirate1", "pirate2", "bountyhunter1", "hedon1" }
local treasureMapData = {
{ planet = "corellia", x = 3400, y = -1400 }, -- Pirate 1
{ planet = "naboo", x = -1900, y = -4000 }, -- Pirate 2
{ planet = "talus", x = 3800, y = -1000 }, -- Bounty Hunter
{ planet = "tatooine", x = 6700, y = 4240 } -- Scythe Schematic
}
local TREASURE_CHEST_LIFESPAN = 600000 --10 minutes
TreasureMapMenuComponent = { }
function TreasureMapMenuComponent:fillObjectMenuResponse(pSceneObject, pMenuResponse, pPlayer)
local menuResponse = LuaObjectMenuResponse(pMenuResponse)
menuResponse:addRadialMenuItem(120, 3, "@treasure_map/treasure_map:use") -- Read
menuResponse:addRadialMenuItem(121, 3, "@treasure_map/treasure_map:search_area") -- Search Area
menuResponse:addRadialMenuItem(122, 3, "@treasure_map/treasure_map:extract_treasure") -- Extract Treasure
end
function TreasureMapMenuComponent:handleObjectMenuSelect(pObject, pPlayer, selectedID)
if (pPlayer == nil or pObject == nil) then
return 0
end
if (SceneObject(pObject):isASubChildOf(pPlayer) == false) then
CreatureObject(pPlayer):sendSystemMessage("@treasure_map/treasure_map:sys_not_in_inv") -- The treasure map must be in your inventory for you to use it!
return 0
end
if (TreasureMapMenuComponent:getMapType(pObject) == 0) then
CreatureObject(pPlayer):sendSystemMessage("@treasure_map/treasure_map:map_fail") -- This map is obviously a fake.
return 0
end
if (selectedID == 120) then
TreasureMapMenuComponent:doReadMap(pObject, pPlayer)
elseif (selectedID == 121) then
TreasureMapMenuComponent:doSearchArea(pObject, pPlayer)
elseif (selectedID == 122) then
TreasureMapMenuComponent:doExtractTreasure(pObject, pPlayer)
end
return 0
end
function TreasureMapMenuComponent:doSearchArea(pObject, pPlayer)
if (pPlayer == nil or pObject == nil) then
return 0
end
local mapType = TreasureMapMenuComponent:getMapType(pObject)
ObjectManager.withCreatureAndPlayerObject(pPlayer, function(creature, player)
local mapData = treasureMapData[mapType]
local playerID = creature:getObjectID()
local waypointID = readData(playerID .. ":treasureMapSearchAreaWaypointID")
local searchAreaID = readData(playerID .. ":treasureMapSearchAreaActiveAreaID")
if (waypointID == 0 or searchAreaID == 0) then
creature:sendSystemMessage("@treasure_map/treasure_map:sys_no_waypoint") -- You must store the treasure's waypoint in your datapad before you can search for it!
return 0
end
if (TangibleObject(pPlayer):hasActiveArea(searchAreaID) == false) then
creature:sendSystemMessage("@treasure_map/treasure_map:sys_cant_pinpoint") -- You are not close enough to pinpoint the treasure's location.
return 0
end
local pWaypoint = getSceneObject(waypointID)
local pActiveArea = getSceneObject(searchAreaID)
SceneObject(pActiveArea):destroyObjectFromWorld()
local spawnPoint
ObjectManager.withSceneObject(pWaypoint, function(waypoint)
if (mapType == 4) then
spawnPoint = getSpawnPoint(pPlayer, waypoint:getWorldPositionX(), waypoint:getWorldPositionY(), 15, 30, true)
else
spawnPoint = getSpawnPoint(pPlayer, waypoint:getWorldPositionX(), waypoint:getWorldPositionY(), 30, 60)
end
end)
creature:sendSystemMessage("@treasure_map/treasure_map:sys_pinpoint") -- You have successfully pinpointed the exact location of the treasure!
local waypointID = player:addWaypoint(mapData.planet, "@treasure_map/treasure_map:waypoint_name", "", spawnPoint[1], spawnPoint[3], WAYPOINTGREEN, true, true, WAYPOINTTREASUREMAP, 0)
writeData(playerID .. ":treasureMapExactWaypointID", waypointID)
deleteData(playerID .. ":treasureMapSearchAreaWaypointID")
deleteData(playerID .. ":treasureMapSearchAreaActiveAreaID")
end)
end
function TreasureMapMenuComponent:doExtractTreasure(pObject, pPlayer)
if (pObject == nil or pPlayer == nil) then
return 0
end
local mapType = TreasureMapMenuComponent:getMapType(pObject)
local playerID = SceneObject(pPlayer):getObjectID()
local mapData = treasureMapData[mapType]
local waypointID = readData(playerID .. ":treasureMapExactWaypointID")
local x, z, y
local pWaypoint = getSceneObject(waypointID)
ObjectManager.withSceneObject(pWaypoint, function(waypoint)
x = waypoint:getWorldPositionX()
y = waypoint:getWorldPositionY()
z = getTerrainHeight(pPlayer, x, y)
end)
if (SceneObject(pPlayer):getDistanceToPosition(x, z, y) > 5) then
CreatureObject(pPlayer):sendSystemMessage("@treasure_map/treasure_map:sys_dist_far") -- You aren't close enough to extract the treasure.
return 0
end
local treasureChestID = readData(playerID .. ":treasureChestID")
if (treasureChestID ~= nil) then
local pExistingChest = getSceneObject(treasureChestID)
if (pExistingChest ~= nil) then
self:removeTreasureChest(pExistingChest)
end
end
CreatureObject(pPlayer):sendSystemMessage("@treasure_map/treasure_map:sys_found") -- You successfully extract the treasure!
local pChest = spawnSceneObject(mapData.planet, "object/tangible/container/drum/treasure_drum.iff", x, z, y, 0, 0, 0, 0, 0)
if (pChest ~= nil) then
local chestID = SceneObject(pChest):getObjectID()
writeData(playerID .. ":treasureChestID", chestID)
writeData(chestID .. ":ownerID", playerID)
SceneObject(pChest):setContainerOwnerID(playerID)
createObserver(OPENCONTAINER, "TreasureMapMenuComponent", "openChestEvent", pChest)
createObserver(CONTAINERCONTENTSCHANGED, "TreasureMapMenuComponent", "chestLootedEvent", pChest)
TreasureMapMenuComponent:spawnTreasureLoot(pChest, pPlayer, mapType)
createEvent(TREASURE_CHEST_LIFESPAN, "TreasureMapMenuComponent", "removeTreasureChest", pChest)
end
TreasureMapMenuComponent:spawnTreasureDefenders(pObject, pPlayer, x, z, y, mapType)
SceneObject(pObject):destroyObjectFromWorld()
SceneObject(pObject):destroyObjectFromDatabase(true)
end
function TreasureMapMenuComponent:chestLootedEvent(pChest, pCreature)
if (pChest == nil) then
return 0
end
if (SceneObject(pChest):getContainerObjectsSize() == 0) then
TreasureMapMenuComponent:removeTreasureChest(pChest)
end
return 0
end
function TreasureMapMenuComponent:openChestEvent(pChest, pCreature)
if pCreature == nil or pChest == nil or not SceneObject(pCreature):isCreatureObject() then
return 0
end
local chestOwnerID = readData(SceneObject(pChest):getObjectID() .. ":ownerID")
local playerID = CreatureObject(pCreature):getObjectID()
if (chestOwnerID ~= playerID) then
CreatureObject(pCreature):sendSystemMessage("@treasure_map/treasure_map:sys_not_yours") -- That treasure chest doesn't belong to you.
return 0
end
local hasOpenedChest = readData(playerID .. ":hasOpenedChest")
if (hasOpenedChest ~= 1) then
local credits = getRandomNumber(500, 5000)
CreatureObject(pCreature):addCashCredits(credits, true)
CreatureObject(pCreature):sendSystemMessage("You find " .. credits .. " credits in the chest.")
writeData(playerID .. ":hasOpenedChest", 1)
end
return 0
end
function TreasureMapMenuComponent:spawnTreasureLoot(pChest, pPlayer, mapType)
if (pPlayer == nil or pChest == nil) then
return
end
if (mapType == 1 or mapType == 2 or mapType == 3) then
local playerLevelRange = getRandomNumber(CreatureObject(pPlayer):getLevel() - 5, CreatureObject(pPlayer):getLevel() + 5)
for i = 1, 5 do
createLoot(pChest, "treasure_map_group", playerLevelRange, false)
end
else
createLoot(pChest, "hedon_istee_treasure", 10, false)
end
end
function TreasureMapMenuComponent:spawnTreasureDefenders(pObject, pPlayer, x, z, y, mapType)
if (pObject == nil or pPlayer == nil) then
return
end
local mapType = TreasureMapMenuComponent:getMapType(pObject)
local mapData = treasureMapData[mapType]
local firstSpawnPoint, secondSpawnPoint, thirdSpawnPoint
if (mapType ~= 4) then
firstSpawnPoint = getSpawnPoint(pPlayer, x, y, 10, 20)
end
if (mapType == 1 or mapType == 2) then
secondSpawnPoint = getSpawnPoint(pPlayer, x, y, 10, 20)
thirdSpawnPoint = getSpawnPoint(pPlayer, x, y, 10, 20)
local pMobile = spawnMobile(mapData.planet, "pirate_leader", 0, firstSpawnPoint[1], firstSpawnPoint[2], firstSpawnPoint[3], 0, 0)
TreasureMapMenuComponent:setDefenderAggro(pMobile, pPlayer)
spatialChat(pMobile, "@treasure_map/treasure_map:bark_" .. mapStringName[mapType])
local pMobile2 = spawnMobile(mapData.planet, "pirate_armsman", 0, secondSpawnPoint[1], secondSpawnPoint[2], secondSpawnPoint[3], 0, 0)
TreasureMapMenuComponent:setDefenderAggro(pMobile2, pPlayer)
local pMobile3 = spawnMobile(mapData.planet, "pirate_armsman", 0, thirdSpawnPoint[1], thirdSpawnPoint[2], thirdSpawnPoint[3], 0, 0)
TreasureMapMenuComponent:setDefenderAggro(pMobile3, pPlayer)
elseif (mapType == 3) then
local pMobile = spawnMobile(mapData.planet, "bounty_hunter_thug", 0, firstSpawnPoint[1], firstSpawnPoint[2], firstSpawnPoint[3], 0, 0)
spatialChat(pMobile, "@treasure_map/treasure_map:bark_" .. mapStringName[mapType])
TreasureMapMenuComponent:setDefenderAggro(pMobile, pPlayer)
else
spawnMobile(mapData.planet, "canyon_krayt_dragon", 0, x, z, y, 0, 0)
end
end
function TreasureMapMenuComponent:setDefenderAggro(pCreature, pPlayer)
if (pCreature == nil) then
return
end
AiAgent(pCreature):setDefender(pPlayer)
end
function TreasureMapMenuComponent:removeTreasureChest(pChest)
if (pChest == nil) then
return
end
local chestID = SceneObject(pChest):getObjectID()
local chestOwnerID = readData(chestID .. ":ownerID")
local pOwner = getSceneObject(chestOwnerID)
ObjectManager.withCreaturePlayerObject(pOwner, function(owner)
owner:removeWaypointBySpecialType(WAYPOINTTREASUREMAP)
end)
deleteData(chestOwnerID .. ":treasureChestID")
deleteData(chestID .. ":ownerID")
SceneObject(pChest):destroyObjectFromWorld()
deleteData(chestOwnerID .. ":hasOpenedChest")
deleteData(chestOwnerID .. ":treasureMapExactWaypointID")
end
function TreasureMapMenuComponent:doReadMap(pObject, pPlayer)
if (pObject == nil or pPlayer == nil) then
return
end
local mapType = TreasureMapMenuComponent:getMapType(pObject)
local suiManager = LuaSuiManager()
suiManager:sendMessageBox(pObject, pPlayer, "@treasure_map/treasure_map:title_" .. mapStringName[mapType], "@treasure_map/treasure_map:text_" .. mapStringName[mapType], "@treasure_map/treasure_map:store_waypoint", "TreasureMapMenuComponent", "handleTreasureMapSuiCallback")
end
function TreasureMapMenuComponent:handleTreasureMapSuiCallback(pCreature, pSui, cancelPressed)
if (cancelPressed or pCreature == nil) then
return 0
end
local suiBox = LuaSuiBox(pSui)
local pUsingObject = suiBox:getUsingObject()
if (pUsingObject == nil) then
return 0
end
local mapType = TreasureMapMenuComponent:getMapType(pUsingObject)
ObjectManager.withCreatureAndPlayerObject(pCreature, function(creature, player)
local mapData = treasureMapData[mapType]
if (creature:getZoneName() ~= mapData.planet) then
creature:sendSystemMessage("@treasure_map/treasure_map:wrong_planet") -- The coordinates stored in the map data do not appear to be for this planet.
return 0
end
local playerID = creature:getObjectID()
local currentWaypointID = readData(playerID .. ":treasureMapSearchAreaWaypointID")
local exactWaypointID = readData(playerID .. ":treasureMapExactWaypointID")
local pExactWaypoint = getSceneObject(currentWaypointID)
local pWaypoint = getSceneObject(currentWaypointID)
if (pWaypoint ~= nil or pExactWaypoint ~= nil) then
creature:sendSystemMessage("@treasure_map/treasure_map:sys_waypoint_exists") -- A waypoint to this location already exists in your datapad.
return 0
end
local spawnPoint
if (mapType == 4) then
spawnPoint = getSpawnPoint(pCreature, mapData.x, mapData.y, 1, 50, true)
else
spawnPoint = getSpawnPoint(pCreature, mapData.x, mapData.y, 1, 2000)
end
local waypointID = player:addWaypoint(mapData.planet, "@treasure_map/treasure_map:waypoint_name", "", spawnPoint[1], spawnPoint[3], WAYPOINTGREEN, true, true, WAYPOINTTREASUREMAP, 0)
local activeAreaID = self:spawnSearchArea(mapType, pCreature, spawnPoint[1], spawnPoint[3])
writeData(playerID .. ":treasureMapSearchAreaWaypointID", waypointID)
writeData(playerID .. ":treasureMapSearchAreaActiveAreaID", activeAreaID)
end)
end
function TreasureMapMenuComponent:spawnSearchArea(mapType, pCreature, x, y)
if (pCreature == nil) then
return 0
end
local mapData = treasureMapData[mapType]
local z = getTerrainHeight(pCreature, x, y)
local pActiveArea = spawnActiveArea(mapData.planet, "object/active_area.iff", x, z, y, 64, 0)
if pActiveArea ~= nil then
return SceneObject(pActiveArea):getObjectID()
else
return 0
end
end
function TreasureMapMenuComponent:getMapType(pObject)
if (pObject == nil) then
return 0
end
local objectTemplate = SceneObject(pObject):getTemplateObjectPath()
if (objectTemplate == "object/tangible/treasure_map/treasure_map_pirate1.iff") then
return 1
elseif (objectTemplate == "object/tangible/treasure_map/treasure_map_pirate2.iff") then
return 2
elseif (objectTemplate == "object/tangible/treasure_map/treasure_map_bh.iff") then
return 3
elseif (objectTemplate == "object/tangible/loot/quest/treasure_map_hedon.iff") then
return 4
else
return 0
end
end
|
lasko2112/legend-of-hondo
|
MMOCoreORB/bin/scripts/screenplays/treasure_map/TreasureMapMenuComponent.lua
|
Lua
|
agpl-3.0
| 13,311
|
//
// LocationSelectViewController.h
// HospitalFinder
//
// Created by Ramesh Patel on 20/04/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "MapKit/MapKit.h"
#import "CoreLocation/CoreLocation.h"
@interface LocationSelectViewController : UIViewController<UISearchBarDelegate,MKMapViewDelegate,MKReverseGeocoderDelegate,UITableViewDelegate,UITableViewDataSource>
{
MKMapView *userLocationAddMapView;
CLLocationManager *locationManager;
NSMutableArray *arrAddress;
NSMutableArray *arrLat;
NSMutableArray *arrLong;
CLLocationCoordinate2D cordinate;
}
@property (retain, nonatomic) IBOutlet UITableView *tblView;
- (IBAction)btncurrentClick:(id)sender;
@property (retain, nonatomic) IBOutlet UISearchBar *searchBarLocation;
@property (retain, nonatomic) IBOutlet UIButton *btncurrent;
-(void)findLatLong;
-(void)retryGeo;
@end
|
MicroHealthLLC/Hospital-Info-Finder
|
iphone/HospitalFinder/HospitalFinder/LocationSelectViewController.h
|
C
|
agpl-3.0
| 909
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.