code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.quickstep;
import static com.android.launcher3.FastBitmapDrawable.newIcon;
import static com.android.launcher3.uioverrides.QuickstepLauncher.GO_LOW_RAM_RECENTS_ENABLED;
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import android.app.ActivityManager.TaskDescription;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.UserHandle;
import android.util.SparseArray;
import android.view.accessibility.AccessibilityManager;
import androidx.annotation.WorkerThread;
import com.android.launcher3.FastBitmapDrawable;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.icons.BitmapInfo;
import com.android.launcher3.icons.IconProvider;
import com.android.launcher3.icons.LauncherIcons;
import com.android.launcher3.icons.cache.HandlerRunnable;
import com.android.launcher3.util.Preconditions;
import com.android.quickstep.util.TaskKeyLruCache;
import com.android.systemui.shared.recents.model.Task;
import com.android.systemui.shared.recents.model.Task.TaskKey;
import com.android.systemui.shared.system.ActivityManagerWrapper;
import com.android.systemui.shared.system.PackageManagerWrapper;
import com.android.systemui.shared.system.TaskDescriptionCompat;
import java.util.function.Consumer;
/**
* Manages the caching of task icons and related data.
*/
public class TaskIconCache {
private final Handler mBackgroundHandler;
private final AccessibilityManager mAccessibilityManager;
private final Context mContext;
private final TaskKeyLruCache<TaskCacheEntry> mIconCache;
private final SparseArray<BitmapInfo> mDefaultIcons = new SparseArray<>();
private final IconProvider mIconProvider;
public TaskIconCache(Context context, Looper backgroundLooper) {
mContext = context;
mBackgroundHandler = new Handler(backgroundLooper);
mAccessibilityManager = context.getSystemService(AccessibilityManager.class);
Resources res = context.getResources();
int cacheSize = res.getInteger(R.integer.recentsIconCacheSize);
mIconCache = new TaskKeyLruCache<>(cacheSize);
mIconProvider = new IconProvider(context);
}
/**
* Asynchronously fetches the icon and other task data.
*
* @param task The task to fetch the data for
* @param callback The callback to receive the task after its data has been populated.
* @return A cancelable handle to the request
*/
public IconLoadRequest updateIconInBackground(Task task, Consumer<Task> callback) {
Preconditions.assertUIThread();
if (task.icon != null) {
// Nothing to load, the icon is already loaded
callback.accept(task);
return null;
}
IconLoadRequest request = new IconLoadRequest(mBackgroundHandler) {
@Override
public void run() {
TaskCacheEntry entry = getCacheEntry(task);
if (isCanceled()) {
// We don't call back to the provided callback in this case
return;
}
MAIN_EXECUTOR.execute(() -> {
task.icon = entry.icon;
task.titleDescription = entry.contentDescription;
callback.accept(task);
onEnd();
});
}
};
Utilities.postAsyncCallback(mBackgroundHandler, request);
return request;
}
public void clear() {
mIconCache.evictAll();
}
void onTaskRemoved(TaskKey taskKey) {
mIconCache.remove(taskKey);
}
void invalidateCacheEntries(String pkg, UserHandle handle) {
Utilities.postAsyncCallback(mBackgroundHandler,
() -> mIconCache.removeAll(key ->
pkg.equals(key.getPackageName()) && handle.getIdentifier() == key.userId));
}
@WorkerThread
private TaskCacheEntry getCacheEntry(Task task) {
TaskCacheEntry entry = mIconCache.getAndInvalidateIfModified(task.key);
if (entry != null) {
return entry;
}
TaskDescription desc = task.taskDescription;
TaskKey key = task.key;
ActivityInfo activityInfo = null;
// Create new cache entry
entry = new TaskCacheEntry();
// Load icon
// TODO: Load icon resource (b/143363444)
Bitmap icon = TaskDescriptionCompat.getIcon(desc, key.userId);
if (icon != null) {
entry.icon = new FastBitmapDrawable(getBitmapInfo(
new BitmapDrawable(mContext.getResources(), icon),
key.userId,
desc.getPrimaryColor(),
false /* isInstantApp */));
} else {
activityInfo = PackageManagerWrapper.getInstance().getActivityInfo(
key.getComponent(), key.userId);
if (activityInfo != null) {
BitmapInfo bitmapInfo = getBitmapInfo(
mIconProvider.getIcon(activityInfo, UserHandle.of(key.userId)),
key.userId,
desc.getPrimaryColor(),
activityInfo.applicationInfo.isInstantApp());
entry.icon = newIcon(mContext, bitmapInfo);
} else {
entry.icon = getDefaultIcon(key.userId);
}
}
// Loading content descriptions if accessibility or low RAM recents is enabled.
if (GO_LOW_RAM_RECENTS_ENABLED || mAccessibilityManager.isEnabled()) {
// Skip loading the content description if the activity no longer exists
if (activityInfo == null) {
activityInfo = PackageManagerWrapper.getInstance().getActivityInfo(
key.getComponent(), key.userId);
}
if (activityInfo != null) {
entry.contentDescription = ActivityManagerWrapper.getInstance()
.getBadgedContentDescription(activityInfo, task.key.userId,
task.taskDescription);
}
}
mIconCache.put(task.key, entry);
return entry;
}
@WorkerThread
private Drawable getDefaultIcon(int userId) {
synchronized (mDefaultIcons) {
BitmapInfo info = mDefaultIcons.get(userId);
if (info == null) {
try (LauncherIcons la = LauncherIcons.obtain(mContext)) {
info = la.makeDefaultIcon(UserHandle.of(userId));
}
mDefaultIcons.put(userId, info);
}
return new FastBitmapDrawable(info);
}
}
@WorkerThread
private BitmapInfo getBitmapInfo(Drawable drawable, int userId,
int primaryColor, boolean isInstantApp) {
try (LauncherIcons la = LauncherIcons.obtain(mContext)) {
la.disableColorExtraction();
la.setWrapperBackgroundColor(primaryColor);
// User version code O, so that the icon is always wrapped in an adaptive icon container
return la.createBadgedIconBitmap(drawable, UserHandle.of(userId),
Build.VERSION_CODES.O, isInstantApp);
}
}
public static abstract class IconLoadRequest extends HandlerRunnable {
IconLoadRequest(Handler handler) {
super(handler, null);
}
}
private static class TaskCacheEntry {
public Drawable icon;
public String contentDescription = "";
}
}
| Java |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 6 22:58:00 2016
@author: Diogo
"""
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 26 19:08:00 2016
@author: Diogo
"""
def ImportGames():
games = list()
user_games = dict()
with open('C:\\Users\\Diogo\\Documents\\Monografia FIA\\UserGamesCleansed.txt', 'r', encoding = 'utf-8') as lines:
next(lines) # Skiping headers
for ln in lines:
user, board_game, board_type, list_type, score10 = ln.split('##')
if board_game not in games:
games.append(board_game.replace('\t',' ').replace(' ', ' '))
if user not in user_games:
user_games[user] = dict()
if board_game not in user_games[user].keys():
user_games[user][board_game] = 1
return (games, user_games)
games, user_games = ImportGames()
def BuildMatrix(games, user_games):
with open('C:\\Users\\Diogo\\Documents\\Monografia FIA\\UserGamesMatrix.tab', 'a', encoding = 'utf-8') as lines:
lines.write('user\t' + '\t'.join(games) + '\n')
for user in user_games:
user_line = list()
for game in games:
if game in user_games[user].keys():
user_line.append('1')
else:
user_line.append('0')
with open('C:\\Users\\Diogo\\Documents\\Monografia FIA\\UserGamesMatrix.tab', 'a', encoding = 'utf-8') as lines:
lines.write(user + '\t' + '\t'.join(user_line) + '\n')
BuildMatrix(games, user_games) | Java |
<?php
/******************************************************************************
*
* Subrion - open source content management system
* Copyright (C) 2017 Intelliants, LLC <https://intelliants.com>
*
* This file is part of Subrion.
*
* Subrion 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.
*
* Subrion 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 Subrion. If not, see <http://www.gnu.org/licenses/>.
*
*
* @link https://subrion.org/
*
******************************************************************************/
require_once IA_INCLUDES . 'helpers/ia.category.interface.php';
abstract class iaAbstractFrontHelperCategoryFlat extends abstractModuleFront
{
const ROOT_PARENT_ID = 0;
const COL_PARENT_ID = 'parent_id';
const COL_LEVEL = 'level';
protected $_tableFlat;
protected $_recountEnabled = true;
protected $_recountOptions = []; // this to be extended by ancestor
private $_defaultRecountOptions = [
'listingsTable' => null,
'activeStatus' => iaCore::STATUS_ACTIVE,
'columnCounter' => 'num_listings',
'columnTotalCounter' => 'num_all_listings'
];
private $_root;
public function init()
{
parent::init();
$this->_tableFlat = self::getTable() . '_flat';
}
public function getTableFlat($prefix = false)
{
return ($prefix ? $this->iaDb->prefix : '') . $this->_tableFlat;
}
public function getRoot()
{
if (is_null($this->_root)) {
$this->_root = $this->getOne(iaDb::convertIds(self::ROOT_PARENT_ID, self::COL_PARENT_ID));
}
return $this->_root;
}
public function getRootId()
{
return $this->getRoot()['id'];
}
public function getTopLevel($fields = null)
{
return $this->getByLevel(1, $fields);
}
public function getByLevel($level, $fields = null)
{
$where = '`status` = :status and `level` = :level';
$this->iaDb->bind($where, ['status' => iaCOre::STATUS_ACTIVE, 'level' => $level]);
return $this->getAll($where, $fields);
}
public function getParents($entryId)
{
$where = sprintf('`id` IN (SELECT `parent_id` FROM `%s` WHERE `child_id` = %d)',
$this->getTableFlat(true), $entryId);
return $this->getAll($where);
}
public function getChildren($entryId, $recursive = false)
{
$where = $recursive
? sprintf('`id` IN (SELECT `child_id` FROM `%s` WHERE `parent_id` = %d)', $this->getTableFlat(true), $entryId)
: iaDb::convertIds($entryId, self::COL_PARENT_ID);
return $this->getAll($where);
}
public function getTreeVars($id, $title)
{
$nodes = [];
foreach ($this->getParents($id) as $category) {
$nodes[] = $category['id'];
}
$result = [
'url' => $this->getInfo('url') . 'add/tree.json',
'id' => $id,
'nodes' => implode(',', $nodes),
'title' => $title
];
return $result;
}
public function getJsonTree(array $data)
{
$output = [];
$this->iaDb->setTable(self::getTable());
$dynamicLoadMode = ((int)$this->iaDb->one(iaDb::STMT_COUNT_ROWS) > 150);
$rootId = $this->getRootId();
$parentId = isset($data['id']) && is_numeric($data['id']) ? (int)$data['id'] : $rootId;
$where = $dynamicLoadMode
? iaDb::convertIds($parentId, self::COL_PARENT_ID)
: iaDb::convertIds($rootId, 'id', false);
$where .= ' ORDER BY `title`';
$fields = '`id`, `title_' . $this->iaCore->language['iso'] . '` `title`, `parent_id`, '
. '(SELECT COUNT(*) FROM `' . $this->getTableFlat(true) . '` f WHERE f.`parent_id` = `id`) `children_count`';
foreach ($this->iaDb->all($fields, $where) as $row) {
$entry = ['id' => $row['id'], 'text' => $row['title']];
if ($dynamicLoadMode) {
$entry['children'] = $row['children_count'] > 1;
} else {
$entry['state'] = [];
$entry['parent'] = $rootId == $row[self::COL_PARENT_ID] ? '#' : $row[self::COL_PARENT_ID];
}
$output[] = $entry;
}
return $output;
}
public function recountById($id, $factor = 1)
{
if (!$this->_recountEnabled) {
return;
}
$options = array_merge($this->_defaultRecountOptions, $this->_recountOptions);
$sql = <<<SQL
UPDATE `:table_data`
SET `:col_counter` = IF(`id` = :id, `:col_counter` + :factor, `:col_counter`),
`:col_total_counter` = `:col_total_counter` + :factor
WHERE `id` IN (SELECT `parent_id` FROM `:table_flat` WHERE `child_id` = :id)
SQL;
$sql = iaDb::printf($sql, [
'table_data' => self::getTable(true),
'table_flat' => self::getTableFlat(true),
'col_counter' => $options['columnCounter'],
'col_total_counter' => $options['columnTotalCounter'],
'id' => (int)$id,
'factor' => (int)$factor
]);
$this->iaDb->query($sql);
}
}
| Java |
<?php
/**
* \PHPCompatibility\Sniffs\LanguageConstructs\NewEmptyNonVariableSniff.
*
* PHP version 5.5
*
* @category PHP
* @package PHPCompatibility
* @author Juliette Reinders Folmer <phpcompatibility_nospam@adviesenzo.nl>
*/
namespace PHPCompatibility\Sniffs\LanguageConstructs;
use PHPCompatibility\Sniff;
use PHP_CodeSniffer_File as File;
use PHP_CodeSniffer_Tokens as Tokens;
/**
* \PHPCompatibility\Sniffs\LanguageConstructs\NewEmptyNonVariableSniff.
*
* Verify that nothing but variables are passed to empty().
*
* PHP version 5.5
*
* @category PHP
* @package PHPCompatibility
* @author Juliette Reinders Folmer <phpcompatibility_nospam@adviesenzo.nl>
*/
class NewEmptyNonVariableSniff extends Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(\T_EMPTY);
}
/**
* Processes this test, when one of its tokens is encountered.
*
* @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in the
* stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
if ($this->supportsBelow('5.4') === false) {
return;
}
$tokens = $phpcsFile->getTokens();
$open = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true, null, true);
if ($open === false
|| $tokens[$open]['code'] !== \T_OPEN_PARENTHESIS
|| isset($tokens[$open]['parenthesis_closer']) === false
) {
return;
}
$close = $tokens[$open]['parenthesis_closer'];
$nestingLevel = 0;
if ($close !== ($open + 1) && isset($tokens[$open + 1]['nested_parenthesis'])) {
$nestingLevel = count($tokens[$open + 1]['nested_parenthesis']);
}
if ($this->isVariable($phpcsFile, ($open + 1), $close, $nestingLevel) === true) {
return;
}
$phpcsFile->addError(
'Only variables can be passed to empty() prior to PHP 5.5.',
$stackPtr,
'Found'
);
}
}
| Java |
/*
============================================================================
Name : lcd_scroll_text.c
Author : Kiran N <niekiran@gmail.com >
Version : 1.0
Copyright : Your copyright notice
Description : This application prints pre-stored strings on a LCD panel with shifting/scrolling effect
TODOs for the students
1) Take multiple strings as a command line argumentsinstead of pre-stored.
============================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#include<stdint.h>
#include <time.h>
#include <math.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>
#include "lcd_driver.h"
#include "gpio_driver.h"
#include "lcd_text_scroll.h"
/*=========================================================================================================
BBB_expansion_heade_P8_pins GPIO number 16x2 LCD pin Purpose
===========================================================================================================
P8.7 GPIO_66 4(RS) Register selection (Character vs. Command)
P8.8 GPIO_67 5(RW) Read/write
P8.9 GPIO_69 6(EN) Enable
P8.10 GPIO_68 7(D4) Data line 4
P8.11 GPIO_45 8(D5) Data line 5
P8.12 GPIO_44 9(D6) Data line 6
P8.14 GPIO_26 10(D7) Data line 7
P8.16 GPIO_46 15(BKLTA) Backlight anode
P9.15 GPIO_48 16(BKLTK) Backlight cathode
============================================================================================================= */
char* some_strings[]=
{
"Mahatma Gandhi said,",
"First they ignore you,",
"then they laugh at you ",
"then they fight with you,",
"then you win !",
};
/* This function initializes all the gpios for this application
* TODO : Error handling implementation
*/
int initialize_all_gpios(void)
{
/* first lets export all the GPIOs */
gpio_export(GPIO_66_P8_7_RS_4);
gpio_export(GPIO_67_P8_8_RW_5);
gpio_export(GPIO_69_P8_9_EN_6);
gpio_export(GPIO_68_P8_10_D4_11);
gpio_export(GPIO_45_P8_11_D5_12);
gpio_export(GPIO_44_P8_12_D6_13);
gpio_export(GPIO_26_P8_14_D7_14);
/*first configure the direction for LCD pins */
gpio_configure_dir(GPIO_66_P8_7_RS_4,GPIO_DIR_OUT);
gpio_configure_dir(GPIO_67_P8_8_RW_5,GPIO_DIR_OUT);
gpio_configure_dir(GPIO_69_P8_9_EN_6,GPIO_DIR_OUT);
gpio_configure_dir(GPIO_68_P8_10_D4_11,GPIO_DIR_OUT);
gpio_configure_dir(GPIO_45_P8_11_D5_12,GPIO_DIR_OUT);
gpio_configure_dir(GPIO_44_P8_12_D6_13,GPIO_DIR_OUT);
gpio_configure_dir(GPIO_26_P8_14_D7_14,GPIO_DIR_OUT);
return 0;
}
/* This function gathers the ip address of the system and prints it on LCD */
int print_ip_address()
{
int fd;
struct ifreq ifr;
char iface[] = "usb0";
fd = socket(AF_INET, SOCK_DGRAM, 0);
//Type of address to retrieve - IPv4 IP address
ifr.ifr_addr.sa_family = AF_INET;
//Copy the interface name in the ifreq structure
strncpy(ifr.ifr_name , iface , IFNAMSIZ-1);
ioctl(fd, SIOCGIFADDR, &ifr);
close(fd);
//display result
lcd_printf("%s - %s\n" , iface , inet_ntoa(( (struct sockaddr_in *)&ifr.ifr_addr )->sin_addr) );
return 0;
}
/* Some silly graphics :) */
void tansition_graphics(void)
{
sleep(1);
lcd_set_cursor(1,1);
lcd_send_command(LCD_CMD_CLEAR_DISPLAY);
for (uint8_t n =0 ; n < 2 ; n++)
{
for(uint8_t i=0;i<16;i++)
{
lcd_print_char('*');
usleep(75*1000);
}
lcd_set_cursor(2,16);
lcd_send_command(0x04);
}
lcd_set_cursor(1,1);
lcd_send_command(0x06);
usleep(450 * 1000);
lcd_send_command(LCD_CMD_CLEAR_DISPLAY);
}
int main(int argc, char *argv[])
{
printf("Application to print text in scrollable fashion on LCD\n");
initialize_all_gpios();
gpio_write_value(GPIO_66_P8_7_RS_4,LOW_VALUE);
/*The RW pin is always tied to ground in this implementation, meaning that you are only writing to
the display and never reading from it.*/
gpio_write_value(GPIO_67_P8_8_RW_5,LOW_VALUE);
/* The EN pin is used to tell the LCD when data is ready*/
gpio_write_value(GPIO_69_P8_9_EN_6,LOW_VALUE);
/*Data pins 4~7 are used for actually transmitting data, and data pins 0~3 are left unconnected*/
gpio_write_value(GPIO_68_P8_10_D4_11,LOW_VALUE);
gpio_write_value(GPIO_45_P8_11_D5_12,LOW_VALUE);
gpio_write_value(GPIO_44_P8_12_D6_13,LOW_VALUE);
gpio_write_value(GPIO_26_P8_14_D7_14,LOW_VALUE);
/*
You can illuminate the backlight by connecting the anode pin to 5V and the cathode pin to ground
if you are using an LCD with a built-in resistor for the backlight. If you are not, you must put a
current-limiting resistor in-line with the anode or cathode pin. The datasheet for your device will
generally tell you if you need to do this. */
uint8_t cmd=0;
lcd_init();
//setting function
// only single line mode is chosen here , that means all the 80 characters of the DDRAM will be mapped to lcd line 1.
cmd= LCD_CMD_FUNCTION_SET | DATA_LEN_4 | DISPLAY_1_LINE | MATRIX_5_X_8;
lcd_send_command(cmd);
//3.display on/off control , no cursor
cmd = LCD_CMD_DISPLAY_CURSOR_ONOFF_CONTROL |DISPLAY_ON |CURSOR_OFF ;
lcd_send_command(cmd);
lcd_send_command(LCD_CMD_CLEAR_DISPLAY yo);
//lets start printing from extreme right end of first row of the lcd. .
lcd_set_cursor( 1,17);
#if 1
char *ptr = NULL;
uint8_t i;
while(1)
{
//we have total five strings.
for ( i = 0 ;i < 5 ; i++)
{
//print till each string meets NULL char
ptr= some_strings[i];
while( *ptr != '\0' )
{
lcd_print_char((uint8_t)*ptr);
//printing one character at a time and then left shifting by sending this command.
cmd = LCD_CMD_CURSOR_DISPLAY_SHIFT_CONTROL | DISPLAY_SHIFT | SHIFT_TO_LEFT ;
lcd_send_command(cmd);
ptr++;
usleep(500 * 1000);
}
}
}
#endif
}
| Java |
%include lhs2TeX.fmt
\usepackage{ stmaryrd }
%format <?> = "~\lightning~"
| Java |
*{
font-family: 'Raleway', sans-serif;
}
body{
background: #d6d6d6;
color: #333;
margin: 0;
font-family: 'Raleway', sans-serif;
}
#masterContainer{
width: 100vw;
height: 100vh;
padding: 0;
margin: 0;
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
align-items: center;
justify-content: center;
}
#logindiv{
background: #dfdfdf;
padding: 50px 20px;
border-radius: 3px;
box-shadow: 0 0 3px #888;
}
#logindiv span {
width: 80px;
display: inline-block;
font-size: 15px;
}
#logindiv input {
width: 220px;
height: 30px;
padding: 5px;
margin: 5px 0px;
display: inline-block;
font-size: 15px;
outline: none;
transition: 0.2s;
border: 1px solid #aaa;
}
#logindiv input[type=submit] {
display: block;
width: 100%;
margin: 20px 0 0 0;
border: 0;
border-radius: 3px;
background-color: #29b0d0;
color: #fff;
height: 35px;
}
#logindiv input[type=submit]:hover {
background: #2990a0;
}
.logo {
background-image: url(./logo.png);
background-size: contain;
filter: hue-rotate(120);
display: block;
width: 80px;
height: 80px;
margin: 0 auto 20px auto;
}
#about{
width: 100%;
text-align: center;
bottom: 20px;
position: fixed;
color: #777;
font-weight: 300;
text-shadow: 0 0 0px #b1b1b1;
}
html {
height: 100%;
}
.h1, .h2, .h3, .h4, .h5, .h6, h1, h2, h3, h4, h5, h6 {
font-family: inherit;
font-weight: 400;
line-height: 1.1;
color: inherit;
}
input[type=submit]{
padding: 10px;
background-color: #29b0d0;
color: #fff;
border: 0;
border-radius: 3px;
font-size: 13px;
outline: none;
}
input[type=text], input[type=password]{
padding: 10px;
background-color: #eee;
color: #000;
border: 1px solid #ccc;
font-size: 13px;
border-radius: 3px;
min-width: 270px;
outline: none;
transition: 0.2s;
}
input[type=text]:hover, input[type=password]:hover{
border: 1px solid #aaa;
}
input[type=text]:focus, input[type=password]:focus{
border: 1px solid #29b0d0;
}
nav {
height: 60px;
background: #fff;
display: block;
padding: 0;
-webkit-box-shadow: 0 0px 2px #777;
-moz-box-shadow: 0 0px 2px #777;
box-shadow: 0 0px 2px #777;
z-index: 9999;
color: #333;
box-shadow: 0 1px 0 rgba(12,13,14,0.1), 0 1px 3px rgba(12,13,14,0.1), 0 4px 20px rgba(12,13,14,0.035), 0 1px 1px rgba(12,13,14,0.025);
}
#title {
width: 80px;
background-size: 50px 50px;
background-repeat: no-repeat;
background-position: center;
font-size: 14px;
color: #655dff;
display: inline-block;
margin: 0;
height: 59px;
min-width: 60px;
cursor: pointer;
max-width: 200px;
}
#search{
display: inline-block;
width: 250px;
height: 40px;
margin: 10px 25px;
background-color: #29b0d0;
position: absolute;
border: 0;
box-shadow: 0 0 2px #ddd;
color: #fff;
}
#search::placeholder{
color: #ddd;
}
#headerRight {
height: 60px;
margin: 0;
}
.headerButton {
margin: 10px 5px;
background-color: #29b0d0;
color: #fff;
min-width: 40px;
border: 0;
border-radius: 4px;
height: 40px;
box-shadow: 0 0 3px #cccccc;
}
.headerButton:hover {
background: #f0f0f0;
transition: 0.2s;
}
.headerText {
font-weight: 400;
font-size: 15px;
padding: 0;
margin: 9px 12px 9px 2px;
display: inline-block;
vertical-align: top;
text-align: center;
}
.userPhoto {
width: 30px;
height: 30px;
margin: 5px;
display: inline-block;
border-radius: 15px;
background-size: contain;
}
.mainContent{
padding-top: 100px;
background-color: #f6f6f6;
padding-bottom: 40px;
box-shadow: 0 0 20px 2px #aaa;
min-height: 100%;
position: relative;
}
.post {
min-width: 500px;
max-width: 800px;
min-height: 200px;
position: relative;
margin: 30px auto;
margin-bottom: 60px;
background-color: #fff;
border-radius: 3px;
border: 1px solid #ccc;
box-shadow: 0 10px 0px 0px #29b0d0, 0 4px 8px 0 rgba(0,0,0,0.2);
display: block;
transition: 0.3s;
}
.post:hover {
box-shadow: 0 10px 0px 0px #2292ac, 0 8px 16px 0 rgba(0,0,0,0.2);
}
.post .row > .col > *{
display: inline-block;
vertical-align: middle;
}
.postText {
padding-bottom: 60px;
margin: 20px;
}
.postTitle {
padding: 2px 20px 10px 20px;
display: block;
font-size: 1.5em;
color: #333;
text-align: center;
}
.react {
width: 100%;
left: 0;
height: 60px;
bottom: 0;
left: 15px;
position: absolute;
background-color: #eee;
overflow: hidden;
border: 0;
padding: 0;
border-top: 1px solid #ddd;
}
.reactButton{
width: 40px;
height: 40px;
margin: 0;
padding: 0;
border-radius: 40px;
border: 1px solid #ddd;
display: inline-block;
background: #fff;
color: #555;
position: relative;
bottom: 0;
transition: 0.2s;
margin: 10px;
}
.reactButton:focus{
outline: none;
}
.react > input[type=submit]{
background: #eee;
color: #666;
}
.react > input[type=submit]:hover {
background: #e0e0e0;
transition: 0.2s;
color: #29b0d0;
}
.reactButton:hover {
background-color: #555;
color: #fff;
border: 0;
cursor: pointer;
}
._thumbsup:hover {
background-color: #29b0d0;
}
._heart:hover {
background-color: #f03;
}
._comments{
}
._comments:hover {
background-color: #555;
}
._post:hover {
background-color: #590;
}
.comments {
left: 0;
height: 0px;
position: relative;
background-color: #f4f4f4;
overflow: hidden;
border: 0;
padding: 0;
border-top: 1px solid #ddd;
display: block;
overflow-y: scroll;
max-height: 199px;
padding: 10px 10px 10px 0;
}
.UpostText {
display: block;
height: 180px;
margin: 20px;
margin-bottom: 0px;
border: 1px solid #ccc;
border-radius: 3px;
background-color: #fcfcfc;
max-height: 160px;
outline: 0px;
resize: none;
padding: 10px;
}
.UpostText:hover {
transition: 0.2s;
border: 1px solid #aaa;
}
.UpostText:focus {
transition: 0.2s;
border: 1px solid #29b0d0;
}
hr {
border: 0;
height: 1px;
background-image: -webkit-linear-gradient(left, #f0f0f0, #8c8b8b, #f0f0f0);
background-image: -moz-linear-gradient(left, #f0f0f0, #8c8b8b, #f0f0f0);
background-image: -ms-linear-gradient(left, #f0f0f0, #8c8b8b, #f0f0f0);
background-image: -o-linear-gradient(left, #f0f0f0, #8c8b8b, #f0f0f0);
}
#register{
width: 380px;
margin: 0 auto;
margin-top: 100px;
height: 550px;
background-color: #fff;
border-radius: 3px;
font-size: 14px;
border: 1px solid #ccc;
box-shadow: 0 5px 10px -2px #888;
font-weight: 300;
}
#register input{
display: block;
margin-top: 15px;
width: 270px;
}
#register form {
padding-top: 15px;
width: 270px;
margin: auto;
display: block;
}
#register h1 {
margin: 15px;
font-size: 30px;
}
#register h3 {
margin-top: 10px;
font-size: 20px;
}
.comment{
background: white;
max-height: 50px;
padding: 5px;
border-radius: 10px;
margin: 15px;
box-shadow: 0 0 15px #d8d8d8;
display: block;
}
.commentUserImage{
width: 30px;
height: 30px;
border-radius: 15px;
margin: 5px;
}
.commentUser{
font-weight: 700;
}
.commentText{
font-weight: 200;
font-family: monospace;
}
.commentInput{
height: 40px;
width: 200px;
border-radius: 20px;
border: 1px solid #ddd;
padding: 10px;
margin: 10px;
display: inline-block;
background: #fff;
color: #555;
position: relative;
bottom: 0;
outline: 0;
} | Java |
// Copyright (c) 2012-2014 Lotaris SA
//
// This file is part of ROX Center.
//
// ROX Center 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.
//
// ROX Center 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 ROX Center. If not, see <http://www.gnu.org/licenses/>.
App.autoModule('globalSettings', function() {
var Settings = Backbone.Model.extend({
url: LegacyApiPath.builder('settings')
});
var SettingsForm = Marionette.ItemView.extend({
template: 'globalSettings',
ui: {
ticketingSystemUrl: '#settings_ticketing_system_url',
reportsCacheSize: '#settings_reports_cache_size',
tagCloudSize: '#settings_tag_cloud_size',
testOutdatedDays: '#settings_test_outdated_days',
testPayloadsLifespan: '#settings_test_payloads_lifespan',
testRunsLifespan: '#settings_test_runs_lifespan',
fields: 'form :input',
saveButton: 'form button',
formControls: 'form .form-controls'
},
events: {
'submit form': 'save'
},
modelEvents: {
'change': 'refresh'
},
appEvents: {
'maintenance:changed': 'updateControls'
},
model: new Settings(),
initialize: function() {
App.bindEvents(this);
},
onRender: function() {
this.$el.button();
this.model.fetch(this.requestOptions());
this.updateControls();
},
setBusy: function(busy) {
this.busy = busy;
this.updateControls();
},
updateControls: function() {
this.ui.saveButton.attr('disabled', this.busy || !!App.maintenance);
this.ui.fields.attr('disabled', !!App.maintenance);
},
refresh: function() {
this.ui.ticketingSystemUrl.val(this.model.get('ticketing_system_url'));
this.ui.reportsCacheSize.val(this.model.get('reports_cache_size'));
this.ui.tagCloudSize.val(this.model.get('tag_cloud_size'));
this.ui.testOutdatedDays.val(this.model.get('test_outdated_days'));
this.ui.testPayloadsLifespan.val(this.model.get('test_payloads_lifespan'));
this.ui.testRunsLifespan.val(this.model.get('test_runs_lifespan'));
},
save: function(e) {
e.preventDefault();
this.setNotice(false);
this.setBusy(true);
var options = this.requestOptions();
options.type = 'PUT';
options.success = _.bind(this.onSaved, this, 'success');
options.error = _.bind(this.onSaved, this, 'error');
this.model.save({
ticketing_system_url: this.ui.ticketingSystemUrl.val(),
reports_cache_size: this.ui.reportsCacheSize.val(),
tag_cloud_size: this.ui.tagCloudSize.val(),
test_outdated_days: this.ui.testOutdatedDays.val(),
test_payloads_lifespan: this.ui.testPayloadsLifespan.val(),
test_runs_lifespan: this.ui.testRunsLifespan.val()
}, options).always(_.bind(this.setBusy, this, false));
},
onSaved: function(result) {
this.setNotice(result);
if (result == 'success') {
this.refresh();
}
},
setNotice: function(type) {
this.ui.saveButton.next('.text-success,.text-danger').remove();
if (type == 'success') {
$('<span class="text-success" />').text(I18n.t('jst.globalSettings.success')).insertAfter(this.ui.saveButton).hide().fadeIn('fast');
} else if (type == 'error') {
$('<span class="text-danger" />').text(I18n.t('jst.globalSettings.error')).insertAfter(this.ui.saveButton).hide().fadeIn('fast');
}
},
requestOptions: function() {
return {
dataType: 'json',
accepts: {
json: 'application/json'
}
};
}
});
this.addAutoInitializer(function(options) {
options.region.show(new SettingsForm());
});
});
| Java |
@charset "utf-8";
html{
background: FloralWhite;
/*background:#40A0DA; Ivory PowderBlue Lavender Azure Honeydew*/
}
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,form,fieldset,input,textarea,p,blockquote,th,td{
margin:0 auto;
padding:0;
}
table{
border-collapse:collapse;
border-spacing:0;
}
a{
text-decoration:none;
}
a:link{color: #fff;} /* 未访问的链接 */
a:visited {color: #fff;} /* 已访问的链接 */
a:hover{color: #fff;} /* 鼠标在链接上 */
a:active {color: #fff;} /* 点击激活链接——在你点击该链接之后,页面正在转向新地址的时候,链接显示此颜色;当你已经到了要链接的页面,然后再返回,原页面上的此链接仍是此颜色 */
em,strong,b,u,i{
font-style:normal;
font-weight:normal;
}
ul,ol{
list-style:none;
}
h1,h2,h3{
font-size:100%;
font-weight:normal;
}
input,textarea,select{
font-family:inherit;
font-size:inherit;
font-weight:inherit;
*font-size:100%;/*ie*/
}
input,textarea{
border:none;
} | Java |
package com.glory.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Log {
@Id
@GeneratedValue
private Long id;
private Long transactionId;
private String message;
public Log() {
}
public Log(Long id, Long transactionId, String message) {
super();
this.id = id;
this.transactionId = transactionId;
this.message = message;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getTransactionId() {
return transactionId;
}
public void setTransactionId(Long transactionId) {
this.transactionId = transactionId;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| Java |
Imports Microsoft.VisualBasic
Imports System
'
' * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
' * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
'
Namespace java.lang.invoke
''' <summary>
''' <p>Methods to facilitate the creation of simple "function objects" that
''' implement one or more interfaces by delegation to a provided <seealso cref="MethodHandle"/>,
''' possibly after type adaptation and partial evaluation of arguments. These
''' methods are typically used as <em>bootstrap methods</em> for {@code invokedynamic}
''' call sites, to support the <em>lambda expression</em> and <em>method
''' reference expression</em> features of the Java Programming Language.
'''
''' <p>Indirect access to the behavior specified by the provided {@code MethodHandle}
''' proceeds in order through three phases:
''' <ul>
''' <li><em>Linkage</em> occurs when the methods in this class are invoked.
''' They take as arguments an interface to be implemented (typically a
''' <em>functional interface</em>, one with a single abstract method), a
''' name and signature of a method from that interface to be implemented, a
''' method handle describing the desired implementation behavior
''' for that method, and possibly other additional metadata, and produce a
''' <seealso cref="CallSite"/> whose target can be used to create suitable function
''' objects. Linkage may involve dynamically loading a new class that
''' implements the target interface. The {@code CallSite} can be considered a
''' "factory" for function objects and so these linkage methods are referred
''' to as "metafactories".</li>
'''
''' <li><em>Capture</em> occurs when the {@code CallSite}'s target is
''' invoked, typically through an {@code invokedynamic} call site,
''' producing a function object. This may occur many times for
''' a single factory {@code CallSite}. Capture may involve allocation of a
''' new function object, or may return an existing function object. The
''' behavior {@code MethodHandle} may have additional parameters beyond those
''' of the specified interface method; these are referred to as <em>captured
''' parameters</em>, which must be provided as arguments to the
''' {@code CallSite} target, and which may be early-bound to the behavior
''' {@code MethodHandle}. The number of captured parameters and their types
''' are determined during linkage.</li>
'''
''' <li><em>Invocation</em> occurs when an implemented interface method
''' is invoked on a function object. This may occur many times for a single
''' function object. The method referenced by the behavior {@code MethodHandle}
''' is invoked with the captured arguments and any additional arguments
''' provided on invocation, as if by <seealso cref="MethodHandle#invoke(Object...)"/>.</li>
''' </ul>
'''
''' <p>It is sometimes useful to restrict the set of inputs or results permitted
''' at invocation. For example, when the generic interface {@code Predicate<T>}
''' is parameterized as {@code Predicate<String>}, the input must be a
''' {@code String}, even though the method to implement allows any {@code Object}.
''' At linkage time, an additional <seealso cref="MethodType"/> parameter describes the
''' "instantiated" method type; on invocation, the arguments and eventual result
''' are checked against this {@code MethodType}.
'''
''' <p>This class provides two forms of linkage methods: a standard version
''' (<seealso cref="#metafactory(MethodHandles.Lookup, String, MethodType, MethodType, MethodHandle, MethodType)"/>)
''' using an optimized protocol, and an alternate version
''' <seealso cref="#altMetafactory(MethodHandles.Lookup, String, MethodType, Object...)"/>).
''' The alternate version is a generalization of the standard version, providing
''' additional control over the behavior of the generated function objects via
''' flags and additional arguments. The alternate version adds the ability to
''' manage the following attributes of function objects:
'''
''' <ul>
''' <li><em>Bridging.</em> It is sometimes useful to implement multiple
''' variations of the method signature, involving argument or return type
''' adaptation. This occurs when multiple distinct VM signatures for a method
''' are logically considered to be the same method by the language. The
''' flag {@code FLAG_BRIDGES} indicates that a list of additional
''' {@code MethodType}s will be provided, each of which will be implemented
''' by the resulting function object. These methods will share the same
''' name and instantiated type.</li>
'''
''' <li><em>Multiple interfaces.</em> If needed, more than one interface
''' can be implemented by the function object. (These additional interfaces
''' are typically marker interfaces with no methods.) The flag {@code FLAG_MARKERS}
''' indicates that a list of additional interfaces will be provided, each of
''' which should be implemented by the resulting function object.</li>
'''
''' <li><em>Serializability.</em> The generated function objects do not
''' generally support serialization. If desired, {@code FLAG_SERIALIZABLE}
''' can be used to indicate that the function objects should be serializable.
''' Serializable function objects will use, as their serialized form,
''' instances of the class {@code SerializedLambda}, which requires additional
''' assistance from the capturing class (the class described by the
''' <seealso cref="MethodHandles.Lookup"/> parameter {@code caller}); see
''' <seealso cref="SerializedLambda"/> for details.</li>
''' </ul>
'''
''' <p>Assume the linkage arguments are as follows:
''' <ul>
''' <li>{@code invokedType} (describing the {@code CallSite} signature) has
''' K parameters of types (D1..Dk) and return type Rd;</li>
''' <li>{@code samMethodType} (describing the implemented method type) has N
''' parameters, of types (U1..Un) and return type Ru;</li>
''' <li>{@code implMethod} (the {@code MethodHandle} providing the
''' implementation has M parameters, of types (A1..Am) and return type Ra
''' (if the method describes an instance method, the method type of this
''' method handle already includes an extra first argument corresponding to
''' the receiver);</li>
''' <li>{@code instantiatedMethodType} (allowing restrictions on invocation)
''' has N parameters, of types (T1..Tn) and return type Rt.</li>
''' </ul>
'''
''' <p>Then the following linkage invariants must hold:
''' <ul>
''' <li>Rd is an interface</li>
''' <li>{@code implMethod} is a <em>direct method handle</em></li>
''' <li>{@code samMethodType} and {@code instantiatedMethodType} have the same
''' arity N, and for i=1..N, Ti and Ui are the same type, or Ti and Ui are
''' both reference types and Ti is a subtype of Ui</li>
''' <li>Either Rt and Ru are the same type, or both are reference types and
''' Rt is a subtype of Ru</li>
''' <li>K + N = M</li>
''' <li>For i=1..K, Di = Ai</li>
''' <li>For i=1..N, Ti is adaptable to Aj, where j=i+k</li>
''' <li>The return type Rt is void, or the return type Ra is not Sub and is
''' adaptable to Rt</li>
''' </ul>
'''
''' <p>Further, at capture time, if {@code implMethod} corresponds to an instance
''' method, and there are any capture arguments ({@code K > 0}), then the first
''' capture argument (corresponding to the receiver) must be non-null.
'''
''' <p>A type Q is considered adaptable to S as follows:
''' <table summary="adaptable types">
''' <tr><th>Q</th><th>S</th><th>Link-time checks</th><th>Invocation-time checks</th></tr>
''' <tr>
''' <td>Primitive</td><td>Primitive</td>
''' <td>Q can be converted to S via a primitive widening conversion</td>
''' <td>None</td>
''' </tr>
''' <tr>
''' <td>Primitive</td><td>Reference</td>
''' <td>S is a supertype of the Wrapper(Q)</td>
''' <td>Cast from Wrapper(Q) to S</td>
''' </tr>
''' <tr>
''' <td>Reference</td><td>Primitive</td>
''' <td>for parameter types: Q is a primitive wrapper and Primitive(Q)
''' can be widened to S
''' <br>for return types: If Q is a primitive wrapper, check that
''' Primitive(Q) can be widened to S</td>
''' <td>If Q is not a primitive wrapper, cast Q to the base Wrapper(S);
''' for example Number for numeric types</td>
''' </tr>
''' <tr>
''' <td>Reference</td><td>Reference</td>
''' <td>for parameter types: S is a supertype of Q
''' <br>for return types: none</td>
''' <td>Cast from Q to S</td>
''' </tr>
''' </table>
'''
''' @apiNote These linkage methods are designed to support the evaluation
''' of <em>lambda expressions</em> and <em>method references</em> in the Java
''' Language. For every lambda expressions or method reference in the source code,
''' there is a target type which is a functional interface. Evaluating a lambda
''' expression produces an object of its target type. The recommended mechanism
''' for evaluating lambda expressions is to desugar the lambda body to a method,
''' invoke an invokedynamic call site whose static argument list describes the
''' sole method of the functional interface and the desugared implementation
''' method, and returns an object (the lambda object) that implements the target
''' type. (For method references, the implementation method is simply the
''' referenced method; no desugaring is needed.)
'''
''' <p>The argument list of the implementation method and the argument list of
''' the interface method(s) may differ in several ways. The implementation
''' methods may have additional arguments to accommodate arguments captured by
''' the lambda expression; there may also be differences resulting from permitted
''' adaptations of arguments, such as casting, boxing, unboxing, and primitive
''' widening. (Varargs adaptations are not handled by the metafactories; these are
''' expected to be handled by the caller.)
'''
''' <p>Invokedynamic call sites have two argument lists: a static argument list
''' and a dynamic argument list. The static argument list is stored in the
''' constant pool; the dynamic argument is pushed on the operand stack at capture
''' time. The bootstrap method has access to the entire static argument list
''' (which in this case, includes information describing the implementation method,
''' the target interface, and the target interface method(s)), as well as a
''' method signature describing the number and static types (but not the values)
''' of the dynamic arguments and the static return type of the invokedynamic site.
'''
''' @implNote The implementation method is described with a method handle. In
''' theory, any method handle could be used. Currently supported are direct method
''' handles representing invocation of virtual, interface, constructor and static
''' methods.
''' </summary>
Public Class LambdaMetafactory
''' <summary>
''' Flag for alternate metafactories indicating the lambda object
''' must be serializable
''' </summary>
Public Shared ReadOnly FLAG_SERIALIZABLE As Integer = 1 << 0
''' <summary>
''' Flag for alternate metafactories indicating the lambda object implements
''' other marker interfaces
''' besides Serializable
''' </summary>
Public Shared ReadOnly FLAG_MARKERS As Integer = 1 << 1
''' <summary>
''' Flag for alternate metafactories indicating the lambda object requires
''' additional bridge methods
''' </summary>
Public Shared ReadOnly FLAG_BRIDGES As Integer = 1 << 2
Private Shared ReadOnly EMPTY_CLASS_ARRAY As [Class]() = New [Class](){}
Private Shared ReadOnly EMPTY_MT_ARRAY As MethodType() = New MethodType(){}
''' <summary>
''' Facilitates the creation of simple "function objects" that implement one
''' or more interfaces by delegation to a provided <seealso cref="MethodHandle"/>,
''' after appropriate type adaptation and partial evaluation of arguments.
''' Typically used as a <em>bootstrap method</em> for {@code invokedynamic}
''' call sites, to support the <em>lambda expression</em> and <em>method
''' reference expression</em> features of the Java Programming Language.
'''
''' <p>This is the standard, streamlined metafactory; additional flexibility
''' is provided by <seealso cref="#altMetafactory(MethodHandles.Lookup, String, MethodType, Object...)"/>.
''' A general description of the behavior of this method is provided
''' <seealso cref="LambdaMetafactory above"/>.
'''
''' <p>When the target of the {@code CallSite} returned from this method is
''' invoked, the resulting function objects are instances of a class which
''' implements the interface named by the return type of {@code invokedType},
''' declares a method with the name given by {@code invokedName} and the
''' signature given by {@code samMethodType}. It may also override additional
''' methods from {@code Object}.
''' </summary>
''' <param name="caller"> Represents a lookup context with the accessibility
''' privileges of the caller. When used with {@code invokedynamic},
''' this is stacked automatically by the VM. </param>
''' <param name="invokedName"> The name of the method to implement. When used with
''' {@code invokedynamic}, this is provided by the
''' {@code NameAndType} of the {@code InvokeDynamic}
''' structure and is stacked automatically by the VM. </param>
''' <param name="invokedType"> The expected signature of the {@code CallSite}. The
''' parameter types represent the types of capture variables;
''' the return type is the interface to implement. When
''' used with {@code invokedynamic}, this is provided by
''' the {@code NameAndType} of the {@code InvokeDynamic}
''' structure and is stacked automatically by the VM.
''' In the event that the implementation method is an
''' instance method and this signature has any parameters,
''' the first parameter in the invocation signature must
''' correspond to the receiver. </param>
''' <param name="samMethodType"> Signature and return type of method to be implemented
''' by the function object. </param>
''' <param name="implMethod"> A direct method handle describing the implementation
''' method which should be called (with suitable adaptation
''' of argument types, return types, and with captured
''' arguments prepended to the invocation arguments) at
''' invocation time. </param>
''' <param name="instantiatedMethodType"> The signature and return type that should
''' be enforced dynamically at invocation time.
''' This may be the same as {@code samMethodType},
''' or may be a specialization of it. </param>
''' <returns> a CallSite whose target can be used to perform capture, generating
''' instances of the interface named by {@code invokedType} </returns>
''' <exception cref="LambdaConversionException"> If any of the linkage invariants
''' described <seealso cref="LambdaMetafactory above"/>
''' are violated </exception>
Public Shared Function metafactory( caller As MethodHandles.Lookup, invokedName As String, invokedType As MethodType, samMethodType As MethodType, implMethod As MethodHandle, instantiatedMethodType As MethodType) As CallSite
Dim mf As AbstractValidatingLambdaMetafactory
mf = New InnerClassLambdaMetafactory(caller, invokedType, invokedName, samMethodType, implMethod, instantiatedMethodType, False, EMPTY_CLASS_ARRAY, EMPTY_MT_ARRAY)
mf.validateMetafactoryArgs()
Return mf.buildCallSite()
End Function
''' <summary>
''' Facilitates the creation of simple "function objects" that implement one
''' or more interfaces by delegation to a provided <seealso cref="MethodHandle"/>,
''' after appropriate type adaptation and partial evaluation of arguments.
''' Typically used as a <em>bootstrap method</em> for {@code invokedynamic}
''' call sites, to support the <em>lambda expression</em> and <em>method
''' reference expression</em> features of the Java Programming Language.
'''
''' <p>This is the general, more flexible metafactory; a streamlined version
''' is provided by {@link #metafactory(java.lang.invoke.MethodHandles.Lookup,
''' String, MethodType, MethodType, MethodHandle, MethodType)}.
''' A general description of the behavior of this method is provided
''' <seealso cref="LambdaMetafactory above"/>.
'''
''' <p>The argument list for this method includes three fixed parameters,
''' corresponding to the parameters automatically stacked by the VM for the
''' bootstrap method in an {@code invokedynamic} invocation, and an {@code Object[]}
''' parameter that contains additional parameters. The declared argument
''' list for this method is:
'''
''' <pre>{@code
''' CallSite altMetafactory(MethodHandles.Lookup caller,
''' String invokedName,
''' MethodType invokedType,
''' Object... args)
''' }</pre>
'''
''' <p>but it behaves as if the argument list is as follows:
'''
''' <pre>{@code
''' CallSite altMetafactory(MethodHandles.Lookup caller,
''' String invokedName,
''' MethodType invokedType,
''' MethodType samMethodType,
''' MethodHandle implMethod,
''' MethodType instantiatedMethodType,
''' int flags,
''' int markerInterfaceCount, // IF flags has MARKERS set
''' Class... markerInterfaces, // IF flags has MARKERS set
''' int bridgeCount, // IF flags has BRIDGES set
''' MethodType... bridges // IF flags has BRIDGES set
''' )
''' }</pre>
'''
''' <p>Arguments that appear in the argument list for
''' <seealso cref="#metafactory(MethodHandles.Lookup, String, MethodType, MethodType, MethodHandle, MethodType)"/>
''' have the same specification as in that method. The additional arguments
''' are interpreted as follows:
''' <ul>
''' <li>{@code flags} indicates additional options; this is a bitwise
''' OR of desired flags. Defined flags are <seealso cref="#FLAG_BRIDGES"/>,
''' <seealso cref="#FLAG_MARKERS"/>, and <seealso cref="#FLAG_SERIALIZABLE"/>.</li>
''' <li>{@code markerInterfaceCount} is the number of additional interfaces
''' the function object should implement, and is present if and only if the
''' {@code FLAG_MARKERS} flag is set.</li>
''' <li>{@code markerInterfaces} is a variable-length list of additional
''' interfaces to implement, whose length equals {@code markerInterfaceCount},
''' and is present if and only if the {@code FLAG_MARKERS} flag is set.</li>
''' <li>{@code bridgeCount} is the number of additional method signatures
''' the function object should implement, and is present if and only if
''' the {@code FLAG_BRIDGES} flag is set.</li>
''' <li>{@code bridges} is a variable-length list of additional
''' methods signatures to implement, whose length equals {@code bridgeCount},
''' and is present if and only if the {@code FLAG_BRIDGES} flag is set.</li>
''' </ul>
'''
''' <p>Each class named by {@code markerInterfaces} is subject to the same
''' restrictions as {@code Rd}, the return type of {@code invokedType},
''' as described <seealso cref="LambdaMetafactory above"/>. Each {@code MethodType}
''' named by {@code bridges} is subject to the same restrictions as
''' {@code samMethodType}, as described <seealso cref="LambdaMetafactory above"/>.
'''
''' <p>When FLAG_SERIALIZABLE is set in {@code flags}, the function objects
''' will implement {@code Serializable}, and will have a {@code writeReplace}
''' method that returns an appropriate <seealso cref="SerializedLambda"/>. The
''' {@code caller} class must have an appropriate {@code $deserializeLambda$}
''' method, as described in <seealso cref="SerializedLambda"/>.
'''
''' <p>When the target of the {@code CallSite} returned from this method is
''' invoked, the resulting function objects are instances of a class with
''' the following properties:
''' <ul>
''' <li>The class implements the interface named by the return type
''' of {@code invokedType} and any interfaces named by {@code markerInterfaces}</li>
''' <li>The class declares methods with the name given by {@code invokedName},
''' and the signature given by {@code samMethodType} and additional signatures
''' given by {@code bridges}</li>
''' <li>The class may override methods from {@code Object}, and may
''' implement methods related to serialization.</li>
''' </ul>
''' </summary>
''' <param name="caller"> Represents a lookup context with the accessibility
''' privileges of the caller. When used with {@code invokedynamic},
''' this is stacked automatically by the VM. </param>
''' <param name="invokedName"> The name of the method to implement. When used with
''' {@code invokedynamic}, this is provided by the
''' {@code NameAndType} of the {@code InvokeDynamic}
''' structure and is stacked automatically by the VM. </param>
''' <param name="invokedType"> The expected signature of the {@code CallSite}. The
''' parameter types represent the types of capture variables;
''' the return type is the interface to implement. When
''' used with {@code invokedynamic}, this is provided by
''' the {@code NameAndType} of the {@code InvokeDynamic}
''' structure and is stacked automatically by the VM.
''' In the event that the implementation method is an
''' instance method and this signature has any parameters,
''' the first parameter in the invocation signature must
''' correspond to the receiver. </param>
''' <param name="args"> An {@code Object[]} array containing the required
''' arguments {@code samMethodType}, {@code implMethod},
''' {@code instantiatedMethodType}, {@code flags}, and any
''' optional arguments, as described
''' <seealso cref="#altMetafactory(MethodHandles.Lookup, String, MethodType, Object...)"/> above} </param>
''' <returns> a CallSite whose target can be used to perform capture, generating
''' instances of the interface named by {@code invokedType} </returns>
''' <exception cref="LambdaConversionException"> If any of the linkage invariants
''' described <seealso cref="LambdaMetafactory above"/>
''' are violated </exception>
Public Shared Function altMetafactory( caller As MethodHandles.Lookup, invokedName As String, invokedType As MethodType, ParamArray args As Object()) As CallSite
Dim samMethodType As MethodType = CType(args(0), MethodType)
Dim implMethod As MethodHandle = CType(args(1), MethodHandle)
Dim instantiatedMethodType As MethodType = CType(args(2), MethodType)
Dim flags As Integer = CInt(Fix(args(3)))
Dim markerInterfaces As [Class]()
Dim bridges As MethodType()
Dim argIndex As Integer = 4
If (flags And FLAG_MARKERS) <> 0 Then
Dim markerCount As Integer = CInt(Fix(args(argIndex)))
argIndex += 1
markerInterfaces = New [Class](markerCount - 1){}
Array.Copy(args, argIndex, markerInterfaces, 0, markerCount)
argIndex += markerCount
Else
markerInterfaces = EMPTY_CLASS_ARRAY
End If
If (flags And FLAG_BRIDGES) <> 0 Then
Dim bridgeCount As Integer = CInt(Fix(args(argIndex)))
argIndex += 1
bridges = New MethodType(bridgeCount - 1){}
Array.Copy(args, argIndex, bridges, 0, bridgeCount)
argIndex += bridgeCount
Else
bridges = EMPTY_MT_ARRAY
End If
Dim isSerializable As Boolean = ((flags And FLAG_SERIALIZABLE) <> 0)
If isSerializable Then
Dim foundSerializableSupertype As Boolean = invokedType.returnType().IsSubclassOf(GetType(java.io.Serializable))
For Each c As [Class] In markerInterfaces
foundSerializableSupertype = foundSerializableSupertype Or c.IsSubclassOf(GetType(java.io.Serializable))
Next c
If Not foundSerializableSupertype Then
markerInterfaces = java.util.Arrays.copyOf(markerInterfaces, markerInterfaces.Length + 1)
markerInterfaces(markerInterfaces.Length-1) = GetType(java.io.Serializable)
End If
End If
Dim mf As AbstractValidatingLambdaMetafactory = New InnerClassLambdaMetafactory(caller, invokedType, invokedName, samMethodType, implMethod, instantiatedMethodType, isSerializable, markerInterfaces, bridges)
mf.validateMetafactoryArgs()
Return mf.buildCallSite()
End Function
End Class
End Namespace | Java |
::-webkit-scrollbar { width: 8px; height: 8px; }
::-webkit-scrollbar-track { background-color: #222; }
::-webkit-scrollbar-thumb { background-color: #ddd; }
.no-select {
user-select: none;
-webkit-user-select: none;
}
html,
body {
height: 100%;
margin: 0;
overflow: hidden;
font-family: var( --gsui-font );
background-color: var( --app-bg );
}
a {
color: inherit;
text-decoration: none;
}
| Java |
<?php
/**
* @copyright © 2005-2022 PHPBoost
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPL-3.0
* @author Julien BRISWALTER <j1.seth@phpboost.com>
* @version PHPBoost 6.0 - last update: 2021 12 05
* @since PHPBoost 3.0 - 2013 04 29
* @contributor Arnaud GENET <elenwii@phpboost.com>
* @contributor Sebastien LARTIGUE <babsolune@phpboost.com>
*/
class BugtrackerViews
{
public static function build_body_view(View $view, $current_page, $bug_id = 0, $bug_type = "")
{
$lang = LangLoader::get_all_langs('bugtracker');
$config = BugtrackerConfig::load();
$types = $config->get_types();
$body_view = new FileTemplate('bugtracker/BugtrackerBody.tpl');
$body_view->add_lang($lang);
$body_view->put_all(array(
'C_ROADMAP_ENABLED' => $config->is_roadmap_displayed(),
'C_STATS_ENABLED' => $config->are_stats_enabled(),
'C_DISPLAY_MENU' => in_array($current_page, array('unsolved', 'solved', 'roadmap', 'stats')),
'C_SYNDICATION' => $current_page == 'unsolved' || $current_page == 'solved',
'C_UNSOLVED' => $current_page == 'unsolved',
'C_SOLVED' => $current_page == 'solved',
'C_ROADMAP' => $current_page == 'roadmap',
'C_STATS' => $current_page == 'stats',
'L_TITLE' => $lang['bugtracker.' . $current_page] . (in_array($current_page, array('change_status', 'history', 'detail', 'edit')) ? " : " . $types[$bug_type] . ' #' .$bug_id : ''),
'TEMPLATE' => $view,
'U_SYNDICATION_UNSOLVED' => SyndicationUrlBuilder::rss('bugtracker', 0)->rel(),
'U_SYNDICATION_SOLVED' => SyndicationUrlBuilder::rss('bugtracker', 1)->rel()
));
return $body_view;
}
public static function build_filters($current_page, $nbr_bugs = 0)
{
$lang = LangLoader::get_all_langs('bugtracker');
$object = new self();
$request = AppContext::get_request();
$page = $request->get_int('page', 1);
$filter = $request->get_value('filter', '');
$filter_id = $request->get_value('filter_id', '');
if (!empty($filter) && empty($filter_id))
{
$filter = $filter_id = '';
}
$filters_tmp = $filters = !empty($filter) ? explode('-', $filter) : array();
$nb_filters = count($filters);
$filters_ids_tmp = $filters_ids = !empty($filter_id) ? explode('-', $filter_id) : array();
$nb_filters_ids = count($filters_ids);
if ($nb_filters != $nb_filters_ids)
{
for ($i = $nb_filters_ids; $i < $nb_filters; $i++)
{
$filters_ids[] = 0;
}
}
$display_save_button = AppContext::get_current_user()->check_level(User::MEMBER_LEVEL) && count($filters) >= 1;
$config = BugtrackerConfig::load();
$types = $config->get_types();
$categories = $config->get_categories();
$severities = $config->get_severities();
$versions = $config->get_versions_detected();
$all_versions = $config->get_versions();
$display_types = count($types);
$display_categories = count($categories);
$display_severities = count($severities);
$display_versions = count($versions);
$display_all_versions = count($all_versions);
$filters_number = 1;
if ($display_types) $filters_number = $filters_number + 1;
if ($display_categories) $filters_number = $filters_number + 1;
if ($display_severities) $filters_number = $filters_number + 1;
if ($display_versions || $display_all_versions) $filters_number = $filters_number + 1;
if (!empty($filters)) $filters_number = $filters_number + 1;
$filters_view = new FileTemplate('bugtracker/BugtrackerFilter.tpl');
$filters_view->add_lang($lang);
$result = PersistenceContext::get_querier()->select("SELECT *
FROM " . BugtrackerSetup::$bugtracker_users_filters_table . "
WHERE page = :page AND user_id = :user_id",
array(
'page' => $current_page,
'user_id' => AppContext::get_current_user()->get_id()
), SelectQueryResult::FETCH_ASSOC
);
$saved_filters = false;
while ($row = $result->fetch())
{
$row_filters_tmp = $row_filters = !empty($row['filters']) ? explode('-', $row['filters']) : array();
$row_filters_ids_tmp = $row_filters_ids = !empty($row['filters_ids']) ? explode('-', $row['filters_ids']) : array();
sort($filters_tmp, SORT_STRING);
sort($row_filters_tmp, SORT_STRING);
sort($filters_ids_tmp, SORT_STRING);
sort($row_filters_ids_tmp, SORT_STRING);
if (implode('-', $filters_tmp) == implode('-', $row_filters_tmp) && implode('-', $filters_ids_tmp) == implode('-', $row_filters_ids_tmp))
$display_save_button = false;
$filter_not_saved_value = '-------------';
$filter_type_value = in_array('type', $row_filters) && $row_filters_ids[array_search('type', $row_filters)] && isset($types[$row_filters_ids[array_search('type', $row_filters)]]) ? $types[$row_filters_ids[array_search('type', $row_filters)]] : $filter_not_saved_value;
$filter_category_value = in_array('category', $row_filters) && $row_filters_ids[array_search('category', $row_filters)] && isset($categories[$row_filters_ids[array_search('category', $row_filters)]]) ? $categories[$row_filters_ids[array_search('category', $row_filters)]] : $filter_not_saved_value;
$filter_severity_value = in_array('severity', $row_filters) && $row_filters_ids[array_search('severity', $row_filters)] && isset($severities[$row_filters_ids[array_search('severity', $row_filters)]]) ? $severities[$row_filters_ids[array_search('severity', $row_filters)]]['name'] : $filter_not_saved_value;
$filter_status_value = in_array('status', $row_filters) && $row_filters_ids[array_search('status', $row_filters)] && isset($lang['status.' . $row_filters_ids[array_search('status', $row_filters)]]) ? $lang['status.' . $row_filters_ids[array_search('status', $row_filters)]] : $filter_not_saved_value;
$filter_version_value = ($current_page == 'unsolved' ? (in_array('detected_in', $row_filters) && $row_filters_ids[array_search('detected_in', $row_filters)] && isset($versions[$row_filters_ids[array_search('detected_in', $row_filters)]]) ? $versions[$row_filters_ids[array_search('detected_in', $row_filters)]]['name'] : $filter_not_saved_value) : (in_array('fixed_in', $row_filters) && $row_filters_ids[array_search('fixed_in', $row_filters)] && isset($all_versions[$row_filters_ids[array_search('fixed_in', $row_filters)]]) ? $all_versions[$row_filters_ids[array_search('fixed_in', $row_filters)]]['name'] : $filter_not_saved_value));
$filters_view->assign_block_vars('filters', array(
'ID' => $row['id'],
'FILTER' => '| ' . $filter_type_value . ' | ' . $filter_category_value . ' | ' . $filter_severity_value . ' | ' . $filter_status_value . ' | ' . $filter_version_value . ' |',
'LINK_FILTER' => ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, $row['filters'], $row['filters_ids'])->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, $row['filters'], $row['filters_ids'])->rel()),
));
$saved_filters = true;
}
$result->dispose();
$filters_view->put_all(array(
'C_SEVERAL_FILTERS' => $filters_number > 1,
'C_DISPLAY_TYPES' => $display_types,
'C_DISPLAY_CATEGORIES' => $display_categories,
'C_DISPLAY_SEVERITIES' => $display_severities,
'C_DISPLAY_VERSIONS' => $current_page == 'solved' ? $display_all_versions : $display_versions,
'C_DISPLAY_SAVE_BUTTON' => $display_save_button,
'C_SAVED_FILTERS' => $saved_filters,
'C_HAS_SELECTED_FILTERS'=> $filters,
'FILTERS_NUMBER' => $filters_number,
'BUGS_NUMBER' => $nbr_bugs,
'LINK_FILTER_SAVE' => BugtrackerUrlBuilder::add_filter($current_page, $filter, $filter_id)->rel(),
'SELECT_TYPE' => $object->build_types_form($current_page,($filter == 'type') ? $filter_id : (in_array('type', $filters) ? $filters_ids[array_search('type', $filters)] : 0), $filters, $filters_ids)->display(),
'SELECT_CATEGORY' => $object->build_categories_form($current_page, ($filter == 'category') ? $filter_id : (in_array('category', $filters) ? $filters_ids[array_search('category', $filters)] : 0), $filters, $filters_ids)->display(),
'SELECT_SEVERITY' => $object->build_severities_form($current_page, ($filter == 'severity') ? $filter_id : (in_array('severity', $filters) ? $filters_ids[array_search('severity', $filters)] : 0), $filters, $filters_ids)->display(),
'SELECT_STATUS' => $object->build_status_form($current_page, ($filter == 'status') ? $filter_id : (in_array('status', $filters) ? $filters_ids[array_search('status', $filters)] : 0), $filters, $filters_ids, $lang)->display(),
'SELECT_VERSION' => $object->build_versions_form($current_page, ($current_page == 'unsolved' ? (($filter == 'detected_in') ? $filter_id : (in_array('detected_in', $filters) ? $filters_ids[array_search('detected_in', $filters)] : 0)) : (($filter == 'fixed_in') ? $filter_id : (in_array('fixed_in', $filters) ? $filters_ids[array_search('fixed_in', $filters)] : 0))), $filters, $filters_ids)->display(),
));
return $filters_view;
}
public static function build_legend($list, $current_page)
{
$lang = LangLoader::get_all_langs('bugtracker');
$config = BugtrackerConfig::load();
$severities = $config->get_severities();
$legend_view = new FileTemplate('bugtracker/BugtrackerLegend.tpl');
$legend_view->add_lang($lang);
$legend_colspan = 0;
foreach ($list as $element)
{
if (($current_page == 'solved') || (!empty($element) && isset($severities[$element])))
{
$legend_view->assign_block_vars('legend', array(
'COLOR' => $current_page == 'solved' ? ($element == 'fixed' ? $config->get_fixed_bug_color() : $config->get_rejected_bug_color()) : stripslashes($severities[$element]['color']),
'NAME' => $current_page == 'solved' ? $lang['status.' . $element] : stripslashes($severities[$element]['name'])
));
$legend_colspan = $legend_colspan + 3;
}
}
$legend_view->put_all(array(
'LEGEND_COLSPAN' => $legend_colspan
));
return ($legend_colspan ? $legend_view : new StringTemplate(''));
}
private function build_types_form($current_page, $requested_type, $filters, $filters_ids)
{
if (in_array('type', $filters))
{
$key = array_search('type', $filters);
unset($filters[$key]);
unset($filters_ids[$key]);
}
$filter = implode('-', $filters);
$filter_id = implode('-', $filters_ids);
$form = new HTMLForm('type-form', '', false);
$fieldset = new FormFieldsetHorizontal('filter-type');
$form->add_fieldset($fieldset);
$fieldset->add_field(new FormFieldSimpleSelectChoice('filter_type', '', $requested_type, $this->build_select_types(),
array(
'events' => array('change' => '
if (HTMLForms.getField("filter_type").getValue() > 0) {
document.location = "'. ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'type', (!empty($filter_id) ? $filter_id . '-' : ''))->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'type', (!empty($filter_id) ? $filter_id . '-' : ''))->rel()) .'" + HTMLForms.getField("filter_type").getValue();
} else {
document.location = "'. ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, $filter, $filter_id)->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, $filter, $filter_id)->rel()) .'";
}'
)
)
));
return $form;
}
private function build_select_types()
{
$types = BugtrackerConfig::load()->get_types();
$array_types = array();
$array_types[] = new FormFieldSelectChoiceOption(' ', 0);
foreach ($types as $key => $type)
{
$array_types[] = new FormFieldSelectChoiceOption(stripslashes($type), $key);
}
return $array_types;
}
private function build_categories_form($current_page, $requested_category, $filters, $filters_ids)
{
if (in_array('category', $filters))
{
$key = array_search('category', $filters);
unset($filters[$key]);
unset($filters_ids[$key]);
}
$filter = implode('-', $filters);
$filter_id = implode('-', $filters_ids);
$form = new HTMLForm('category-form', '', false);
$fieldset = new FormFieldsetHorizontal('filter-category');
$form->add_fieldset($fieldset);
$fieldset->add_field(new FormFieldSimpleSelectChoice('filter_category', '', $requested_category, $this->build_select_categories(),
array('events' => array('change' => 'if (HTMLForms.getField("filter_category").getValue() > 0) {
document.location = "'. ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'category', (!empty($filter_id) ? $filter_id . '-' : ''))->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'category', (!empty($filter_id) ? $filter_id . '-' : ''))->rel()) .'" + HTMLForms.getField("filter_category").getValue();
} else {
document.location = "'. ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, $filter, $filter_id)->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, $filter, $filter_id)->rel()) .'";
}')
)));
return $form;
}
private function build_select_categories()
{
$categories = BugtrackerConfig::load()->get_categories();
$array_categories = array();
$array_categories[] = new FormFieldSelectChoiceOption(' ', 0);
foreach ($categories as $key => $category)
{
$array_categories[] = new FormFieldSelectChoiceOption(stripslashes($category), $key);
}
return $array_categories;
}
private function build_severities_form($current_page, $requested_severity, $filters, $filters_ids)
{
if (in_array('severity', $filters))
{
$key = array_search('severity', $filters);
unset($filters[$key]);
unset($filters_ids[$key]);
}
$filter = implode('-', $filters);
$filter_id = implode('-', $filters_ids);
$form = new HTMLForm('severity-form', '', false);
$fieldset = new FormFieldsetHorizontal('filter-severity');
$form->add_fieldset($fieldset);
$fieldset->add_field(new FormFieldSimpleSelectChoice('filter_severity', '', $requested_severity, $this->build_select_severities(),
array('events' => array('change' => 'if (HTMLForms.getField("filter_severity").getValue() > 0) {
document.location = "'. ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'severity', (!empty($filter_id) ? $filter_id . '-' : ''))->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'severity', (!empty($filter_id) ? $filter_id . '-' : ''))->rel()) .'" + HTMLForms.getField("filter_severity").getValue();
} else {
document.location = "'. ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, $filter, $filter_id)->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, $filter, $filter_id)->rel()) .'";
}')
)));
return $form;
}
private function build_select_severities()
{
$severities = BugtrackerConfig::load()->get_severities();
$array_categories = array();
$array_severities[] = new FormFieldSelectChoiceOption(' ', 0);
foreach ($severities as $key => $severity)
{
$array_severities[] = new FormFieldSelectChoiceOption(stripslashes($severity['name']), $key);
}
return $array_severities;
}
private function build_status_form($current_page, $requested_status, $filters, $filters_ids, $lang)
{
if (in_array('status', $filters))
{
$key = array_search('status', $filters);
unset($filters[$key]);
unset($filters_ids[$key]);
}
$filter = implode('-', $filters);
$filter_id = implode('-', $filters_ids);
$form = new HTMLForm('status-form', '', false);
$fieldset = new FormFieldsetHorizontal('filter-status');
$form->add_fieldset($fieldset);
$fieldset->add_field(new FormFieldSimpleSelectChoice('filter_status', '', $requested_status, $this->build_select_status($current_page, $lang),
array('events' => array('change' => 'if (HTMLForms.getField("filter_status").getValue()) {
document.location = "'. ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'status', (!empty($filter_id) ? $filter_id . '-' : ''))->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'status', (!empty($filter_id) ? $filter_id . '-' : ''))->rel()) .'" + HTMLForms.getField("filter_status").getValue();
} else {
document.location = "'. ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, $filter, $filter_id)->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, $filter, $filter_id)->rel()) .'";
}')
)));
return $form;
}
private function build_select_status($current_page, $lang)
{
$status_list = BugtrackerConfig::load()->get_status_list();
$array_status = array();
$array_status[] = new FormFieldSelectChoiceOption(' ', '');
foreach ($status_list as $status => $progress)
{
if (($current_page == 'unsolved' && !in_array($status, array(BugtrackerItem::FIXED, BugtrackerItem::REJECTED))) || ($current_page == 'solved' && in_array($status, array(BugtrackerItem::FIXED, BugtrackerItem::REJECTED))))
$array_status[] = new FormFieldSelectChoiceOption($lang['status.' . $status], $status);
}
return $array_status;
}
private function build_versions_form($current_page, $requested_version, $filters, $filters_ids)
{
$search_field = ($current_page == 'unsolved' ? 'detected_in' : 'fixed_in');
if (in_array($search_field , $filters))
{
$key = array_search($search_field , $filters);
unset($filters[$key]);
unset($filters_ids[$key]);
}
$filter = implode('-', $filters);
$filter_id = implode('-', $filters_ids);
$form = new HTMLForm('version-form', '', false);
$fieldset = new FormFieldsetHorizontal('filter-version');
$form->add_fieldset($fieldset);
$fieldset->add_field(new FormFieldSimpleSelectChoice('filter_version', '', $requested_version, $this->build_select_versions($current_page),
array('events' => array('change' => 'if (HTMLForms.getField("filter_version").getValue() > 0) {
document.location = "'. ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'detected_in', (!empty($filter_id) ? $filter_id . '-' : ''))->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'fixed_in', (!empty($filter_id) ? $filter_id . '-' : ''))->rel()) .'" + HTMLForms.getField("filter_version").getValue();
} else {
document.location = "'. ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, $filter, $filter_id)->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, $filter, $filter_id)->rel()) .'";
}')
)));
return $form;
}
private function build_select_versions($current_page)
{
$versions = ($current_page == 'unsolved' ? BugtrackerConfig::load()->get_versions_detected() : BugtrackerConfig::load()->get_versions());
$versions = array_reverse($versions, true);
$array_versions = array();
$array_versions[] = new FormFieldSelectChoiceOption(' ', '');
foreach ($versions as $key => $version)
{
$array_versions[] = new FormFieldSelectChoiceOption(stripslashes($version['name']), $key);
}
return $array_versions;
}
}
?>
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entidades
{
public class Class1
{
}
}
| Java |
package l2s.gameserver.network.l2.s2c;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import l2s.commons.lang.ArrayUtils;
import l2s.gameserver.model.Player;
import l2s.gameserver.model.items.ItemInfo;
import l2s.gameserver.model.items.ItemInstance;
import l2s.gameserver.model.items.Warehouse.ItemClassComparator;
import l2s.gameserver.model.items.Warehouse.WarehouseType;
public class WareHouseWithdrawListPacket extends L2GameServerPacket
{
private long _adena;
private List<ItemInfo> _itemList = new ArrayList<ItemInfo>();
private int _type;
private int _inventoryUsedSlots;
public WareHouseWithdrawListPacket(Player player, WarehouseType type)
{
_adena = player.getAdena();
_type = type.ordinal();
ItemInstance[] items;
switch(type)
{
case PRIVATE:
items = player.getWarehouse().getItems();
break;
case FREIGHT:
items = player.getFreight().getItems();
break;
case CLAN:
case CASTLE:
items = player.getClan().getWarehouse().getItems();
break;
default:
_itemList = Collections.emptyList();
return;
}
_itemList = new ArrayList<ItemInfo>(items.length);
ArrayUtils.eqSort(items, ItemClassComparator.getInstance());
for(ItemInstance item : items)
_itemList.add(new ItemInfo(item));
_inventoryUsedSlots = player.getInventory().getSize();
}
@Override
protected final void writeImpl()
{
writeH(_type);
writeQ(_adena);
writeH(_itemList.size());
if(_type == 1 || _type == 2)
{
if(_itemList.size() > 0)
{
writeH(0x01);
writeD(0x1063); // TODO: writeD(_itemList.get(0).getItemId()); первый предмет в списке.
}
else
writeH(0x00);
}
writeD(_inventoryUsedSlots); //Количество занятых ячеек в инвентаре.
for(ItemInfo item : _itemList)
{
writeItemInfo(item);
writeD(item.getObjectId());
writeD(0);
writeD(0);
}
}
} | Java |
# -*- coding: utf-8 -*-
from django.contrib import admin
from models import FileMapping
# Register your models here.
admin.site.register(FileMapping)
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Aviso de Privacidad</title>
<!-- Bootstrap Core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Cinzel:400,700" rel="stylesheet" type="text/css">
<!-- Theme CSS -->
<link href="css/creative.min.css" rel="stylesheet">
<!-- Pagina Inicial CSS -->
<link href="css/pagina-inicial.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body id="page-top">
<!-- Navegacion inicia -->
<nav id="mainNav" class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i>
</button>
<a class="navbar-brand page-scroll" href="index.html">La Caja Blanca</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li>
<a class="page-scroll" href="index.html#services">¿Cómo funciona?</a>
</li>
<li>
<a class="page-scroll" href="index.html#contact">Contacto</a>
</li>
<li>
<a class="page-scroll" href="#">Aviso de Privacidad</a>
</li>
<li>
<a class="page-scroll" href="terminos-condiciones.html">Términos y Condiciones</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Navegacion termina -->
<!-- Aviso inicia -->
<section id="aviso">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 text-center">
<h2 class="section-heading">Aviso de Privacidad</h2>
<hr class="primary">
</div>
<div class="col-lg-8 aviso-privacidad">
<p>Nemosíntesis SC de RL, mejor conocido como La Caja Blanca, con domicilio en calle Río de la Plata 209, colonia
Navarro, ciudad Torreón, municipio o delegación Torreón, C.P. 27010, en la entidad de Coahuila, país México, y portal
de internet www.lacajablanca.mx, es el responsable del uso y protección de sus datos personales, y al respecto
le informamos lo siguiente:</p>
<p>¿Para qué fines utilizaremos sus datos personales?</p>
<p>Los datos personales que recabamos de usted, los utilizaremos para las siguientes finalidades que son necesarias
para el servicio que solicita:</p>
<ul>
<li>Para verificar y confirmar su identidad</li>
<li>Para entrega de productos a domicilio</li>
<li>Para llevar a cabo encuestas de satisfacción</li>
<li>Para informarle y/o contactarle con fines mercadológicos</li>
<li>Para evaluar la calidad de los productos</li>
</ul>
<p>De manera adicional, utilizaremos su información personal para las siguientes <b>finalidades secundarias</b> que no son
necesarias para el servicio solicitado, pero que nos permiten y facilitan brindarle una mejor atención:</p>
<ul>
<li>Mercadotecnia o publicidad</li>
<li>Prospección comercial</li>
</ul>
<p>En caso de que no desee que sus datos personales se utilicen para estos <b>fines secundarios</b>, indíquelo por medio de un correo electrónico a sitiodelacaja@gmail.com con el mensaje:</p>
<blockquote>
No consiento que mis datos personales se utilicen para los fines de Mercadotecnia, publicidad o prospección comercial
</blockquote>
<p>La negativa para el uso de sus datos personales para estas finalidades no podrá ser un motivo para que le neguemos
los servicios y productos que solicita o contrata con nosotros.</p>
<p>¿Qué datos personales utilizaremos para estos fines?</p>
Para llevar a cabo las finalidades descritas en el presente aviso de privacidad, utilizaremos los siguientes datos
personales:
<ul>
<li>Nombre</li>
<li>Nombre de su pareja o cónyuge</li>
<li>Estado Civil</li>
<li>Fecha de nacimiento</li>
<li>Fecha de matrimonio civil</li>
<li>Domicilio</li>
<li>Teléfono particular</li>
<li>Teléfono celular</li>
<li> Correo electrónico</li>
</ul>
<p>¿Con quién compartimos su información personal y para qué fines?</p>
<p>Le informamos que sus datos personales son compartidos dentro del país con empresas dedicadas al servicio de paquetería con la finalidad de hacer llegar los productos a su domicilio.</p>
<p>¿Cómo puede acceder, rectificar o cancelar sus datos personales, u oponerse a su uso?</p>
<p>Usted tiene derecho a conocer qué datos personales tenemos de usted, para qué los utilizamos y las condiciones del
uso que les damos (Acceso). Asimismo, es su derecho solicitar la corrección de su información personal en caso de
que esté desactualizada, sea inexacta o incompleta (Rectificación); que la eliminemos de nuestros registros o bases
de datos cuando considere que la misma no está siendo utilizada adecuadamente (Cancelación); así como oponerse
al uso de sus datos personales para fines específicos (Oposición). Estos derechos se conocen como derechos
ARCO.</p>
<p>Para el ejercicio de cualquiera de los derechos ARCO, usted deberá presentar la solicitud respectiva enviando un correo electrónico a sitiodelacaja@gmail.com</p>
<p>Para conocer el procedimiento y requisitos para el ejercicio de los derechos ARCO, ponemos a su disposición el
siguiente medio: www.lacajablanca.mx/aviso-privacidad.html</p>
<p>Los datos de contacto de la persona o departamento de datos personales, que está a cargo de dar trámite a las
solicitudes de derechos ARCO, son los siguientes:</p>
<p>
a) Nombre de la persona o departamento de datos personales: Atención a Clientes La Caja Blanca<br>
b) Domicilio: Calle Río de la Plata 2019, Colonia Navarro, Ciudad Torreón, C.P. 27010<br>
c) Correo electrónico: sitiodelacaja@gmail.com<br>
d) Número telefónico: 8717179849<br></p>
<p>Usted puede revocar el consentimiento que, en su caso, nos haya otorgado para el tratamiento de sus datos
personales. Sin embargo, es importante que tenga en cuenta que no en todos los casos podremos atender su
solicitud o concluir el uso de forma inmediata, ya que es posible que por alguna obligación legal requiramos seguir
tratando sus datos personales. Asimismo, usted deberá considerar que para ciertos fines, la revocación de su
consentimiento implicará que no le podamos seguir prestando el servicio que nos solicitó, o la conclusión de su
relación con nosotros.</p>
<p>Para revocar su consentimiento deberá presentar su solicitud a través del siguiente medio:
sitiodelacaja@gmail.com</p>
<p>Para conocer el procedimiento y requisitos para la revocación del consentimiento, ponemos a su disposición el
siguiente medio: www.lacajablanca.mx/aviso-privacidad.html</p>
<p>¿Cómo puede limitar el uso o divulgación de su información personal?
<p>Con objeto de que usted pueda limitar el uso y divulgación de su información personal, le ofrecemos los siguientes
medios: sitiodelacaja@gmail.com</p>
<p>Asimismo, usted se podrá inscribir a los siguientes registros, en caso de que no desee obtener publicidad de nuestra
parte:</p>
<p>Registro Público para Evitar Publicidad, para mayor información consulte el portal de internet de la <a href="https://www.gob.mx/profeco">PROFECO</a><br>
Registro Público de Usuarios, para mayor información consulte el portal de internet de la <a href="https://www.gob.mx/condusef">CONDUSEF</a>.</p>
<p>¿Cómo puede conocer los cambios en este aviso de privacidad?</p>
<p>El presente aviso de privacidad puede sufrir modificaciones, cambios o actualizaciones derivadas de nuevos
requerimientos legals; de nuestras propias necesidades por los productos o servicios que ofrecemos; de nuestras
prácticas de privacidad; de cambios en nuestro modelo de negocio, o por otras causas.
Nos comprometemos a mantenerlo informado sobre los cambios que pueda sufrir el presente aviso de privacidad, a
través de: www.lacajablanca.mx.</p>
<p>El procedimiento a través del cual se llevarán a cabo las notificaciones sobre cambios o actualizaciones al presente
aviso de privacidad es el siguiente: a través de la página de internet www.lacajablanca.mx</p>
<p>Última actualización: 22/08/2017</p>
</div>
</div>
</div>
</section>
<!-- Aviso termina -->
<!-- jQuery -->
<script src="vendor/jquery/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<!-- Theme JavaScript -->
<script src="js/creative.min.js"></script>
</body>
</html>
| Java |
<?php
/**
* BwPostman Newsletter Component
*
* BwPostman form field Text templates class.
*
* @version %%version_number%%
* @package BwPostman-Admin
* @author Karl Klostermann
* @copyright (C) %%copyright_year%% Boldt Webservice <forum@boldt-webservice.de>
* @support https://www.boldt-webservice.de/en/forum-en/forum/bwpostman.html
* @license GNU/GPL, see LICENSE.txt
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace BoldtWebservice\Component\BwPostman\Administrator\Field;
defined('JPATH_PLATFORM') or die;
use BoldtWebservice\Component\BwPostman\Administrator\Helper\BwPostmanHelper;
use Exception;
use Joomla\CMS\Factory;
use Joomla\CMS\Form\Field\RadioField;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Uri\Uri;
use RuntimeException;
/**
* Form Field class for the Joomla Platform.
* Supports a nested check box field listing user groups.
* Multi select is available by default.
*
* @package BwPostman.Administrator
*
* @since 1.2.0
*/
class TexttemplatesField extends RadioField
{
/**
* The form field type.
*
* @var string
*
* @since 1.2.0
*/
protected $type = 'Texttemplates';
/**
* Method to get the Text template field input markup.
*
* @return string The field input markup.
*
* @throws Exception
*
* @since 1.2.0
*/
protected function getInput(): string
{
$item = Factory::getApplication()->getUserState('com_bwpostman.edit.newsletter.data');
$html = array();
$selected = '';
// Initialize some field attributes.
$readonly = $this->readonly;
// Get the field options.
$options = $this->getOptions();
// Get selected template.
if (is_object($item))
{
$selected = $item->text_template_id;
}
// note for old templates
if ($selected < 1)
{
$html[] = Text::_('COM_BWPOSTMAN_NOTE_OLD_TEMPLATE');
}
if (count($options) > 0)
{
// Build the radio field output.
foreach ($options as $i => $option)
{
// Initialize some option attributes.
$checked = ((string) $option->value == (string) $selected) ? ' checked="checked"' : '';
$lblclass = ' class="mailinglists form-check-label"';
$inputclass = ' class="mailinglists form-check-input"';
$disabled = !empty($option->disable) || ($readonly && !$checked);
$disabled = $disabled ? ' disabled' : '';
// Initialize some JavaScript option attributes.
$onclick = !empty($option->onclick) ? ' onclick="' . $option->onclick . '"' : '';
$onchange = !empty($option->onchange) ? ' onchange="' . $option->onchange . '"' : '';
$html[] = '<div class="form-check" aria-describedby="tip-' . $this->id . $i . '">';
$html[] = '<input type="radio" id="' . $this->id . $i . '" name="' . $this->name . '" value="'
. htmlspecialchars($option->value, ENT_COMPAT) . '"' . $checked . $inputclass . $onclick
. $onchange . $disabled . ' />';
$html[] = '<label for="' . $this->id . $i . '"' . $lblclass . ' >';
$html[] = $option->title . '</label>';
$tooltip = '<strong>' . $option->description . '</strong><br /><br />'
. '<div><img src="' . Uri::root() . $option->thumbnail . '" alt="' . $option->title . '"'
.'style="max-width:160px; max-height:100px;" /></div>';
$html[] = '<div role="tooltip" id="tip-' . $this->id . $i . '">'.$tooltip.'</div>';
$html[] = '</div>';
}
}
else
{
$html[] = Text::_('COM_BWPOSTMAN_NO_DATA');
}
// End the radio field output.
// $html[] = '</div>';
return implode($html);
}
/**
* Method to get the field options.
*
* @return array The field option objects.
*
* @throws Exception
*
* @since 1.2.0
*/
public function getOptions(): array
{
$app = Factory::getApplication();
// Initialize variables.
$item = $app->getUserState('com_bwpostman.edit.newsletter.data');
$options = array();
// prepare query
$db = BwPostmanHelper::getDbo();
// Build the select list for the templates
$query = $db->getQuery(true);
$query->select($db->quoteName('id') . ' AS ' . $db->quoteName('value'));
$query->select($db->quoteName('title') . ' AS ' . $db->quoteName('title'));
$query->select($db->quoteName('description') . ' AS ' . $db->quoteName('description'));
$query->select($db->quoteName('thumbnail') . ' AS ' . $db->quoteName('thumbnail'));
$query->from($db->quoteName('#__bwpostman_templates'));
// special for old newsletters with template_id < 1
if (is_object($item))
{
if ($item->text_template_id < 1 && !is_null($item->text_template_id))
{
$query->where($db->quoteName('id') . ' >= ' . $db->quote('-2'));
}
else
{
$query->where($db->quoteName('id') . ' > ' . $db->quote('0'));
}
}
$query->where($db->quoteName('archive_flag') . ' = ' . $db->quote('0'));
$query->where($db->quoteName('published') . ' = ' . $db->quote('1'));
$query->where($db->quoteName('tpl_id') . ' > ' . $db->quote('997'));
$query->order($db->quoteName('title') . ' ASC');
try
{
$db->setQuery($query);
$options = $db->loadObjectList();
}
catch (RuntimeException $e)
{
Factory::getApplication()->enqueueMessage($e->getMessage(), 'error');
}
// Merge any additional options in the XML definition.
return array_merge(parent::getOptions(), $options);
}
}
| Java |
#ifndef __BACKTRACE_H__
#define __BACKTRACE_H__
#include <stdint.h>
void __backtrace(uintptr_t rbp, uintptr_t stack_begin, uintptr_t stack_end);
uintptr_t stack_begin(void);
uintptr_t stack_end(void);
void backtrace(void);
#endif /*__BACKTRACE_H__*/
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="ro">
<head>
<!-- Generated by javadoc (version 1.7.0_80) on Mon Jun 20 18:37:10 EEST 2016 -->
<title>SimplePrintPart (JasperReports 6.3.0 API)</title>
<meta name="date" content="2016-06-20">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="SimplePrintPart (JasperReports 6.3.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/SimplePrintPart.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../net/sf/jasperreports/engine/SimplePrintPageFormat.html" title="class in net.sf.jasperreports.engine"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../net/sf/jasperreports/engine/SimpleReportContext.html" title="class in net.sf.jasperreports.engine"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?net/sf/jasperreports/engine/SimplePrintPart.html" target="_top">Frames</a></li>
<li><a href="SimplePrintPart.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">net.sf.jasperreports.engine</div>
<h2 title="Class SimplePrintPart" class="title">Class SimplePrintPart</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>net.sf.jasperreports.engine.SimplePrintPart</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.io.Serializable, <a href="../../../../net/sf/jasperreports/engine/PrintPart.html" title="interface in net.sf.jasperreports.engine">PrintPart</a></dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong">SimplePrintPart</span>
extends java.lang.Object
implements <a href="../../../../net/sf/jasperreports/engine/PrintPart.html" title="interface in net.sf.jasperreports.engine">PrintPart</a>, java.io.Serializable</pre>
<dl><dt><span class="strong">Author:</span></dt>
<dd>Teodor Danciu (teodord@users.sourceforge.net)</dd>
<dt><span class="strong">See Also:</span></dt><dd><a href="../../../../serialized-form.html#net.sf.jasperreports.engine.SimplePrintPart">Serialized Form</a></dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html#SimplePrintPart()">SimplePrintPart</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html" title="class in net.sf.jasperreports.engine">SimplePrintPart</a></code></td>
<td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html#fromJasperPrint(net.sf.jasperreports.engine.JasperPrint,%20java.lang.String)">fromJasperPrint</a></strong>(<a href="../../../../net/sf/jasperreports/engine/JasperPrint.html" title="class in net.sf.jasperreports.engine">JasperPrint</a> partJasperPrint,
java.lang.String partName)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html#getName()">getName</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../net/sf/jasperreports/engine/PrintPageFormat.html" title="interface in net.sf.jasperreports.engine">PrintPageFormat</a></code></td>
<td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html#getPageFormat()">getPageFormat</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html#setName(java.lang.String)">setName</a></strong>(java.lang.String name)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html#setPageFormat(net.sf.jasperreports.engine.PrintPageFormat)">setPageFormat</a></strong>(<a href="../../../../net/sf/jasperreports/engine/PrintPageFormat.html" title="interface in net.sf.jasperreports.engine">PrintPageFormat</a> pageFormat)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="SimplePrintPart()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>SimplePrintPart</h4>
<pre>public SimplePrintPart()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="fromJasperPrint(net.sf.jasperreports.engine.JasperPrint, java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>fromJasperPrint</h4>
<pre>public static <a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html" title="class in net.sf.jasperreports.engine">SimplePrintPart</a> fromJasperPrint(<a href="../../../../net/sf/jasperreports/engine/JasperPrint.html" title="class in net.sf.jasperreports.engine">JasperPrint</a> partJasperPrint,
java.lang.String partName)</pre>
</li>
</ul>
<a name="getName()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getName</h4>
<pre>public java.lang.String getName()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../net/sf/jasperreports/engine/PrintPart.html#getName()">getName</a></code> in interface <code><a href="../../../../net/sf/jasperreports/engine/PrintPart.html" title="interface in net.sf.jasperreports.engine">PrintPart</a></code></dd>
</dl>
</li>
</ul>
<a name="setName(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setName</h4>
<pre>public void setName(java.lang.String name)</pre>
</li>
</ul>
<a name="getPageFormat()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getPageFormat</h4>
<pre>public <a href="../../../../net/sf/jasperreports/engine/PrintPageFormat.html" title="interface in net.sf.jasperreports.engine">PrintPageFormat</a> getPageFormat()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../net/sf/jasperreports/engine/PrintPart.html#getPageFormat()">getPageFormat</a></code> in interface <code><a href="../../../../net/sf/jasperreports/engine/PrintPart.html" title="interface in net.sf.jasperreports.engine">PrintPart</a></code></dd>
</dl>
</li>
</ul>
<a name="setPageFormat(net.sf.jasperreports.engine.PrintPageFormat)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>setPageFormat</h4>
<pre>public void setPageFormat(<a href="../../../../net/sf/jasperreports/engine/PrintPageFormat.html" title="interface in net.sf.jasperreports.engine">PrintPageFormat</a> pageFormat)</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/SimplePrintPart.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../net/sf/jasperreports/engine/SimplePrintPageFormat.html" title="class in net.sf.jasperreports.engine"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../net/sf/jasperreports/engine/SimpleReportContext.html" title="class in net.sf.jasperreports.engine"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?net/sf/jasperreports/engine/SimplePrintPart.html" target="_top">Frames</a></li>
<li><a href="SimplePrintPart.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<span style="font-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:8pt;font-style:normal;color:#000000;">© 2001 - 2016 TIBCO Software Inc. <a href="http://www.jaspersoft.com" target="_blank" style="color:#000000;">www.jaspersoft.com</a></span>
</small></p>
</body>
</html>
| Java |
/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo
* This benchmark is part of SWSC */
#include <assert.h>
#include <stdint.h>
#include <stdatomic.h>
#include <pthread.h>
atomic_int vars[3];
atomic_int atom_0_r3_2;
atomic_int atom_1_r1_1;
void *t0(void *arg){
label_1:;
atomic_store_explicit(&vars[0], 2, memory_order_seq_cst);
int v2_r3 = atomic_load_explicit(&vars[0], memory_order_seq_cst);
int v3_r4 = v2_r3 ^ v2_r3;
atomic_store_explicit(&vars[1+v3_r4], 1, memory_order_seq_cst);
atomic_store_explicit(&vars[2], 1, memory_order_seq_cst);
int v14 = (v2_r3 == 2);
atomic_store_explicit(&atom_0_r3_2, v14, memory_order_seq_cst);
return NULL;
}
void *t1(void *arg){
label_2:;
int v5_r1 = atomic_load_explicit(&vars[2], memory_order_seq_cst);
int v6_r3 = v5_r1 ^ v5_r1;
int v7_r3 = v6_r3 + 1;
atomic_store_explicit(&vars[0], v7_r3, memory_order_seq_cst);
int v15 = (v5_r1 == 1);
atomic_store_explicit(&atom_1_r1_1, v15, memory_order_seq_cst);
return NULL;
}
int main(int argc, char *argv[]){
pthread_t thr0;
pthread_t thr1;
atomic_init(&vars[0], 0);
atomic_init(&vars[2], 0);
atomic_init(&vars[1], 0);
atomic_init(&atom_0_r3_2, 0);
atomic_init(&atom_1_r1_1, 0);
pthread_create(&thr0, NULL, t0, NULL);
pthread_create(&thr1, NULL, t1, NULL);
pthread_join(thr0, NULL);
pthread_join(thr1, NULL);
int v8 = atomic_load_explicit(&atom_0_r3_2, memory_order_seq_cst);
int v9 = atomic_load_explicit(&vars[0], memory_order_seq_cst);
int v10 = (v9 == 2);
int v11 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst);
int v12_conj = v10 & v11;
int v13_conj = v8 & v12_conj;
if (v13_conj == 1) assert(0);
return 0;
}
| Java |
<?php
namespace App\Model\Table;
use App\Model\Entity\Guest;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
/**
* Guests Model
*
* @property \Cake\ORM\Association\BelongsTo $Matchteams
* @property \Cake\ORM\Association\BelongsToMany $Hosts
*/
class GuestsTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->table('guests');
$this->displayField('name');
$this->primaryKey('id');
$this->belongsTo('Matchteams', [
'foreignKey' => 'matchteam_id'
]);
$this->belongsToMany('Hosts', [
'foreignKey' => 'guest_id',
'targetForeignKey' => 'host_id',
'joinTable' => 'hosts_guests'
]);
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->allowEmpty('id', 'create');
$validator
->add('primary_squad', 'valid', ['rule' => 'boolean'])
->allowEmpty('primary_squad');
$validator
->allowEmpty('name');
$validator
->allowEmpty('yellow');
$validator
->allowEmpty('red');
$validator
->allowEmpty('substitution');
$validator
->allowEmpty('goals');
$validator
->allowEmpty('rating');
$validator
->allowEmpty('assist');
$validator
->allowEmpty('injuries');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['matchteam_id'], 'Matchteams'));
return $rules;
}
}
| Java |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
require_once('../../config.php');
require_once($CFG->dirroot.'/mod/scorm/locallib.php');
$id = optional_param('id', '', PARAM_INT); // Course Module ID, or
$a = optional_param('a', '', PARAM_INT); // scorm ID
$scoid = required_param('scoid', PARAM_INT); // sco ID
$attempt = required_param('attempt', PARAM_INT); // attempt number
if (!empty($id)) {
if (! $cm = get_coursemodule_from_id('scorm', $id)) {
print_error('invalidcoursemodule');
}
if (! $course = $DB->get_record("course", array("id"=>$cm->course))) {
print_error('coursemisconf');
}
if (! $scorm = $DB->get_record("scorm", array("id"=>$cm->instance))) {
print_error('invalidcoursemodule');
}
} else if (!empty($a)) {
if (! $scorm = $DB->get_record("scorm", array("id"=>$a))) {
print_error('invalidcoursemodule');
}
if (! $course = $DB->get_record("course", array("id"=>$scorm->course))) {
print_error('coursemisconf');
}
if (! $cm = get_coursemodule_from_instance("scorm", $scorm->id, $course->id)) {
print_error('invalidcoursemodule');
}
} else {
print_error('missingparameter');
}
$PAGE->set_url('/mod/scorm/datamodel.php', array('scoid'=>$scoid, 'attempt'=>$attempt, 'id'=>$cm->id));
require_login($course, false, $cm);
if (confirm_sesskey() && (!empty($scoid))) {
$result = true;
$request = null;
if (has_capability('mod/scorm:savetrack', context_module::instance($cm->id))) {
foreach (data_submitted() as $element => $value) {
$element = str_replace('__', '.', $element);
if (substr($element, 0, 3) == 'cmi') {
$netelement = preg_replace('/\.N(\d+)\./', "\.\$1\.", $element);
$result = scorm_insert_track($USER->id, $scorm->id, $scoid, $attempt, $element, $value, $scorm->forcecompleted) && $result;
}
if (substr($element, 0, 15) == 'adl.nav.request') {
// SCORM 2004 Sequencing Request
require_once($CFG->dirroot.'/mod/scorm/datamodels/scorm_13lib.php');
$search = array('@continue@', '@previous@', '@\{target=(\S+)\}choice@', '@exit@', '@exitAll@', '@abandon@', '@abandonAll@');
$replace = array('continue_', 'previous_', '\1', 'exit_', 'exitall_', 'abandon_', 'abandonall');
$action = preg_replace($search, $replace, $value);
if ($action != $value) {
// Evaluating navigation request
$valid = scorm_seq_overall ($scoid, $USER->id, $action, $attempt);
$valid = 'true';
// Set valid request
$search = array('@continue@', '@previous@', '@\{target=(\S+)\}choice@');
$replace = array('true', 'true', 'true');
$matched = preg_replace($search, $replace, $value);
if ($matched == 'true') {
$request = 'adl.nav.request_valid["'.$action.'"] = "'.$valid.'";';
}
}
}
}
}
if ($result) {
echo "true\n0";
} else {
echo "false\n101";
}
if ($request != null) {
echo "\n".$request;
}
}
| Java |
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Richard Benson In Memory</title>
<link rel="stylesheet" href="build/benson.css">
<script type="text/javascript" src="../../node_modules/jquery/dist/jquery.js"></script>
<script type="text/javascript" src="../../node_modules/materialize-css/dist/js/materialize.js"></script>
</head>
<body>
<div id="all">
<nav>
<a href="../Home/">
<div id="brand">
<img src="../Logo.png" alt="Yale School of Art" id="logo">
<h1>Yale School of Art</h1>
</div>
</a>
<div class="menu-list">
<div class="menu-item">
<div class="sub-items-trigger">Academic</div>
<ul class="sub-items">
<li><a href="../Calendar">Calendar</a></li>
<li><a href="http://art.yale.edu/Courses">Courses</a></li>
<li><a href="http://art.yale.edu/StudyAreas">Study Area</a></li>
<li><a href="http://art.yale.edu/SummerPrograms">Summer Programs</a></li>
<li><a href="http://art.yale.edu/gallery">Gallery</a></li>
</ul>
</div>
<div class="menu-item">
<div class="sub-items-trigger">Admission</div>
<ul class="sub-items">
<li><a href="http://art.yale.edu/Admissions">General</a></li>
<li><a href="http://art.yale.edu/FinancialAid">Financial Aid</a></li>
<li><a href="http://art.yale.edu/Visiting">Visiting</a></li>
</ul>
</div>
<div class="menu-item">
<div class="sub-items-trigger">Events</div>
<ul class="sub-items">
<li><a href="../Events/112days.html">112 Days in New Heaven</a></li>
<li><a href="../Events/1971life.html">Life of Color</a></li>
<li><a href="../Events/benson.html">Richard Benson</a></li>
</ul>
</div>
<div class="menu-item">
<div class="sub-items-trigger">People</div>
<ul class="sub-items">
<li><a href="http://art.yale.edu/Alums">Alums</a></li>
<li><a href="http://art.yale.edu/CurrentStudents">Current Students</a></li>
<li><a href="http://art.yale.edu/FacultyAndStaff">Faculty</a></li>
<li><a href="http://art.yale.edu/undergraduate">Undergrads</a></li>
</ul>
</div>
<div class="menu-item">
<div class="sub-items-trigger">About</div>
<ul class="sub-items">
<li><a href="http://art.yale.edu/AboutThisSite">This Site</a></li>
<li><a href="http://art.yale.edu/RecentChanges">Recent Changes</a></li>
<li><a href="../Contact">Contact</a></li>
</ul>
</div>
</div>
</nav>
<div class="section" id="content">
<div class="header">
<img src="memory.png" alt="good looking professor" id="prof-photo">
<h1>Richard Benson In Memory 1943 - 2017</h1>
</div>
<div class="articles">
<div class="article">
<h2>A Letter from Dean Marta Kuzma</h2>
<p>Dear Members of the Yale School of Art Community,</p>
<p>It is with sincere regret that I must inform you of the death of Richard Benson—a renowned authority on the
history of photographic printing, an American photographer, an author, a former Yale University professor, and
Dean of the Yale School of Art from 1996 to 2006. I hadn’t the opportunity to get to know my predecessor,
although one does not need to look far to understand his immense contribution to the field of photography.
Some years ago, The Guardian’s literary editor Liz Jobey aptly wrote:</p>
<p>“A long time ago I read a New Yorker profile of a master photographic printer called Richard Benson. It was
titled, with that deliberate matter-of-factness that New Yorker titles invariably have, ‘A single person
making a single thing’. This man was a unique craftsman, who great photographers and great institutions turned
to when they wanted their pictures printed better than ever before. He had printed photographs by Alfred
Stieglitz, Paul Strand and Lee Friedlander, as well as three volumes of the works of great French photographer
Eugène Atget for the Museum of Modern Art. He had made an unsurpassed volume of prints for the collector
Howard Gilman, whose collection is now part of the Metropolitan Museum of Art in New York. And in 1986 Benson
had been awarded a MacArthur Foundation grant worth nearly quarter of a million dollars to carry on doing what
he did so well.”</p>
<p>As a testimony to the series of lectures he had given at the Yale School of Art over a period of three
decades, Richard Benson, more commonly known among friends as “Chip” co-curated with Peter Galassi an
exhibition at New York’s MoMA in 2008 called “The Printed Picture.” The exhibition and accompanying book
reflected Benson’s perspective on the evolution of the printed still image and traced the changing technology
of making and distributing pictures from the Renaissance to the present. He was the recipient of numerous
honors including two publication grants from the National Endowment of the Arts; two Guggenheim fellowships;
the Rhode Island Governor’s Medal for the Arts; and a MacArthur Foundation fellowship. His work—located within
the permanent collections of the Metropolitan Museum; New York’s MoMA; the Nelson-Atkins Museum of Art in
Kansas City, Missouri; and the Yale University Art Gallery in New Haven; among others.</p>
<p>Upon his retirement from Yale, the acclaimed photographer and Yale School of Art Professor Emeritus Tod
Papageorge noted in his Tribute to Richard Benson, “He’s a special kind, the sort that reminds us that the
words genius and genial share a common root. For who here doesn’t understand that Benson’s great good nature
is at the core of his ability to accomplish so much in so many different ways?” Tod has written another
tribute in memory of Chip, which you can read on the School of Art website by clicking here .</p>
<p>I expect there are so many who would wish to express their sincere condolences and also to reflect upon Chip
Benson as a friend, teacher, and dean. We ask that you kindly send your thoughts to the School of Art so that
we may gather these respects in celebration of Richard Benson and share them with our community in the coming
weeks.</p>
With respectful wishes,<br>
Marta Kuzma Dean Yale School of Art New Haven
</div>
<div class="article">
<h2>RICHARD BENSON: IN MEMORIAM</h2>
<p>Richard Benson was born and raised in the seacoast town of Newport, Rhode Island, the third and youngest son
of a Quaker mother and an ardent Catholic father. As a boy, he was so happy in his skin that his mother called
him her “little ray of sunshine”; later on, befitting a child whose father was a stonecutter, she and nearly
everyone else came to call him “Chip.”</p>
<p>His father, John Howard Benson, considered the greatest calligrapher and stone-letterer of his time, died
when Chip was twelve. The year before, W. K. Wimsatt, a chess partner of Benson’s and a legendary English
professor at Yale, successfully championed his dying friend for an honorary degree at the university, joining,
for the first time, the Benson name and the school. This, however, had no observable effect on Chip, who, left
with only a few sharp memories of his father, and thereby insulated from having to measure his life against
that of an extraordinary man, gave up his education after one semester at Brown, explaining to Brown’s
president—another friend of John Howard Benson’s—that he was leaving the school so that he could work with his
hands. (It’s worth adding that Richard was directed from the president’s office to the dean of students for
his send-off, which, in its entirety, consisted of the dean reading to him the first chapter of Moby
Dick.)</p>
<p>From Providence, he took a crooked course for himself, moving on from the Navy to a minimum-wage job in a
Connecticut printing plant and then an unparalleled career back in Newport as a photographer, master printer,
and inventor of radical new techniques of photographic reproduction. Only after all of that did he himself
cross paths with Yale, first as a great teacher in the Department of Photography and, fifteen years later, as
an admired dean of the School of Art, before retiring in 2011 to pursue whatever interests attracted the sharp
edge of his curiosity.</p>
<p>In 1986, Richard was awarded a grant from the MacArthur Foundation, an achievement characterized in the
popular press as the “genius” award. In his case, the description was appropriate, as anyone who was exposed
to the range and depth of his understanding about any number of things, including, of course, photography—or
sailing ships or electricity or hydraulics—would testify. But, to my mind, Richard more nearly demonstrated
through his life and actions that “genius” shares a common root with the word “genial,” the subject I feel
myself pressed to write about here. For his great, good nature was at the core of his ability to accomplish so
much in so many different ways, and to earn effortlessly the admiration and love of so many people. After all,
who can resist loving the person who, out of hand, has just offered to help by giving over his time and
knowledge in response to an earnest, or even casual, request? And, moreover, a person who, it turns out, will
give more greatly the more he’s asked to, as if, like the sun, he trusts his own energy will grow as its
excess burns away serving others.</p>
<p>We’ve recently learned that, put crudely, the more a person gives, the happier, or better, he or she will
feel, a truth that’s now been traced in the workings of the brain. Richard Benson demonstrated that bit of
science in how he lived, although, in his case, it appeared that feeling good, his natural state, directed his
doing good, rather than the other way around. And, perhaps because of this difference, his mode and range of
doing good, at least to me, seemed virtually Olympian, by being so outsized and barely earthbound (although,
like the sailor he was, the man himself cantered his way bow-legged through the world). For as his students
and friends all recognized, there was something large and unprecedented in his willingness to shower his
energy and brilliance on everyone around him, more and yet more, today and forever. Until now.</p>
<p>Perhaps, rather than invoking the sun and the Olympians, it would have been enough for me to say about
Richard that whenever I worked through the logic of imagining a possible model of an achieved human being for
my son, I invariably ended up with him, a man who straddled with natural ease—I’d guess because of his happy
marriage to Barbara—what artists often find to be the intractable contradiction between loving and art that
Yeats described as “the perfection of the life or of the work.” But this isn’t the time, immediately after his
death, for teasing contradictions into sense. And so I’ve been led, at least at this moment, to invoke a star,
and the Greek gods, to counter sense. For Richard Benson was so unrelentingly generous, and good, and spirited
in the manner that only the very best of us have been, that a nod to the heavens—or more, as each of us is
inclined—seems the least we can do to honor his memory. A small enough gesture to give back to our dear friend
and extraordinary man.</p>
<p>The first portion of this text was adapted from a talk presented by Tod Papageorge during a celebration of
Richard Benson’s deanship, from 1995 to 2006, of the Yale School of Art.</p>
</div>
</div>
</div>
<footer id="footer">
<div id="about">
<h3>About This Page</h3>
<p><b>A canvas for everyone.</b> This website is a wiki. All School of Art grad students, faculty, staff, and
alums have the ability to change most of this site’s content (with some exceptions); and to add new content and
pages.</p>
<p> Content is the property of its various authors. When you contribute to this site, you agree to abide by Yale
University academic and network use policy, and to act as a responsible member of our community. In this way, we
hope the content of this site reflects the unique vitality of our school.</p>
</div>
<div id="contact">
<h3>Contact Us</h3>
Yale School of Art<br>
1156 Chapel Street, POB 208339<br>
New Haven, Connecticut, 06520-8339<br>
(203) 432-2600
</div>
</footer>
</div>
</body>
</html>
| Java |
"use strict";
/*
Copyright (C) 2013-2017 Bryan Hughes <bryan@nebri.us>
Aquarium Control 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.
Aquarium Control 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 Aquarium Control. If not, see <http://www.gnu.org/licenses/>.
*/
Object.defineProperty(exports, "__esModule", { value: true });
// Force to "any" type, otherwise TypeScript thinks the type is too strict
exports.cleaningValidationSchema = {
type: 'object',
properties: {
time: {
required: true,
type: 'number'
},
bioFilterReplaced: {
required: true,
type: 'boolean'
},
mechanicalFilterReplaced: {
required: true,
type: 'boolean'
},
spongeReplaced: {
required: true,
type: 'boolean'
}
}
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiSUNsZWFuaW5nLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2NvbW1vbi9zcmMvSUNsZWFuaW5nLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTs7Ozs7Ozs7Ozs7Ozs7O0VBZUU7O0FBYUYsMEVBQTBFO0FBQzdELFFBQUEsd0JBQXdCLEdBQVE7SUFDM0MsSUFBSSxFQUFFLFFBQVE7SUFDZCxVQUFVLEVBQUU7UUFDVixJQUFJLEVBQUU7WUFDSixRQUFRLEVBQUUsSUFBSTtZQUNkLElBQUksRUFBRSxRQUFRO1NBQ2Y7UUFDRCxpQkFBaUIsRUFBRTtZQUNqQixRQUFRLEVBQUUsSUFBSTtZQUNkLElBQUksRUFBRSxTQUFTO1NBQ2hCO1FBQ0Qsd0JBQXdCLEVBQUU7WUFDeEIsUUFBUSxFQUFFLElBQUk7WUFDZCxJQUFJLEVBQUUsU0FBUztTQUNoQjtRQUNELGNBQWMsRUFBRTtZQUNkLFFBQVEsRUFBRSxJQUFJO1lBQ2QsSUFBSSxFQUFFLFNBQVM7U0FDaEI7S0FDRjtDQUNGLENBQUMifQ== | Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
namespace Chess
{
public abstract class Screen : UserControl
{
public ScreenControl parentWindow;
public ScreenControl ParentWindow { get { return parentWindow; } }
protected Screen() { }
public Screen(ScreenControl parentWindow)
{
this.parentWindow = parentWindow;
}
}
}
| Java |
package com.habitrpg.android.habitica.ui.activities;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TableRow;
import android.widget.TextView;
import com.amplitude.api.Amplitude;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.habitrpg.android.habitica.APIHelper;
import com.habitrpg.android.habitica.HostConfig;
import com.habitrpg.android.habitica.R;
import com.habitrpg.android.habitica.callbacks.HabitRPGUserCallback;
import com.habitrpg.android.habitica.prefs.scanner.IntentIntegrator;
import com.habitrpg.android.habitica.prefs.scanner.IntentResult;
import com.magicmicky.habitrpgwrapper.lib.models.HabitRPGUser;
import com.magicmicky.habitrpgwrapper.lib.models.UserAuthResponse;
import org.json.JSONException;
import org.json.JSONObject;
import butterknife.Bind;
import butterknife.BindString;
import butterknife.ButterKnife;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
/**
* @author Mickael Goubin
*/
public class LoginActivity extends AppCompatActivity
implements Callback<UserAuthResponse>,HabitRPGUserCallback.OnUserReceived {
private final static String TAG_ADDRESS="address";
private final static String TAG_USERID="user";
private final static String TAG_APIKEY="key";
private APIHelper mApiHelper;
public String mTmpUserToken;
public String mTmpApiToken;
public Boolean isRegistering;
private Menu menu;
@BindString(R.string.SP_address_default)
String apiAddress;
//private String apiAddress;
//private String apiAddress = "http://192.168.2.155:8080/"; // local testing
private CallbackManager callbackManager;
@Bind(R.id.login_btn)
Button mLoginNormalBtn;
@Bind(R.id.PB_AsyncTask)
ProgressBar mProgressBar;
@Bind(R.id.username)
EditText mUsernameET;
@Bind(R.id.password)
EditText mPasswordET;
@Bind(R.id.email)
EditText mEmail;
@Bind(R.id.confirm_password)
EditText mConfirmPassword;
@Bind(R.id.email_row)
TableRow mEmailRow;
@Bind(R.id.confirm_password_row)
TableRow mConfirmPasswordRow;
@Bind(R.id.login_button)
LoginButton mFacebookLoginBtn;
@Bind(R.id.forgot_pw_tv)
TextView mForgotPWTV;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
//Set default values to avoid null-responses when requesting unedited settings
PreferenceManager.setDefaultValues(this, R.xml.preferences_account_details, false);
PreferenceManager.setDefaultValues(this, R.xml.preferences_fragment, false);
ButterKnife.bind(this);
mLoginNormalBtn.setOnClickListener(mLoginNormalClick);
mFacebookLoginBtn.setReadPermissions("user_friends");
mForgotPWTV.setOnClickListener(mForgotPWClick);
SpannableString content = new SpannableString(mForgotPWTV.getText());
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
mForgotPWTV.setText(content);
callbackManager = CallbackManager.Factory.create();
mFacebookLoginBtn.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
mApiHelper.connectSocial(accessToken.getUserId(), accessToken.getToken(), LoginActivity.this);
}
@Override
public void onCancel() {
Log.d("FB Login", "Cancelled");
}
@Override
public void onError(FacebookException exception) {
Log.e("FB Login", "Error", exception);
}
});
HostConfig hc= PrefsActivity.fromContext(this);
if(hc ==null) {
hc = new HostConfig(apiAddress, "80", "", "");
}
mApiHelper = new APIHelper(hc);
this.isRegistering = true;
JSONObject eventProperties = new JSONObject();
try {
eventProperties.put("eventAction", "navigate");
eventProperties.put("eventCategory", "navigation");
eventProperties.put("hitType", "pageview");
eventProperties.put("page", this.getClass().getSimpleName());
} catch (JSONException exception) {
}
Amplitude.getInstance().logEvent("navigate", eventProperties);
}
private void resetLayout() {
if (this.isRegistering) {
if (this.mEmailRow.getVisibility() == View.GONE) {
expand(this.mEmailRow);
}
if (this.mConfirmPasswordRow.getVisibility() == View.GONE) {
expand(this.mConfirmPasswordRow);
}
} else {
if (this.mEmailRow.getVisibility() == View.VISIBLE) {
collapse(this.mEmailRow);
}
if (this.mConfirmPasswordRow.getVisibility() == View.VISIBLE) {
collapse(this.mConfirmPasswordRow);
}
}
}
private View.OnClickListener mLoginNormalClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
mProgressBar.setVisibility(View.VISIBLE);
if (isRegistering) {
String username, email,password,cpassword;
username = String.valueOf(mUsernameET.getText()).trim();
email = String.valueOf(mEmail.getText()).trim();
password = String.valueOf(mPasswordET.getText());
cpassword = String.valueOf(mConfirmPassword.getText());
if (username.length() == 0 || password.length() == 0 || email.length() == 0 || cpassword.length() == 0) {
showValidationError(R.string.login_validation_error_fieldsmissing);
return;
}
mApiHelper.registerUser(username,email,password, cpassword, LoginActivity.this);
} else {
String username,password;
username = String.valueOf(mUsernameET.getText()).trim();
password = String.valueOf(mPasswordET.getText());
if (username.length() == 0 || password.length() == 0) {
showValidationError(R.string.login_validation_error_fieldsmissing);
return;
}
mApiHelper.connectUser(username,password, LoginActivity.this);
}
}
};
private View.OnClickListener mForgotPWClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = getString(R.string.SP_address_default);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
};
public static void expand(final View v) {
v.setVisibility(View.VISIBLE);
}
public static void collapse(final View v) {
v.setVisibility(View.GONE);
}
private void startMainActivity() {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
private void startSetupActivity() {
Intent intent = new Intent(LoginActivity.this, SetupActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
private void toggleRegistering() {
this.isRegistering = !this.isRegistering;
this.setRegistering();
}
private void setRegistering() {
MenuItem menuItem = menu.findItem(R.id.action_toggleRegistering);
if (this.isRegistering) {
this.mLoginNormalBtn.setText(getString(R.string.register_btn));
menuItem.setTitle(getString(R.string.login_btn));
mUsernameET.setHint(R.string.username);
mPasswordET.setImeOptions(EditorInfo.IME_ACTION_NEXT);
} else {
this.mLoginNormalBtn.setText(getString(R.string.login_btn));
menuItem.setTitle(getString(R.string.register_btn));
mUsernameET.setHint(R.string.email_username);
mPasswordET.setImeOptions(EditorInfo.IME_ACTION_DONE);
}
this.resetLayout();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
callbackManager.onActivityResult(requestCode, resultCode, intent);
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
try {
Log.d("scanresult", scanResult.getContents());
this.parse(scanResult.getContents());
} catch(Exception e) {
Log.e("scanresult", "Could not parse scanResult", e);
}
}
}
private void parse(String contents) {
String adr,user,key;
try {
JSONObject obj;
obj = new JSONObject(contents);
adr = obj.getString(TAG_ADDRESS);
user = obj.getString(TAG_USERID);
key = obj.getString(TAG_APIKEY);
Log.d("", "adr" + adr + " user:" + user + " key" + key);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
boolean ans = editor.putString(getString(R.string.SP_address), adr)
.putString(getString(R.string.SP_APIToken), key)
.putString(getString(R.string.SP_userID), user)
.commit();
if(!ans) {
throw new Exception("PB_string_commit");
}
startMainActivity();
} catch (JSONException e) {
showSnackbar(getString(R.string.ERR_pb_barcode));
e.printStackTrace();
} catch(Exception e) {
if("PB_string_commit".equals(e.getMessage())) {
showSnackbar(getString(R.string.ERR_pb_barcode));
}
}
}
private void showSnackbar(String content)
{
Snackbar snackbar = Snackbar
.make(this.findViewById(R.id.login_linear_layout), content, Snackbar.LENGTH_LONG);
View snackbarView = snackbar.getView();
snackbarView.setBackgroundColor(Color.RED);//change Snackbar's background color;
snackbar.show(); // Don’t forget to show!
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.login, menu);
this.menu = menu;
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_toggleRegistering:
toggleRegistering();
break;
}
return super.onOptionsItemSelected(item);
}
private void afterResults() {
mProgressBar.setVisibility(View.INVISIBLE);
}
@Override
public void success(UserAuthResponse userAuthResponse, Response response) {
try {
saveTokens(userAuthResponse.getToken(), userAuthResponse.getId());
} catch (Exception e) {
e.printStackTrace();
}
if (this.isRegistering) {
this.startSetupActivity();
} else {
JSONObject eventProperties = new JSONObject();
try {
eventProperties.put("eventAction", "lofin");
eventProperties.put("eventCategory", "behaviour");
eventProperties.put("hitType", "event");
} catch (JSONException exception) {
}
Amplitude.getInstance().logEvent("login", eventProperties);
this.startMainActivity();
}
}
private void saveTokens(String api, String user) throws Exception {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
SharedPreferences.Editor editor = prefs.edit();
boolean ans = editor.putString(getString(R.string.SP_APIToken), api)
.putString(getString(R.string.SP_userID), user)
.putString(getString(R.string.SP_address),getString(R.string.SP_address_default))
.commit();
if(!ans) {
throw new Exception("PB_string_commit");
}
}
@Override
public void failure(RetrofitError error) {
mProgressBar.setVisibility(View.GONE);
}
@Override
public void onUserReceived(HabitRPGUser user) {
try {
saveTokens(mTmpApiToken, mTmpUserToken);
} catch (Exception e) {
e.printStackTrace();
}
this.startMainActivity();
}
@Override
public void onUserFail() {
mProgressBar.setVisibility(View.GONE);
showSnackbar(getString(R.string.unknown_error));
}
private void showValidationError(int resourceMessageString) {
mProgressBar.setVisibility(View.GONE);
new android.support.v7.app.AlertDialog.Builder(this)
.setTitle(R.string.login_validation_error_title)
.setMessage(resourceMessageString)
.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(R.drawable.ic_warning_black)
.show();
}
}
| Java |
<?php
namespace hemio\html;
/**
* The <code>figure</code> element represents a unit of content, optionally with
* a caption, that is self-contained, that is typically referenced as a single
* unit from the main flow of the document, and that can be moved away from the
* main flow of the document without affecting the document’s meaning.
*
* @since version 1.0
* @url http://www.w3.org/TR/html5/grouping-content.html#the-figure-element
*/
class Figure extends Abstract_\ElementContent
{
use Trait_\DefaultElementContent;
public static function tagName()
{
return 'figure';
}
public function blnIsBlock()
{
return true;
}
}
| Java |
/*
* Copyright (C) 2010-2019 The ESPResSo project
* Copyright (C) 2002,2003,2004,2005,2006,2007,2008,2009,2010
* Max-Planck-Institute for Polymer Research, Theory Group
*
* This file is part of ESPResSo.
*
* ESPResSo 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.
*
* ESPResSo is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SCRIPT_INTERFACE_COM_FIXED_HPP
#define SCRIPT_INTERFACE_COM_FIXED_HPP
#include "script_interface/ScriptInterface.hpp"
#include "core/comfixed_global.hpp"
namespace ScriptInterface {
class ComFixed : public AutoParameters<ComFixed> {
public:
ComFixed() {
add_parameters({{"types",
[](Variant const &v) {
comfixed.set_fixed_types(get_value<std::vector<int>>(v));
},
[]() { return comfixed.get_fixed_types(); }}});
}
};
} // namespace ScriptInterface
#endif
| Java |
/**
* Copyright (C) 2010-2016 Structr GmbH
*
* This file is part of Structr <http://structr.org>.
*
* Structr 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.
*
* Structr 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 Structr. If not, see <http://www.gnu.org/licenses/>.
*/
package org.structr.core.function;
import org.structr.common.error.FrameworkException;
import org.structr.common.error.SemanticErrorToken;
import org.structr.core.GraphObject;
import org.structr.core.app.StructrApp;
import org.structr.core.property.PropertyKey;
import org.structr.schema.action.ActionContext;
import org.structr.schema.action.Function;
/**
*
*/
public class ErrorFunction extends Function<Object, Object> {
public static final String ERROR_MESSAGE_ERROR = "Usage: ${error(...)}. Example: ${error(\"base\", \"must_equal\", int(5))}";
@Override
public String getName() {
return "error()";
}
@Override
public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException {
final Class entityType;
final String type;
if (entity != null) {
entityType = entity.getClass();
type = entity.getType();
} else {
entityType = GraphObject.class;
type = "Base";
}
try {
if (sources == null) {
throw new IllegalArgumentException();
}
switch (sources.length) {
case 1:
throw new IllegalArgumentException();
case 2:
{
arrayHasLengthAndAllElementsNotNull(sources, 2);
final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(entityType, sources[0].toString());
ctx.raiseError(422, new SemanticErrorToken(type, key, sources[1].toString()));
break;
}
case 3:
{
arrayHasLengthAndAllElementsNotNull(sources, 3);
final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(entityType, sources[0].toString());
ctx.raiseError(422, new SemanticErrorToken(type, key, sources[1].toString(), sources[2]));
break;
}
default:
logParameterError(entity, sources, ctx.isJavaScriptContext());
break;
}
} catch (final IllegalArgumentException e) {
logParameterError(entity, sources, ctx.isJavaScriptContext());
return usage(ctx.isJavaScriptContext());
}
return null;
}
@Override
public String usage(boolean inJavaScriptContext) {
return ERROR_MESSAGE_ERROR;
}
@Override
public String shortDescription() {
return "Signals an error to the caller";
}
}
| Java |
package com.risevision.gcslogs.delete;
import com.risevision.gcslogs.auth.MockCredentialProvider;
import java.util.logging.Logger;
import java.util.Map;
import java.util.HashMap;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import static com.risevision.gcslogs.BuildConfig.*;
public class DeleteLoadJobFilesServletHandlerTest {
Map<String, String[]> params;
DeleteLoadJobFilesServletHandler deleter;
@Before public void setUp() {
params = new HashMap<String, String[]>();
params.put("jobId", new String[]{"testId"});
deleter =
new DeleteLoadJobFilesServletHandler(params, new MockCredentialProvider());
}
@Test public void itExists() {
assertThat("it exists", deleter, isA(DeleteLoadJobFilesServletHandler.class));
}
@Test public void itGetsTheJobId() {
assertThat("the id exists", deleter.jobId, is(not(nullValue())));
}
@Test public void itExtractsObjectNamesFromUris() {
String uri = "gs://" + LOGS_BUCKET_NAME.toString() + "/folder/name";
assertThat("the name is correct", deleter.extractObjectName(uri),
is("folder/name"));
}
@Test public void itExtractsBucketNamesFromUris() {
String uri = "gs://" + LOGS_BUCKET_NAME.toString() + "/folder/name";
assertThat("the bucket is correct", deleter.extractBucketName(uri),
is(LOGS_BUCKET_NAME.toString()));
}
}
| Java |
package org.maxgamer.rs.model.skill.prayer;
import java.util.LinkedList;
/**
* @author netherfoam, alva
*/
public enum PrayerGroup {
//Standard prayer book
/** All prayers that boost defense */
DEFENSE(PrayerType.THICK_SKIN, PrayerType.ROCK_SKIN, PrayerType.STEEL_SKIN, PrayerType.CHIVALRY, PrayerType.PIETY, PrayerType.RIGOUR, PrayerType.AUGURY),
/** All prayers that boost strength */
STRENGTH(PrayerType.BURST_OF_STRENGTH, PrayerType.SUPERHUMAN_STRENGTH, PrayerType.ULTIMATE_STRENGTH, PrayerType.CHIVALRY, PrayerType.PIETY),
/** All prayers that boost attack */
ATTACK(PrayerType.CLARITY_OF_THOUGHT, PrayerType.IMPROVED_REFLEXES, PrayerType.INCREDIBLE_REFLEXES, PrayerType.CHIVALRY, PrayerType.PIETY),
/** All prayers that boost range */
RANGE(PrayerType.SHARP_EYE, PrayerType.HAWK_EYE, PrayerType.EAGLE_EYE, PrayerType.RIGOUR),
/** All prayers that boost magic */
MAGIC(PrayerType.MYSTIC_WILL, PrayerType.MYSTIC_LORE, PrayerType.MYSTIC_MIGHT, PrayerType.AUGURY),
/**
* most prayers that put a symbol above player head (Prot
* (melee/magic/range), retribution, smite, redemption)
*/
STANDARD_SPECIAL(PrayerType.PROTECT_FROM_MELEE, PrayerType.PROTECT_FROM_MISSILES, PrayerType.PROTECT_FROM_MAGIC, PrayerType.RETRIBUTION, PrayerType.REDEMPTION, PrayerType.SMITE),
/** Protect from melee/range/magic prayers */
PROTECT_DAMAGE(PrayerType.PROTECT_FROM_MELEE, PrayerType.PROTECT_FROM_MISSILES, PrayerType.PROTECT_FROM_MAGIC),
//Curses prayer book
/** Sap prayers (warrior, range, spirit) */
SAP(PrayerType.SAP_WARRIOR, PrayerType.SAP_RANGER, PrayerType.SAP_SPIRIT),
/**
* leech prayers (attack, range, magic, defence, strength, energy, special
* attack)
*/
LEECH(PrayerType.LEECH_ATTACK, PrayerType.LEECH_RANGE, PrayerType.LEECH_MAGIC, PrayerType.LEECH_DEFENCE, PrayerType.LEECH_STRENGTH, PrayerType.LEECH_ENERGY, PrayerType.LEECH_SPECIAL_ATTACK),
/**
* similar to standard_special. Wrath, Soulsplit, deflect (magic, missiles,
* melee)
*/
CURSE_SPECIAL(PrayerType.WRATH, PrayerType.SOUL_SPLIT, PrayerType.DEFLECT_MAGIC, PrayerType.DEFLECT_MISSILES, PrayerType.DEFLECT_MELEE),
/** All deflections (magic, missiles, melee) */
DEFLECT(PrayerType.DEFLECT_MAGIC, PrayerType.DEFLECT_MISSILES, PrayerType.DEFLECT_MELEE);
private PrayerType[] types;
private PrayerGroup(PrayerType... types) {
this.types = types;
}
public PrayerType[] getTypes() {
return types;
}
/**
* Returns true if this prayer group contains the given prayer.
* @param type the prayer
* @return true if it is contained, else false.
*/
public boolean contains(PrayerType type) {
for (PrayerType p : this.types) {
if (type == p) {
return true;
}
}
return false;
}
/**
* Returns an array of groups that the given prayer is in.
* @param type the prayer
* @return an array of groups that the given prayer is in.
*/
public static LinkedList<PrayerGroup> getGroups(PrayerType type) {
LinkedList<PrayerGroup> groups = new LinkedList<PrayerGroup>();
for (PrayerGroup g : values()) {
if (g.contains(type)) {
groups.add(g);
}
}
return groups;
}
} | Java |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Colorinator</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=410">
<!-- jQuery -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<!-- Wijmo CSS and script -->
<link type="text/css" href="http://cdn.wijmo.com/themes/metro/jquery-wijmo.css" rel="stylesheet" title="metro-jqueryui" />
<link type="text/css" href="http://cdn.wijmo.com/jquery.wijmo-complete.all.2.1.5.min.css" rel="stylesheet" />
<script type="text/javascript" src="http://cdn.wijmo.com/jquery.wijmo-open.all.2.1.5.min.js"></script>
<!-- KnockoutJS for MVVM-->
<script type="text/javascript" src="http://cdn.wijmo.com/external/knockout-2.0.0.js"></script>
<script type="text/javascript" src="http://cdn.wijmo.com/external/knockout.wijmo.js"></script>
<script type="text/javascript">
//Create ViewModel
var viewModel = function () {
var self = this;
self.red = ko.observable(120);
self.green = ko.observable(120);
self.blue = ko.observable(120);
self.minRGB = ko.observable(0);
self.maxRGB = ko.observable(255);
self.rgbColor = ko.computed(function () {
// Knockout tracks dependencies automatically. It knows that rgbColor depends on hue, saturation and lightness, because these get called when evaluating rgbColor.
return "rgb(" + self.red() + ", " + self.green() + ", " + self.blue() + ")";
}, self);
self.hslColor = ko.computed(function () {
//Convert red, green and blue numbers to hue (degree), saturation (percentage) and lightness (percentage)
var r = self.red() / 255, g = self.green() / 255, b = self.blue() / 255;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, l = (max + min) / 2;
var hue, saturation, lightness;
if (max == min) {
h = s = 0;
} else {
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
hue = Math.round(h * 360);
saturation = Math.round(s * 100) + "%";
lightness = Math.round(l * 100) + "%";
return "hsl(" + hue + ", " + saturation + ", " + lightness + ")";
}, self);
self.hexColor = ko.computed({
read: function () {
//Convert red, green and blue numbers to base 16 strings
var r = self.red(), g = self.green(), b = self.blue();
var hex = 1 << 24 | r << 16 | g << 8 | b;
return '#' + hex.toString(16).substr(1);
},
write: function (value) {
//This is a writable computed observable so that one can type in a hex color to update the RGB values.
var r, g, b;
if (value[0] === "#") {
value = value.substr(1);
}
if (value.length < 3) {
return;
}
else if (value.length > 6) {
value = value.substr(0, 6);
}
else if (value.length === 3) {
//Short code hex converted to full hex
r = value.substr(0, 1) + value.substr(0, 1);
g = value.substr(1, 1) + value.substr(1, 1);
b = value.substr(2, 1) + value.substr(2, 1);
value = r + g + b;
}
//Update ViewModel red, green and blue values
self.red(parseInt(value.substr(0, 2), 16));
self.green(parseInt(value.substr(2, 2), 16));
self.blue(parseInt(value.substr(4, 2), 16));
},
owner: self
});
};
//Bind ViewModel and Event Handlers
$(document).ready(function () {
var vm = new viewModel();
//check for hex color passed in URL
getColorFromHash();
//Apply ViewModel bindings in markup
ko.applyBindings(vm);
//Trigger CSS3 animation to show color picker pane when ViewModel is initialized
$(".wait").addClass("show").removeClass("wait");
//Check if browser supports hashchange event
if ("onhashchange" in window) {
window.onhashchange = getColorFromHash;
}
//Get hex color from URL and update ViewModel with value
function getColorFromHash() {
if (window.location.hash && window.location.hash != vm.hexColor()) {
vm.hexColor(window.location.hash);
}
}
});
</script>
<style type="text/css">
body
{
font-family: "Segoe UI Light" , Frutiger, "Frutiger Linotype" , "Dejavu Sans" , "Helvetica Neue" , Arial, sans-serif;
font-size: 14px;
background: #000;
}
h1
{
font-size: 2.4em;
color: #fff;
padding: 20px 0 0 6px;
margin: 0;
}
.container
{
margin: 0 auto;
width: 400px;
}
.wait
{
height: 1px;
}
.show
{
height: 530px;
-webkit-transition: all 1.2s ease-out;
-moz-transition: all 1.2s ease-out;
-o-transition: all 1.2s ease-out;
transition: all 1.2s ease-out;
}
.color-picker
{
overflow: hidden;
background: #fff;
padding: 20px;
box-shadow: 5px 5px 50px rgba(0, 0, 0, 0.5);
}
.swatch
{
margin: 20px;
width: 320px;
height: 200px;
box-shadow: 5px 5px 20px rgba(0, 0, 0, 0.5) inset;
}
.color-section
{
padding: 6px 0 0 0;
}
.color-label
{
width: 70px;
display: inline-block;
}
.unit
{
width: 30px;
}
.color-value
{
width: 140px;
}
.color-slider
{
width: 200px;
}
.wijmo-wijslider-horizontal
{
display: inline-block;
}
</style>
</head>
<body data-bind="style: { background: hexColor }">
<div class="container">
<h1>
Colorinator</h1>
<div class="color-picker wait">
<div class="swatch" data-bind="style: { background: hexColor }">
</div>
<div class="color-section">
<label class="color-label">
Red</label>
<div data-bind="wijslider: { value: red, min: minRGB, max: maxRGB }" class="color-slider">
</div>
<input type="text" data-bind="value: red, valueUpdate: 'keyup', wijtextbox: {}" class="unit" />
</div>
<div class="color-section">
<label class="color-label">
Green</label>
<div data-bind="wijslider: { value: green, min: minRGB, max: maxRGB }" class="color-slider">
</div>
<input type="text" data-bind="value: green, valueUpdate: 'keyup', wijtextbox: {}" class="unit" />
</div>
<div class="color-section">
<label class="color-label">
Blue</label>
<div data-bind="wijslider: { value: blue, min: minRGB, max: maxRGB }" class="color-slider">
</div>
<input type="text" data-bind="value: blue, valueUpdate: 'keyup', wijtextbox: {}" class="unit" />
</div>
<div class="color-section">
<label class="color-label">
RGB Color</label>
<input type="text" data-bind="value: rgbColor, disable: true, wijtextbox: { disabled: true }" class="color-value" />
<span data-bind="text: rgbColor"></span>
</div>
<div class="color-section">
<label class="color-label">
HSL Color</label>
<input type="text" data-bind="value: hslColor, disable: true, wijtextbox: { disabled: true }" class="color-value" />
<span data-bind="text: hslColor"></span>
</div>
<div class="color-section">
<label class="color-label">
HEX Color</label>
<input type="text" data-bind="value: hexColor, wijtextbox: { }" class="color-value" />
<a data-bind="text: hexColor, attr: { href: hexColor }" title="Link to this color"></a>
</div>
<p>
Made with <a href="http://knockoutjs.com">KnockoutJS</a> and <a href="http://wijmo.com">Wijmo</a></p>
</div>
</div>
</body>
</html>
| Java |
import ast
import json
import arrow
import elasticsearch
from bson import ObjectId
from flask import request
from eve.utils import config
from eve.io.base import DataLayer
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
def parse_date(date_str):
"""Parse elastic datetime string."""
try:
date = arrow.get(date_str)
except TypeError:
date = arrow.get(date_str[0])
return date.datetime
def get_dates(schema):
"""Return list of datetime fields for given schema."""
dates = [config.LAST_UPDATED, config.DATE_CREATED]
for field, field_schema in schema.items():
if field_schema['type'] == 'datetime':
dates.append(field)
return dates
def format_doc(hit, schema, dates):
"""Format given doc to match given schema."""
doc = hit.get('_source', {})
doc.setdefault(config.ID_FIELD, hit.get('_id'))
doc.setdefault('_type', hit.get('_type'))
for key in dates:
if key in doc:
doc[key] = parse_date(doc[key])
return doc
def noop():
pass
def is_elastic(datasource):
"""Detect if given resource uses elastic."""
return datasource.get('backend') == 'elastic' or datasource.get('search_backend') == 'elastic'
class ElasticJSONSerializer(elasticsearch.JSONSerializer):
"""Customize the JSON serializer used in Elastic"""
def default(self, value):
"""Convert mongo.ObjectId."""
if isinstance(value, ObjectId):
return str(value)
return super(ElasticJSONSerializer, self).default(value)
class ElasticCursor(object):
"""Search results cursor."""
no_hits = {'hits': {'total': 0, 'hits': []}}
def __init__(self, hits=None, docs=None):
"""Parse hits into docs."""
self.hits = hits if hits else self.no_hits
self.docs = docs if docs else []
def __getitem__(self, key):
return self.docs[key]
def first(self):
"""Get first doc."""
return self.docs[0] if self.docs else None
def count(self, **kwargs):
"""Get hits count."""
return int(self.hits['hits']['total'])
def extra(self, response):
"""Add extra info to response."""
if 'facets' in self.hits:
response['_facets'] = self.hits['facets']
if 'aggregations' in self.hits:
response['_aggregations'] = self.hits['aggregations']
def set_filters(query, base_filters):
"""Put together all filters we have and set them as 'and' filter
within filtered query.
:param query: elastic query being constructed
:param base_filters: all filters set outside of query (eg. resource config, sub_resource_lookup)
"""
filters = [f for f in base_filters if f is not None]
query_filter = query['query']['filtered'].get('filter', None)
if query_filter is not None:
if 'and' in query_filter:
filters.extend(query_filter['and'])
else:
filters.append(query_filter)
if filters:
query['query']['filtered']['filter'] = {'and': filters}
def set_sort(query, sort):
query['sort'] = []
for (key, sortdir) in sort:
sort_dict = dict([(key, 'asc' if sortdir > 0 else 'desc')])
query['sort'].append(sort_dict)
def get_es(url):
o = urlparse(url)
es = elasticsearch.Elasticsearch(hosts=[{'host': o.hostname, 'port': o.port}])
es.transport.serializer = ElasticJSONSerializer()
return es
def get_indices(es):
return elasticsearch.client.IndicesClient(es)
class Elastic(DataLayer):
"""ElasticSearch data layer."""
serializers = {
'integer': int,
'datetime': parse_date,
'objectid': ObjectId,
}
def init_app(self, app):
app.config.setdefault('ELASTICSEARCH_URL', 'http://localhost:9200/')
app.config.setdefault('ELASTICSEARCH_INDEX', 'eve')
self.index = app.config['ELASTICSEARCH_INDEX']
self.es = get_es(app.config['ELASTICSEARCH_URL'])
self.create_index(self.index)
self.put_mapping(app)
def _get_field_mapping(self, schema):
"""Get mapping for given field schema."""
if 'mapping' in schema:
return schema['mapping']
elif schema['type'] == 'datetime':
return {'type': 'date'}
elif schema['type'] == 'string' and schema.get('unique'):
return {'type': 'string', 'index': 'not_analyzed'}
def create_index(self, index=None):
if index is None:
index = self.index
try:
get_indices(self.es).create(self.index)
except elasticsearch.TransportError:
pass
def put_mapping(self, app):
"""Put mapping for elasticsearch for current schema.
It's not called automatically now, but rather left for user to call it whenever it makes sense.
"""
indices = get_indices(self.es)
for resource, resource_config in app.config['DOMAIN'].items():
datasource = resource_config.get('datasource', {})
if not is_elastic(datasource):
continue
if datasource.get('source', resource) != resource: # only put mapping for core types
continue
properties = {}
properties[config.DATE_CREATED] = self._get_field_mapping({'type': 'datetime'})
properties[config.LAST_UPDATED] = self._get_field_mapping({'type': 'datetime'})
for field, schema in resource_config['schema'].items():
field_mapping = self._get_field_mapping(schema)
if field_mapping:
properties[field] = field_mapping
mapping = {'properties': properties}
indices.put_mapping(index=self.index, doc_type=resource, body=mapping, ignore_conflicts=True)
def find(self, resource, req, sub_resource_lookup):
args = getattr(req, 'args', request.args if request else {})
source_config = config.SOURCES[resource]
if args.get('source'):
query = json.loads(args.get('source'))
if 'filtered' not in query.get('query', {}):
_query = query.get('query')
query['query'] = {'filtered': {}}
if _query:
query['query']['filtered']['query'] = _query
else:
query = {'query': {'filtered': {}}}
if args.get('q', None):
query['query']['filtered']['query'] = _build_query_string(args.get('q'),
default_field=args.get('df', '_all'))
if 'sort' not in query:
if req.sort:
sort = ast.literal_eval(req.sort)
set_sort(query, sort)
elif self._default_sort(resource) and 'query' not in query['query']['filtered']:
set_sort(query, self._default_sort(resource))
if req.max_results:
query.setdefault('size', req.max_results)
if req.page > 1:
query.setdefault('from', (req.page - 1) * req.max_results)
filters = []
filters.append(source_config.get('elastic_filter'))
filters.append(source_config.get('elastic_filter_callback', noop)())
filters.append({'term': sub_resource_lookup} if sub_resource_lookup else None)
filters.append(json.loads(args.get('filter')) if 'filter' in args else None)
set_filters(query, filters)
if 'facets' in source_config:
query['facets'] = source_config['facets']
if 'aggregations' in source_config:
query['aggs'] = source_config['aggregations']
args = self._es_args(resource)
hits = self.es.search(body=query, **args)
return self._parse_hits(hits, resource)
def find_one(self, resource, req, **lookup):
def is_found(hit):
if 'exists' in hit:
hit['found'] = hit['exists']
return hit.get('found', False)
args = self._es_args(resource)
if config.ID_FIELD in lookup:
try:
hit = self.es.get(id=lookup[config.ID_FIELD], **args)
except elasticsearch.NotFoundError:
return
if not is_found(hit):
return
docs = self._parse_hits({'hits': {'hits': [hit]}}, resource)
return docs.first()
else:
query = {
'query': {
'term': lookup
}
}
try:
args['size'] = 1
hits = self.es.search(body=query, **args)
docs = self._parse_hits(hits, resource)
return docs.first()
except elasticsearch.NotFoundError:
return
def find_one_raw(self, resource, _id):
args = self._es_args(resource)
hit = self.es.get(id=_id, **args)
return self._parse_hits({'hits': {'hits': [hit]}}, resource).first()
def find_list_of_ids(self, resource, ids, client_projection=None):
args = self._es_args(resource)
return self._parse_hits(self.es.multi_get(ids, **args), resource)
def insert(self, resource, doc_or_docs, **kwargs):
ids = []
kwargs.update(self._es_args(resource))
for doc in doc_or_docs:
doc.update(self.es.index(body=doc, id=doc.get('_id'), **kwargs))
ids.append(doc['_id'])
get_indices(self.es).refresh(self.index)
return ids
def update(self, resource, id_, updates):
args = self._es_args(resource, refresh=True)
return self.es.update(id=id_, body={'doc': updates}, **args)
def replace(self, resource, id_, document):
args = self._es_args(resource, refresh=True)
return self.es.index(body=document, id=id_, **args)
def remove(self, resource, lookup=None):
args = self._es_args(resource)
if lookup:
try:
return self.es.delete(id=lookup.get('_id'), refresh=True, **args)
except elasticsearch.NotFoundError:
return
else:
query = {'query': {'match_all': {}}}
return self.es.delete_by_query(body=query, **args)
def is_empty(self, resource):
args = self._es_args(resource)
res = self.es.count(body={'query': {'match_all': {}}}, **args)
return res.get('count', 0) == 0
def get_mapping(self, index, doc_type=None):
return get_indices(self.es).get_mapping(index=index, doc_type=doc_type)
def _parse_hits(self, hits, resource):
"""Parse hits response into documents."""
datasource = self._datasource(resource)
schema = config.DOMAIN[datasource[0]]['schema']
dates = get_dates(schema)
docs = []
for hit in hits.get('hits', {}).get('hits', []):
docs.append(format_doc(hit, schema, dates))
return ElasticCursor(hits, docs)
def _es_args(self, resource, refresh=None):
"""Get index and doctype args."""
datasource = self._datasource(resource)
args = {
'index': self.index,
'doc_type': datasource[0],
}
if refresh:
args['refresh'] = refresh
return args
def _fields(self, resource):
"""Get projection fields for given resource."""
datasource = self._datasource(resource)
keys = datasource[2].keys()
return ','.join(keys) + ','.join([config.LAST_UPDATED, config.DATE_CREATED])
def _default_sort(self, resource):
datasource = self._datasource(resource)
return datasource[3]
def build_elastic_query(doc):
"""
Builds a query which follows ElasticSearch syntax from doc.
1. Converts {"q":"cricket"} to the below elastic query
{
"query": {
"filtered": {
"query": {
"query_string": {
"query": "cricket",
"lenient": false,
"default_operator": "AND"
}
}
}
}
}
2. Converts a faceted query
{"q":"cricket", "type":['text'], "source": "AAP"}
to the below elastic query
{
"query": {
"filtered": {
"filter": {
"and": [
{"terms": {"type": ["text"]}},
{"term": {"source": "AAP"}}
]
},
"query": {
"query_string": {
"query": "cricket",
"lenient": false,
"default_operator": "AND"
}
}
}
}
}
:param doc: A document object which is inline with the syntax specified in the examples.
It's the developer responsibility to pass right object.
:returns ElasticSearch query
"""
elastic_query, filters = {"query": {"filtered": {}}}, []
for key in doc.keys():
if key == 'q':
elastic_query['query']['filtered']['query'] = _build_query_string(doc['q'])
else:
_value = doc[key]
filters.append({"terms": {key: _value}} if isinstance(_value, list) else {"term": {key: _value}})
set_filters(elastic_query, filters)
return elastic_query
def _build_query_string(q, default_field=None):
"""
Builds "query_string" object from 'q'.
:param: q of type String
:param: default_field
:return: dictionary object.
"""
query_string = {'query_string': {'query': q, 'default_operator': 'AND'}}
query_string['query_string'].update({'lenient': False} if default_field else {'default_field': default_field})
return query_string
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc on Thu Nov 22 16:43:24 EST 2007 -->
<TITLE>
Xalan-Java 2.7.1: Uses of Interface org.apache.xml.serializer.ExtendedLexicalHandler
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<!-- ========== START OF NAVBAR ========== -->
<A NAME="navbar_top"><!-- --></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">
<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="../../../../../org/apache/xml/serializer/ExtendedLexicalHandler.html"><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>
</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" TARGET="_top"><B>FRAMES</B></A>
<A HREF="ExtendedLexicalHandler.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
</TR>
</TABLE>
<!-- =========== END OF NAVBAR =========== -->
<HR>
<CENTER>
<H2>
<B>Uses of Interface<br>org.apache.xml.serializer.ExtendedLexicalHandler</B></H2>
</CENTER>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Packages that use <A HREF="../../../../../org/apache/xml/serializer/ExtendedLexicalHandler.html">ExtendedLexicalHandler</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.xalan.xsltc.dom"><B>org.apache.xalan.xsltc.dom</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.xalan.xsltc.runtime"><B>org.apache.xalan.xsltc.runtime</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.xml.serializer"><B>org.apache.xml.serializer</B></A></TD>
<TD>Processes SAX events into streams. </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.xalan.xsltc.dom"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/apache/xml/serializer/ExtendedLexicalHandler.html">ExtendedLexicalHandler</A> in <A HREF="../../../../../org/apache/xalan/xsltc/dom/package-summary.html">org.apache.xalan.xsltc.dom</A></FONT></TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Classes in <A HREF="../../../../../org/apache/xalan/xsltc/dom/package-summary.html">org.apache.xalan.xsltc.dom</A> that implement <A HREF="../../../../../org/apache/xml/serializer/ExtendedLexicalHandler.html">ExtendedLexicalHandler</A></FONT></TD>
</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="../../../../../org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.html">AdaptiveResultTreeImpl</A></B></CODE>
<BR>
AdaptiveResultTreeImpl is a adaptive DOM model for result tree fragments (RTF).</TD>
</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="../../../../../org/apache/xalan/xsltc/dom/SimpleResultTreeImpl.html">SimpleResultTreeImpl</A></B></CODE>
<BR>
This class represents a light-weight DOM model for simple result tree fragment(RTF).</TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.xalan.xsltc.runtime"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/apache/xml/serializer/ExtendedLexicalHandler.html">ExtendedLexicalHandler</A> in <A HREF="../../../../../org/apache/xalan/xsltc/runtime/package-summary.html">org.apache.xalan.xsltc.runtime</A></FONT></TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Classes in <A HREF="../../../../../org/apache/xalan/xsltc/runtime/package-summary.html">org.apache.xalan.xsltc.runtime</A> that implement <A HREF="../../../../../org/apache/xml/serializer/ExtendedLexicalHandler.html">ExtendedLexicalHandler</A></FONT></TD>
</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="../../../../../org/apache/xalan/xsltc/runtime/StringValueHandler.html">StringValueHandler</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.xml.serializer"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/apache/xml/serializer/ExtendedLexicalHandler.html">ExtendedLexicalHandler</A> in <A HREF="../../../../../org/apache/xml/serializer/package-summary.html">org.apache.xml.serializer</A></FONT></TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Subinterfaces of <A HREF="../../../../../org/apache/xml/serializer/ExtendedLexicalHandler.html">ExtendedLexicalHandler</A> in <A HREF="../../../../../org/apache/xml/serializer/package-summary.html">org.apache.xml.serializer</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> interface</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/SerializationHandler.html">SerializationHandler</A></B></CODE>
<BR>
This interface is the one that a serializer implements.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Classes in <A HREF="../../../../../org/apache/xml/serializer/package-summary.html">org.apache.xml.serializer</A> that implement <A HREF="../../../../../org/apache/xml/serializer/ExtendedLexicalHandler.html">ExtendedLexicalHandler</A></FONT></TD>
</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="../../../../../org/apache/xml/serializer/EmptySerializer.html">EmptySerializer</A></B></CODE>
<BR>
This class is an adapter class.</TD>
</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="../../../../../org/apache/xml/serializer/SerializerBase.html">SerializerBase</A></B></CODE>
<BR>
This class acts as a base class for the XML "serializers"
and the stream serializers.</TD>
</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="../../../../../org/apache/xml/serializer/ToHTMLSAXHandler.html">ToHTMLSAXHandler</A></B></CODE>
<BR>
<B>Deprecated.</B> <I>As of Xalan 2.7.1, replaced by the use of <A HREF="../../../../../org/apache/xml/serializer/ToXMLSAXHandler.html"><CODE>ToXMLSAXHandler</CODE></A>.</I></TD>
</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="../../../../../org/apache/xml/serializer/ToHTMLStream.html">ToHTMLStream</A></B></CODE>
<BR>
This serializer takes a series of SAX or
SAX-like events and writes its output
to the given stream.</TD>
</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="../../../../../org/apache/xml/serializer/ToSAXHandler.html">ToSAXHandler</A></B></CODE>
<BR>
This class is used to provide a base behavior to be inherited
by other To...SAXHandler serializers.</TD>
</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="../../../../../org/apache/xml/serializer/ToStream.html">ToStream</A></B></CODE>
<BR>
This abstract class is a base class for other stream
serializers (xml, html, text ...) that write output to a stream.</TD>
</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="../../../../../org/apache/xml/serializer/ToTextSAXHandler.html">ToTextSAXHandler</A></B></CODE>
<BR>
<B>Deprecated.</B> <I>As of Xalan 2.7.1, replaced by the use of <A HREF="../../../../../org/apache/xml/serializer/ToXMLSAXHandler.html"><CODE>ToXMLSAXHandler</CODE></A>.</I></TD>
</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="../../../../../org/apache/xml/serializer/ToTextStream.html">ToTextStream</A></B></CODE>
<BR>
This class is not a public API.</TD>
</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="../../../../../org/apache/xml/serializer/ToUnknownStream.html">ToUnknownStream</A></B></CODE>
<BR>
This class wraps another SerializationHandler.</TD>
</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="../../../../../org/apache/xml/serializer/ToXMLSAXHandler.html">ToXMLSAXHandler</A></B></CODE>
<BR>
This class receives notification of SAX-like events, and with gathered
information over these calls it will invoke the equivalent SAX methods
on a handler, the ultimate xsl:output method is known to be "xml".</TD>
</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="../../../../../org/apache/xml/serializer/ToXMLStream.html">ToXMLStream</A></B></CODE>
<BR>
This class converts SAX or SAX-like calls to a
serialized xml document.</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ========== START OF NAVBAR ========== -->
<A NAME="navbar_bottom"><!-- --></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">
<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="../../../../../org/apache/xml/serializer/ExtendedLexicalHandler.html"><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>
</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" TARGET="_top"><B>FRAMES</B></A>
<A HREF="ExtendedLexicalHandler.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
</TR>
</TABLE>
<!-- =========== END OF NAVBAR =========== -->
<HR>
Copyright © 2006 Apache XML Project. All Rights Reserved.
</BODY>
</HTML>
| Java |
ProjectTop := /Volumes/Polaris/polymake
include ${ProjectTop}/support/extension.make
| Java |
=head1 NAME
EPrints::Plugin::Screen::Search
=cut
package EPrints::Plugin::Screen::Search;
use EPrints::Plugin::Screen::AbstractSearch;
@ISA = ( 'EPrints::Plugin::Screen::AbstractSearch' );
use strict;
sub new
{
my( $class, %params ) = @_;
my $self = $class->SUPER::new(%params);
$self->{appears} = [];
push @{$self->{actions}}, "advanced", "savesearch";
return $self;
}
sub datasets
{
my( $self ) = @_;
my $session = $self->{session};
my @datasets;
foreach my $datasetid ($session->get_dataset_ids)
{
local $self->{processor}->{dataset} = $session->dataset( $datasetid );
next if !$self->can_be_viewed();
push @datasets, $datasetid;
}
return @datasets;
}
sub search_dataset
{
my( $self ) = @_;
return $self->{processor}->{dataset};
}
sub allow_advanced { shift->can_be_viewed( @_ ) }
sub allow_export { shift->can_be_viewed( @_ ) }
sub allow_export_redir { shift->can_be_viewed( @_ ) }
sub allow_savesearch
{
my( $self ) = @_;
return 0 if !$self->can_be_viewed();
my $user = $self->{session}->current_user;
return defined $user && $user->allow( "create_saved_search" );
}
sub can_be_viewed
{
my( $self ) = @_;
# note this method is also used by $self->datasets()
my $dataset = $self->{processor}->{dataset};
return 0 if !defined $dataset;
my $searchid = $self->{processor}->{searchid};
if( $dataset->id eq "archive" )
{
return $self->allow( "eprint_search" );
}
elsif( defined($searchid) && (my $rc = $self->allow( $dataset->id . "/search/$searchid" )) )
{
return $rc;
}
{
return $self->allow( $dataset->id . "/search" );
}
}
sub get_controls_before
{
my( $self ) = @_;
my @controls = $self->get_basic_controls_before;
my $cacheid = $self->{processor}->{results}->{cache_id};
my $escexp = $self->{processor}->{search}->serialise;
my $baseurl = URI->new( $self->{session}->get_uri );
$baseurl->query_form(
cache => $cacheid,
exp => $escexp,
screen => $self->{processor}->{screenid},
dataset => $self->search_dataset->id,
order => $self->{processor}->{search}->{custom_order},
);
# Maybe add links to the pagination controls to switch between simple/advanced
# if( $self->{processor}->{searchid} eq "simple" )
# {
# push @controls, {
# url => "advanced",
# label => $self->{session}->html_phrase( "lib/searchexpression:advanced_link" ),
# };
# }
my $user = $self->{session}->current_user;
if( defined $user && $user->allow( "create_saved_search" ) )
{
#my $cacheid = $self->{processor}->{results}->{cache_id};
#my $exp = $self->{processor}->{search}->serialise;
my $url = $baseurl->clone;
$url->query_form(
$url->query_form,
_action_savesearch => 1
);
push @controls, {
url => "$url",
label => $self->{session}->html_phrase( "lib/searchexpression:savesearch" ),
};
}
return @controls;
}
sub hidden_bits
{
my( $self ) = @_;
my %bits = $self->SUPER::hidden_bits;
my @datasets = $self->datasets;
# if there's more than 1 dataset, then the search form will render the list of "search-able" datasets - see render_dataset below
if( scalar( @datasets ) < 2 )
{
$bits{dataset} = $self->{processor}->{dataset}->id;
}
return %bits;
}
sub render_result_row
{
my( $self, $session, $result, $searchexp, $n ) = @_;
my $staff = $self->{processor}->{sconf}->{staff};
my $citation = $self->{processor}->{sconf}->{citation};
if( $staff )
{
return $result->render_citation_link_staff( $citation,
n => [$n,"INTEGER"] );
}
else
{
return $result->render_citation_link( $citation,
n => [$n,"INTEGER"] );
}
}
sub export_url
{
my( $self, $format ) = @_;
my $plugin = $self->{session}->plugin( "Export::".$format );
if( !defined $plugin )
{
EPrints::abort( "No such plugin: $format\n" );
}
my $url = URI->new( $self->{session}->current_url() . "/export_" . $self->{session}->get_repository->get_id . "_" . $format . $plugin->param( "suffix" ) );
$url->query_form(
$self->hidden_bits,
_action_export => 1,
output => $format,
exp => $self->{processor}->{search}->serialise,
n => scalar($self->{session}->param( "n" )),
);
return $url;
}
sub action_advanced
{
my( $self ) = @_;
my $adv_url;
my $datasetid = $self->{session}->param( "dataset" );
$datasetid = "archive" if !defined $datasetid; # something odd happened
if( $datasetid eq "archive" )
{
$adv_url = $self->{session}->current_url( path => "cgi", "search/advanced" );
}
else
{
$adv_url = $self->{session}->current_url( path => "cgi", "search/$datasetid/advanced" );
}
$self->{processor}->{redirect} = $adv_url;
}
sub action_savesearch
{
my( $self ) = @_;
my $ds = $self->{session}->dataset( "saved_search" );
my $searchexp = $self->{processor}->{search};
$searchexp->{searchid} = $self->{processor}->{searchid};
my $name = $searchexp->render_conditions_description;
my $userid = $self->{session}->current_user->id;
my $spec = $searchexp->freeze;
my $results = $ds->search(
filters => [
{ meta_fields => [qw( userid )], value => $userid, },
{ meta_fields => [qw( spec )], value => $spec, match => "EX" },
]);
my $savedsearch = $results->item( 0 );
my $screen;
if( defined $savedsearch )
{
$screen = "View";
}
else
{
$screen = "Edit";
$savedsearch = $ds->create_dataobj( {
userid => $self->{session}->current_user->id,
name => $self->{session}->xml->text_contents_of( $name ),
spec => $searchexp->freeze
} );
}
$self->{session}->xml->dispose( $name );
my $url = URI->new( $self->{session}->config( "userhome" ) );
$url->query_form(
screen => "Workflow::$screen",
dataset => "saved_search",
dataobj => $savedsearch->id,
);
$self->{session}->redirect( $url );
exit;
}
sub render_search_form
{
my( $self ) = @_;
if( $self->{processor}->{searchid} eq "simple" && @{$self->{processor}->{sconf}->{search_fields}} == 1 )
{
return $self->render_simple_form;
}
else
{
return $self->SUPER::render_search_form;
}
}
sub render_preamble
{
my( $self ) = @_;
my $pphrase = $self->{processor}->{sconf}->{"preamble_phrase"};
return $self->{session}->make_doc_fragment if !defined $pphrase;
return $self->{session}->html_phrase( $pphrase );
}
sub render_simple_form
{
my( $self ) = @_;
my $session = $self->{session};
my $xhtml = $session->xhtml;
my $xml = $session->xml;
my $input;
my $div = $xml->create_element( "div", class => "ep_block" );
my $form = $self->{session}->render_form( "get" );
$div->appendChild( $form );
my $label = $xml->create_element( "label", for => "q_merge", class => "ep_lbl_merge" );
$label->appendChild( $session->html_phrase( "lib/searchexpression:merge" ) );
$form->appendChild( $label );
# avoid adding "dataset", which is selectable here
$form->appendChild( $self->SUPER::render_hidden_bits );
# maintain the order if it was specified (might break if dataset is
# changed)
$input = $xhtml->hidden_field( "order", $session->param( "order" ) );
$form->appendChild( $input );
$form->appendChild( $self->render_preamble );
$form->appendChild( $self->{processor}->{search}->render_simple_fields( 'aria-labelledby' => $session->phrase( "lib/searchexpression:action_search" ) ) );
$input = $xml->create_element( "input",
type => "submit",
name => "_action_search",
value => $session->phrase( "lib/searchexpression:action_search" ),
class => "ep_form_action_button",
id => $session->phrase( "lib/searchexpression:action_search" ),
);
$form->appendChild( $input );
$input = $xml->create_element( "input",
type => "submit",
name => "_action_advanced",
value => $self->{session}->phrase( "lib/searchexpression:advanced_link" ),
class => "ep_form_action_button ep_form_search_advanced_link",
);
$form->appendChild( $input );
$form->appendChild( $xml->create_element( "br" ) );
$form->appendChild( $self->render_dataset );
return( $div );
}
sub render_dataset
{
my( $self ) = @_;
my $session = $self->{session};
my $xhtml = $session->xhtml;
my $xml = $session->xml;
my $frag = $xml->create_document_fragment;
my @datasetids = $self->datasets;
return $frag if @datasetids <= 1;
foreach my $datasetid (sort @datasetids)
{
my $input = $xml->create_element( "input",
name => "dataset",
type => "radio",
value => $datasetid );
if( $datasetid eq $self->{processor}->{dataset}->id )
{
$input->setAttribute( checked => "yes" );
}
my $label = $xml->create_element( "label", id=>$datasetid );
$frag->appendChild( $label );
$label->appendChild( $input );
$label->appendChild( $session->html_phrase( "datasetname_$datasetid" ) );
}
return $frag;
}
sub properties_from
{
my( $self ) = @_;
$self->SUPER::properties_from();
my $processor = $self->{processor};
my $repo = $self->{session};
my $dataset = $processor->{dataset};
my $searchid = $processor->{searchid};
return if !defined $dataset;
return if !defined $searchid;
# get the dataset's search configuration
my $sconf = $dataset->search_config( $searchid );
$sconf = $self->default_search_config if !%$sconf;
$processor->{sconf} = $sconf;
$processor->{template} = $sconf->{template};
}
sub default_search_config {}
sub from
{
my( $self ) = @_;
my $session = $self->{session};
my $processor = $self->{processor};
my $sconf = $processor->{sconf};
# This rather oddly now checks for the special case of one parameter, but
# that parameter being a screenid, in which case the search effectively has
# no parameters and should not default to action = 'search'.
# maybe this can be removed later, but for a minor release this seems safest.
if( !EPrints::Utils::is_set( $self->{processor}->{action} ) )
{
my %params = map { $_ => 1 } $self->{session}->param();
foreach my $param (keys %{{$self->hidden_bits}}) {
delete $params{$param};
}
if( EPrints::Utils::is_set( $self->{session}->param( "output" ) ) )
{
$self->{processor}->{action} = "export";
}
elsif( scalar keys %params )
{
$self->{processor}->{action} = "search";
}
else
{
$self->{processor}->{action} = "";
}
}
my $satisfy_all = $self->{session}->param( "satisfyall" );
$satisfy_all = !defined $satisfy_all || $satisfy_all eq "ALL";
my $searchexp = $processor->{search};
if( !defined $searchexp )
{
my $format = $processor->{searchid} . "/" . $processor->{dataset}->base_id;
if( !defined $sconf )
{
EPrints->abort( "No available configuration for search type $format" );
}
$searchexp = $session->plugin( "Search" )->plugins(
{
session => $session,
dataset => $self->search_dataset,
keep_cache => 1,
satisfy_all => $satisfy_all,
%{$sconf},
filters => [
$self->search_filters,
@{$sconf->{filters} || []},
],
},
type => "Search",
can_search => $format,
);
if( !defined $searchexp )
{
EPrints->abort( "No available search plugin for $format" );
}
$processor->{search} = $searchexp;
}
if( $searchexp->is_blank && $self->{processor}->{action} ne "newsearch" )
{
my $ok = 0;
if( my $id = $session->param( "cache" ) )
{
$ok = $searchexp->from_cache( $id );
}
if( !$ok && (my $exp = $session->param( "exp" )) )
{
# cache expired
$ok = $searchexp->from_string( $exp );
}
if( !$ok )
{
for( $searchexp->from_form )
{
$self->{processor}->add_message( "warning", $_ );
}
}
}
$sconf->{order_methods} = {} if !defined $sconf->{order_methods};
if( $searchexp->param( "result_order" ) )
{
$sconf->{order_methods}->{"byrelevance"} = "";
}
# have we been asked to reorder?
if( defined( my $order_opt = $self->{session}->param( "order" ) ) )
{
my $allowed_order = 0;
foreach my $custom_order ( values %{$sconf->{order_methods}} )
{
$allowed_order = 1 if $order_opt eq $custom_order;
}
my $custom_order;
if( $allowed_order )
{
$custom_order = $order_opt;
}
elsif( defined $sconf->{default_order} )
{
$custom_order = $sconf->{order_methods}->{$sconf->{default_order}};
}
else
{
$custom_order = "";
}
$searchexp->{custom_order} = $custom_order;
}
# use default order
else
{
$searchexp->{custom_order} = $sconf->{order_methods}->{$sconf->{default_order}};
}
# feeds are always limited and ordered by -datestamp
if( $self->{processor}->{action} eq "export" )
{
my $output = $self->{session}->param( "output" );
my $export_plugin = $self->{session}->plugin( "Export::$output" );
if( !defined($self->{session}->param( "order" )) && defined($export_plugin) && $export_plugin->is_feed )
{
# borrow the max from latest_tool (which we're replicating anyway)
my $limit = $self->{session}->config(
"latest_tool_modes", "default", "max"
);
$limit = 20 if !$limit;
my $n = $self->{session}->param( "n" );
if( $n && $n > 0 && $n < $limit)
{
$limit = $n;
}
$searchexp->{limit} = $limit;
$searchexp->{custom_order} = "-datestamp";
}
}
# do actions
$self->EPrints::Plugin::Screen::from;
if( $searchexp->is_blank && $self->{processor}->{action} ne "export" )
{
if( $self->{processor}->{action} eq "search" )
{
$self->{processor}->add_message( "warning",
$self->{session}->html_phrase(
"lib/searchexpression:least_one" ) );
}
$self->{processor}->{search_subscreen} = "form";
}
}
1;
=head1 COPYRIGHT
=for COPYRIGHT BEGIN
Copyright 2000-2011 University of Southampton.
=for COPYRIGHT END
=for LICENSE BEGIN
This file is part of EPrints L<http://www.eprints.org/>.
EPrints is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
EPrints is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public
License along with EPrints. If not, see L<http://www.gnu.org/licenses/>.
=for LICENSE END
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>PHP MySQL Database Interface: UnknownDatabaseException Klassenreferenz</title>
<link href="../../tabs.css" rel="stylesheet" type="text/css">
<link href="../../doxygen.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Erzeugt von Doxygen 1.5.9 -->
<div class="navigation" id="top">
<div class="tabs">
<ul>
<li><a href="../../main.html"><span>Hauptseite</span></a></li>
<li><a href="../../namespaces.html"><span>Namensbereiche</span></a></li>
<li class="current"><a href="../../annotated.html"><span>Datenstrukturen</span></a></li>
<li><a href="../../files.html"><span>Dateien</span></a></li>
</ul>
</div>
<div class="tabs">
<ul>
<li><a href="../../annotated.html"><span>Datenstrukturen</span></a></li>
<li><a href="../../hierarchy.html"><span>Klassenhierarchie</span></a></li>
<li><a href="../../functions.html"><span>Datenstruktur-Elemente</span></a></li>
</ul>
</div>
</div>
<div class="contents">
<h1>UnknownDatabaseException Klassenreferenz</h1><!-- doxytag: class="UnknownDatabaseException" --><!-- doxytag: inherits="DatabaseException" --><div class="dynheader">
Klassendiagramm für UnknownDatabaseException:</div>
<div class="dynsection">
<p><center><img src="../../dc/daa/class_unknown_database_exception.png" usemap="#UnknownDatabaseException_map" border="0" alt=""></center>
<map name="UnknownDatabaseException_map">
<area href="../../d1/d5d/class_database_exception.html" alt="DatabaseException" shape="rect" coords="0,0,171,24">
</map>
</div>
<table border="0" cellpadding="0" cellspacing="0">
<tr><td></td></tr>
<tr><td colspan="2"><br><h2>Öffentliche Methoden</h2></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="../../dc/daa/class_unknown_database_exception.html#d9192420bc35f927ea5bcc2b6da93b0c">__construct</a> ($message=null, $code=0, Exception $previous=null)</td></tr>
</table>
<hr><a name="_details"></a><h2>Ausführliche Beschreibung</h2>
<a class="el" href="../../dc/daa/class_unknown_database_exception.html">UnknownDatabaseException</a> <hr><h2>Beschreibung der Konstruktoren und Destruktoren</h2>
<a class="anchor" name="d9192420bc35f927ea5bcc2b6da93b0c"></a><!-- doxytag: member="UnknownDatabaseException::__construct" ref="d9192420bc35f927ea5bcc2b6da93b0c" args="($message=null, $code=0, Exception $previous=null)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">__construct </td>
<td>(</td>
<td class="paramtype">$ </td>
<td class="paramname"> <em>message</em> = <code>null</code>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">$ </td>
<td class="paramname"> <em>code</em> = <code>0</code>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">Exception $ </td>
<td class="paramname"> <em>previous</em> = <code>null</code></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
<dl compact><dt><b>Parameter:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>string</em> </td><td>$message </td></tr>
<tr><td valign="top"></td><td valign="top"><em>number</em> </td><td>$code </td></tr>
<tr><td valign="top"></td><td valign="top"><em>Exception</em> </td><td>$previous </td></tr>
</table>
</dl>
<p>Erneute Implementation von <a class="el" href="../../d1/d5d/class_database_exception.html#d9192420bc35f927ea5bcc2b6da93b0c">DatabaseException</a>.</p>
</div>
</div><p>
<hr>Die Dokumentation für diese Klasse wurde erzeugt aufgrund der Datei:<ul>
<li>S:/Documents/Projekte/phpDBI/workbench/0.02/classes/exception/<a class="el" href="../../d1/d9b/_unknown_database_exception_8php.html">UnknownDatabaseException.php</a></ul>
</div>
<hr size="1"><address style="text-align: right;"><small>Erzeugt am Fri Dec 25 15:32:56 2009 für PHP MySQL Database Interface von
<a href="http://www.doxygen.org/index.html">
<img src="../../doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.9 </small></address>
</body>
</html>
| Java |
/*
* ASpark
* Copyright (C) 2015 Nikolay Platov
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nikoladasm.aspark;
import java.io.IOException;
import java.io.InputStream;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import io.netty.buffer.ByteBuf;
import static nikoladasm.aspark.HttpMethod.*;
public final class ASparkUtil {
private static final String PARAMETERS_PATTERN = "(?i)(:[A-Z_][A-Z_0-9]*)";
private static final Pattern PATTERN = Pattern.compile(PARAMETERS_PATTERN);
private static final String DEFAULT_ACCEPT_TYPE = "*/*";
private static final String REGEXP_METACHARS = "<([{\\^-=$!|]})?*+.>";
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private static final String FOLDER_SEPARATOR = "/";
private static final String WINDOWS_FOLDER_SEPARATOR = "\\";
private static final String TOP_PATH = "..";
private static final String CURRENT_PATH = ".";
private static final String QUERY_KEYS_PATTERN = "\\s*\\[?\\s*([^\\]\\[\\s]+)\\s*\\]?\\s*";
private static final Pattern QK_PATTERN = Pattern.compile(QUERY_KEYS_PATTERN);
private ASparkUtil() {}
private static String processRegexPath(String path, String asteriskReplacement, String slashAsteriskReplacement) {
String pathToUse = sanitizePath(path);
int length = pathToUse.length();
StringBuilder sb = new StringBuilder();
boolean startWithWildcard = false;
for (int i = 0; i < length; i++) {
char c = pathToUse.charAt(i);
if (i == 0 && c == '*') {
sb.append(asteriskReplacement);
startWithWildcard = true;
continue;
}
if (i == length-2 && c == '/' && pathToUse.charAt(i+1) == '*') {
if (startWithWildcard)
throw new IllegalArgumentException("Path can't contain first and last star wildcard");
sb.append(slashAsteriskReplacement);
break;
}
if (i == length-1 && c == '*') {
if (startWithWildcard)
throw new IllegalArgumentException("Path can't contain first and last star wildcard");
sb.append(asteriskReplacement);
continue;
}
if (REGEXP_METACHARS.contains(String.valueOf(c))) {
sb.append('\\').append(c);
continue;
}
sb.append(c);
}
return sb.toString();
}
public static Pattern buildParameterizedPathPattern(String path, Map<String, Integer> parameterNamesMap, Boolean startWithWildcard) {
String pathToUse = processRegexPath(path, "(.*)", "(?:/?|/(.+))");
Matcher parameterMatcher = PATTERN.matcher(pathToUse);
int i = 1;
while (parameterMatcher.find()) {
String parameterName = parameterMatcher.group(1);
if (parameterNamesMap.containsKey(parameterName))
throw new ASparkException("Duplicate parameter name.");
parameterNamesMap.put(parameterName, i);
i++;
}
return Pattern.compile("^"+parameterMatcher.replaceAll("([^/]+)")+"$");
}
public static Pattern buildPathPattern(String path) {
String pathToUse = processRegexPath(path, ".*", "(?:/?|/.+)");
return Pattern.compile("^"+pathToUse+"$");
}
public static boolean isAcceptContentType(String requestAcceptTypes,
String routeAcceptType) {
if (requestAcceptTypes == null)
return routeAcceptType.trim().equals(DEFAULT_ACCEPT_TYPE);
String[] requestAcceptTypesArray = requestAcceptTypes.split(",");
String[] rtat = routeAcceptType.trim().split("/");
for (int i=0; i<requestAcceptTypesArray.length; i++) {
String requestAcceptType = requestAcceptTypesArray[i].split(";")[0];
String[] rqat = requestAcceptType.trim().split("/");
if (((rtat[0].equals("*")) ? true : rqat[0].trim().equals(rtat[0])) &&
((rtat[1].equals("*")) ? true : rqat[1].equals(rtat[1]))) return true;
}
return false;
}
public static long copyStreamToByteBuf(InputStream input, ByteBuf buf) throws IOException {
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
long count = 0;
int n = 0;
while ((n = input.read(buffer)) != -1) {
buf.writeBytes(buffer, 0, n);
count += n;
}
return count;
}
public static String collapsePath(String path) {
String pathToUse = path.trim();
if (pathToUse.isEmpty()) return pathToUse;
String rpath = pathToUse.replace(WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);
String[] directories = rpath.split(FOLDER_SEPARATOR);
Deque<String> newDirectories = new LinkedList<>();
for (int i=0; i<directories.length; i++) {
String directory = directories[i].trim();
if (directory.equals(TOP_PATH) && !newDirectories.isEmpty())
newDirectories.removeLast();
else if (!directory.equals(CURRENT_PATH) && !directory.isEmpty())
newDirectories.addLast(directory);
}
String result = FOLDER_SEPARATOR;
for (String directory : newDirectories)
result += directory + FOLDER_SEPARATOR;
if (!path.startsWith(FOLDER_SEPARATOR))
result = result.substring(1);
if (!path.endsWith(FOLDER_SEPARATOR) && result.equals(FOLDER_SEPARATOR))
result = result.substring(0, result.length()-1);
return result;
}
public static boolean isEqualHttpMethod(HttpMethod requestHttpMethod,
HttpMethod routeHttpMethod) {
if (requestHttpMethod.equals(HEAD) && routeHttpMethod.equals(GET))
return true;
return requestHttpMethod.equals(routeHttpMethod);
}
public static ParamsMap parseParams(Map<String, List<String>> params) {
ParamsMap result = new ParamsMap();
params.forEach((keys, values) -> {
ParamsMap root = result;
Matcher keyMatcher = QK_PATTERN.matcher(keys);
while (keyMatcher.find()) {
String key = keyMatcher.group(1);
root = root.createIfAbsentAndGet(key);
}
root.values(values.toArray(new String[values.size()]));
});
return result;
}
public static ParamsMap parseUniqueParams(Map<String, String> params) {
ParamsMap result = new ParamsMap();
params.forEach((key, value) -> {
result.createIfAbsentAndGet(key).value(value);
});
return result;
}
public static String sanitizePath(String path) {
String pathToUse = collapsePath(path);
if (pathToUse.isEmpty()) return pathToUse;
if (pathToUse.endsWith("/")) pathToUse = pathToUse.substring(0, pathToUse.length()-1);
return pathToUse;
}
public static String mimeType(String file, Properties mimeTypes) {
int extIndex = file.lastIndexOf('.');
extIndex = (extIndex < 0 ) ? 0 : extIndex;
String ext = file.substring(extIndex);
return mimeTypes.getProperty(ext, "application/octet-stream");
}
}
| Java |
package controller;
import java.io.IOException;
import java.sql.Time;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.simple.JSONObject;
import utils.Common;
import utils.Constant;
import utils.MessageProperties;
import dao.HocKyDao;
import dao.OnlDao;
import dao.WeekDao;
import dao.impl.HocKyDaoImpl;
import dao.impl.OnlDaoImpl;
import dao.impl.PositionDaoImpl;
import dao.impl.WeekDaoImpl;
import entity.HocKy;
import entity.Onl;
import entity.Position;
import entity.User;
import entity.Week;
/**
* Servlet implementation class OnlController
*/
@WebServlet("/jsp/onl.htm")
public class OnlController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
// get list học kỳ
HocKyDao hocKyDao = new HocKyDaoImpl();
List<HocKy> listHocKy = hocKyDao.getListHocKy();
request.setAttribute("listHocKy", listHocKy);
// lấy học kỳ hiện tại
String currentHocKy = hocKyDao.getHocKy(Common.getNow());
request.setAttribute("currentHocKy", currentHocKy);
// lấy danh sách tuần theo học kỳ hiện tại
WeekDao weekDao = new WeekDaoImpl();
List<Week> listWeek = weekDao.getListWeek(currentHocKy);
request.setAttribute("listWeek", listWeek);
// lấy tuần hiện tại
Week currentWeek = weekDao.getCurrentWeek(Common.getNow());
request.setAttribute("currentWeek", currentWeek);
// lấy lịch trực trong tuần
List<Onl> listOnl = new OnlDaoImpl().getListOnl(null, currentWeek.getWeekId(), user.getUserId());
request.setAttribute(Constant.ACTION, "viewOnl");
request.setAttribute("listOnl", listOnl);
request.getRequestDispatcher("view_onl_cal.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
@SuppressWarnings({ "unchecked", "deprecation" })
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if ("position".equals(action)) {
double latitude = Double.parseDouble(request
.getParameter("latitude"));
double longitude = Double.parseDouble(request
.getParameter("longitude"));
long onlId = Long.parseLong(request.getParameter("id"));
// lấy tọa độ phòng B1-502
Position position = new PositionDaoImpl().getPositionById("B1-502");
JSONObject jsonObject = new JSONObject();
ServletOutputStream out = response.getOutputStream();
if (position == null) {
jsonObject.put(Constant.STATUS, false);
jsonObject.put(Constant.DATA,
MessageProperties.getData("ERR12"));
out.write(jsonObject.toJSONString().getBytes());
out.flush();
return;
}
// check vị trí
if (!checkPosition(position, latitude, longitude)) {
jsonObject.put(Constant.STATUS, false);
jsonObject.put(Constant.DATA,
MessageProperties.getData("ERR13"));
out.write(jsonObject.toJSONString().getBytes());
out.flush();
return;
}
// if (!(latitude >= 20 && latitude <= 22 && longitude >= 105 &&
// longitude <= 106)) {
// String error = MessageProperties.getData("ERR09");
// jsonObject.put(Constant.STATUS, false);
// jsonObject.put(Constant.DATA, error);
// out.write(jsonObject.toJSONString().getBytes());
// out.flush();
// return;
// }
// check thời giạn click nhận giao ban
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("Asia/Ho_Chi_Minh"));
Time now = new Time(cal.get(Calendar.HOUR_OF_DAY),
cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND));
// lấy lịch trực bởi id
OnlDao onlDao = new OnlDaoImpl();
Onl onl = onlDao.getOnlById(onlId);
if (now.after(onl.getTimeStart()) && now.before(onl.getTimeEnd())) {
// tính thời gian muộn
int lateMin = (int) Math.round((double) ((now.getTime() - onl
.getTimeStart().getTime()) / 1000) / 60);
// thay đổi trạng thái
onl.setLate(true);
onl.setLateMin(lateMin);
} else if (now.after(onl.getTimeEnd())) {
// nghỉ
String error = MessageProperties.getData("ERR14");
jsonObject.put(Constant.STATUS, false);
jsonObject.put("flagHol", true);
jsonObject.put(Constant.DATA, error);
out.write(jsonObject.toJSONString().getBytes());
out.flush();
return;
}
// cập nhật trạng thái nghỉ
onl.setHol(false);
// cập nhật
if (!onlDao.update(onl, true)) {
jsonObject.put(Constant.STATUS, false);
jsonObject.put(Constant.DATA,
MessageProperties.getData("ERR10"));
out.write(jsonObject.toJSONString().getBytes());
out.flush();
return;
}
jsonObject.put(Constant.STATUS, true);
jsonObject.put(Constant.DATA, MessageProperties.getData("MSG04"));
out.write(jsonObject.toJSONString().getBytes());
out.flush();
return;
} else if ("addReason".equals(action)) {
JSONObject jsonObject = new JSONObject();
ServletOutputStream out = response.getOutputStream();
String reason = request.getParameter("reason");
long onlId = Long.parseLong(request.getParameter("id"));
// update lý do
if (!new OnlDaoImpl().setReason(reason, onlId)) {
jsonObject.put(Constant.STATUS, false);
jsonObject.put(Constant.DATA,
MessageProperties.getData("ERR10"));
out.write(jsonObject.toJSONString().getBytes());
out.flush();
return;
}
jsonObject.put(Constant.STATUS, true);
jsonObject.put(Constant.DATA, MessageProperties.getData("MSG01"));
out.write(jsonObject.toJSONString().getBytes());
out.flush();
return;
}
}
/**
* check vị trí khi nhận giao ban
*
* @param position
* tọa độ vị trí phòng B1-502
* @param latitude
* vĩ độ lấy được ở vị trí hiện tại
* @param longitude
* kinh độ ở vị trí hiện tại
* @return true nếu vị trí hiện tại trùng với vị trí phòng B1-502. flase nếu
* ngược lại không trùng
*/
public boolean checkPosition(Position position, double latitude,
double longitude) {
double latitudeMin = Math.floor(position.getLatitude() * 1000000) / 1000000;
double latitudeMax = Math.ceil(position.getLatitude() * 1000000) / 1000000;
double longitudeMin = Math.floor(position.getLongitude() * 10000000) / 10000000;
double longitudeMax = Math.ceil((position.getLongitude()) * 10000000) / 10000000;
System.out.println(latitudeMin + " <= " + latitude + " <= "+ latitudeMax);
System.out.println(longitudeMin + " <= " + longitude + " <= "+ longitudeMax);
return latitudeMin <= latitude && latitude <= latitudeMax && longitudeMin <= longitude && longitude <= longitudeMax;
}
}
| Java |
#ifndef __PLATFORM_H_
#define __PLATFORM_H_
#define STDOUT_IS_PS7_UART
#define UART_DEVICE_ID 0
#include "xil_io.h"
#include "xtmrctr.h"
#include "assert.h"
/* Write to memory location or register */
#define X_mWriteReg(BASE_ADDRESS, RegOffset, data) \
*(unsigned volatile int *)(BASE_ADDRESS + RegOffset) = ((unsigned volatile int) data);
/* Read from memory location or register */
#define X_mReadReg(BASE_ADDRESS, RegOffset) \
*(unsigned volatile int *)(volatile)(BASE_ADDRESS + RegOffset);
#define XUartChanged_IsTransmitFull(BaseAddress) \
((Xil_In32((BaseAddress) + 0x2C) & \
0x10) == 0x10)
void wait_ms(unsigned int time);
void init_platform();
void cleanup_platform();
void ChangedPrint(char *ptr);
void timer_init();
void tic();
void toc();
u64 elapsed_time_us();
#endif
| Java |
<!DOCTYPE html>
<!--
Copyright (C) 2017 ss
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-->
<div style="min-height: 100px;">
<div [hidden]="result.length > 0">
<h4 style="text-align: center;"
[translate]="'transport-map.search-result.no-result'"></h4>
<h5 [translate]="'transport-map.search-result.no-result-desc'"></h5>
<h5 [translate]="'transport-map.search-result.no-result-geocoder'"></h5>
<h5>{{'transport-map.search-result.no-result-plain-schedule' | translate}}
<span class="sr-link" (click)="goToSchedule()">{{'transport-map.search-result.no-result-plain-schedule-link' | translate}}</span></h5>
<h5 [translate]="'transport-map.search-result.no-result-tooltip'"></h5>
</div>
<md-list *ngIf="mapComponent.activeProfile && result.length === 0">
<h3 md-subheader class="srl-result-h"
[translate]="'transport-map.search-result.legend'"></h3>
<md-list-item *ngFor="let typ of mapComponent.activeProfile.routeProfiles">
<span md-list-icon [style.background-color]="typ.lineColor" class="srl-route-label-2"></span>
<p md-line style="line-height: 30px;" [translate]="'route-type.' + typ.name"></p>
</md-list-item>
</md-list>
<div [hidden]="result.length < 1">
<md-list *ngIf="!flags.isDetailsOpen">
<h3 md-subheader class="srl-result-h"
[translate]="'transport-map.search-result.found-results'" [translateParams]="{count: result.length}"></h3>
<md-list-item *ngFor="let op of result" class="srl-item" (click)="showPath(op)"
[@flyInOut]="op.animationTrigger">
<md-icon *ngIf="!mapComponent.isMobile()" md-list-icon
[ngClass]="{'srl-selected-path': op === activePath}">chevron_right</md-icon>
<p md-line style="line-height: 30px; height: 30px;">
<span *ngFor="let path of op.path" class="srl-route-label"
[style.background-color]="path.route.type.lineColor"
[style.font-size]="mapComponent.isMobile() ? '12px' : null"
mdTooltip="{{path.description}}" mdTooltipPosition="above">{{path.route.namePrefix}}{{path.route.namePostfix}}</span>
<span class="srl-time-lbl">{{tripPeriod(op)}}</span>
</p>
<md-icon mdTooltip="{{'transport-map.search-result.open-details' | translate }}"
mdTooltipPosition="above" (click)="openDetails(op, $event)"
style="margin-left: 5px"
[ngClass]="{'srl-selected-path': op === activePath}">access_time</md-icon>
</md-list-item>
</md-list>
<!-- DETAILS -->
<div *ngIf="flags.isDetailsOpen" [@flyInOut]="detailsTrigger">
<md-grid-list cols="7" rowHeight="56px" >
<md-grid-tile>
<md-icon>schedule</md-icon>
</md-grid-tile>
<md-grid-tile colspan="5">
<h3 class="srl-details-h" [translate]="'transport-map.search-result.trip-details'"></h3>
</md-grid-tile>
<md-grid-tile>
<button md-mini-fab mdTooltip="{{'transport-map.search-result.back-to-summary' | translate }}"
mdTooltipPosition="above" (click)="closeDetails()" color="accent">
<md-icon>close</md-icon>
</button>
</md-grid-tile>
</md-grid-list>
<hr/>
<div *ngFor="let p of activePath.path; let i = index;">
<md-grid-list cols="10" rowHeight="50px">
<md-grid-tile colspan="2">
<img [src]="'/rest/data/transport-profile/route/marker/' + p.route.type.id">
</md-grid-tile>
<md-grid-tile colspan="6" class="srl-details-item"
(click)="flyToBusStop(activePath.way[i][0])">
<p class="srl-d-bs-lbl">{{activePath.way[i][0].name}}</p>
</md-grid-tile>
<md-grid-tile colspan="2">{{getBusStopTime(i, 'start')}}</md-grid-tile>
<md-grid-tile colspan="2">
<span class="srl-route-label"
[style.background-color]="p.route.type.lineColor">{{p.route.namePrefix}}{{p.route.namePostfix}}</span>
</md-grid-tile>
<md-grid-tile colspan="6" class="srl-details-item"
(click)="flyToWay(activePath.way[i])">
<p class="srl-d-bs-lbl">{{p.description}}</p>
</md-grid-tile>
<md-grid-tile colspan="2">{{pathTripDuration(i, p)}} {{'common.time.min' | translate}}</md-grid-tile>
<md-grid-tile colspan="2">
<img [src]="'/rest/data/transport-profile/route/marker/' + p.route.type.id">
</md-grid-tile>
<md-grid-tile colspan="6" class="srl-details-item"
(click)="flyToBusStop(activePath.way[i][activePath.way[i].length - 1])">
<p class="srl-d-bs-lbl">{{activePath.way[i][activePath.way[i].length - 1].name}}</p>
</md-grid-tile>
<md-grid-tile colspan="2">{{getBusStopTime(i, 'end')}}</md-grid-tile>
</md-grid-list>
<hr/>
</div>
<!-- Summary -->
<md-grid-list cols="8" rowHeight="50px">
<md-grid-tile>
<md-icon>directions_run</md-icon>
</md-grid-tile>
<md-grid-tile colspan="5">
<p class="srl-d-bs-lbl" [translate]="'transport-map.search-result.full-distance'"></p>
</md-grid-tile>
<md-grid-tile colspan="2">
{{summaryDistance()}} {{'common.unit.km' | translate}}
</md-grid-tile>
<md-grid-tile>
<md-icon>alarm</md-icon>
</md-grid-tile>
<md-grid-tile colspan="5">
<p class="srl-d-bs-lbl" [translate]="'transport-map.search-result.full-time'"></p>
</md-grid-tile>
<md-grid-tile colspan="2">
{{summaryTime()}} {{'common.time.min' | translate}}
</md-grid-tile>
</md-grid-list>
<button md-raised-button (click)="closeDetails()" class="full-width">
<md-icon>chevron_left</md-icon> {{'transport-map.search-result.back-to-summary' | translate }}
</button>
</div>
</div>
</div>
| Java |
import platform
import glob
from .io import DxlIO, Dxl320IO, DxlError
from .error import BaseErrorHandler
from .controller import BaseDxlController
from .motor import DxlMXMotor, DxlAXRXMotor, DxlXL320Motor
from ..robot import Robot
def _get_available_ports():
""" Tries to find the available usb2serial port on your system. """
if platform.system() == 'Darwin':
return glob.glob('/dev/tty.usb*')
elif platform.system() == 'Linux':
return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*')
elif platform.system() == 'Windows':
import _winreg
import itertools
ports = []
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path)
for i in itertools.count():
try:
ports.append(str(_winreg.EnumValue(key, i)[1]))
except WindowsError:
return ports
return []
def get_available_ports(only_free=False):
ports = _get_available_ports()
if only_free:
ports = list(set(ports) - set(DxlIO.get_used_ports()))
return ports
def find_port(ids, strict=True):
""" Find the port with the specified attached motor ids.
:param list ids: list of motor ids to find
:param bool strict: specify if all ids should be find (when set to False, only half motor must be found)
.. warning:: If two (or more) ports are attached to the same list of motor ids the first match will be returned.
"""
for port in get_available_ports():
for DxlIOCls in (DxlIO, Dxl320IO):
try:
with DxlIOCls(port) as dxl:
founds = len(dxl.scan(ids))
if strict and founds == len(ids):
return port
if not strict and founds >= len(ids) / 2:
return port
except DxlError:
continue
raise IndexError('No suitable port found for ids {}!'.format(ids))
def autodetect_robot():
""" Creates a :class:`~pypot.robot.robot.Robot` by detecting dynamixel motors on all available ports. """
motor_controllers = []
for port in get_available_ports():
for DxlIOCls in (DxlIO, Dxl320IO):
dxl_io = DxlIOCls(port)
ids = dxl_io.scan()
if not ids:
dxl_io.close()
continue
models = dxl_io.get_model(ids)
motorcls = {
'MX': DxlMXMotor,
'RX': DxlAXRXMotor,
'AX': DxlAXRXMotor,
'XL': DxlXL320Motor
}
motors = [motorcls[model[:2]](id, model=model)
for id, model in zip(ids, models)]
c = BaseDxlController(dxl_io, motors)
motor_controllers.append(c)
return Robot(motor_controllers)
| Java |
/* -----------------------------------------------------------------------------
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
----------------------------------------------------------------------------- */
package ppm_java._dev.concept.example.event;
import ppm_java.backend.TController;
import ppm_java.typelib.IControllable;
import ppm_java.typelib.IEvented;
import ppm_java.typelib.VBrowseable;
/**
*
*/
class TSink extends VBrowseable implements IEvented, IControllable
{
public TSink (String id)
{
super (id);
}
public void OnEvent (int e, String arg0)
{
String msg;
msg = GetID () + ": " + "Received messaging event. Message: " + arg0;
System.out.println (msg);
}
public void Start () {/* Do nothing */}
public void Stop () {/* Do nothing */}
public void OnEvent (int e) {/* Do nothing */}
public void OnEvent (int e, int arg0) {/* Do nothing */}
public void OnEvent (int e, long arg0) {/* Do nothing */}
protected void _Register ()
{
TController.Register (this);
}
}
| Java |
<?php
// This file is part of VPL for Moodle - http://vpl.dis.ulpgc.es/
//
// VPL for Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// VPL for Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with VPL for Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Class to show two files diff
*
* @package mod_vpl
* @copyright 2012 Juan Carlos Rodríguez-del-Pino
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @author Juan Carlos Rodríguez-del-Pino <jcrodriguez@dis.ulpgc.es>
*/
require_once dirname(__FILE__).'/../../../config.php';
require_once dirname(__FILE__).'/../locallib.php';
require_once dirname(__FILE__).'/../vpl.class.php';
require_once dirname(__FILE__).'/../vpl_submission.class.php';
require_once dirname(__FILE__).'/../views/sh_base.class.php';
require_once dirname(__FILE__).'/similarity_factory.class.php';
require_once dirname(__FILE__).'/similarity_base.class.php';
class vpl_diff{
/**
* Remove chars and digits
* @param $line string to process
* @return string without chars and digits
*/
static function removeAlphaNum($line){
$ret='';
$l= strlen($line);
//Parse line to remove alphanum chars
for($i=0; $i<$l; $i++){
$c=$line[$i];
if(!ctype_alnum($c) && $c != ' '){
$ret.=$c;
}
}
return $ret;
}
/**
* Calculate the similarity of two lines
* @param $line1
* @param $line2
* @return int (3 => trimmed equal, 2 =>removeAlphaNum , 1 => start of line , 0 => not equal)
*/
static function diffLine($line1,$line2){
//TODO Refactor.
//This is a bad solution that must be rebuild to consider diferent languages
//Compare trimed text
$line1=trim($line1);
$line2=trim($line2);
if($line1==$line2){
if(strlen($line1)>0){
return 3;
}else{
return 1;
}
}
//Compare filtered text (removing alphanum)
$rAN1=self::removeAlphaNum($line1);
$limit = strlen($rAN1);
if($limit>0){
if($limit>3){
$limite = 3;
}
if(strncmp($rAN1,self::removeAlphaNum($line2),$limit) == 0){
return 2;
}
}
//Compare start of line
$l=4;
if($l>strlen($line1)){
$l=strlen($line1);
}
if($l>strlen($line2)){
$l=strlen($line2);
}
for($i=0; $i<$l; ++$i){
if($line1[$i] !=$line2[$i]){
break;
}
}
return $i>0 ? 1:0;
}
static function newLineInfo($type,$ln1,$ln2=0){
$ret = new StdClass();
$ret->type = $type;
$ret->ln1 = $ln1;
$ret->ln2 = $ln2;
return $ret;
}
/**
* Initialize used matrix
* @param $matrix matrix to initialize
* @param $prev matrix to initialize
* @param $nl1 number of rows
* @param $nl2 number of columns
* @return void
*/
static function initAuxiliarMatrices(&$matrix,&$prev,$nl1,$nl2){
// matrix[0..nl1+1][0..nl2+1]=0
$row = array_pad(array(),$nl2+1,0);
$matrix = array_pad(array(),$nl1+1,$row);
// prev[0..nl1+1][0..nl2+1]=0
$prev = $matrix;
//update first column
for($i=0; $i<=$nl1;$i++){
$matriz[$i][0]=0;
$prev[$i][0]=-1;
}
//update first row
for($j=1; $j<=$nl2;$j++){
$matriz[0][$j]=0;
$prev[0][$j]=1;
}
}
/**
* Calculate diff for two array of lines
* @param $lines1 array of string
* @param $lines2 array of string
* @return array of objects with info to show the two array of lines
*/
static function calculateDiff($lines1,$lines2){
$ret = array();
$nl1=count($lines1);
$nl2=count($lines2);
if($nl1==0 && $nl2==0){
return false;
}
if($nl1==0){ //There is no first file
foreach($lines2 as $pos => $line){
$ret[] = self::newLineInfo('>',0,$pos+1);
}
return $ret;
}
if($nl2==0){ //There is no second file
foreach($lines1 as $pos => $line){
$ret[] = self::newLineInfo('<',$pos+1);
}
return $ret;
}
self::initAuxiliarMatrices($matrix,$prev,$nl1,$nl2);
//Matrix processing
for($i=1; $i <= $nl1;$i++){
$line=$lines1[$i-1];
for($j=1; $j<=$nl2;$j++){
if($matrix[$i][$j-1]>$matrix[$i-1][$j]) {
$max=$matrix[$i][$j-1];
$best = 1;
}else{
$max=$matrix[$i-1][$j];
$best = -1;
}
$prize=self::diffLine($line,$lines2[$j-1]);
if($matrix[$i-1][$j-1]+$prize>=$max){
$max=$matrix[$i-1][$j-1]+$prize;
$best = 0;
}
$matrix[$i][$j]=$max;
$prev[$i][$j]=$best;
}
}
//Calculate show info
$limit=$nl1+$nl2;
$pairs = array();
$pi=$nl1;
$pj=$nl2;
while((!($pi == 0 && $pj == 0)) && $limit>0){
$pair = new stdClass();
$pair->i = $pi;
$pair->j = $pj;
$pairs[]=$pair;
$p = $prev[$pi][$pj];
if($p == 0){
$pi--;
$pj--;
}elseif($p == -1){
$pi--;
}else{
$pj--;
}
$limit--;
}
krsort($pairs);
$prevpair = new stdClass();
$prevpair->i=0;
$prevpair->j=0;
foreach($pairs as $pair){
if($pair->i == $prevpair->i+1 && $pair->j == $prevpair->j+1){ //Regular advance
if($lines1[$pair->i-1] == $lines2[$pair->j-1]){ //Equals
$ret[]=self::newLineInfo('=',$pair->i,$pair->j);
}else{
$ret[]=self::newLineInfo('#',$pair->i,$pair->j);
}
}elseif($pair->i == $prevpair->i+1){ //Removed next line
$ret[]=self::newLineInfo('<',$pair->i);
}elseif($pair->j == $prevpair->j+1){ //Added one line
$ret[]=self::newLineInfo('>',0,$pair->j);
}else{
debugging("Internal error ".print_r($pair,true)." ".print_r($prevpair,true));
}
$prevpair=$pair;
}
return $ret;
}
static function show($filename1, $data1, $HTMLheader1, $filename2, $data2, $HTMLheader2) {
//Get file lines
$nl = vpl_detect_newline($data1);
$lines1 = explode($nl,$data1);
$nl = vpl_detect_newline($data2);
$lines2 = explode($nl,$data2);
//Get dif as an array of info
$diff = self::calculateDiff($lines1,$lines2);
if($diff === false){
return;
}
$separator= array('<'=>' <<< ', '>'=>' >>> ','='=>' === ','#'=>' ### ');
$emptyline=" \n";
$data1='';
$data2='';
$datal1='';
$datal2='';
$diffl='';
$lines1[-1]='';
$lines2[-1]='';
foreach($diff as $line){
$diffl.= $separator[$line->type]."\n";
if($line->ln1){
$datal1.=$line->ln1." \n";
$data1.=$lines1[$line->ln1-1]."\n";
}else{
$data1.=" \n";
$datal1.=$emptyline;
}
if($line->ln2){
$datal2.=$line->ln2." \n";
$data2.=$lines2[$line->ln2-1]."\n";
}else{
$data2.=" \n";
$datal2.=$emptyline;
}
}
echo '<div style="width: 100%;min-width: 950px; overflow: auto">';
//Header
echo '<div style="float:left; width: 445px">';
echo $HTMLheader1;
echo '</div>';
echo '<div style="float:left; width: 445px">';
echo $HTMLheader2;
echo '</div>';
echo '<div style="clear:both;"></div>';
//Files
echo '<div style="float:left; text-align: right">';
echo '<pre class="'.vpl_sh_base::c_general.'">';
echo $datal1;
echo '</pre>';
echo '</div>';
echo '<div style="float:left; width: 390px; overflow:auto">';
$shower= vpl_sh_factory::get_sh($filename1);
$shower->print_file($filename1,$data1,false);
echo '</div>';
echo '<div style="float:left">';
echo '<pre class="'.vpl_sh_base::c_general.'">';
echo $diffl;
echo '</pre>';
echo '</div>';
echo '<div style="float:left; text-align: right;">';
echo '<pre class="'.vpl_sh_base::c_general.'">';
echo $datal2;
echo '</pre>';
echo '</div>';
echo '<div style="float:left; width: 390px; overflow:auto">';
$shower= vpl_sh_factory::get_sh($filename2);
$shower->print_file($filename2,$data2,false);
echo '</div>';
echo '</div>';
echo '<div style="clear:both;"></div>';
}
static function vpl_get_similfile($f,$vpl,&$HTMLheader,&$filename,&$data){
global $DB;
$HTMLheader='';
$filename='';
$data='';
$type = required_param('type'.$f, PARAM_INT);
if($type==1){
$subid = required_param('subid'.$f, PARAM_INT);
$filename = required_param('filename'.$f, PARAM_TEXT);
$subinstance = $DB->get_record('vpl_submissions',array('id' => $subid));
if($subinstance !== false){
$vpl = new mod_vpl(false,$subinstance->vpl);
$vpl->require_capability(VPL_SIMILARITY_CAPABILITY);
$submission = new mod_vpl_submission($vpl,$subinstance);
$user = $DB->get_record('user', array('id' => $subinstance->userid));
if($user){
$HTMLheader .='<a href="'.vpl_mod_href('/forms/submissionview.php',
'id',$vpl->get_course_module()->id,'userid',$subinstance->userid).'">';
}
$HTMLheader .=s($filename).' ';
if($user){
$HTMLheader .= '</a>';
$HTMLheader .= $vpl->user_fullname_picture($user);
}
$fg = $submission->get_submitted_fgm();
$data = $fg->getFileData($filename);
\mod_vpl\event\vpl_diff_viewed::log($submission);
}
}elseif($type == 2){
//FIXME adapt to moodle 2.x
/*
global $CFG;
$dirname = required_param('dirname'.$f,PARAM_RAW);
$filename = required_param('filename'.$f,PARAM_RAW);
$base=$CFG->dataroot.'/'.$vpl->get_course()->id.'/';
$data = file_get_contents($base.$dirname.'/'.$filename);
$HTMLheader .= $filename.' '.optional_param('username'.$f,'',PARAM_TEXT);
*/
}elseif($type == 3){
global $CFG;
$data='';
$zipname = required_param('zipfile'.$f,PARAM_RAW);
$filename = required_param('filename'.$f,PARAM_RAW);
$HTMLheader .= $filename.' '.optional_param('username'.$f,'',PARAM_TEXT);
$ext = strtoupper(pathinfo($zipfile,PATHINFO_EXTENSION));
if($ext != 'ZIP'){
print_error('nozipfile');
}
$zip = new ZipArchive();
$zipfilename=self::get_zip_filepath($zipname);
if($zip->open($zipfilename)){
$data=$zip->getFromName($filename);
$zip->close();
}
}else{
print_error('type error');
}
}
}
| Java |
package org.runnerup.notification;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import org.runnerup.R;
import org.runnerup.common.util.Constants;
import org.runnerup.view.MainLayout;
@TargetApi(Build.VERSION_CODES.FROYO)
public class GpsBoundState implements NotificationState {
private final Notification notification;
public GpsBoundState(Context context) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Intent i = new Intent(context, MainLayout.class);
i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
i.putExtra(Constants.Intents.FROM_NOTIFICATION, true);
PendingIntent pi = PendingIntent.getActivity(context, 0, i, 0);
builder.setContentIntent(pi);
builder.setContentTitle(context.getString(R.string.activity_ready));
builder.setContentText(context.getString(R.string.ready_to_start_running));
builder.setSmallIcon(R.drawable.icon);
builder.setOnlyAlertOnce(true);
org.runnerup.util.NotificationCompat.setLocalOnly(builder);
notification = builder.build();
}
@Override
public Notification createNotification() {
return notification;
}
}
| Java |
<!DOCTYPE html>
<html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head lang="en-GB">
<title>Ross Gammon’s Family Tree - Events</title>
<meta charset="UTF-8" />
<meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" />
<meta name ="apple-mobile-web-app-capable" content="yes" />
<meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" />
<meta name="author" content="" />
<link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" />
<link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1 id="SiteTitle">Ross Gammon’s Family Tree</h1>
</div>
<div class="wrapper" id="nav" role="navigation">
<div class="container">
<ul class="menu" id="dropmenu">
<li><a href="../../../individuals.html" title="Individuals">Individuals</a></li>
<li><a href="../../../index.html" title="Surnames">Surnames</a></li>
<li><a href="../../../families.html" title="Families">Families</a></li>
<li class = "CurrentSection"><a href="../../../events.html" title="Events">Events</a></li>
<li><a href="../../../places.html" title="Places">Places</a></li>
<li><a href="../../../sources.html" title="Sources">Sources</a></li>
<li><a href="../../../repositories.html" title="Repositories">Repositories</a></li>
<li><a href="../../../media.html" title="Media">Media</a></li>
<li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li>
</ul>
</div>
</div>
<div class="content" id="EventDetail">
<h3>Birth</h3>
<table class="infolist eventlist">
<tbody>
<tr>
<td class="ColumnAttribute">Gramps ID</td>
<td class="ColumnGRAMPSID">E3500</td>
</tr>
<tr>
<td class="ColumnAttribute">Date</td>
<td class="ColumnColumnDate">
1905
</td>
</tr>
</tbody>
</table>
<div class="subsection" id="references">
<h4>References</h4>
<ol class="Col1" role="Volume-n-Page"type = 1>
<li>
<a href="../../../ppl/2/b/d15f5fe11fe5628177d349cc4b2.html">
ANDERSON, Laurence
<span class="grampsid"> [I3142]</span>
</a>
</li>
</ol>
</div>
</div>
<div class="fullclear"></div>
<div id="footer">
<p id="createdate">
Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:54:14<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a>
</p>
<p id="copyright">
</p>
</div>
</body>
</html>
| Java |
package pl.idedyk.japanese.dictionary.web.html;
import java.util.List;
public class Ul extends HtmlElementCommon {
public Ul() {
super();
}
public Ul(String clazz) {
super(clazz);
}
public Ul(String clazz, String style) {
super(clazz, style);
}
@Override
protected String getTagName() {
return "ul";
}
@Override
protected boolean isSupportHtmlElementList() {
return true;
}
@Override
protected List<String[]> getAdditionalTagAttributes() {
return null;
}
}
| Java |
<?php
/* checklinks.class.php ver.1.1
** Author: Jason Henry www.yourarcadescript.com
** Please keep authorship info intact
** Nov. 26, 2011
**
** Class is used to validate that a link exists on a given web page
** Usage example:
** include("checklinks.class.php");
** $checklink = new checkLink;
** $response = $checklink->validateLink("www.website.com/links.html", "www.mywebsite.com");
** $response will be: LINKDATAERROR(means unable to get data from the website) or LINKFOUND or LINKNOTFOUND or LINKFOUNDNOFOLLOW
** Updates in ver. 1.1
Added the port and path to the link choices to check allowing for a deep link search. Was returning a false negative.
*/
class checkLink {
const LINKFOUND = 1;
const LINKNOTFOUND = 0;
const LINKFOUNDNOFOLLOW = 2;
const LINKDATAERROR = 3;
public function get_data($url) {
$ch = curl_init();
$timeout = 5;
$userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)';
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
public function linkChoices($link) {
$array = parse_url($link);
$link1 = $array['host'];
if (isset($array['port'])) {
$link1 .= ":" . $array['port'];
}
if (isset($array['path'])) {
$link1 .= $array['path'];
}
$links[0] = rtrim($link1,"/");
$links[1] = str_replace("www.", "", $links[0]);
$links[2] = "http://".trim($links[1]);
$links[3] = "http://www.".$links[1];
return $links;
}
public function validateLink($url, $url_tofind) {
$page = $this->get_data($url);
if (!$page) return LINKDATAERROR;
$urlchoices = $this->linkChoices($url_tofind);
$dom = new DOMDocument();
@$dom->loadHTML($page);
$x = new DOMXPath($dom);
foreach($x->query("//a") as $node) {
$link = rtrim($node->getAttribute("href"), "/");
$rel = $node->getAttribute("rel");
if (in_array($link, $urlchoices)) {
if(strtolower($rel) == "nofollow") {
return LINKFOUNDNOFOLLOW;
} else {
return LINKFOUND;
}
}
}
return LINKNOTFOUND;
}
}
?> | Java |
"use strict";
function HelpTutorial()
{
let _getText = function()
{
return "HelpTutorial_Base";
};
this.getName = function(){ return "HelpTutorial_Base"; };
this.getImageId = function(){ return "button_help"; };
this.getText = _getText;
}
function HelpTutorialBuilding(name, image)
{
this.getName = function(){ return name; };
this.getImageId = function(){ return image; };
}
function HelpQueueData(colonyState)
{
let queue = [new HelpTutorial()];
let available = [];
let discovery = colonyState.getDiscovery();
for(let i = 0; i < discovery.length; i++)
{
if(discovery[i].startsWith("Resource_"))
{
queue.push(new HelpTutorialBuilding(discovery[i], discovery[i]));
}
}
let technology = colonyState.getTechnology();
for(let i = 0; i < technology.length; i++)
{
let item = PrototypeLib.get(technology[i]);
available.push(new HelpTutorialBuilding(technology[i], item.getBuildingImageId()));
}
QueueData.call(this, queue, available);
this.getInfo = function(item)
{
let text = "";
if(item != null)
{
let imgSize = GetImageSize(ImagesLib.getImage(item.getImageId()));
text += '<div class="queueInfo">';
if(item.getText != undefined)
{
text += '<div class="queueInfoTitle" style="height: ' + (imgSize.height + 5) + 'px;">';
text += '<img class="queueInfoTitleImage" style="height: ' + imgSize.height + 'px;" src="' + ImagesLib.getFileName(item.getImageId()) + '">';
text += '<div class="queueInfoTitleData queueInfoTitleName">' + TextRepository.get(item.getName()) + '</div>';
text += '</div>';
text += '<div class="queueInfoDetails">' + TextRepository.get(item.getName() + "Description") + '</div>';
}
else
{
let baseImgSize = GetImageSize(ImagesLib.getImage("baseTile"));
text += '<div class="queueInfoTitle" style="height: ' + (imgSize.height + 5) + 'px;">';
text += '<div style="float: left; height: ' + imgSize.height + 'px; background: url(\'' + ImagesLib.getFileName("baseTile") + '\') no-repeat; background-position: 0 ' + (imgSize.height - baseImgSize.height) + 'px;">';
text += '<img style="height: ' + imgSize.height + 'px; border-size: 0;" src="' + ImagesLib.getFileName(item.getImageId()) + '">';
text += '</div>';
text += '<div class="queueInfoTitleData">';
text += '<div class="queueInfoTitleName">' + TextRepository.get(item.getName()) + '</div>';
text += '<div class="queueInfoTitleDescription">' + TextRepository.get(item.getName() + "Description") + '</div>';
text += '</div>';
text += '</div>';
text += '<div class="queueInfoDetails">';
let proto = PrototypeLib.get(item.getName());
text += '<table>';
text += '<tr><td class="tableMainColumn">' + TextRepository.get("TerrainLayer") + ':</td><td></td><td>' + TextRepository.get(proto.getTerrainLayer()) + '</td></tr>';
let list;
let listItem;
if(proto.getBuildingTime() > 0 || Object.keys(proto.getBuildingCost()).length > 0)
{
//text += '<tr><td>' + TextRepository.get("BuildingTitle") + '</td></tr>';
text += '<tr><td>' + TextRepository.get("BuildingTime") + ':</td><td class="tableDataRight">' + proto.getBuildingTime() + '</td><td>' + TextRepository.get("TimeUnit") + '</td></tr>';
list = proto.getBuildingCost();
if(Object.keys(list).length > 0)
{
text += '<tr><td>' + TextRepository.get("BuildingCost") + ':</td></tr>';
for (listItem in list)
{
if(list.hasOwnProperty(listItem))
{
text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td>';
if(list[listItem] > colonyState.getProduced(listItem))
{
text += '<td class="colorError">' + TextRepository.get("unavailable") + '</td>';
}
text += '</tr>';
}
}
}
}
if(proto.getRequiredResource() != null)
{
text += '<tr><td>' + TextRepository.get("Requirements") + ':</td><td>' + TextRepository.get(proto.getRequiredResource()) + '</td></tr>';
}
list = proto.getCapacity();
if(Object.keys(list).length > 0)
{
text += '<tr><td>' + TextRepository.get("BuildingCapacity") + ':</td></tr>';
for (listItem in list)
{
if(list.hasOwnProperty(listItem))
{
text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td></tr>';
}
}
}
if((Object.keys(proto.getConsumption()).length +
Object.keys(proto.getProduction()).length +
Object.keys(proto.getProductionWaste()).length) > 0)
{
//text += '<tr><td>' + TextRepository.get("ProductionTitle") + '</td></tr>';
list = proto.getConsumption();
if(Object.keys(list).length > 0)
{
text += '<tr><td>' + TextRepository.get("BuildingConsumption") + ':</td></tr>';
for (listItem in list)
{
if(list.hasOwnProperty(listItem))
{
text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td></tr>';
}
}
}
list = proto.getProduction();
if(Object.keys(list).length > 0)
{
text += '<tr><td>' + TextRepository.get("BuildingProduction") + ':</td></tr>';
for (listItem in list)
{
if(list.hasOwnProperty(listItem))
{
text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td></tr>';
}
}
}
list = proto.getProductionWaste();
if(Object.keys(list).length > 0)
{
text += '<tr><td>' + TextRepository.get("BuildingWaste") + ':</td></tr>';
for (listItem in list)
{
if(list.hasOwnProperty(listItem))
{
text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td></tr>';
}
}
}
}
text += '</table>';
text += '</div>';
}
text += '</div>';
}
return text;
};
this.isSortable = function() { return false; };
this.getTitle = function() { return "HelpTitle"; };
this.getQueueTitle = function() { return "HelpBase"; };
this.getAvailableTitle = function() { return "Buildings"; };
}
HelpQueueData.inherits(QueueData); | Java |
/* Dylan Secreast
* dsecrea2@uoregon.edu
* CIS 415 Project 0
* This is my own work except for the base
* code that was provided by Prof. Sventek
*/
#ifndef _DATE_H_INCLUDED_
#define _DATE_H_INCLUDED_
typedef struct date Date;
/*
* date_create creates a Date structure from `datestr`
* `datestr' is expected to be of the form "dd/mm/yyyy"
* returns pointer to Date structure if successful,
* NULL if not (syntax error)
*/
Date *date_create(char *datestr);
/*
* date_duplicate creates a duplicate of `d'
* returns pointer to new Date structure if successful,
* NULL if not (memory allocation failure)
*/
Date *date_duplicate(Date *d);
/*
* date_compare compares two dates, returning <0, 0, >0 if
* date1<date2, date1==date2, date1>date2, respectively
*/
int date_compare(Date *date1, Date *date2);
/*
* date_destroy returns any storage associated with `d' to the system
*/
void date_destroy(Date *d);
#endif /* _DATE_H_INCLUDED_ */
| Java |
/**
* @file test-mus-got.cpp
* @brief Test code for God of Thunder files.
*
* Copyright (C) 2010-2015 Adam Nielsen <malvineous@shikadi.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "test-music.hpp"
class test_mus_got: public test_music
{
public:
test_mus_got()
{
this->type = "got";
this->numInstruments = 1;
this->indexInstrumentOPL = 0;
this->indexInstrumentMIDI = -1;
this->indexInstrumentPCM = -1;
}
void addTests()
{
this->test_music::addTests();
// c00: Normal
this->isInstance(MusicType::Certainty::PossiblyYes, this->standard());
// c01: Too short
this->isInstance(MusicType::Certainty::DefinitelyNo, STRING_WITH_NULLS(
"\x01"
"\x00\x00\x00" "\x00"
));
// c02: Uneven length
this->isInstance(MusicType::Certainty::DefinitelyNo, STRING_WITH_NULLS(
"\x01\x00"
"\x00\x20\xAE"
"\x00"
"\x00\x00\x00" "\x00"
));
// c03: Bad signature
this->isInstance(MusicType::Certainty::DefinitelyNo, STRING_WITH_NULLS(
"\x02\x00"
"\x00\x20\xAE"
"\x00\x40\x7F"
"\x00\x60\xED"
"\x00\x80\xCB"
"\x00\xE0\x06"
"\x00\x23\xA7"
"\x00\x43\x1F"
"\x00\x63\x65"
"\x00\x83\x43"
"\x00\xE3\x02"
"\x00\xC0\x04"
"\x00\xA0\x44"
"\x01\xB0\x32"
"\x00\xB0\x12"
"\x00\x00\x00" "\x00"
));
// c04: Missing/incomplete loop-to-start marker
this->isInstance(MusicType::Certainty::DefinitelyNo, STRING_WITH_NULLS(
"\x01\x00"
"\x00\x20\xAE"
"\x00\x40\x7F"
"\x00\x60\xED"
"\x00\x80\xCB"
"\x00\xE0\x06"
"\x00\x23\xA7"
"\x00\x43\x1F"
"\x00\x63\x65"
"\x00\x83\x43"
"\x00\xE3\x02"
"\x00\xC0\x04"
"\x00\xA0\x44"
"\x01\xB0\x32"
"\x00\xB0\x12"
"\x00\x00\x00"
));
}
virtual std::string standard()
{
return STRING_WITH_NULLS(
"\x01\x00"
"\x00\x20\xFF"
"\x00\x40\xFF"
"\x00\x60\xFF"
"\x00\x80\xFF"
"\x00\xE0\x07"
"\x00\x23\x0E"
"\x00\x43\xBE"
"\x00\x63\xEE"
"\x00\x83\xEE"
"\x00\xE3\x06"
"\x00\xC0\x0F"
"\x00\xA0\x44"
"\x01\xB0\x32"
"\x00\xB0\x12"
"\x00\x00\x00" "\x00"
);
}
};
IMPLEMENT_TESTS(mus_got);
| Java |
#include <fstream>
#include <algorithm>
#include "anime_db.hpp"
#include "trim.hpp"
bool anime_database::dump_anime_db(const astd::filesystem::path& db_path, const anime_database& db)
{
bool result = false;
std::ofstream stream{ db_path.c_str(), std::ios::out | std::ios::trunc };
if (stream)
{
result = true;
configuration_input::dump_config(stream, db.input);
for (auto& num : db.number_fetched)
{
stream << num << std::endl;
}
}
return result;
}
std::pair<bool, anime_database> anime_database::parse_anime_db(const astd::filesystem::path& db_path)
{
std::pair<bool, anime_database> result{ false, anime_database() };
std::ifstream stream{ db_path.c_str() };
if (stream)
{
std::string line;
result.first = true;
bool ok = true;
std::size_t line_num = 1;
while (result.first && std::getline(stream, line))
{
auto trimmed_line = xts::trim<char>(line);
ok = ok && configuration_input::parse_line(trimmed_line, result.second.input);
if (!ok)
{
if (std::all_of(trimmed_line.begin(), trimmed_line.end(), [](auto& c) { return std::isdigit(c) != 0 || c == '.'; })) //if the line is a interger/float
{
result.second.number_fetched.emplace_back(trimmed_line.to_string());
}
else //something when bad
{
result.first = false;
}
}
if (!result.first)
std::cerr << "error at line : no " << line_num << " : " << line << std::endl;
line_num++;
}
}
return result;
} | Java |
public class Main {
public static void main(String[] args) {
ProdutoContext manga = new ProdutoContext();
System.out.println("Quantia: " + manga.getQuantia());
manga.fazerCompra(5);
manga.reestocar(5);
manga.fazerCompra(5);
manga.reestocar(15);
System.out.println("Quantia: " + manga.getQuantia());
manga.fazerCompra(5);
System.out.println("Quantia: " + manga.getQuantia());
}
}
| Java |
using CatalokoService.Helpers.DTO;
using CatalokoService.Helpers.FacebookAuth;
using CatalokoService.Models;
using System;
using System.Web.Mvc;
namespace CatalokoService.Controllers
{
public class HomeController : Controller
{
CatalokoEntities bd = new CatalokoEntities();
public ActionResult Index()
{
ViewBag.Title = "Home Page";
return View();
}
}
}
| Java |
var Util = require( 'findhit-util' );
// -----------------------------------------------------------------------------
// Data handles wizard data into session
function Data ( route ) {
var session = route.req[ route.router.options.reqSessionKey ];
// If there isn't a `wiz` object on session, just add it
if( ! session.wiz ) {
session.wiz = {};
}
// Save route on this instance
this.route = route;
// Gather session from session, or just create a new one
this.session = session.wiz[ route.id ] || ( session.wiz[ route.id ] = {} );
// Add a control variable for changed state
this.changed = false;
return this;
};
// Export Data
module.exports = Data;
/* instance methods */
Data.prototype.currentStep = function ( step ) {
// If there is no `step` provided, it means that we wan't to get!
// Otherwise, lets set it!
};
/*
Data.prototype.save = function () {
};
Data.prototype.destroy = function () {
};
*/
Data.prototype.getFromStep = function ( step ) {
};
| Java |
using System;
namespace RadarrAPI
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
} | Java |
/**
Copyright (C) 2012 Delcyon, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.delcyon.capo.protocol.server;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author jeremiah
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface ClientRequestProcessorProvider
{
String name();
} | Java |
<html>
<head>
<title>datypus</title>
<link rel="stylesheet" type="text/css" href="/css/datystyle.css">
<body>
<div class="chart"></div>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script type="text/javascript">
var data = [4, 8, 15, 16, 2, 42];
var x = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, 420]);
d3.select(".chart")
.selectAll("div")
.data(data)
.enter().append("div")
.style("width", function(d) { return x(d) + "px"; })
.text(function(d) { return d; });
</script>
</body>
</html>
| Java |
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* ClusterMembership.java
* Copyright (C) 2004 Mark Hall
*
*/
package weka.filters.unsupervised.attribute;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
import weka.filters.unsupervised.attribute.Remove;
import weka.clusterers.Clusterer;
import weka.clusterers.DensityBasedClusterer;
import weka.core.Attribute;
import weka.core.Instances;
import weka.core.Instance;
import weka.core.OptionHandler;
import weka.core.Range;
import weka.core.FastVector;
import weka.core.Option;
import weka.core.Utils;
import java.util.Enumeration;
import java.util.Vector;
/**
* A filter that uses a clusterer to obtain cluster membership values
* for each input instance and outputs them as new instances. The
* clusterer needs to be a density-based clusterer. If
* a (nominal) class is set, then the clusterer will be run individually
* for each class.<p>
*
* Valid filter-specific options are: <p>
*
* Full class name of clusterer to use. Clusterer options may be
* specified at the end following a -- .(required)<p>
*
* -I range string <br>
* The range of attributes the clusterer should ignore. Note:
* the class attribute (if set) is automatically ignored during clustering.<p>
*
* @author Mark Hall (mhall@cs.waikato.ac.nz)
* @author Eibe Frank
* @version $Revision: 1.7 $
*/
public class ClusterMembership extends Filter implements UnsupervisedFilter,
OptionHandler {
/** The clusterer */
protected DensityBasedClusterer m_clusterer = new weka.clusterers.EM();
/** Array for storing the clusterers */
protected DensityBasedClusterer[] m_clusterers;
/** Range of attributes to ignore */
protected Range m_ignoreAttributesRange;
/** Filter for removing attributes */
protected Filter m_removeAttributes;
/** The prior probability for each class */
protected double[] m_priors;
/**
* Sets the format of the input instances.
*
* @param instanceInfo an Instances object containing the input instance
* structure (any instances contained in the object are ignored - only the
* structure is required).
* @return true if the outputFormat may be collected immediately
* @exception Exception if the inputFormat can't be set successfully
*/
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_removeAttributes = null;
m_priors = null;
return false;
}
/**
* Signify that this batch of input to the filter is finished.
*
* @return true if there are instances pending output
* @exception IllegalStateException if no input structure has been defined
*/
public boolean batchFinished() throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (outputFormatPeek() == null) {
Instances toFilter = getInputFormat();
Instances[] toFilterIgnoringAttributes;
// Make subsets if class is nominal
if ((toFilter.classIndex() >= 0) && toFilter.classAttribute().isNominal()) {
toFilterIgnoringAttributes = new Instances[toFilter.numClasses()];
for (int i = 0; i < toFilter.numClasses(); i++) {
toFilterIgnoringAttributes[i] = new Instances(toFilter, toFilter.numInstances());
}
for (int i = 0; i < toFilter.numInstances(); i++) {
toFilterIgnoringAttributes[(int)toFilter.instance(i).classValue()].add(toFilter.instance(i));
}
m_priors = new double[toFilter.numClasses()];
for (int i = 0; i < toFilter.numClasses(); i++) {
toFilterIgnoringAttributes[i].compactify();
m_priors[i] = toFilterIgnoringAttributes[i].sumOfWeights();
}
Utils.normalize(m_priors);
} else {
toFilterIgnoringAttributes = new Instances[1];
toFilterIgnoringAttributes[0] = toFilter;
m_priors = new double[1];
m_priors[0] = 1;
}
// filter out attributes if necessary
if (m_ignoreAttributesRange != null || toFilter.classIndex() >= 0) {
m_removeAttributes = new Remove();
String rangeString = "";
if (m_ignoreAttributesRange != null) {
rangeString += m_ignoreAttributesRange.getRanges();
}
if (toFilter.classIndex() >= 0) {
if (rangeString.length() > 0) {
rangeString += (","+(toFilter.classIndex()+1));
} else {
rangeString = ""+(toFilter.classIndex()+1);
}
}
((Remove)m_removeAttributes).setAttributeIndices(rangeString);
((Remove)m_removeAttributes).setInvertSelection(false);
((Remove)m_removeAttributes).setInputFormat(toFilter);
for (int i = 0; i < toFilterIgnoringAttributes.length; i++) {
toFilterIgnoringAttributes[i] = Filter.useFilter(toFilterIgnoringAttributes[i],
m_removeAttributes);
}
}
// build the clusterers
if ((toFilter.classIndex() <= 0) || !toFilter.classAttribute().isNominal()) {
m_clusterers = DensityBasedClusterer.makeCopies(m_clusterer, 1);
m_clusterers[0].buildClusterer(toFilterIgnoringAttributes[0]);
} else {
m_clusterers = DensityBasedClusterer.makeCopies(m_clusterer, toFilter.numClasses());
for (int i = 0; i < m_clusterers.length; i++) {
if (toFilterIgnoringAttributes[i].numInstances() == 0) {
m_clusterers[i] = null;
} else {
m_clusterers[i].buildClusterer(toFilterIgnoringAttributes[i]);
}
}
}
// create output dataset
FastVector attInfo = new FastVector();
for (int j = 0; j < m_clusterers.length; j++) {
if (m_clusterers[j] != null) {
for (int i = 0; i < m_clusterers[j].numberOfClusters(); i++) {
attInfo.addElement(new Attribute("pCluster_" + j + "_" + i));
}
}
}
if (toFilter.classIndex() >= 0) {
attInfo.addElement(toFilter.classAttribute().copy());
}
attInfo.trimToSize();
Instances filtered = new Instances(toFilter.relationName()+"_clusterMembership",
attInfo, 0);
if (toFilter.classIndex() >= 0) {
filtered.setClassIndex(filtered.numAttributes() - 1);
}
setOutputFormat(filtered);
// build new dataset
for (int i = 0; i < toFilter.numInstances(); i++) {
convertInstance(toFilter.instance(i));
}
}
flushInput();
m_NewBatch = true;
return (numPendingOutput() != 0);
}
/**
* Input an instance for filtering. Ordinarily the instance is processed
* and made available for output immediately. Some filters require all
* instances be read before producing output.
*
* @param instance the input instance
* @return true if the filtered instance may now be
* collected with output().
* @exception IllegalStateException if no input format has been defined.
*/
public boolean input(Instance instance) throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (outputFormatPeek() != null) {
convertInstance(instance);
return true;
}
bufferInput(instance);
return false;
}
/**
* Converts logs back to density values.
*/
protected double[] logs2densities(int j, Instance in) throws Exception {
double[] logs = m_clusterers[j].logJointDensitiesForInstance(in);
for (int i = 0; i < logs.length; i++) {
logs[i] += Math.log(m_priors[j]);
}
return logs;
}
/**
* Convert a single instance over. The converted instance is added to
* the end of the output queue.
*
* @param instance the instance to convert
*/
protected void convertInstance(Instance instance) throws Exception {
// set up values
double [] instanceVals = new double[outputFormatPeek().numAttributes()];
double [] tempvals;
if (instance.classIndex() >= 0) {
tempvals = new double[outputFormatPeek().numAttributes() - 1];
} else {
tempvals = new double[outputFormatPeek().numAttributes()];
}
int pos = 0;
for (int j = 0; j < m_clusterers.length; j++) {
if (m_clusterers[j] != null) {
double [] probs;
if (m_removeAttributes != null) {
m_removeAttributes.input(instance);
probs = logs2densities(j, m_removeAttributes.output());
} else {
probs = logs2densities(j, instance);
}
System.arraycopy(probs, 0, tempvals, pos, probs.length);
pos += probs.length;
}
}
tempvals = Utils.logs2probs(tempvals);
System.arraycopy(tempvals, 0, instanceVals, 0, tempvals.length);
if (instance.classIndex() >= 0) {
instanceVals[instanceVals.length - 1] = instance.classValue();
}
push(new Instance(instance.weight(), instanceVals));
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
public Enumeration listOptions() {
Vector newVector = new Vector(2);
newVector.
addElement(new Option("\tFull name of clusterer to use (required).\n"
+ "\teg: weka.clusterers.EM",
"W", 1, "-W <clusterer name>"));
newVector.
addElement(new Option("\tThe range of attributes the clusterer should ignore."
+"\n\t(the class attribute is automatically ignored)",
"I", 1,"-I <att1,att2-att4,...>"));
return newVector.elements();
}
/**
* Parses the options for this object. Valid options are: <p>
*
* -W clusterer string <br>
* Full class name of clusterer to use. Clusterer options may be
* specified at the end following a -- .(required)<p>
*
* -I range string <br>
* The range of attributes the clusterer should ignore. Note:
* the class attribute (if set) is automatically ignored during clustering.<p>
*
* @param options the list of options as an array of strings
* @exception Exception if an option is not supported
*/
public void setOptions(String[] options) throws Exception {
String clustererString = Utils.getOption('W', options);
if (clustererString.length() == 0) {
throw new Exception("A clusterer must be specified"
+ " with the -W option.");
}
setDensityBasedClusterer((DensityBasedClusterer)Utils.
forName(DensityBasedClusterer.class, clustererString,
Utils.partitionOptions(options)));
setIgnoredAttributeIndices(Utils.getOption('I', options));
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
public String [] getOptions() {
String [] clustererOptions = new String [0];
if ((m_clusterer != null) &&
(m_clusterer instanceof OptionHandler)) {
clustererOptions = ((OptionHandler)m_clusterer).getOptions();
}
String [] options = new String [clustererOptions.length + 5];
int current = 0;
if (!getIgnoredAttributeIndices().equals("")) {
options[current++] = "-I";
options[current++] = getIgnoredAttributeIndices();
}
if (m_clusterer != null) {
options[current++] = "-W";
options[current++] = getDensityBasedClusterer().getClass().getName();
}
options[current++] = "--";
System.arraycopy(clustererOptions, 0, options, current,
clustererOptions.length);
current += clustererOptions.length;
while (current < options.length) {
options[current++] = "";
}
return options;
}
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return "A filter that uses a density-based clusterer to generate cluster "
+ "membership values; filtered instances are composed of these values "
+ "plus the class attribute (if set in the input data). If a (nominal) "
+ "class attribute is set, the clusterer is run separately for each "
+ "class. The class attribute (if set) and any user-specified "
+ "attributes are ignored during the clustering operation";
}
/**
* Returns a description of this option suitable for display
* as a tip text in the gui.
*
* @return description of this option
*/
public String clustererTipText() {
return "The clusterer that will generate membership values for the instances.";
}
/**
* Set the clusterer for use in filtering
*
* @param newClusterer the clusterer to use
*/
public void setDensityBasedClusterer(DensityBasedClusterer newClusterer) {
m_clusterer = newClusterer;
}
/**
* Get the clusterer used by this filter
*
* @return the clusterer used
*/
public DensityBasedClusterer getDensityBasedClusterer() {
return m_clusterer;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String ignoredAttributeIndicesTipText() {
return "The range of attributes to be ignored by the clusterer. eg: first-3,5,9-last";
}
/**
* Gets ranges of attributes to be ignored.
*
* @return a string containing a comma-separated list of ranges
*/
public String getIgnoredAttributeIndices() {
if (m_ignoreAttributesRange == null) {
return "";
} else {
return m_ignoreAttributesRange.getRanges();
}
}
/**
* Sets the ranges of attributes to be ignored. If provided string
* is null, no attributes will be ignored.
*
* @param rangeList a string representing the list of attributes.
* eg: first-3,5,6-last
* @exception IllegalArgumentException if an invalid range list is supplied
*/
public void setIgnoredAttributeIndices(String rangeList) {
if ((rangeList == null) || (rangeList.length() == 0)) {
m_ignoreAttributesRange = null;
} else {
m_ignoreAttributesRange = new Range();
m_ignoreAttributesRange.setRanges(rangeList);
}
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String [] argv) {
try {
if (Utils.getFlag('b', argv)) {
Filter.batchFilterFile(new ClusterMembership(), argv);
} else {
Filter.filterFile(new ClusterMembership(), argv);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
| Java |
/*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
/**
* A supplier with a priority.
*
* <a href="http://stackoverflow.com/questions/34866757/how-do-i-use-completablefuture-supplyasync-together-with-priorityblockingqueue">stackoverflow</a>
*
* @author Matthias Eichner
*
* @param <T> the type of results supplied by this supplier
*/
public class MCRPrioritySupplier<T> implements Supplier<T>, MCRPrioritizable {
private static AtomicLong CREATION_COUNTER = new AtomicLong(0);
private Supplier<T> delegate;
private int priority;
private long created;
public MCRPrioritySupplier(Supplier<T> delegate, int priority) {
this.delegate = delegate;
this.priority = priority;
this.created = CREATION_COUNTER.incrementAndGet();
}
@Override
public T get() {
return delegate.get();
}
@Override
public int getPriority() {
return this.priority;
}
@Override
public long getCreated() {
return created;
}
/**
* use this instead of {@link CompletableFuture#supplyAsync(Supplier, Executor)}
*
* This method keep the priority
* @param es
* @return
*/
public CompletableFuture<T> runAsync(ExecutorService es) {
CompletableFuture<T> result = new CompletableFuture<>();
MCRPrioritySupplier<T> supplier = this;
class MCRAsyncPrioritySupplier
implements Runnable, MCRPrioritizable, CompletableFuture.AsynchronousCompletionTask {
@Override
@SuppressWarnings("PMD.AvoidCatchingThrowable")
public void run() {
try {
if (!result.isDone()) {
result.complete(supplier.get());
}
} catch (Throwable t) {
result.completeExceptionally(t);
}
}
@Override
public int getPriority() {
return supplier.getPriority();
}
@Override
public long getCreated() {
return supplier.getCreated();
}
}
es.execute(new MCRAsyncPrioritySupplier());
return result;
}
}
| Java |
<ion-header>
<ion-navbar>
<ion-title>Login</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<!-- Shows error message is socket is not connected. -->
<ion-item no-lines *ngIf="!loginManager.loginAvailable()">
<ion-label style="color: #ea6153">
Login service unavailable as cannot connect to server.
</ion-label>
</ion-item>
<!-- Shows a login error message if one exists. -->
<ion-item no-lines *ngIf="loginErrorMessage">
<ion-label style="color: #ea6153">
{{loginErrorMessage}}
</ion-label>
</ion-item>
<form (ngSubmit)="doLogin()" [formGroup]="loginForm">
<!-- Username input field -->
<ion-item>
<ion-label>Username</ion-label>
<ion-input type="text" formControlName="username"></ion-input>
</ion-item>
<!-- Invalid username error -->
<ion-item no-lines *ngIf="!loginForm.controls.username.valid && loginForm.controls.username.dirty">
<ion-label style="color: #ea6153">
Invalid username.
</ion-label>
</ion-item>
<!-- Password input field -->
<ion-item>
<ion-label>Password</ion-label>
<ion-input type="password" formControlName="password"></ion-input>
</ion-item>
<!-- Invalid password error -->
<ion-item no-lines *ngIf="!loginForm.controls.password.valid && loginForm.controls.password.dirty">
<ion-label style="color: #ea6153">
Invalid password
</ion-label>
</ion-item>
<br />
<!-- Login button -->
<span>
<button ion-button type="submit" color="primary" [disabled]="!loginManager.loginAvailable()">Login</button>
</span>
<!-- Skip login button -->
<span *ngIf="!popped">
<button type="button" ion-button color="dark" (click)="doLeavePage()" clear>Skip</button>
</span>
</form>
</ion-content>
| Java |
#include <iostream>
using namespace std;
int main() {
int n, x, y;
cin >> n;
int a[n];
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
x = a[1] - a[0];
y = a[2] - a[0];
for (int i = 2; i < n; ++i) {
x = max(a[i] - a[i - 1], x);
y = min(a[i] - a[i - 2], y);
}
cout << max(x, y);
}
| Java |
<?php namespace PrivCode;
defined('ROOT_DIR') or die('Forbidden');
/**
* Base Model Class
*
* @package Priv Code
* @subpackage Libraries
* @category Libraries
* @author Supian M
* @link http://www.priv-code.com
*/
use PrivCode\Database\Database;
class BaseModel extends Database
{
public function __construct()
{
parent::__construct();
}
}
/* End of file URI.php */
/* Location: ./System/URI/URI.php */
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.power.text.Run;
import static com.power.text.dialogs.WebSearch.squerry;
import java.awt.Desktop;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import javax.swing.JOptionPane;
import static com.power.text.Main.searchbox;
/**
*
* @author thecarisma
*/
public class WikiSearch {
public static void wikisearch(){
String searchqueryw = searchbox.getText();
searchqueryw = searchqueryw.replace(' ', '-');
String squeryw = squerry.getText();
squeryw = squeryw.replace(' ', '-');
if ("".equals(searchqueryw)){
searchqueryw = squeryw ;
} else {}
String url = "https://www.wikipedia.org/wiki/" + searchqueryw ;
try
{
URI uri = new URL(url).toURI();
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE))
desktop.browse(uri);
}
catch (URISyntaxException | IOException e)
{
/*
* I know this is bad practice
* but we don't want to do anything clever for a specific error
*/
JOptionPane.showMessageDialog(null, e.getMessage());
// Copy URL to the clipboard so the user can paste it into their browser
StringSelection stringSelection = new StringSelection(url);
Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
clpbrd.setContents(stringSelection, null);
// Notify the user of the failure
System.out.println("This program just tried to open a webpage." + "\n"
+ "The URL has been copied to your clipboard, simply paste into your browser to accessWebpage: " + url);
}
}
}
| Java |
/**
*
*/
package org.jbpt.pm.bpmn;
import org.jbpt.pm.IDataNode;
/**
* Interface class for BPMN Document.
*
* @author Cindy F�hnrich
*/
public interface IDocument extends IDataNode {
/**
* Marks this Document as list.
*/
public void markAsList();
/**
* Unmarks this Document as list.
*/
public void unmarkAsList();
/**
* Checks whether the current Document is a list.
* @return
*/
public boolean isList();
}
| Java |
#include <QtGui/QApplication>
#include "xmlparser.h"
#include "myfiledialog.h"
#include <iostream>
#include <QMessageBox>
using namespace std;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);/*
MainWindow w;
w.show();*/
MyFileDialog my;//Create dialog
QString name=my.openFile();//Open dialog, and chose file. We get file path and file name as result
cout<<name.toUtf8().constData()<<"Podaci uspjeno uèitani!";
return 0;
}
| Java |
//
// SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2004-2005 Steve Baker <sjbaker1@airmail.net>
// Copyright (C) 2006 Joerg Henrichs, Steve Baker
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#ifndef HEADER_PLAYERKART_HPP
#define HEADER_PLAYERKART_HPP
#include "config/player.hpp"
#include "karts/controller/controller.hpp"
class AbstractKart;
class Player;
class SFXBase;
/** PlayerKart manages control events from the player and moves
* them to the Kart
*
* \ingroup controller
*/
class PlayerController : public Controller
{
private:
int m_steer_val, m_steer_val_l, m_steer_val_r;
int m_prev_accel;
bool m_prev_brake;
bool m_prev_nitro;
float m_penalty_time;
SFXBase *m_bzzt_sound;
SFXBase *m_wee_sound;
SFXBase *m_ugh_sound;
SFXBase *m_grab_sound;
SFXBase *m_full_sound;
void steer(float, int);
public:
PlayerController (AbstractKart *kart,
StateManager::ActivePlayer *_player,
unsigned int player_index);
~PlayerController ();
void update (float);
void action (PlayerAction action, int value);
void handleZipper (bool play_sound);
void collectedItem (const Item &item, int add_info=-1,
float previous_energy=0);
virtual void skidBonusTriggered();
virtual void setPosition (int p);
virtual void finishedRace (float time);
virtual bool isPlayerController() const {return true;}
virtual bool isNetworkController() const { return false; }
virtual void reset ();
void resetInputState ();
virtual void crashed (const AbstractKart *k) {}
virtual void crashed (const Material *m) {}
// ------------------------------------------------------------------------
/** Player will always be able to get a slipstream bonus. */
virtual bool disableSlipstreamBonus() const { return false; }
// ------------------------------------------------------------------------
/** Callback whenever a new lap is triggered. Used by the AI
* to trigger a recomputation of the way to use. */
virtual void newLap(int lap) {}
};
#endif
| Java |
// ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2019
// MIT License
#pragma once
#include "../Array/ArrayShortcuts.hpp"
#include "../Object/ObjectShortcuts.hpp"
namespace ARDUINOJSON_NAMESPACE {
template <typename TVariant>
class VariantShortcuts : public ObjectShortcuts<TVariant>,
public ArrayShortcuts<TVariant> {
public:
using ArrayShortcuts<TVariant>::createNestedArray;
using ArrayShortcuts<TVariant>::createNestedObject;
using ArrayShortcuts<TVariant>::operator[];
using ObjectShortcuts<TVariant>::createNestedArray;
using ObjectShortcuts<TVariant>::createNestedObject;
using ObjectShortcuts<TVariant>::operator[];
};
} // namespace ARDUINOJSON_NAMESPACE
| Java |
// Mantid Repository : https://github.com/mantidproject/mantid
//
// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
// NScD Oak Ridge National Laboratory, European Spallation Source
// & Institut Laue - Langevin
// SPDX - License - Identifier: GPL - 3.0 +
#ifndef VTKPEAKMARKERFACTORY_TEST_H_
#define VTKPEAKMARKERFACTORY_TEST_H_
#include "MantidAPI/IPeaksWorkspace.h"
#include "MantidAPI/Run.h"
#include "MantidDataObjects/PeakShapeSpherical.h"
#include "MantidDataObjects/PeaksWorkspace.h"
#include "MantidKernel/WarningSuppressions.h"
#include "MantidVatesAPI/vtkPeakMarkerFactory.h"
#include "MockObjects.h"
#include <vtkPolyData.h>
#include <vtkSmartPointer.h>
#include <cxxtest/TestSuite.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using namespace Mantid;
using namespace Mantid::Kernel;
using namespace Mantid::API;
using namespace Mantid::Geometry;
using namespace Mantid::DataObjects;
using namespace ::testing;
using namespace Mantid::VATES;
using Mantid::VATES::vtkPeakMarkerFactory;
GNU_DIAG_OFF_SUGGEST_OVERRIDE
class MockPeakShape : public Peak {
public:
MOCK_CONST_METHOD0(getHKL, Mantid::Kernel::V3D(void));
MOCK_CONST_METHOD0(getQLabFrame, Mantid::Kernel::V3D(void));
MOCK_CONST_METHOD0(getQSampleFrame, Mantid::Kernel::V3D(void));
MOCK_CONST_METHOD0(getPeakShape, const Mantid::Geometry::PeakShape &(void));
};
class MockPeak : public Peak {
public:
MOCK_CONST_METHOD0(getHKL, Mantid::Kernel::V3D(void));
MOCK_CONST_METHOD0(getQLabFrame, Mantid::Kernel::V3D(void));
MOCK_CONST_METHOD0(getQSampleFrame, Mantid::Kernel::V3D(void));
};
class MockPeaksWorkspace : public PeaksWorkspace {
using Mantid::DataObjects::PeaksWorkspace::addPeak;
public:
MOCK_METHOD1(setInstrument,
void(const Mantid::Geometry::Instrument_const_sptr &inst));
MOCK_CONST_METHOD0(clone, Mantid::DataObjects::PeaksWorkspace *());
MOCK_CONST_METHOD0(getNumberPeaks, int());
MOCK_METHOD1(removePeak, void(int peakNum));
MOCK_METHOD1(addPeak, void(const IPeak &ipeak));
MOCK_METHOD1(getPeak, Mantid::DataObjects::Peak &(int peakNum));
MOCK_CONST_METHOD1(getPeak, const Mantid::DataObjects::Peak &(int peakNum));
};
GNU_DIAG_ON_SUGGEST_OVERRIDE
//=====================================================================================
// Functional Tests
//=====================================================================================
class vtkPeakMarkerFactoryTest : public CxxTest::TestSuite {
public:
void do_test(MockPeak &peak1, vtkPeakMarkerFactory::ePeakDimensions dims) {
FakeProgressAction updateProgress;
auto pw_ptr = boost::make_shared<MockPeaksWorkspace>();
MockPeaksWorkspace &pw = *pw_ptr;
// Peaks workspace will return 5 identical peaks
EXPECT_CALL(pw, getNumberPeaks()).WillOnce(Return(5));
EXPECT_CALL(pw, getPeak(_)).WillRepeatedly(ReturnRef(peak1));
vtkPeakMarkerFactory factory("signal", dims);
factory.initialize(pw_ptr);
auto set = factory.create(updateProgress);
// As the marker type are three axes(2 points), we expect 5*2*3 points
// The angle is 0 degrees and the size is 0.3
TS_ASSERT(set);
TS_ASSERT_EQUALS(set->GetNumberOfPoints(), 30);
TS_ASSERT(testing::Mock::VerifyAndClearExpectations(&pw));
TS_ASSERT(testing::Mock::VerifyAndClearExpectations(&peak1));
}
void test_progress_updates() {
MockPeak peak1;
EXPECT_CALL(peak1, getQLabFrame()).WillRepeatedly(Return(V3D(1, 2, 3)));
EXPECT_CALL(peak1, getHKL()).Times(AnyNumber());
EXPECT_CALL(peak1, getQSampleFrame()).Times(AnyNumber());
MockProgressAction mockProgress;
// Expectation checks that progress should be >= 0 and <= 100 and called at
// least once!
EXPECT_CALL(mockProgress, eventRaised(AllOf(Le(100), Ge(0))))
.Times(AtLeast(1));
boost::shared_ptr<MockPeaksWorkspace> pw_ptr =
boost::make_shared<MockPeaksWorkspace>();
MockPeaksWorkspace &pw = *pw_ptr;
// Peaks workspace will return 5 identical peaks
EXPECT_CALL(pw, getNumberPeaks()).WillRepeatedly(Return(5));
EXPECT_CALL(pw, getPeak(_)).WillRepeatedly(ReturnRef(peak1));
vtkPeakMarkerFactory factory("signal", vtkPeakMarkerFactory::Peak_in_Q_lab);
factory.initialize(pw_ptr);
auto set = factory.create(mockProgress);
TSM_ASSERT("Progress Updates not used as expected.",
Mock::VerifyAndClearExpectations(&mockProgress));
}
void test_q_lab() {
MockPeak peak1;
EXPECT_CALL(peak1, getQLabFrame())
.Times(5)
.WillRepeatedly(Return(V3D(1, 2, 3)));
EXPECT_CALL(peak1, getHKL()).Times(0);
EXPECT_CALL(peak1, getQSampleFrame()).Times(0);
do_test(peak1, vtkPeakMarkerFactory::Peak_in_Q_lab);
}
void test_q_sample() {
MockPeak peak1;
EXPECT_CALL(peak1, getQSampleFrame())
.Times(5)
.WillRepeatedly(Return(V3D(1, 2, 3)));
EXPECT_CALL(peak1, getHKL()).Times(0);
EXPECT_CALL(peak1, getQLabFrame()).Times(0);
do_test(peak1, vtkPeakMarkerFactory::Peak_in_Q_sample);
}
void test_hkl() {
MockPeak peak1;
EXPECT_CALL(peak1, getHKL()).Times(5).WillRepeatedly(Return(V3D(1, 2, 3)));
EXPECT_CALL(peak1, getQLabFrame()).Times(0);
EXPECT_CALL(peak1, getQSampleFrame()).Times(0);
do_test(peak1, vtkPeakMarkerFactory::Peak_in_HKL);
}
void testIsValidThrowsWhenNoWorkspace() {
using namespace Mantid::VATES;
using namespace Mantid::API;
IMDWorkspace *nullWorkspace = nullptr;
Mantid::API::IMDWorkspace_sptr ws_sptr(nullWorkspace);
vtkPeakMarkerFactory factory("signal");
TSM_ASSERT_THROWS(
"No workspace, so should not be possible to complete initialization.",
factory.initialize(ws_sptr), std::runtime_error);
}
void testCreateWithoutInitializeThrows() {
FakeProgressAction progressUpdate;
vtkPeakMarkerFactory factory("signal");
TS_ASSERT_THROWS(factory.create(progressUpdate), std::runtime_error);
}
void testTypeName() {
vtkPeakMarkerFactory factory("signal");
TS_ASSERT_EQUALS("vtkPeakMarkerFactory", factory.getFactoryTypeName());
}
void testGetPeakRadiusDefault() {
vtkPeakMarkerFactory factory("signal");
TS_ASSERT_EQUALS(-1, factory.getIntegrationRadius());
}
void testIsPeaksWorkspaceIntegratedDefault() {
vtkPeakMarkerFactory factory("signal");
TS_ASSERT_EQUALS(false, factory.isPeaksWorkspaceIntegrated());
}
void testGetPeakRadiusWhenNotIntegrated() {
auto mockWorkspace = Mantid::Kernel::make_unique<MockPeaksWorkspace>();
const double expectedRadius = -1; // The default
// Note that no PeaksRadius property has been set.
vtkPeakMarkerFactory factory("signal");
factory.initialize(
Mantid::API::IPeaksWorkspace_sptr(std::move(mockWorkspace)));
TS_ASSERT_EQUALS(expectedRadius, factory.getIntegrationRadius());
}
void testIsPeaksWorkspaceIntegratedWhenNotIntegrated() {
auto mockWorkspace = Mantid::Kernel::make_unique<MockPeaksWorkspace>();
// Note that no PeaksRadius property has been set.
vtkPeakMarkerFactory factory("signal");
factory.initialize(
Mantid::API::IPeaksWorkspace_sptr(std::move(mockWorkspace)));
TS_ASSERT_EQUALS(
false, factory.isPeaksWorkspaceIntegrated()); // false is the default
}
void testGetPeakRadiusWhenIntegrated() {
auto mockWorkspace = Mantid::Kernel::make_unique<MockPeaksWorkspace>();
const double expectedRadius = 4;
mockWorkspace->mutableRun().addProperty("PeakRadius", expectedRadius,
true); // Has a PeaksRadius so must
// have been processed via
// IntegratePeaksMD
vtkPeakMarkerFactory factory("signal");
factory.initialize(
Mantid::API::IPeaksWorkspace_sptr(std::move(mockWorkspace)));
TS_ASSERT_EQUALS(expectedRadius, factory.getIntegrationRadius());
}
void testIsPeaksWorkspaceIntegratedWhenIntegrated() {
auto mockWorkspace = Mantid::Kernel::make_unique<MockPeaksWorkspace>();
const double expectedRadius = 4;
mockWorkspace->mutableRun().addProperty("PeakRadius", expectedRadius,
true); // Has a PeaksRadius so must
// have been processed via
// IntegratePeaksMD
vtkPeakMarkerFactory factory("signal");
factory.initialize(
Mantid::API::IPeaksWorkspace_sptr(std::move(mockWorkspace)));
TS_ASSERT_EQUALS(true, factory.isPeaksWorkspaceIntegrated());
}
void testShapeOfSphere() {
FakeProgressAction updateProgress;
auto pw_ptr = boost::make_shared<MockPeaksWorkspace>();
MockPeaksWorkspace &pw = *pw_ptr;
double actualRadius = 2.0;
PeakShapeSpherical sphere(actualRadius,
Kernel::SpecialCoordinateSystem::QLab);
MockPeakShape peak1;
EXPECT_CALL(pw, getNumberPeaks()).WillOnce(Return(1));
EXPECT_CALL(pw, getPeak(_)).WillRepeatedly(ReturnRef(peak1));
EXPECT_CALL(peak1, getQLabFrame()).WillRepeatedly(Return(V3D(0., 0., 0.)));
EXPECT_CALL(peak1, getPeakShape()).WillRepeatedly(ReturnRef(sphere));
vtkPeakMarkerFactory factory("signal");
factory.initialize(pw_ptr);
auto set = factory.create(updateProgress);
TS_ASSERT(set);
TS_ASSERT_EQUALS(set->GetNumberOfPoints(), 300);
for (vtkIdType i = 0; i < set->GetNumberOfPoints(); ++i) {
double pt[3];
set->GetPoint(i, pt);
double radius = std::sqrt(pt[0] * pt[0] + pt[1] * pt[1] + pt[2] * pt[2]);
TS_ASSERT_DELTA(radius, actualRadius, 1.0e-5);
}
TS_ASSERT(testing::Mock::VerifyAndClearExpectations(&pw));
TS_ASSERT(testing::Mock::VerifyAndClearExpectations(&peak1));
}
void testShapeOfEllipsoid() {
FakeProgressAction updateProgress;
auto pw_ptr = boost::make_shared<MockPeaksWorkspace>();
MockPeaksWorkspace &pw = *pw_ptr;
// rotate in 60 degree increments in the x-y plane.
for (size_t dir = 0; dir < 6; ++dir) {
double theta = 2. * M_PI * static_cast<double>(dir) / 6.;
std::vector<Mantid::Kernel::V3D> directions{
{cos(theta), -1. * sin(theta), 0.},
{sin(theta), cos(theta), 0.},
{0., 0., 1.}};
std::vector<double> abcRadii{1., 2., 3.};
// not using these but the constructor requires we set a value.
std::vector<double> abcRadiiBackgroundInner{1., 2., 3.};
std::vector<double> abcRadiiBackgroundOuter{1., 2., 3.};
PeakShapeEllipsoid ellipsoid(
directions, abcRadii, abcRadiiBackgroundInner,
abcRadiiBackgroundOuter, Kernel::SpecialCoordinateSystem::QLab);
MockPeakShape peak1;
EXPECT_CALL(pw, getNumberPeaks()).WillOnce(Return(1));
EXPECT_CALL(pw, getPeak(_)).WillRepeatedly(ReturnRef(peak1));
EXPECT_CALL(peak1, getQLabFrame())
.WillRepeatedly(Return(V3D(0., 0., 0.)));
EXPECT_CALL(peak1, getPeakShape()).WillRepeatedly(ReturnRef(ellipsoid));
vtkPeakMarkerFactory factory("signal");
factory.initialize(pw_ptr);
auto set = factory.create(updateProgress);
TS_ASSERT(set);
TS_ASSERT_EQUALS(set->GetNumberOfPoints(), 300);
// Use the standard equation of an ellipsoid to test the resulting
// workspace.
// https://en.wikipedia.org/wiki/Ellipsoid
for (vtkIdType i = 0; i < set->GetNumberOfPoints(); ++i) {
double pt[3];
set->GetPoint(i, pt);
double rot_x = pt[0] * cos(theta) - pt[1] * sin(theta);
double rot_y = pt[0] * sin(theta) + pt[1] * cos(theta);
double test = rot_x * rot_x / (abcRadii[0] * abcRadii[0]) +
rot_y * rot_y / (abcRadii[1] * abcRadii[1]) +
pt[2] * pt[2] / (abcRadii[2] * abcRadii[2]);
TS_ASSERT_DELTA(test, 1., 1.0e-5);
}
TS_ASSERT(testing::Mock::VerifyAndClearExpectations(&pw));
TS_ASSERT(testing::Mock::VerifyAndClearExpectations(&peak1));
}
}
};
#endif
| Java |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SimpleDownload
{
public partial class Downloader : Form
{
public Downloader()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Download dn=new Download();
dn.DownloadFile(url.Text, @"c:\NewImages\");
}
}
}
| Java |
/**
* 表示データ作成用テンプレート(patTemplate)
*
* LICENSE: This source file is licensed under the terms of the GNU General Public License.
*
* @package Magic3 Framework
* @author 平田直毅(Naoki Hirata) <naoki@aplo.co.jp>
* @copyright Copyright 2006-2014 Magic3 Project.
* @license http://www.gnu.org/copyleft/gpl.html GPL License
* @version SVN: $Id$
* @link http://www.magic3.org
*/
<patTemplate:tmpl name="_widget">
<script type="text/javascript">
//<![CDATA[
function addItem(){
if (!window.confirm('項目を新規追加しますか?')) return false;
document.main.act.value = 'add';
document.main.submit();
return true;
}
function updateItem(){
if (!window.confirm('設定を更新しますか?')) return false;
document.main.act.value='update';
document.main.submit();
return true;
}
function selectItem()
{
document.main.act.value = 'select';
document.main.submit();
return true;
}
function listItem(){
document.main.task.value = 'list';
document.main.submit();
return true;
}
$(function(){
// WYSIWYGエディター作成
m3SetWysiwygEditor('item_html', 450);
});
//]]>
</script>
<div align="center">
<br />
<!-- m3:ErrorMessage -->
<form method="post" name="main">
<input type="hidden" name="task" />
<input type="hidden" name="act" />
<input type="hidden" name="serial" value="{SERIAL}" />
<!-- m3:PostParam -->
<table width="90%">
<tr><td><label>汎用HTML詳細</label></td>
<td align="right"><input type="button" class="button" onclick="listItem();" value="設定一覧" />
</td></tr>
<tr><td colspan="2">
<table class="simple-table" style="margin: 0 auto;width:950px;">
<tbody>
<tr>
<td class="table-headside" width="150">名前</td>
<td>
<select name="item_id" onchange="selectItem();" {ID_DISABLED}>
<option value="0">-- 新規登録 --</option>
<patTemplate:tmpl name="title_list">
<option value="{VALUE}" {SELECTED}>{NAME}</option>
</patTemplate:tmpl>
</select>
<patTemplate:tmpl name="item_name_visible" visibility="hidden">
<input type="text" name="item_name" value="{NAME}" size="40" maxlength="40" />
</patTemplate:tmpl>
</td>
</tr>
<tr class="even">
<td class="table-headside">HTML</td>
<td><textarea name="item_html">{HTML}</textarea></td>
</tr>
<tr>
<td align="right" colspan="2">
<patTemplate:tmpl name="del_button" visibility="hidden">
<input type="button" class="button" onclick="deleteItem();" value="削除" />
</patTemplate:tmpl>
<patTemplate:tmpl name="update_button" visibility="hidden">
<input type="button" class="button" onclick="updateItem();" value="更新" />
</patTemplate:tmpl>
<patTemplate:tmpl name="add_button" visibility="hidden">
<input type="button" class="button" onclick="addItem();" value="新規追加" />
</patTemplate:tmpl>
</td>
</tr>
</tbody>
</table>
</td></tr>
</table>
</form>
</div>
</patTemplate:tmpl>
| Java |
reopen
======
The Repo+Open Project Framework Manifest
license
-------
[GNU GENERAL PUBLIC LICENSE Version 3](http://www.gnu.org/licenses/gpl-3.0-standalone.html)
| Java |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Case Free Report Groups by View for Revit 2017")]
[assembly: AssemblyDescription("Case Free Report Groups by View for Revit 2017")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Case Design, Inc.")]
[assembly: AssemblyProduct("Case Free Report Groups by View for Revit 2017")]
[assembly: AssemblyCopyright("Copyright © Case Design, Inc. 2014")]
[assembly: AssemblyTrademark("Case Design, Inc.")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("372c7cb9-6d40-4880-91ff-16971c7e4661")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2014.6.2.0")]
[assembly: AssemblyFileVersion("2014.6.2.0")]
| Java |
<?php
/*
* Micrositio-Phoenix v1.0 Software para gestion de la planeación operativa.
* PHP v5
* Autor: Prof. Jesus Antonio Peyrano Luna <antonio.peyrano@live.com.mx>
* Nota aclaratoria: Este programa se distribuye bajo los terminos y disposiciones
* definidos en la GPL v3.0, debidamente incluidos en el repositorio original.
* Cualquier copia y/o redistribucion del presente, debe hacerse con una copia
* adjunta de la licencia en todo momento.
* Licencia: http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
*/
header('Content-Type: text/html; charset=iso-8859-1'); //Forzar la codificación a ISO-8859-1.
$sufijo= "col_";
echo ' <html>
<link rel= "stylesheet" href= "./css/queryStyle.css"></style>
<div id="paginado" style="display:none">
<input id="pagina" type="text" value="1">
<input id="pgcolonia" type="text" value="">
<input id="pgestado" type="text" value="">
<input id="pgciudad" type="text" value="">
<input id="pgcp" type="text" value="">
</div>
<center><div id= "divbusqueda">
<form id="frmbusqueda" method="post" action="">
<table class="queryTable" colspan= "7">
<tr><td class= "queryRowsnormTR" width ="180">Por nombre de la colonia: </td><td class= "queryRowsnormTR" width ="250"><input type= "text" id= "nomcolonia"></td><td rowspan= "4"><img id="'.$sufijo.'buscar" align= "left" src= "./img/grids/view.png" width= "25" height= "25" alt="Buscar"/></td></tr>
<tr><td class= "queryRowsnormTR">Por codigo postal: </td><td class= "queryRowsnormTR"><input type= "text" id= "cpcolonia"></td><td></td></tr>
<tr><td class= "queryRowsnormTR">Por ciudad: </td><td class= "queryRowsnormTR"><input type= "text" id= "ciucolonia"></td><td></td></tr>
<tr><td class= "queryRowsnormTR">Por estado: </td><td class= "queryRowsnormTR"><input type= "text" id= "estcolonia"></td><td></td></tr>
</table>
</form>
</div></center>';
echo '<div id= "busRes">';
include_once("catColonias.php");
echo '</div>
</html>';
?> | Java |
from numpy import sqrt
from pacal.standard_distr import NormalDistr, ChiSquareDistr
from pacal.distr import Distr, SumDistr, DivDistr, InvDistr
from pacal.distr import sqrt as distr_sqrt
class NoncentralTDistr(DivDistr):
def __init__(self, df = 2, mu = 0):
d1 = NormalDistr(mu, 1)
d2 = distr_sqrt(ChiSquareDistr(df) / df)
super(NoncentralTDistr, self).__init__(d1, d2)
self.df = df
self.mu = mu
def __str__(self):
return "NoncentralTDistr(df={0},mu={1})#{2}".format(self.df, self.mu, self.id())
def getName(self):
return "NoncT({0},{1})".format(self.df, self.mu)
class NoncentralChiSquareDistr(SumDistr):
def __new__(cls, df, lmbda = 0):
assert df >= 1
d1 = NormalDistr(sqrt(lmbda))**2
if df == 1:
return d1
d2 = ChiSquareDistr(df - 1)
ncc2 = super(NoncentralChiSquareDistr, cls).__new__(cls, d1, d2)
super(NoncentralChiSquareDistr, ncc2).__init__(d1, d2)
ncc2.df = df
ncc2.lmbda = lmbda
return ncc2
def __init__(self, df, lmbda = 0):
pass
def __str__(self):
return "NoncentralChiSquare(df={0},lambda={1})#{2}".format(self.df, self.lmbda, self.id())
def getName(self):
return "NoncChi2({0},{1})".format(self.df, self.lmbda)
class NoncentralBetaDistr(InvDistr):
def __init__(self, alpha = 1, beta = 1, lmbda = 0):
d = 1 + ChiSquareDistr(2.0 * beta) / NoncentralChiSquareDistr(2 * alpha, lmbda)
super(NoncentralBetaDistr, self).__init__(d)
self.alpha = alpha
self.beta = beta
self.lmbda = lmbda
def __str__(self):
return "NoncentralBetaDistr(alpha={0},beta={1},lambda={2})#{3}".format(self.alpha, self.beta, self.lmbda, self.id())
def getName(self):
return "NoncBeta({0},{1},{2})".format(self.alpha, self.beta, self.lmbda)
class NoncentralFDistr(DivDistr):
def __init__(self, df1 = 1, df2 = 1, lmbda = 0):
d1 = NoncentralChiSquareDistr(df1, lmbda) / df1
d2 = ChiSquareDistr(df2) / df2
super(NoncentralFDistr, self).__init__(d1, d2)
self.df1 = df1
self.df2 = df2
self.lmbda = lmbda
def __str__(self):
return "NoncentralFDistr(df1={0},df2={1},lambda={2})#{3}".format(self.df1, self.df2, self.lmbda, self.id())
def getName(self):
return "NoncF({0},{1},{2})".format(self.df1, self.df2, self.lmbda)
| Java |
IWitness.ErrorsView = Ember.View.extend({
classNames: ["error-bubble"],
classNameBindings: ["isError"],
isError: function() {
return !!this.get("error");
}.property("error")
});
| Java |
/*
* Copyright 2008-2013, ETH Zürich, Samuel Welten, Michael Kuhn, Tobias Langner,
* Sandro Affentranger, Lukas Bossard, Michael Grob, Rahul Jain,
* Dominic Langenegger, Sonia Mayor Alonso, Roger Odermatt, Tobias Schlueter,
* Yannick Stucki, Sebastian Wendland, Samuel Zehnder, Samuel Zihlmann,
* Samuel Zweifel
*
* This file is part of Jukefox.
*
* Jukefox 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 any later version. Jukefox 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
* Jukefox. If not, see <http://www.gnu.org/licenses/>.
*/
package ch.ethz.dcg.jukefox.model.collection;
public class MapTag extends BaseTag {
float[] coordsPca2D;
private float varianceOverPCA;
public MapTag(int id, String name, float[] coordsPca2D, float varianceOverPCA) {
super(id, name);
this.coordsPca2D = coordsPca2D;
this.varianceOverPCA = varianceOverPCA;
}
public float[] getCoordsPca2D() {
return coordsPca2D;
}
public float getVarianceOverPCA() {
return varianceOverPCA;
}
}
| Java |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Page to handle actions associated with badges management.
*
* @package core
* @subpackage badges
* @copyright 2012 onwards Corplms Learning Solutions Ltd {@link http://www.corplmslms.com/}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @author Yuliya Bozhko <yuliya.bozhko@corplmslms.com>
*/
require_once(dirname(dirname(__FILE__)) . '/config.php');
require_once($CFG->libdir . '/badgeslib.php');
$badgeid = required_param('id', PARAM_INT);
$copy = optional_param('copy', 0, PARAM_BOOL);
$activate = optional_param('activate', 0, PARAM_BOOL);
$deactivate = optional_param('lock', 0, PARAM_BOOL);
$confirm = optional_param('confirm', 0, PARAM_BOOL);
$return = optional_param('return', 0, PARAM_LOCALURL);
require_login();
$badge = new badge($badgeid);
$context = $badge->get_context();
$navurl = new moodle_url('/badges/index.php', array('type' => $badge->type));
if ($badge->type == BADGE_TYPE_COURSE) {
require_login($badge->courseid);
$navurl = new moodle_url('/badges/index.php', array('type' => $badge->type, 'id' => $badge->courseid));
$PAGE->set_pagelayout('standard');
navigation_node::override_active_url($navurl);
} else {
$PAGE->set_pagelayout('admin');
navigation_node::override_active_url($navurl, true);
}
$PAGE->set_context($context);
$PAGE->set_url('/badges/action.php', array('id' => $badge->id));
if ($return !== 0) {
$returnurl = new moodle_url($return);
} else {
$returnurl = new moodle_url('/badges/overview.php', array('id' => $badge->id));
}
$returnurl->remove_params('awards');
if ($copy) {
require_sesskey();
require_capability('moodle/badges:createbadge', $context);
$cloneid = $badge->make_clone();
// If a user can edit badge details, they will be redirected to the edit page.
if (has_capability('moodle/badges:configuredetails', $context)) {
redirect(new moodle_url('/badges/edit.php', array('id' => $cloneid, 'action' => 'details')));
}
redirect(new moodle_url('/badges/overview.php', array('id' => $cloneid)));
}
if ($activate) {
require_capability('moodle/badges:configurecriteria', $context);
$PAGE->url->param('activate', 1);
$status = ($badge->status == BADGE_STATUS_INACTIVE) ? BADGE_STATUS_ACTIVE : BADGE_STATUS_ACTIVE_LOCKED;
if ($confirm == 1) {
require_sesskey();
list($valid, $message) = $badge->validate_criteria();
if ($valid) {
$badge->set_status($status);
if ($badge->type == BADGE_TYPE_SITE) {
// Review on cron if there are more than 1000 users who can earn a site-level badge.
$sql = 'SELECT COUNT(u.id) as num
FROM {user} u
LEFT JOIN {badge_issued} bi
ON u.id = bi.userid AND bi.badgeid = :badgeid
WHERE bi.badgeid IS NULL AND u.id != :guestid AND u.deleted = 0';
$toearn = $DB->get_record_sql($sql, array('badgeid' => $badge->id, 'guestid' => $CFG->siteguest));
if ($toearn->num < 1000) {
$awards = $badge->review_all_criteria();
$returnurl->param('awards', $awards);
} else {
$returnurl->param('awards', 'cron');
}
} else {
$awards = $badge->review_all_criteria();
$returnurl->param('awards', $awards);
}
redirect($returnurl);
} else {
echo $OUTPUT->header();
echo $OUTPUT->notification(get_string('error:cannotact', 'badges', $badge->name) . $message);
echo $OUTPUT->continue_button($returnurl);
echo $OUTPUT->footer();
die();
}
}
$strheading = get_string('reviewbadge', 'badges');
$PAGE->navbar->add($strheading);
$PAGE->set_title($strheading);
$PAGE->set_heading($badge->name);
echo $OUTPUT->header();
echo $OUTPUT->heading($strheading);
$params = array('id' => $badge->id, 'activate' => 1, 'sesskey' => sesskey(), 'confirm' => 1, 'return' => $return);
$url = new moodle_url('/badges/action.php', $params);
if (!$badge->has_criteria()) {
echo $OUTPUT->notification(get_string('error:cannotact', 'badges', $badge->name) . get_string('nocriteria', 'badges'));
echo $OUTPUT->continue_button($returnurl);
} else {
$message = get_string('reviewconfirm', 'badges', $badge->name);
echo $OUTPUT->confirm($message, $url, $returnurl);
}
echo $OUTPUT->footer();
die;
}
if ($deactivate) {
require_sesskey();
require_capability('moodle/badges:configurecriteria', $context);
$status = ($badge->status == BADGE_STATUS_ACTIVE) ? BADGE_STATUS_INACTIVE : BADGE_STATUS_INACTIVE_LOCKED;
$badge->set_status($status);
redirect($returnurl);
}
| Java |
/*
* Copyright (C) 2011 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package de.ailis.microblinks.l.lctrl.shell;
import gnu.getopt.Getopt;
import gnu.getopt.LongOpt;
import java.util.Arrays;
import de.ailis.microblinks.l.lctrl.resources.Resources;
/**
* Base class for all CLI programs.
*
* @author Klaus Reimer (k@ailis.de)
*/
public abstract class CLI
{
/** The command-line program name. */
private final String name;
/** The short options. */
private final String shortOpts;
/** The long options. */
private final LongOpt[] longOpts;
/** Debug mode. */
private boolean debug = false;
/**
* Constructor.
*
* @param name
* The command-line program name.
* @param shortOpts
* The short options.
* @param longOpts
* The long options.
*/
protected CLI(final String name, final String shortOpts, final LongOpt[] longOpts)
{
this.name = name;
this.shortOpts = shortOpts;
this.longOpts = longOpts;
}
/**
* Displays command-line help.
*/
private void showHelp()
{
System.out.println(Resources.getText("help.txt"));
}
/**
* Displays version information.
*/
private void showVersion()
{
System.out.println(Resources.getText("version.txt"));
}
/**
* Displays the help hint.
*/
protected void showHelpHint()
{
System.out.println("Use --help to show usage information.");
}
/**
* Prints error message to stderr and then exits with error code 1.
*
* @param message
* The error message.
* @param args
* The error message arguments.
*/
protected void error(final String message, final Object... args)
{
System.err.print(this.name);
System.err.print(": ");
System.err.format(message, args);
System.err.println();
showHelpHint();
System.exit(1);
}
/**
* Processes all command line options.
*
* @param args
* The command line arguments.
* @throws Exception
* When error occurs.
* @return The index of the first non option argument.
*/
private int processOptions(final String[] args) throws Exception
{
final Getopt opts = new Getopt(this.name, args, this.shortOpts, this.longOpts);
int opt;
while ((opt = opts.getopt()) >= 0)
{
switch (opt)
{
case 'h':
showHelp();
System.exit(0);
break;
case 'V':
showVersion();
System.exit(0);
break;
case 'D':
this.debug = true;
break;
case '?':
showHelpHint();
System.exit(111);
break;
default:
processOption(opt, opts.getOptarg());
}
}
return opts.getOptind();
}
/**
* Processes a single option.
*
* @param option
* The option to process
* @param arg
* The optional option argument
* @throws Exception
* When an error occurred.
*/
protected abstract void processOption(final int option, final String arg) throws Exception;
/**
* Executes the program with the specified arguments. This is called from the run() method after options has been
* processed. The specified arguments array only contains the non-option arguments.
*
* @param args
* The non-option command-line arguments.
* @throws Exception
* When something goes wrong.
*/
protected abstract void execute(String[] args) throws Exception;
/**
* Runs the program.
*
* @param args
* The command line arguments.
*/
public void run(final String[] args)
{
try
{
final int commandStart = processOptions(args);
execute(Arrays.copyOfRange(args, commandStart, args.length));
}
catch (final Exception e)
{
if (this.debug)
{
e.printStackTrace(System.err);
}
error(e.getMessage());
System.exit(1);
}
}
/**
* Checks if program runs in debug mode.
*
* @return True if debug mode, false if not.
*/
public boolean isDebug()
{
return this.debug;
}
}
| Java |
/************************************************************************
**
** @file vistoolspline.cpp
** @author Roman Telezhynskyi <dismine(at)gmail.com>
** @date 18 8, 2014
**
** @brief
** @copyright
** This source code is part of the Valentina project, a pattern making
** program, whose allow create and modeling patterns of clothing.
** Copyright (C) 2013-2015 Valentina project
** <https://bitbucket.org/dismine/valentina> All Rights Reserved.
**
** Valentina 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.
**
** Valentina 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 Valentina. If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/
#include "vistoolspline.h"
#include <QLineF>
#include <QPainterPath>
#include <QSharedPointer>
#include <Qt>
#include <new>
#include "../ifc/ifcdef.h"
#include "../vgeometry/vabstractcurve.h"
#include "../vgeometry/vgeometrydef.h"
#include "../vgeometry/vpointf.h"
#include "../vgeometry/vspline.h"
#include "../vpatterndb/vcontainer.h"
#include "../vwidgets/vcontrolpointspline.h"
#include "../vwidgets/scalesceneitems.h"
#include "../visualization.h"
#include "vispath.h"
#include "../vmisc/vmodifierkey.h"
const int EMPTY_ANGLE = -1;
//---------------------------------------------------------------------------------------------------------------------
VisToolSpline::VisToolSpline(const VContainer *data, QGraphicsItem *parent)
: VisPath(data, parent),
object4Id(NULL_ID),
point1(nullptr),
point4(nullptr),
angle1(EMPTY_ANGLE),
angle2(EMPTY_ANGLE),
kAsm1(1),
kAsm2(1),
kCurve(1),
isLeftMousePressed(false),
p2Selected(false),
p3Selected(false),
p2(),
p3(),
controlPoints()
{
point1 = InitPoint(supportColor, this);
point4 = InitPoint(supportColor, this); //-V656
auto *controlPoint1 = new VControlPointSpline(1, SplinePointPosition::FirstPoint, this);
controlPoint1->hide();
controlPoints.append(controlPoint1);
auto *controlPoint2 = new VControlPointSpline(1, SplinePointPosition::LastPoint, this);
controlPoint2->hide();
controlPoints.append(controlPoint2);
}
//---------------------------------------------------------------------------------------------------------------------
VisToolSpline::~VisToolSpline()
{
emit ToolTip(QString());
}
//---------------------------------------------------------------------------------------------------------------------
void VisToolSpline::RefreshGeometry()
{
//Radius of point circle, but little bigger. Need handle with hover sizes.
const static qreal radius = ScaledRadius(SceneScale(qApp->getCurrentScene()))*1.5;
if (object1Id > NULL_ID)
{
const auto first = Visualization::data->GeometricObject<VPointF>(object1Id);
DrawPoint(point1, static_cast<QPointF>(*first), supportColor);
if (mode == Mode::Creation)
{
if (isLeftMousePressed && not p2Selected)
{
p2 = Visualization::scenePos;
controlPoints[0]->RefreshCtrlPoint(1, SplinePointPosition::FirstPoint, p2,
static_cast<QPointF>(*first));
if (not controlPoints[0]->isVisible())
{
if (QLineF(static_cast<QPointF>(*first), p2).length() > radius)
{
controlPoints[0]->show();
}
else
{
p2 = static_cast<QPointF>(*first);
}
}
}
else
{
p2Selected = true;
}
}
if (object4Id <= NULL_ID)
{
VSpline spline(*first, p2, Visualization::scenePos, VPointF(Visualization::scenePos));
spline.SetApproximationScale(m_approximationScale);
DrawPath(this, spline.GetPath(), mainColor, lineStyle, Qt::RoundCap);
}
else
{
const auto second = Visualization::data->GeometricObject<VPointF>(object4Id);
DrawPoint(point4, static_cast<QPointF>(*second), supportColor);
if (mode == Mode::Creation)
{
if (isLeftMousePressed && not p3Selected)
{
QLineF ctrlLine (static_cast<QPointF>(*second), Visualization::scenePos);
ctrlLine.setAngle(ctrlLine.angle()+180);
p3 = ctrlLine.p2();
controlPoints[1]->RefreshCtrlPoint(1, SplinePointPosition::LastPoint, p3,
static_cast<QPointF>(*second));
if (not controlPoints[1]->isVisible())
{
if (QLineF(static_cast<QPointF>(*second), p3).length() > radius)
{
controlPoints[1]->show();
}
else
{
p3 = static_cast<QPointF>(*second);
}
}
}
else
{
p3Selected = true;
}
}
if (VFuzzyComparePossibleNulls(angle1, EMPTY_ANGLE) || VFuzzyComparePossibleNulls(angle2, EMPTY_ANGLE))
{
VSpline spline(*first, p2, p3, *second);
spline.SetApproximationScale(m_approximationScale);
DrawPath(this, spline.GetPath(), mainColor, lineStyle, Qt::RoundCap);
}
else
{
VSpline spline(*first, *second, angle1, angle2, kAsm1, kAsm2, kCurve);
spline.SetApproximationScale(m_approximationScale);
DrawPath(this, spline.GetPath(), spline.DirectionArrows(), mainColor, lineStyle, Qt::RoundCap);
Visualization::toolTip = tr("Use <b>%1</b> for sticking angle!")
.arg(VModifierKey::Shift());
emit ToolTip(Visualization::toolTip);
}
}
}
}
//---------------------------------------------------------------------------------------------------------------------
void VisToolSpline::setObject4Id(const quint32 &value)
{
object4Id = value;
}
//---------------------------------------------------------------------------------------------------------------------
void VisToolSpline::SetAngle1(const qreal &value)
{
angle1 = value;
}
//---------------------------------------------------------------------------------------------------------------------
void VisToolSpline::SetAngle2(const qreal &value)
{
angle2 = value;
}
//---------------------------------------------------------------------------------------------------------------------
void VisToolSpline::SetKAsm1(const qreal &value)
{
kAsm1 = value;
}
//---------------------------------------------------------------------------------------------------------------------
void VisToolSpline::SetKAsm2(const qreal &value)
{
kAsm2 = value;
}
//---------------------------------------------------------------------------------------------------------------------
void VisToolSpline::SetKCurve(const qreal &value)
{
kCurve = value;
}
//---------------------------------------------------------------------------------------------------------------------
QPointF VisToolSpline::GetP2() const
{
return p2;
}
//---------------------------------------------------------------------------------------------------------------------
QPointF VisToolSpline::GetP3() const
{
return p3;
}
//---------------------------------------------------------------------------------------------------------------------
void VisToolSpline::MouseLeftPressed()
{
if (mode == Mode::Creation)
{
isLeftMousePressed = true;
}
}
//---------------------------------------------------------------------------------------------------------------------
void VisToolSpline::MouseLeftReleased()
{
if (mode == Mode::Creation)
{
isLeftMousePressed = false;
RefreshGeometry();
}
}
| Java |
<?php
/**
Copyright 2012-2014-2013 Nick Korbel
This file is part of Booked Scheduler.
Booked Scheduler 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.
Booked Scheduler 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 Booked Scheduler. If not, see <http://www.gnu.org/licenses/>.
*/
require_once(ROOT_DIR . 'Pages/Admin/ManageConfigurationPage.php');
require_once(ROOT_DIR . 'Presenters/ActionPresenter.php');
class ConfigActions
{
const Update = 'update';
}
class ManageConfigurationPresenter extends ActionPresenter
{
/**
* @var IManageConfigurationPage
*/
private $page;
/**
* @var IConfigurationSettings
*/
private $configSettings;
/**
* @var
*/
private $configFilePath;
private $deletedSettings = array('password.pattern');
public function __construct(IManageConfigurationPage $page, IConfigurationSettings $settings)
{
parent::__construct($page);
$this->page = $page;
$this->configSettings = $settings;
$this->configFilePath = ROOT_DIR . 'config/config.php';
$this->configFilePathDist = ROOT_DIR . 'config/config.dist.php';
$this->AddAction(ConfigActions::Update, 'Update');
}
public function PageLoad()
{
$shouldShowConfig = Configuration::Instance()->GetSectionKey(ConfigSection::PAGES,
ConfigKeys::PAGES_ENABLE_CONFIGURATION,
new BooleanConverter());
$this->page->SetIsPageEnabled($shouldShowConfig);
if (!$shouldShowConfig)
{
Log::Debug('Show configuration UI is turned off. Not displaying the config values');
return;
}
$configFiles = $this->GetConfigFiles();
$this->page->SetConfigFileOptions($configFiles);
$this->HandleSelectedConfigFile($configFiles);
$isFileWritable = $this->configSettings->CanOverwriteFile($this->configFilePath);
$this->page->SetIsConfigFileWritable($isFileWritable);
if (!$isFileWritable)
{
Log::Debug('Config file is not writable');
return;
}
Log::Debug('Loading and displaying config file for editing by %s',
ServiceLocator::GetServer()->GetUserSession()->Email);
$this->BringConfigFileUpToDate();
$settings = $this->configSettings->GetSettings($this->configFilePath);
foreach ($settings as $key => $value)
{
if (is_array($value))
{
$section = $key;
foreach ($value as $sectionkey => $sectionvalue)
{
if (!$this->ShouldBeSkipped($sectionkey, $section))
{
$this->page->AddSectionSetting(new ConfigSetting($sectionkey, $section, $sectionvalue));
}
}
}
else
{
if (!$this->ShouldBeSkipped($key))
{
$this->page->AddSetting(new ConfigSetting($key, null, $value));
}
}
}
$this->PopulateHomepages();
}
private function PopulateHomepages()
{
$homepageValues = array();
$homepageOutput = array();
$pages = Pages::GetAvailablePages();
foreach ($pages as $pageid => $page)
{
$homepageValues[] = $pageid;
$homepageOutput[] = Resources::GetInstance()->GetString($page['name']);
}
$this->page->SetHomepages($homepageValues, $homepageOutput);
}
public function Update()
{
$shouldShowConfig = Configuration::Instance()->GetSectionKey(ConfigSection::PAGES,
ConfigKeys::PAGES_ENABLE_CONFIGURATION,
new BooleanConverter());
if (!$shouldShowConfig)
{
Log::Debug('Show configuration UI is turned off. No updates are allowed');
return;
}
$configSettings = $this->page->GetSubmittedSettings();
$configFiles = $this->GetConfigFiles();
$this->HandleSelectedConfigFile($configFiles);
$newSettings = array();
foreach ($configSettings as $setting)
{
if (!empty($setting->Section))
{
$newSettings[$setting->Section][$setting->Key] = $setting->Value;
}
else
{
$newSettings[$setting->Key] = $setting->Value;
}
}
$existingSettings = $this->configSettings->GetSettings($this->configFilePath);
$mergedSettings = array_merge($existingSettings, $newSettings);
foreach ($this->deletedSettings as $deletedSetting)
{
if (array_key_exists($deletedSetting, $mergedSettings))
{
unset($mergedSettings[$deletedSetting]);
}
}
Log::Debug("Saving %s settings", count($configSettings));
$this->configSettings->WriteSettings($this->configFilePath, $mergedSettings);
Log::Debug('Config file saved by %s', ServiceLocator::GetServer()->GetUserSession()->Email);
}
private function ShouldBeSkipped($key, $section = null)
{
if ($section == ConfigSection::DATABASE || $section == ConfigSection::API)
{
return true;
}
if (in_array($key, $this->deletedSettings))
{
return true;
}
switch ($key)
{
case ConfigKeys::INSTALLATION_PASSWORD:
case ConfigKeys::PAGES_ENABLE_CONFIGURATION && $section == ConfigSection::PAGES:
return true;
default:
return false;
}
}
private function GetConfigFiles()
{
$files = array(new ConfigFileOption('config.php', ''));
$pluginBaseDir = ROOT_DIR . 'plugins/';
if ($h = opendir($pluginBaseDir))
{
while (false !== ($entry = readdir($h)))
{
$pluginDir = $pluginBaseDir . $entry;
if (is_dir($pluginDir) && $entry != "." && $entry != "..")
{
$plugins = scandir($pluginDir);
foreach ($plugins as $plugin)
{
if (is_dir("$pluginDir/$plugin") && $plugin != "." && $plugin != ".." && strpos($plugin,'Example') === false)
{
$configFiles = array_merge(glob("$pluginDir/$plugin/*.config.php"), glob("$pluginDir/$plugin/*.config.dist.php"));
if (count($configFiles) > 0)
{
$files[] = new ConfigFileOption("$entry-$plugin", "$entry/$plugin");
}
}
}
}
}
closedir($h);
}
return $files;
}
private function HandleSelectedConfigFile($configFiles)
{
$requestedConfigFile = $this->page->GetConfigFileToEdit();
if (!empty($requestedConfigFile))
{
/** @var $file ConfigFileOption */
foreach ($configFiles as $file)
{
if ($file->Location == $requestedConfigFile)
{
$this->page->SetSelectedConfigFile($requestedConfigFile);
$rootDir = ROOT_DIR . 'plugins/' . $requestedConfigFile;
$distFile = glob("$rootDir/*config.dist.php");
$configFile = glob("$rootDir/*config.php");
if (count($distFile) == 1 && count($configFile) == 0)
{
copy($distFile[0], str_replace('.dist', '', $distFile[0]));
}
$configFile = glob("$rootDir/*config.php");
$this->configFilePath = $configFile[0];
$this->configFilePathDist = str_replace('.php', '.dist.php', $configFile[0]);
}
}
}
}
private function BringConfigFileUpToDate()
{
if (!file_exists($this->configFilePathDist))
{
return;
}
$configurator = new Configurator();
$configurator->Merge($this->configFilePath, $this->configFilePathDist);
}
}
class ConfigFileOption
{
public function __construct($name, $location)
{
$this->Name = $name;
$this->Location = $location;
}
}
class ConfigSetting
{
public $Key;
public $Section;
public $Value;
public $Type;
public $Name;
public function __construct($key, $section, $value)
{
$key = trim($key);
$section = trim($section);
$value = trim($value);
$this->Name = $this->encode($key) . '|' . $this->encode($section);
$this->Key = $key;
$this->Section = $section;
$this->Value = $value . '';
$type = strtolower($value) == 'true' || strtolower($value) == 'false' ? ConfigSettingType::Boolean : ConfigSettingType::String;
$this->Type = $type;
if ($type == ConfigSettingType::Boolean)
{
$this->Value = strtolower($this->Value);
}
}
public static function ParseForm($key, $value)
{
$k = self::decode($key);
$keyAndSection = explode('|', $k);
return new ConfigSetting($keyAndSection[0], $keyAndSection[1], $value);
}
private static function encode($value)
{
return str_replace('.', '__', $value);
}
private static function decode($value)
{
return str_replace('__', '.', $value);
}
}
class ConfigSettingType
{
const String = 'string';
const Boolean = 'boolean';
} | Java |
#include <stdlib.h>
#include <stdio.h>
#include "array_heap.h"
int array_init(array* arr, int size) {
arr->data = realloc(NULL, sizeof(void*) * size);
if (0 == (size_t)arr->data) {
return -1;
}
arr->length = size;
arr->index = 0;
return 0;
}
int array_push(array* arr, void* data) {
((size_t*)arr->data)[arr->index] = (size_t)data;
arr->index += 1;
if (arr->index >= arr->length) {
if (-1 == array_grow(arr, arr->length * 2))
{
return -1;
}
}
return arr->index - 1;
}
int array_grow(array* arr, int size) {
if (size <= arr->length) {
return -1;
}
arr->data = realloc(arr->data, sizeof(void*) * size);
if (-1 == (size_t)arr->data) {
return -1;
}
arr->length = size;
return 0;
}
void array_free(array* arr, void (*free_element)(void*)) {
int i;
for (i = 0; i < arr->index; i += 1) {
free_element((void*)((size_t*)arr->data)[i]);
}
free(arr->data);
arr->index = -1;
arr->length = 0;
arr->data = NULL;
}
| Java |
### Bienvenida
Hora de inicio: 09:12 a.m.
El Lic. Eduardo Holguín da la bienvenida y le concede la palabra al Arq. Rafael Pérez Fernández.
### Introducción
El Arq. Rafael Pérez Fernández expone los objetivos del Plan Estratégico Metropolitano.
Introducción por Lic. Rodrigo González Morales: Explicación de los resultados de la mesa anterior, presentación de los indicadores y futuros tendenciales de cada uno de los problemas de cada temática.
El Arq. Rafael Pérez explica la mecánica del evento. Que en la elección de futuro deseable se llenará un formato de manera individual; luego se realizarán rondas para enriquecer de 15 minutos tomando nota de forma conjunta e interactiva. Al final se hará la integración y propuestas de objetivos y metas.
### Visión – Futuro Deseable
Problema 1. Falta de seguridad
* Una policía de carrera eficiente, con educación y con sueldos y prestaciones remunerados, sociedad apoyada por esta misma.
* Disminuir la tasa de delitos 60 %, en la zona metropolita así como la victimización de los habitantes.
* Abatir los índices de criminalidad; Recuperamos la confianza de la población.
* Personal confiable y con enfoque en prevención de delito.
* Confianza en todos los sectores, mínima inseguridad.
* Una ciudadanía cívicamente educada.
* Alto índice de confianza en la población, confianza en autoridades e instituciones.
* Autoridades gozan de credibilidad, seguridad de las mujeres.
* Torreón incluyente para inversión mano de obra remunerada, respeto a los recursos naturales, zona metro segura.
* Contar y cumplir con indicadores de seguridad, cumplir 95 % de indicadores, fortalecer cultura de la legalidad. Prevención del delito.
* Una vinculación con las instituciones educativas para poder regularizar los recursos. Participación ciudadana en la prevención social.
* Erradicar la corrupción en las instancias de seguridad.
* Que se llenen los demás espacios con cosas concretas. Y visión concreta para poder aterrizar.
Problema 2. Ser municipio saludable
* Especialistas atendiendo a las personas enfermas.
* Disminuir los índices de morbilidad, acceso a salud de calidad para todos.
* Prevención de enfermedades, eficiente infraestructura en sector salud.
* Cultura de prevención, además de alta calidad en atención médica.
* Zona metropolitana física y clínicamente sana.
* Llegar a tener índices bajos y controlados.
* Aumento de atención a la población, calidad en servicio público y control sanitario.
* Municipio saludable.
* Programas Federales, Estatales y Municipales coordinados para que se apliquen en el área de salud necesarias.
* Ciudadanos conscientes.
* Lograr acceso completo por parte de todos los ciudadanos a los servicios de salud. Lograr un estándar a nivel mundial.
* Lograr el estándar de municipio saludable, respetando las leyes y reglamentos.
Problema 3. Vocación educativa para una adecuada vinculación con el desarrollo social.
* Incrementar en las escuelas un análisis de vocación profesional acorde con el desarrollo económico de la Ciudad.
* Combatir rezago escolar, aumentar la calidad en la formación de investigadores en áreas científicas.
* Multiplicación de programas de vinculación con la población, redirigir la atención a grupos de todo tipo, vulnerable, no vulnerable.
* Se cumple con los estándares de calidad de la UNESCO, que se escoja una vocación universitaria específica en la comarca lagunera.
* La zona metro opera con 4 dimensiones sociedad, instituciones de educación, gobierno y empresas.
* Sustento académico desde el kínder a la universidad, de la misma forma sustento para desarrollarse.
* Aumento en la calidad de la educación, aumentar las licenciaturas a nivel humanístico.
* Enfoque de vocación en áreas que la sociedad requiere.
* Las universidades se sustentan en base al desarrollo social
* Formar ciudadanos del mundo respetuoso.
* Vincular al educador con el educando. (Se menciona ejemplo de las adolescentes embarazadas en la actualidad ) Existe una desvinculación entre el profesor y el alumno, la educación atiende este aspecto.
* Formación de ciudadanos responsables
* Desde kinder y todos niveles se incluya curricular desde valores trabajo en equipo.
* Formación de ciudadanos responsables.
* Disminuir los índices de deserción escolar en secundaria y preparatoria.
* Nota: Se integra al temas ciudadanos responsables que denuncian los atropellos
Problema 4. Problema
* Desarrolla en escuelas elementos de arte como musca, pintura.
* Incrementa la calidad y cantidad de programas culturas y espacios públicos en un 50%, aumenta las bibliotecas e inmuebles históricos.
* Multiplicación de espacios en cada barrio de la ciudad. Promoción de actividades de convivencia.
* Dos niveles de infraestructura cultural. Todo tipo de artes, espacio de aprendizaje, otro espacio de disfrute.
* Ser líder en desarrollo cultural y deportivo en el país.
* Espacios distribuidos culturales y que se atienda las diferentes necesidades.
* Alto porcentaje con acceso a centros culturales integrales. Promotores culturales y creadores. Acceso gratuito.
* Identidad del ciudadano con su ciudad.
* Se proyecta como zona turística espacios limpios cuidados, colonias espacios públicos accesibles.
* Fusión entre respeto de la modernidad con raíces.
* Disminuir la brecha cultural y deportiva, infraestructura que promueva la cultura.
* Adaptada con accesibilidad y atraer a turismo, discapacidad de lugares denotar desarrollo del área.
Problema 5. Problema
* Compromiso a trabajar con grupos vulnerables, aumentar pensión de jubilados.
* Disminuir índices de pobreza.
* Vinculación de los programas institucionales de organismos públicos específicos.
* Infraestructura para movilidad, atención a personas vulnerables, cultura de ayuda.
* Reducción en las carencias, atención completa.
* Fomento en las ONG y mayor apoyo.
* Centros especializados para cada grupo vulnerable.
* Programas sociales para disminuir grupos vulnerables.
* Acceso a los servicios de salud al 100% mecanismos de bienestar físico.
* Trabajo conjunto entre sociedad civil, gobierno y empresas, se trabaje con la sociedad, apego a las leyes
* Identifica y monitorea a grupos vulnerables.
La mesa termino antes de lo previsto la actividad por lo que se tomo un breve receso.
### Propuesta de objetivos y metas
Se integraron las visiones y se agregaron a las que ya se tenían por parte de la mesa. Se llenaron los formatos.
### Conclusión
Se establecieron las conclusiones de la mesa.
### Agradecimiento y despedida
Hora de término: 01:08 p.m.
| Java |
from ert.cwrap import CWrapper, BaseCClass
from ert.enkf import ENKF_LIB
from ert.util import StringList
class SummaryKeyMatcher(BaseCClass):
def __init__(self):
c_ptr = SummaryKeyMatcher.cNamespace().alloc()
super(SummaryKeyMatcher, self).__init__(c_ptr)
def addSummaryKey(self, key):
assert isinstance(key, str)
return SummaryKeyMatcher.cNamespace().add_key(self, key)
def __len__(self):
return SummaryKeyMatcher.cNamespace().size(self)
def __contains__(self, key):
return SummaryKeyMatcher.cNamespace().match_key(self, key)
def isRequired(self, key):
""" @rtype: bool """
return SummaryKeyMatcher.cNamespace().is_required(self, key)
def keys(self):
""" @rtype: StringList """
return SummaryKeyMatcher.cNamespace().keys(self)
def free(self):
SummaryKeyMatcher.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("summary_key_matcher", SummaryKeyMatcher)
SummaryKeyMatcher.cNamespace().alloc = cwrapper.prototype("c_void_p summary_key_matcher_alloc()")
SummaryKeyMatcher.cNamespace().free = cwrapper.prototype("void summary_key_matcher_free(summary_key_matcher)")
SummaryKeyMatcher.cNamespace().size = cwrapper.prototype("int summary_key_matcher_get_size(summary_key_matcher)")
SummaryKeyMatcher.cNamespace().add_key = cwrapper.prototype("void summary_key_matcher_add_summary_key(summary_key_matcher, char*)")
SummaryKeyMatcher.cNamespace().match_key = cwrapper.prototype("bool summary_key_matcher_match_summary_key(summary_key_matcher, char*)")
SummaryKeyMatcher.cNamespace().keys = cwrapper.prototype("stringlist_obj summary_key_matcher_get_keys(summary_key_matcher)")
SummaryKeyMatcher.cNamespace().is_required = cwrapper.prototype("bool summary_key_matcher_summary_key_is_required(summary_key_matcher, char*)")
| Java |
<?php
/**
* @module wysiwyg Admin
* @version see info.php of this module
* @authors Dietrich Roland Pehlke
* @copyright 2010-2011 Dietrich Roland Pehlke
* @license GNU General Public License
* @license terms see info.php of this module
* @platform see info.php of this module
* @requirements PHP 5.2.x and higher
*/
// include class.secure.php to protect this file and the whole CMS!
if (defined('WB_PATH')) {
include(WB_PATH.'/framework/class.secure.php');
} else {
$oneback = "../";
$root = $oneback;
$level = 1;
while (($level < 10) && (!file_exists($root.'/framework/class.secure.php'))) {
$root .= $oneback;
$level += 1;
}
if (file_exists($root.'/framework/class.secure.php')) {
include($root.'/framework/class.secure.php');
} else {
trigger_error(sprintf("[ <b>%s</b> ] Can't include class.secure.php!", $_SERVER['SCRIPT_NAME']), E_USER_ERROR);
}
}
// end include class.secure.php
// end include class.secure.php
$database->query("DROP TABLE IF EXISTS `".TABLE_PREFIX."mod_editor_admin`");
$table = TABLE_PREFIX ."mod_wysiwyg_admin";
$database->query("DROP TABLE IF EXISTS `".$table."`");
$database->query("DELETE from `".TABLE_PREFIX."sections` where `section_id`='-1' AND `page_id`='-120'");
$database->query("DELETE from `".TABLE_PREFIX."mod_wysiwyg` where `section_id`='-1' AND `page_id`='-120'");
?> | Java |
#include <cmath>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include "params.h"
#include "pdg_name.h"
#include "parameters.h"
#include "LeptonMass.h"
//#include "jednostki.h"
#include "grv94_bodek.h"
#include "dis_cr_sec.h"
#include "fragmentation.h"
#include "vect.h"
#include "charge.h"
#include "event1.h"
#include <TMCParticle.h>
#include <TPythia6.h>
TPythia6 *pythia2 = new TPythia6 ();
extern "C" int pycomp_ (const int *);
void
dishadr (event & e, bool current, double hama, double entra)
{
////////////////////////////////////////////////////////////////////////////
// Setting Pythia parameters
// Done by Jaroslaw Nowak
//////////////////////////////////////////////
//stabilne pi0
pythia2->SetMDCY (pycomp_ (&pizero), 1, 0);
//C Thorpe: Adding Hyperons as stable dis particles
pythia2->SetMDCY (pycomp_ (&Lambda), 1, 0);
pythia2->SetMDCY (pycomp_ (&Sigma), 1, 0);
pythia2->SetMDCY (pycomp_ (&SigmaP), 1, 0);
pythia2->SetMDCY (pycomp_ (&SigmaM), 1, 0);
// C Thorpe: Stablize kaons
pythia22->SetMDCY ( pycomp_ (&DIS_PDG::Kplus) , 1, 0);
pythia22->SetMDCY ( pycomp_ (&DIS_PDG::Kzero) , 1, 0);
pythia22->SetMDCY ( pycomp_ (&DIS_PDG::Kminus) , 1, 0);
pythia2->SetMSTU (20, 1); //advirsory warning for unphysical flavour switch off
pythia2->SetMSTU (23, 1); //It sets counter of errors at 0
pythia2->SetMSTU (26, 0); //no warnings printed
// PARJ(32)(D=1GeV) is, with quark masses added, used to define the minimum allowable enrgy of a colour singlet parton system
pythia2->SetPARJ (33, 0.1);
// PARJ(33)-PARJ(34)(D=0.8GeV, 1.5GeV) are, with quark masses added, used to define the remaining energy below which
//the fragmentation of a parton system is stopped and two final hadrons formed.
pythia2->SetPARJ (34, 0.5);
pythia2->SetPARJ (35, 1.0);
//PARJ(36) (D=2.0GeV) represents the dependence of the mass of final quark pair for defining the stopping point of the
//fragmentation. Strongly corlated with PARJ(33-35)
pythia2->SetPARJ (37, 1.); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1
//MSTJ(17) (D=2) number of attemps made to find two hadrons that have a combined mass below the cluster mass and thus allow
// a cluster to decay rather than collaps
pythia2->SetMSTJ (18, 3); //do not change
/////////////////////////////////////////////////
// End of setting Pythia parameters
////////////////////////////////////////////////
double Mtrue = (PDG::mass_proton+PDG::mass_neutron)/2;
double Mtrue2 = Mtrue * Mtrue;
double W2 = hama * hama;
double nu = entra;
vect nuc0 = e.in[1];
vect nu0 = e.in[0];
nu0.boost (-nuc0.speed ()); //neutrino 4-momentum in the target rest frame
vec nulab = vec (nu0.x, nu0.y, nu0.z); //can be made simpler ???
int lepton = e.in[0].pdg;
int nukleon = e.in[1].pdg;
double m = lepton_mass (abs (lepton), current); //mass of the given lepton (see pgd header file)
double m2 = m * m;
double E = nu0.t;
double E2 = E * E;
int nParticle = 0;
int nCharged = 0;
int NPar = 0;
Pyjets_t *pythiaParticle; //deklaracja event recordu
double W1 = hama / GeV; //W1 w GeV-ach potrzebne do Pythii
while (NPar < 5)
{
hadronization (E, hama, entra, m, lepton, nukleon, current);
pythiaParticle = pythia2->GetPyjets ();
NPar = pythia2->GetN ();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////Kinematics
///////////////////////////////////////////////
//////////// The input data is: neutrinoo 4-momentum, invariant hadronic mass and energy transfer
//////////// With this data the kinematics is resolved
////////////////////////////////////////////////////
/////////// We know that nu^2-q^2= (k-k')^2=m^2-2*k.k'= m^2-2*E*(E-nu)+ 2*E*sqrt((E-nu)^2-m^2)*cos theta
///////////
/////////// (M+nu)^2-q^2=W^2
////////////
//////////// (k-q)^2= m^2 = nu^2-q^2 -2*E*nu + 2*E*q*cos beta
/////////////
///////////// theta is an angle between leptons and beta is an angle between neutrino and momentum transfer
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////// Of course it is not necessary to calculate vectors k' and q separately because of momentum conservation
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
double q = sqrt (kwad (Mtrue + nu) - W2);
double kprim = sqrt (kwad (E - nu) - m2);
double cth = (E2 + kprim * kprim - q * q) / 2 / E / kprim;
vec kkprim; //the unit vector in the direction of scattered lepton
kinfinder (nulab, kkprim, cth); //hopefully should produce kkprim
kkprim = kprim * kkprim; //multiplied by its length
vect lepton_out = vect (E - nu, kkprim.x, kkprim.y, kkprim.z);
vec momtran = nulab - kkprim;
vec hadrspeed = momtran / sqrt (W2 + q * q);
nParticle = pythia2->GetN ();
if (nParticle == 0)
{
cout << "nie ma czastek" << endl;
cin.get ();
}
vect par[100];
double ks[100]; //int czy double ???
par[0] = lepton_out;
//powrot do ukladu spoczywajacej tarczy
par[0] = par[0].boost (nuc0.speed ()); //ok
particle lept (par[0]);
if (current == true && lepton > 0)
{
lept.pdg = lepton - 1;
}
if (current == true && lepton < 0)
{
lept.pdg = lepton + 1;
}
if (current == false)
{
lept.pdg = lepton;
}
e.out.push_back (lept); //final lepton; ok
for (int i = 0; i < nParticle; i++)
{
par[i].t = pythiaParticle->P[3][i] * GeV;
par[i].x = pythiaParticle->P[0][i] * GeV;
par[i].y = pythiaParticle->P[1][i] * GeV;
par[i].z = pythiaParticle->P[2][i] * GeV;
rotation (par[i], momtran);
ks[i] = pythiaParticle->K[0][i];
par[i] = par[i].boost (hadrspeed); //correct direction ???
par[i] = par[i].boost (nuc0.speed ());
particle part (par[i]);
part.ks = pythiaParticle->K[0][i];
part.pdg = pythiaParticle->K[1][i];
part.orgin = pythiaParticle->K[2][i];
e.temp.push_back (part);
if (ks[i] == 1) //condition for a real particle in the final state
{
e.out.push_back (part);
}
}
}
| Java |
package example;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import com.piedra.excel.annotation.ExcelExport;
import com.piedra.excel.util.ExcelExportor;
/**
* @Description: Excel导出工具 例子程序
* @Creator:linwb 2014-12-19
*/
public class ExcelExportorExample {
public static void main(String[] args) {
new ExcelExportorExample().testSingleHeader();
new ExcelExportorExample().testMulHeaders();
}
/**
* @Description: 测试单表头
* @History
* 1. 2014-12-19 linwb 创建方法
*/
@Test
public void testSingleHeader(){
OutputStream out = null;
try {
out = new FileOutputStream(new File("C://EXCEL-EXPORT-TEST.xls"));
List<ExcelRow> stus = new ArrayList<ExcelRow>();
for(int i=0; i<11120; i++){
stus.add(new ExcelRow());
}
new ExcelExportor<ExcelRow>().exportExcel("测试单表头", stus, out);
System.out.println("excel导出成功!");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(out!=null){
try {
out.close();
} catch (IOException e) {
//Ignore..
} finally{
out = null;
}
}
}
}
/**
* @Description: 测试多表头
* @History
* 1. 2014-12-19 linwb 创建方法
*/
@Test
public void testMulHeaders(){
OutputStream out = null;
try {
out = new FileOutputStream(new File("C://EXCEL-EXPORT-TEST-MULTIHEADER.xls"));
List<ExcelRowForMultiHeaders> stus = new ArrayList<ExcelRowForMultiHeaders>();
for(int i=0; i<1120; i++){
stus.add(new ExcelRowForMultiHeaders());
}
new ExcelExportor<ExcelRowForMultiHeaders>().exportExcel("测试多表头", stus, out);
System.out.println("excel导出成功!");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(out!=null){
try {
out.close();
} catch (IOException e) {
//Ignore..
} finally{
out = null;
}
}
}
}
}
/**
* @Description: Excel的一行对应的JavaBean类
* @Creator:linwb 2014-12-19
*/
class ExcelRow {
@ExcelExport(header="姓名",colWidth=50)
private String name="AAAAAAAAAAASSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS";
@ExcelExport(header="年龄")
private int age=80;
/** 这个属性没别注解,那么将不会出现在导出的excel文件中*/
private String clazz="SSSSSSSSS";
@ExcelExport(header="国家")
private String country="RRRRRRR";
@ExcelExport(header="城市")
private String city="EEEEEEEEE";
@ExcelExport(header="城镇")
private String town="WWWWWWW";
/** 这个属性没别注解,那么将不会出现在导出的excel文件中*/
private String common="DDDDDDDD";
/** 如果colWidth <= 0 那么取默认的 15 */
@ExcelExport(header="出生日期",colWidth=-1)
private Date birth = new Date();
public ExcelRow(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getClazz() {
return clazz;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
public String getCommon() {
return common;
}
public void setCommon(String common) {
this.common = common;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
}
/**
* @Description: Excel的一行对应的JavaBean类
* @Creator:linwb 2014-12-19
*/
class ExcelRowForMultiHeaders {
@ExcelExport(header="姓名",colspan="1",rowspan="3")
private String name="无名氏";
@ExcelExport(header="省份,国家",colspan="1,5",rowspan="1,2")
private String province="福建省";
@ExcelExport(header="城市",colspan="1",rowspan="1")
private String city="福建省";
@ExcelExport(header="城镇",colspan="1",rowspan="1")
private String town="不知何处";
@ExcelExport(header="年龄,年龄和备注",colspan="1,2",rowspan="1,1")
private int age=80;
@ExcelExport(header="备注?",colspan="1",rowspan="1")
private String common="我是备注,我是备注";
@ExcelExport(header="我的生日",colspan="1",rowspan="3",datePattern="yyyy-MM-dd HH:mm:ss")
private Date birth = new Date();
/** 这个属性没别注解,那么将不会出现在导出的excel文件中*/
private String clazz="我不会出现的,除非你给我 @ExcelExport 注解标记";
public ExcelRowForMultiHeaders(){
}
public String getClazz() {
return clazz;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCommon() {
return common;
}
public void setCommon(String common) {
this.common = common;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
}
| Java |
/***************************************************************************
* Project file: NPlugins - NCore - BasicHttpClient.java *
* Full Class name: fr.ribesg.com.mojang.api.http.BasicHttpClient *
* *
* Copyright (c) 2012-2014 Ribesg - www.ribesg.fr *
* This file is under GPLv3 -> http://www.gnu.org/licenses/gpl-3.0.txt *
* Please contact me at ribesg[at]yahoo.fr if you improve this file! *
***************************************************************************/
package fr.ribesg.com.mojang.api.http;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.util.List;
public class BasicHttpClient implements HttpClient {
private static BasicHttpClient instance;
private BasicHttpClient() {
}
public static BasicHttpClient getInstance() {
if (instance == null) {
instance = new BasicHttpClient();
}
return instance;
}
@Override
public String post(final URL url, final HttpBody body, final List<HttpHeader> headers) throws IOException {
return this.post(url, null, body, headers);
}
@Override
public String post(final URL url, Proxy proxy, final HttpBody body, final List<HttpHeader> headers) throws IOException {
if (proxy == null) {
proxy = Proxy.NO_PROXY;
}
final HttpURLConnection connection = (HttpURLConnection)url.openConnection(proxy);
connection.setRequestMethod("POST");
for (final HttpHeader header : headers) {
connection.setRequestProperty(header.getName(), header.getValue());
}
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
final DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
writer.write(body.getBytes());
writer.flush();
writer.close();
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
final StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
response.append('\r');
}
reader.close();
return response.toString();
}
}
| Java |
/*
Fomalhaut
Copyright (C) 2014 mtgto
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#import <RoutingHTTPServer/RoutingConnection.h>
@interface RoutingConnection (Secure)
@end
| Java |
#!/usr/bin/env node
/*jshint -W100*/
'use strict';
/**
* ニコニコ動画ログインサンプル
*
* 以下のusernameとpasswordを書き換えてから実行してください
*/
var username = 'hogehoge';
var password = 'fugafuga';
var client = require('../index');
console.info('ニコニコTOPページにアクセスします');
client.fetch('http://nicovideo.jp/')
.then(function (result) {
console.info('ログインリンクをクリックします');
return result.$('#sideNav .loginBtn').click();
})
.then(function (result) {
console.info('ログインフォームを送信します');
return result.$('#login_form').submit({
mail_tel: username,
password: password
});
})
.then(function (result) {
console.info('ログイン可否をチェックします');
if (! result.response.headers['x-niconico-id']) {
throw new Error('login failed');
}
console.info('クッキー', result.response.cookies);
console.info('マイページに移動します');
return client.fetch('http://www.nicovideo.jp/my/top');
})
.then(function (result) {
console.info('マイページに表示されるアカウント名を取得します');
console.info(result.$('#siteHeaderUserNickNameContainer').text());
})
.catch(function (err) {
console.error('エラーが発生しました', err.message);
})
.finally(function () {
console.info('終了します');
});
| Java |
// Copyright (c) 2018 - 2020, Marcin Drob
// Kainote 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.
// Kainote 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 Kainote. If not, see <http://www.gnu.org/licenses/>.
#pragma once
#include <wx/window.h>
#include <wx/thread.h>
//#define Get_Log LogHandler::Get()
class LogWindow;
class LogHandler
{
friend class LogWindow;
private:
LogHandler(wxWindow *parent);
~LogHandler();
static LogHandler *sthis;
wxString logToAppend;
wxString lastLog;
LogWindow *lWindow = NULL;
wxMutex mutex;
wxWindow *parent;
public:
static void Create(wxWindow *parent);
static LogHandler *Get(){ return sthis; }
static void Destroy();
void LogMessage(const wxString &format, bool showMessage = true);
static void ShowLogWindow();
//void LogMessage1(const wxString &format, ...);
};
static void KaiLog(const wxString &text){
LogHandler * handler = LogHandler::Get();
if (handler)
handler->LogMessage(text);
}
static void KaiLogSilent(const wxString &text) {
LogHandler * handler = LogHandler::Get();
if (handler)
handler->LogMessage(text, false);
}
static void KaiLogDebug(const wxString &text){
#if _DEBUG
LogHandler * handler = LogHandler::Get();
if (handler)
handler->LogMessage(text);
#endif
} | Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_66) on Sat Nov 28 10:51:55 EST 2015 -->
<title>VariableQuantumIndexWriter (MG4J (big) 5.4.1)</title>
<meta name="date" content="2015-11-28">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="VariableQuantumIndexWriter (MG4J (big) 5.4.1)";
}
}
catch(err) {
}
//-->
var methods = {"i0":6};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../it/unimi/di/big/mg4j/index/TooManyTermsException.html" title="class in it.unimi.di.big.mg4j.index"><span class="typeNameLink">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?it/unimi/di/big/mg4j/index/VariableQuantumIndexWriter.html" target="_top">Frames</a></li>
<li><a href="VariableQuantumIndexWriter.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">it.unimi.di.big.mg4j.index</div>
<h2 title="Interface VariableQuantumIndexWriter" class="title">Interface VariableQuantumIndexWriter</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="../../../../../../it/unimi/di/big/mg4j/index/BitStreamHPIndexWriter.html" title="class in it.unimi.di.big.mg4j.index">BitStreamHPIndexWriter</a>, <a href="../../../../../../it/unimi/di/big/mg4j/index/SkipBitStreamIndexWriter.html" title="class in it.unimi.di.big.mg4j.index">SkipBitStreamIndexWriter</a></dd>
</dl>
<hr>
<br>
<pre>public interface <span class="typeNameLabel">VariableQuantumIndexWriter</span></pre>
<div class="block">An index writer supporting variable quanta.
<p>This interface provides an additional <a href="../../../../../../it/unimi/di/big/mg4j/index/VariableQuantumIndexWriter.html#newInvertedList-long-double-long-long-"><code>newInvertedList(long, double, long, long)</code></a> method
that accepts additional information. That information is used to compute the correct quantum
size for a specific list. This approach makes it possible to specify a target fraction of
the index that will be used to store skipping information.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>long</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../it/unimi/di/big/mg4j/index/VariableQuantumIndexWriter.html#newInvertedList-long-double-long-long-">newInvertedList</a></span>(long predictedFrequency,
double skipFraction,
long predictedSize,
long predictedPositionsSize)</code>
<div class="block">Starts a new inverted list.</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="newInvertedList-long-double-long-long-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>newInvertedList</h4>
<pre>long newInvertedList(long predictedFrequency,
double skipFraction,
long predictedSize,
long predictedPositionsSize)
throws <a href="http://download.oracle.com/javase/6/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></pre>
<div class="block">Starts a new inverted list. The previous inverted list, if any, is actually written
to the underlying bit stream.
<p>This method provides additional information that will be used to compute the
correct quantum for the skip structure of the inverted list.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>predictedFrequency</code> - the predicted frequency of the inverted list; this might
just be an approximation.</dd>
<dd><code>skipFraction</code> - the fraction of the inverted list that will be dedicated to
skipping structures.</dd>
<dd><code>predictedSize</code> - the predicted size of the part of the inverted list that stores
terms and counts.</dd>
<dd><code>predictedPositionsSize</code> - the predicted size of the part of the inverted list that
stores positions.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the position (in bits) of the underlying bit stream where the new inverted
list starts.</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code><a href="http://download.oracle.com/javase/6/docs/api/java/lang/IllegalStateException.html?is-external=true" title="class or interface in java.lang">IllegalStateException</a></code> - if too few records were written for the previous inverted
list.</dd>
<dd><code><a href="http://download.oracle.com/javase/6/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></code></dd>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../../../it/unimi/di/big/mg4j/index/IndexWriter.html#newInvertedList--"><code>IndexWriter.newInvertedList()</code></a></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../it/unimi/di/big/mg4j/index/TooManyTermsException.html" title="class in it.unimi.di.big.mg4j.index"><span class="typeNameLink">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?it/unimi/di/big/mg4j/index/VariableQuantumIndexWriter.html" target="_top">Frames</a></li>
<li><a href="VariableQuantumIndexWriter.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| Java |
#!/usr/bin/python
# coding: utf8
import os
import subprocess
from '{% if cookiecutter.namespace %}{{ cookiecutter.namespace }}.{{ cookiecutter.project_slug }}{% else %}{{ cookiecutter.project_slug }}{% endif %}'.commands.base import BaseCommand
from '{% if cookiecutter.namespace %}{{ cookiecutter.namespace }}.{{ cookiecutter.project_slug }}{% else %}{{ cookiecutter.project_slug }}{% endif %}' import PROJECT_DIR
class Configure(BaseCommand):
def execute(self):
os.chdir(os.path.join(PROJECT_DIR, 'build'))
subprocess.run(['cmake', PROJECT_DIR])
| Java |
<a href
tabindex="-1"
ng-attr-title="{{match.label}}">
<span ng-bind-html="match.label.artist | uibTypeaheadHighlight:query"></span>
<br>
<small ng-bind-html="match.label.title | uibTypeaheadHighlight:query"></small>
</a>
| Java |
package Eac.event;
import Eac.Eac;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent;
import net.minecraft.item.ItemStack;
public class EacOnItemPickup extends Eac {
@SubscribeEvent
public void EacOnItemPickup(PlayerEvent.ItemPickupEvent e) {
if (e.pickedUp.getEntityItem().isItemEqual(new ItemStack(oreAir))) {
e.player.addStat(airoremined, 1);
}
else if (e.pickedUp.getEntityItem().isItemEqual(new ItemStack(oreShadow))) {
e.player.addStat(shadoworemined, 1);
}
}
}
| Java |
class PasswordResetsController < ApplicationController
def new
end
def create
@user = User.find_by_email(params[:email])
if @user
@user.deliver_reset_password_instructions!
redirect_to root_path, notice: 'Instructions have been sent to your email.'
else
flash.now[:alert] = "Sorry but we don't recognise the email address \"#{params[:email]}\"."
render :new
end
end
def edit
@user = User.load_from_reset_password_token(params[:id])
@token = params[:id]
if @user.blank?
not_authenticated
return
end
end
def update
@user = User.load_from_reset_password_token(params[:id])
@token = params[:id]
if @user.blank?
not_authenticated
return
end
@user.password_confirmation = params[:user][:password_confirmation]
if @user.change_password!(params[:user][:password])
redirect_to signin_path, notice: 'Password was successfully updated.'
else
render :edit
end
end
end
| Java |
/*
* Copyright 2011 Mect s.r.l
*
* This file is part of FarosPLC.
*
* FarosPLC 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.
*
* FarosPLC 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
* FarosPLC. If not, see http://www.gnu.org/licenses/.
*/
/*
* Filename: BuildNr.h
*/
/* application build number: */
#define PRODUCT_BUILD 4001
/* EOF */
| Java |
//
// DetailViewController.h
// ScrollView+PaperFold+PageControl
//
// Created by Jun Seki on 13/06/2014.
// Copyright (c) 2014 Poq Studio. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "PaperFoldView.h"
#import "SwipeView.h"
@interface DetailViewController : UIViewController <UISplitViewControllerDelegate,PaperFoldViewDelegate,SwipeViewDataSource, SwipeViewDelegate>
@property (strong, nonatomic) id detailItem;
@property (nonatomic, strong) IBOutlet PaperFoldView *paperFoldView;
@property (nonatomic, strong) UIView *topView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UILabel *detailDescriptionLabel;
@property (nonatomic, strong) IBOutlet SwipeView *swipeView;
@property (nonatomic, strong) NSMutableArray *items;
@end
| Java |
/*
* This file is part of gap.
*
* gap is free software: you can redistribute it and/or modify
* under the terms of the GNU General Public License as published by
* Free Software Foundation, either version 3 of the License, or
* your option) any later version.
*
* gap is distributed in the hope that it will be useful,
* WITHOUT ANY WARRANTY; without even the implied warranty of
* CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with gap. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _OPT_H
#define _OPT_H
#include <assert.h>
#define OPT_RELAX_CAPACITY 0
#define OPT_RELAX_CAPACITY_NAME "capacity"
#define OPT_RELAX_QUANTITY 1
#define OPT_RELAX_QUANTITY_NAME "quantity"
typedef struct
{
double alpha;
char *file;
int relax;
int verbose;
} Options;
void opt_free (Options * opt);
static inline double
opt_get_alpha (Options * opt)
{
return opt->alpha;
}
static inline char *
opt_get_file (Options * opt)
{
return opt->file;
}
static inline int
opt_get_relax (Options * opt)
{
return opt->relax;
}
static inline int
opt_get_verbose (Options * opt)
{
return opt->verbose;
}
Options *opt_new ();
static inline void
opt_set_alpha (Options * opt, double alpha)
{
opt->alpha = alpha;
}
static inline void
opt_set_file (Options * opt, char *file)
{
opt->file = file;
}
static inline void
opt_set_relax (Options * opt, int relax)
{
opt->relax = relax;
}
static inline void
opt_set_verbose (Options * opt, int verbose)
{
opt->verbose = verbose;
}
#endif
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.