code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
// @flow import React, { Component } from 'react' import { withStyles } from 'material-ui/styles' import Profile from 'models/Profile' import IconButton from 'material-ui/IconButton' import Typography from 'material-ui/Typography' import FontAwesome from 'react-fontawesome' import Avatar from 'components/common/Avatar' import Pubkey from 'components/common/Pubkey' import InsetText from 'components/common/InsetText' class ShowProfile extends Component { props: { profile: Profile, onEditClick: () => any } render() { const { classes, profile } = this.props return ( <div> <div className={classes.header}> <div className={classes.lateral} /> <Typography className={classes.identity}>{profile.identity}</Typography> <IconButton className={classes.lateral} onClick={this.props.onEditClick}><FontAwesome name="pencil" /></IconButton> </div> { profile.avatarUrl ? <Avatar person={profile} className={classes.avatar} /> : <div className={classes.noAvatar}><Typography>No avatar</Typography></div> } <InsetText text={profile.bio} placeholder='No biography' /> <Typography align="center" variant="body2"> Share your Arbore ID </Typography> <Pubkey pubkey={profile.pubkey} /> </div> ) } } const style = theme => ({ header: { display: 'flex', flexDirection: 'row', alignItems: 'center', margin: '10px 0 20px', }, avatar: { width: '200px !important', height: '200px !important', margin: 'auto', userSelect: 'none', pointerEvents: 'none', }, noAvatar: { width: 200, height: 200, borderRadius: '50%', backgroundColor: theme.palette.background.dark, margin: 'auto', display: 'flex', justifyContent: 'center', alignItems: 'center', }, identity: { margin: '0 10px 0 !important', fontSize: '2em !important', textAlign: 'center', flexGrow: 1, }, lateral: { width: '20px !important', }, }) export default withStyles(style)(ShowProfile)
MichaelMure/TotallyNotArbore
app/components/profile/ShowProfile.js
JavaScript
gpl-3.0
2,101
----------------------------------- -- Area: North Gustaberg (S) (88) -- Mob: Five_Moons ----------------------------------- -- require("scripts/zones/North_Gustaberg_[S]/MobIDs"); ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobSpawn ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobFight ----------------------------------- function onMobFight(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) end;
salamader/ffxi-a
scripts/zones/North_Gustaberg_[S]/mobs/Five_Moons.lua
Lua
gpl-3.0
816
package fr.ybo.transportscommun.activity.commun; import android.widget.ImageButton; public interface ChangeIconActionBar { public void changeIconActionBar(ImageButton imageButton); }
ybonnel/TransportsRennes
TransportsCommun/src/fr/ybo/transportscommun/activity/commun/ChangeIconActionBar.java
Java
gpl-3.0
188
/* Copyright (C) 2003-2013 Runtime Revolution Ltd. This file is part of LiveCode. LiveCode is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License v3 as published by the Free Software Foundation. LiveCode 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 LiveCode. If not see <http://www.gnu.org/licenses/>. */ #include "prefix.h" #include "globdefs.h" #include "png.h" #include "filedefs.h" #include "objdefs.h" #include "parsedef.h" #include "mcio.h" #include "uidc.h" #include "util.h" #include "image.h" #include "globals.h" #include "imageloader.h" #define NATIVE_ALPHA_BEFORE ((kMCGPixelFormatNative & kMCGPixelAlphaPositionFirst) == kMCGPixelAlphaPositionFirst) #define NATIVE_ORDER_BGR ((kMCGPixelFormatNative & kMCGPixelOrderRGB) == 0) #if NATIVE_ALPHA_BEFORE #define MCPNG_FILLER_POSITION PNG_FILLER_BEFORE #else #define MCPNG_FILLER_POSITION PNG_FILLER_AFTER #endif extern "C" void fakeread(png_structp png_ptr, png_bytep data, png_size_t length) { uint8_t **t_data_ptr = (uint8_t**)png_get_io_ptr(png_ptr); memcpy(data, *t_data_ptr, length); *t_data_ptr += length; } extern "C" void fakeflush(png_structp png_ptr) {} bool MCImageValidatePng(const void *p_data, uint32_t p_length, uint16_t& r_width, uint16_t& r_height) { png_structp png_ptr; png_ptr = png_create_read_struct((char *)PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); png_infop info_ptr; info_ptr = png_create_info_struct(png_ptr); png_infop end_info_ptr; end_info_ptr = png_create_info_struct(png_ptr); // If we return to this point, its an error. if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, &end_info_ptr); return false; } png_set_read_fn(png_ptr, &p_data, fakeread); png_read_info(png_ptr, info_ptr); png_uint_32 width, height; int interlace_type, compression_type, filter_type, bit_depth, color_type; png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_type); png_destroy_read_struct(&png_ptr, &info_ptr, &end_info_ptr); r_width = (uint16_t)width; r_height = (uint16_t)height; return true; } //////////////////////////////////////////////////////////////////////////////// extern "C" void stream_read(png_structp png_ptr, png_bytep data, png_size_t length) { IO_handle t_stream = (IO_handle)png_get_io_ptr(png_ptr); uint4 t_length; t_length = length; if (IO_read(data, length, t_stream) != IO_NORMAL) png_error(png_ptr, (char *)"pnglib read error"); } static void MCPNGSetNativePixelFormat(png_structp p_png) { #if NATIVE_ORDER_BGR png_set_bgr(p_png); #endif #if NATIVE_ALPHA_BEFORE png_set_swap_alpha(p_png); #endif } class MCPNGImageLoader : public MCImageLoader { public: MCPNGImageLoader(IO_handle p_stream); virtual ~MCPNGImageLoader(); virtual MCImageLoaderFormat GetFormat() { return kMCImageFormatPNG; } protected: virtual bool LoadHeader(uint32_t &r_width, uint32_t &r_height, uint32_t &r_xhot, uint32_t &r_yhot, MCStringRef &r_name, uint32_t &r_frame_count, MCImageMetadata &r_metadata); virtual bool LoadFrames(MCBitmapFrame *&r_frames, uint32_t &r_count); private: png_structp m_png; png_infop m_info; png_infop m_end_info; int m_bit_depth; int m_color_type; }; MCPNGImageLoader::MCPNGImageLoader(IO_handle p_stream) : MCImageLoader(p_stream) { m_png = nil; m_info = nil; m_end_info = nil; } MCPNGImageLoader::~MCPNGImageLoader() { if (m_png != nil) png_destroy_read_struct(&m_png, &m_info, &m_end_info); } bool MCPNGImageLoader::LoadHeader(uint32_t &r_width, uint32_t &r_height, uint32_t &r_xhot, uint32_t &r_yhot, MCStringRef &r_name, uint32_t &r_frame_count, MCImageMetadata &r_metadata) { bool t_success = true; t_success = nil != (m_png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)); if (t_success) t_success = nil != (m_info = png_create_info_struct(m_png)); if (t_success) t_success = nil != (m_end_info = png_create_info_struct(m_png)); if (t_success) { if (setjmp(png_jmpbuf(m_png))) { t_success = false; } } if (t_success) { png_set_read_fn(m_png, GetStream(), stream_read); png_read_info(m_png, m_info); } png_uint_32 t_width, t_height; int t_interlace_method, t_compression_method, t_filter_method; if (t_success) { png_get_IHDR(m_png, m_info, &t_width, &t_height, &m_bit_depth, &m_color_type, &t_interlace_method, &t_compression_method, &t_filter_method); } // MERG-2014-09-12: [[ ImageMetadata ]] load image metatadata if (t_success) { uint32_t t_X; uint32_t t_Y; int t_units; if (png_get_pHYs(m_png, m_info, &t_X, &t_Y, &t_units) && t_units != PNG_RESOLUTION_UNKNOWN) { MCImageMetadata t_metadata; MCMemoryClear(&t_metadata, sizeof(t_metadata)); t_metadata.has_density = true; t_metadata.density = floor(t_X * 0.0254 + 0.5); r_metadata = t_metadata; } } if (t_success) { r_width = t_width; r_height = t_height; r_xhot = r_yhot = 0; r_name = MCValueRetain(kMCEmptyString); r_frame_count = 1; } return t_success; } bool MCPNGImageLoader::LoadFrames(MCBitmapFrame *&r_frames, uint32_t &r_count) { bool t_success = true; MCBitmapFrame *t_frame; t_frame = nil; MCColorTransformRef t_color_xform; t_color_xform = nil; if (setjmp(png_jmpbuf(m_png))) { t_success = false; } int t_interlace_passes; uint32_t t_width, t_height; if (t_success) t_success = GetGeometry(t_width, t_height); if (t_success) t_success = MCMemoryNew(t_frame); if (t_success) t_success = MCImageBitmapCreate(t_width, t_height, t_frame->image); if (t_success) { bool t_need_alpha = false; t_interlace_passes = png_set_interlace_handling(m_png); if (m_color_type == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(m_png); if (m_color_type == PNG_COLOR_TYPE_GRAY || m_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(m_png); if (png_get_valid(m_png, m_info, PNG_INFO_tRNS)) { png_set_tRNS_to_alpha(m_png); t_need_alpha = true; /* OVERHAUL - REVISIT - assume image has transparent pixels if tRNS is present */ t_frame->image->has_transparency = true; } if (m_color_type & PNG_COLOR_MASK_ALPHA) { t_need_alpha = true; /* OVERHAUL - REVISIT - assume image has alpha if color type allows it */ t_frame->image->has_alpha = t_frame->image->has_transparency = true; } else if (!t_need_alpha) png_set_add_alpha(m_png, 0xFF, MCPNG_FILLER_POSITION); if (m_bit_depth == 16) png_set_strip_16(m_png); MCPNGSetNativePixelFormat(m_png); } // MW-2009-12-10: Support for color profiles // Try to get an embedded ICC profile... if (t_success && t_color_xform == nil && png_get_valid(m_png, m_info, PNG_INFO_iCCP)) { png_charp t_ccp_name; png_bytep t_ccp_profile; int t_ccp_compression_type; png_uint_32 t_ccp_profile_length; png_get_iCCP(m_png, m_info, &t_ccp_name, &t_ccp_compression_type, &t_ccp_profile, &t_ccp_profile_length); MCColorSpaceInfo t_csinfo; t_csinfo . type = kMCColorSpaceEmbedded; t_csinfo . embedded . data = t_ccp_profile; t_csinfo . embedded . data_size = t_ccp_profile_length; t_color_xform = MCscreen -> createcolortransform(t_csinfo); } // Next try an sRGB style profile... if (t_success && t_color_xform == nil && png_get_valid(m_png, m_info, PNG_INFO_sRGB)) { int t_intent; png_get_sRGB(m_png, m_info, &t_intent); MCColorSpaceInfo t_csinfo; t_csinfo . type = kMCColorSpaceStandardRGB; t_csinfo . standard . intent = (MCColorSpaceIntent)t_intent; t_color_xform = MCscreen -> createcolortransform(t_csinfo); } // Finally try for cHRM + gAMA... if (t_success && t_color_xform == nil && png_get_valid(m_png, m_info, PNG_INFO_cHRM) && png_get_valid(m_png, m_info, PNG_INFO_gAMA)) { MCColorSpaceInfo t_csinfo; t_csinfo . type = kMCColorSpaceCalibratedRGB; png_get_cHRM(m_png, m_info, &t_csinfo . calibrated . white_x, &t_csinfo . calibrated . white_y, &t_csinfo . calibrated . red_x, &t_csinfo . calibrated . red_y, &t_csinfo . calibrated . green_x, &t_csinfo . calibrated . green_y, &t_csinfo . calibrated . blue_x, &t_csinfo . calibrated . blue_y); png_get_gAMA(m_png, m_info, &t_csinfo . calibrated . gamma); t_color_xform = MCscreen -> createcolortransform(t_csinfo); } // Could not create any kind, so fallback to gamma transform. if (t_success && t_color_xform == nil) { double image_gamma; if (png_get_gAMA(m_png, m_info, &image_gamma)) png_set_gamma(m_png, MCgamma, image_gamma); else png_set_gamma(m_png, MCgamma, 0.45); } if (t_success) { for (uindex_t t_pass = 0; t_pass < t_interlace_passes; t_pass++) { png_bytep t_data_ptr = (png_bytep)t_frame->image->data; for (uindex_t i = 0; i < t_height; i++) { png_read_row(m_png, t_data_ptr, nil); t_data_ptr += t_frame->image->stride; } } } if (t_success) png_read_end(m_png, m_end_info); // transform colours using extracted colour profile if (t_success && t_color_xform != nil) MCImageBitmapApplyColorTransform(t_frame->image, t_color_xform); if (t_color_xform != nil) MCscreen -> destroycolortransform(t_color_xform); if (t_success) { r_frames = t_frame; r_count = 1; } else MCImageFreeFrames(t_frame, 1); return t_success; } bool MCImageLoaderCreateForPNGStream(IO_handle p_stream, MCImageLoader *&r_loader) { MCPNGImageLoader *t_loader; t_loader = new MCPNGImageLoader(p_stream); if (t_loader == nil) return false; r_loader = t_loader; return true; } //////////////////////////////////////////////////////////////////////////////// // embed stream within wrapper struct containing byte count // so we can update byte_count as we go struct MCPNGWriteContext { IO_handle stream; uindex_t byte_count; }; extern "C" void fakewrite(png_structp png_ptr, png_bytep data, png_size_t length) { MCPNGWriteContext *t_context = (MCPNGWriteContext*)png_get_io_ptr(png_ptr); if (IO_write(data, sizeof(uint1), length, t_context->stream) != IO_NORMAL) png_error(png_ptr, (char *)"pnglib write error"); t_context->byte_count += length; } // MERG-2014-07-16: [[ ImageMetadata ]] Parse the metadata array static void parsemetadata(png_structp png_ptr, png_infop info_ptr, MCImageMetadata *p_metadata) { if (p_metadata == nil) return; if (p_metadata -> has_density) { real64_t t_ppi = p_metadata -> density; if (t_ppi > 0) { // Convert to pixels per metre from pixels per inch png_set_pHYs(png_ptr, info_ptr, t_ppi / 0.0254, t_ppi / 0.0254, PNG_RESOLUTION_METER); } } } bool MCImageEncodePNG(MCImageIndexedBitmap *p_indexed, MCImageMetadata *p_metadata, IO_handle p_stream, uindex_t &r_bytes_written) { bool t_success = true; MCPNGWriteContext t_context; t_context.stream = p_stream; t_context.byte_count = 0; png_structp t_png_ptr = nil; png_infop t_info_ptr = nil; png_color *t_png_palette = nil; png_byte *t_png_transparency = nil; png_bytep t_data_ptr = nil; uindex_t t_stride = 0; /*init png stuff*/ if (t_success) { t_success = nil != (t_png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL, (png_error_ptr)NULL, (png_error_ptr)NULL)); } if (t_success) t_success = nil != (t_info_ptr = png_create_info_struct(t_png_ptr)); /*in case of png error*/ if (setjmp(png_jmpbuf(t_png_ptr))) t_success = false; if (t_success) png_set_write_fn(t_png_ptr,(png_voidp)&t_context,fakewrite,fakeflush); if (t_success) { png_set_IHDR(t_png_ptr, t_info_ptr, p_indexed->width, p_indexed->height, 8, PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_set_gAMA(t_png_ptr, t_info_ptr, 1/MCgamma); } // MERG-2014-07-16: [[ ImageMetadata ]] Parse the metadata array if (t_success) parsemetadata(t_png_ptr, t_info_ptr, p_metadata); if (t_success) t_success = MCMemoryNewArray(p_indexed->palette_size, t_png_palette); /*create palette for 8 bit*/ if (t_success) { for (uindex_t i = 0; i < p_indexed->palette_size ; i++) { t_png_palette[i].red = p_indexed->palette[i].red >> 8; t_png_palette[i].green = p_indexed->palette[i].green >> 8; t_png_palette[i].blue = p_indexed->palette[i].blue >> 8; } png_set_PLTE(t_png_ptr, t_info_ptr, t_png_palette, p_indexed->palette_size); } if (MCImageIndexedBitmapHasTransparency(p_indexed)) { if (t_success) t_success = MCMemoryAllocate(p_indexed->palette_size, t_png_transparency); if (t_success) { memset(t_png_transparency, 0xFF, p_indexed->palette_size); t_png_transparency[p_indexed->transparent_index] = 0x00; png_set_tRNS(t_png_ptr, t_info_ptr, t_png_transparency, p_indexed->palette_size, NULL); } } if (t_success) png_write_info(t_png_ptr, t_info_ptr); if (t_success) { t_data_ptr = (png_bytep)p_indexed->data; t_stride = p_indexed->stride; } if (t_success) { for (uindex_t i = 0; i < p_indexed->height; i++) { png_write_row(t_png_ptr, t_data_ptr); t_data_ptr += t_stride; } } if (t_success) png_write_end(t_png_ptr, t_info_ptr); if (t_png_ptr != nil) png_destroy_write_struct(&t_png_ptr, &t_info_ptr); if (t_png_palette != nil) MCMemoryDeleteArray(t_png_palette); if (t_png_transparency != nil) MCMemoryDeallocate(t_png_transparency); if (t_success) r_bytes_written = t_context.byte_count; return t_success; } bool MCImageEncodePNG(MCImageBitmap *p_bitmap, MCImageMetadata *p_metadata, IO_handle p_stream, uindex_t &r_bytes_written) { bool t_success = true; MCPNGWriteContext t_context; t_context.stream = p_stream; t_context.byte_count = 0; png_structp t_png_ptr = nil; png_infop t_info_ptr = nil; png_color *t_png_palette = nil; png_byte *t_png_transparency = nil; png_bytep t_data_ptr = nil; uindex_t t_stride = 0; MCImageIndexedBitmap *t_indexed = nil; if (MCImageConvertBitmapToIndexed(p_bitmap, false, t_indexed)) { t_success = MCImageEncodePNG(t_indexed, p_metadata, p_stream, r_bytes_written); MCImageFreeIndexedBitmap(t_indexed); return t_success; } /*init png stuff*/ if (t_success) { t_success = nil != (t_png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL, (png_error_ptr)NULL, (png_error_ptr)NULL)); } if (t_success) t_success = nil != (t_info_ptr = png_create_info_struct(t_png_ptr)); /*in case of png error*/ if (setjmp(png_jmpbuf(t_png_ptr))) t_success = false; if (t_success) png_set_write_fn(t_png_ptr,(png_voidp)&t_context,fakewrite,fakeflush); bool t_fully_opaque = true; if (t_success) { t_fully_opaque = !MCImageBitmapHasTransparency(p_bitmap); png_set_IHDR(t_png_ptr, t_info_ptr, p_bitmap->width, p_bitmap->height, 8, t_fully_opaque ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_set_gAMA(t_png_ptr, t_info_ptr, 1/MCgamma); } // MERG-2014-07-16: [[ ImageMetadata ]] Parse the metadata array if (t_success) parsemetadata(t_png_ptr, t_info_ptr, p_metadata); if (t_success) { png_write_info(t_png_ptr, t_info_ptr); if (t_fully_opaque) png_set_filler(t_png_ptr, 0, MCPNG_FILLER_POSITION); MCPNGSetNativePixelFormat(t_png_ptr); } if (t_success) { t_data_ptr = (png_bytep)p_bitmap->data; t_stride = p_bitmap->stride; } if (t_success) { for (uindex_t i = 0; i < p_bitmap->height; i++) { png_write_row(t_png_ptr, t_data_ptr); t_data_ptr += t_stride; } } if (t_success) png_write_end(t_png_ptr, t_info_ptr); if (t_png_ptr != nil) png_destroy_write_struct(&t_png_ptr, &t_info_ptr); if (t_png_palette != nil) MCMemoryDeleteArray(t_png_palette); if (t_png_transparency != nil) MCMemoryDeallocate(t_png_transparency); if (t_success) r_bytes_written = t_context.byte_count; return t_success; } ////////////////////////////////////////////////////////////////////////////////
bright-sparks/livecode
engine/src/ipng.cpp
C++
gpl-3.0
16,341
<?php ob_start(); session_start(); if (session_status() == PHP_SESSION_NONE) { require_once('index.php'); header($uri . '/index.php'); } ?> <html> <head> <meta charset="UTF-8"> <meta name="description" content="Creates a new University by a Super Admin"> <title>Create University</title> <link rel = "stylesheet" href = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="styles.css"> </head> <body> <div class="container form-sigin"> <?php //HTML tags for error messages $err = "<h4 class=\"form-signin-error\">"; $suc = "<h4 class=\"form-signin-success\">"; $end = "</h4>"; $success = $rso = ""; $rsoErr = ""; $missing_data = []; $name = []; //Populates dropdown require_once('connect.php'); $queryDB = "SELECT * FROM rso"; $result = mysqli_query($database, $queryDB); if(mysqli_num_rows($result) > 0){ while($row = mysqli_fetch_assoc($result)){ array_push($name,$row['name']); } } if (empty($_POST["rsoSel"])) { $missing_data[] = "RSO"; $rsoErr = $err."RSO is required".$end; } else { $rso = trim_input($_POST["rsoSel"]); } // Check for each required input data that has been POSTed through Request Method if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($missing_data)) { require_once('connect.php'); $query = "INSERT INTO member (student_id, rso) VALUES (?, ?)"; $stmt = mysqli_prepare($database, $query); mysqli_stmt_bind_param($stmt, "ss", $_SESSION['username'], $rso); mysqli_stmt_execute($stmt); $affected_rows = mysqli_stmt_affected_rows($stmt); if ($affected_rows == 1) { mysqli_stmt_close($stmt); mysqli_close($database); $success = $suc."You've join an RSO".$end; } else { $success = $err."Please reselect a RSO".$end; mysqli_stmt_close($stmt); mysqli_close($database); } } } //process input data function trim_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> </div> <div class="flex-container"> <header> <h1> JOIN RSO </h1> <span><b><?php echo "Welcome ". $_SESSION['username'] . "<br />"; if($_SESSION['user_type']=='s'){ echo "Student Account";} elseif($_SESSION['user_type']=='a'){ echo "Admin Account";} elseif($_SESSION['user_type']=='sa'){ echo "Super Admin Account";}?></b></span><br /> <a href="LOGOUT.php" target="_self"> Log Out</a><br /> </header> <nav class="nav"> <ul> <?php if($_SESSION['user_type']== 's'){ echo " <li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"dashboard.php\" target=\"_self\"> Dashboard</a></b></li> <li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"joinRSO.php\" target=\"_self\"> Join RSO</a></b></li> <li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"createrso.php\" target=\"_self\"> Create RSO</a><br /></b></li>"; } elseif($_SESSION['user_type']== 'a'){ echo " <li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"dashboard.php\" target=\"_self\"> Dashboard</a></b></li> <li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"createEvent.html\" target=\"_self\"> Create Event</a><br /></b></li> <li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"joinRSO.php\" target=\"_self\"> Join RSO</a></b></li> <li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"createrso.php\" target=\"_self\"> Create RSO</a><br /></b></li>"; } elseif($_SESSION['user_type']== 'sa'){ echo " <li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"dashboard.php\" target=\"_self\"> Dashboard</a></b></li> <li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"createuniversity.php\" target=\"_self\"> Create University</a></b></li>"; } ?> </ul> </nav> <article class="article"> <div class="container"> <form class="form-signin" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post"> <?php echo $success; ?> <?php echo $rsoErr ?> <select class="form-control" name="rsoSel"> <?php for($x = 0; $x <= count($name); $x++){ echo "<option value=" . $name[$x] . ">" . $name[$x] . "</option>"; } ?> <input class = "btn btn-lg btn-primary btn-block" type="submit" value="Join"></input><br /> </form> </div> </article> <div> </body> </html>
emcyroyale/COP4710-10
CollegeEvents2/joinrso.php
PHP
gpl-3.0
4,944
<?php /** * Class for the definition of a widget that is * called by the class of the main module * * @package SZGoogle * @subpackage Widgets * @author Massimo Della Rovere * @license http://opensource.org/licenses/gpl-license.php GNU Public License */ if (!defined('SZ_PLUGIN_GOOGLE') or !SZ_PLUGIN_GOOGLE) die(); // Before the definition of the class, check if there is a definition // with the same name or the same as previously defined in other script if (!class_exists('SZGoogleWidgetDriveSaveButton')) { class SZGoogleWidgetDriveSaveButton extends SZGoogleWidget { /** * Definition the constructor function, which is called * at the time of the creation of an instance of this class */ function __construct() { parent::__construct('SZ-Google-Drive-Save-Button',__('SZ-Google - Drive Save Button','szgoogleadmin'),array( 'classname' => 'sz-widget-google sz-widget-google-drive sz-widget-google-drive-save-button', 'description' => ucfirst(__('google drive save button.','szgoogleadmin')) )); } /** * Generation of the HTML code of the widget * for the full display in the sidebar associated */ function widget($args,$instance) { // Checking whether there are the variables that are used during the processing // the script and check the default values ​​in case they were not specified $options = $this->common_empty(array( 'url' => '', // default value 'filename' => '', // default value 'sitename' => '', // default value 'text' => '', // default value 'img' => '', // default value 'position' => '', // default value 'align' => '', // default value 'margintop' => '', // default value 'marginright' => '', // default value 'marginbottom' => '', // default value 'marginleft' => '', // default value 'marginunit' => '', // default value ),$instance); // Definition of the control variables of the widget, these values​ // do not affect the items of basic but affect some aspects $controls = $this->common_empty(array( 'badge' => '', // default value ),$instance); // If the widget I excluded from the badge button I reset // the variables of the badge possibly set and saved if ($controls['badge'] != '1') { $options['img'] = ''; $options['text'] = ''; $options['position'] = ''; } // Create the HTML code for the current widget recalling the basic // function which is also invoked by the corresponding shortcode $OBJC = new SZGoogleActionDriveSave(); $HTML = $OBJC->getHTMLCode($options); // Output HTML code linked to the widget to // display call to the general standard for wrap echo $this->common_widget($args,$instance,$HTML); } /** * Changing parameters related to the widget FORM * with storing the values ​​directly in the database */ function update($new_instance,$old_instance) { // Performing additional operations on fields of the // form widget before it is stored in the database return $this->common_update(array( 'title' => '0', // strip_tags 'badge' => '1', // strip_tags 'url' => '0', // strip_tags 'text' => '0', // strip_tags 'img' => '1', // strip_tags 'align' => '1', // strip_tags 'position' => '1', // strip_tags ),$new_instance,$old_instance); } /** * FORM display the widget in the management of * sidebar in the administration panel of wordpress */ function form($instance) { // Creating arrays for list fields that must be // present in the form before calling wp_parse_args() $array = array( 'title' => '', // default value 'badge' => '', // default value 'url' => '', // default value 'text' => '', // default value 'img' => '', // default value 'align' => '', // default value 'position' => '', // default value ); // Creating arrays for list of fields to be retrieved FORM // and loading the file with the HTML template to display extract(wp_parse_args($instance,$array),EXTR_OVERWRITE); // Calling the template for displaying the part // that concerns the administration panel (admin) @include(dirname(SZ_PLUGIN_GOOGLE_MAIN).'/admin/widgets/SZGoogleWidget.php'); @include(dirname(SZ_PLUGIN_GOOGLE_MAIN).'/admin/widgets/' .__CLASS__.'.php'); } } }
rossonet/maker_imola_city
app-root/data/plugins/sz-google/classes/widget/SZGoogleWidgetDriveSaveButton.php
PHP
gpl-3.0
4,458
// tutorial06.c // A pedagogical video player that really works! // // Code based on FFplay, Copyright (c) 2003 Fabrice Bellard, // and a tutorial by Martin Bohme (boehme@inb.uni-luebeckREMOVETHIS.de) // Tested on Gentoo, CVS version 5/01/07 compiled with GCC 4.1.1 // Use // // gcc -o tutorial02 tutorial02.c -lavutil -lavformat -lavcodec -lz -lm `sdl-config --cflags --libs` // to build (assuming libavformat and libavcodec are correctly installed, // and assuming you have sdl-config. Please refer to SDL docs for your installation.) // // Run using // tutorial06 myvideofile.mpg // // to play the video. #include <ffmpeg/avcodec.h> #include <ffmpeg/avformat.h> #include <SDL.h> #include <SDL_thread.h> #ifdef __MINGW32__ #undef main /* Prevents SDL from overriding main() */ #endif #include <stdio.h> #include <math.h> #define SDL_AUDIO_BUFFER_SIZE 1024 #define MAX_AUDIOQ_SIZE (5 * 16 * 1024) #define MAX_VIDEOQ_SIZE (5 * 256 * 1024) #define AV_SYNC_THRESHOLD 0.01 #define AV_NOSYNC_THRESHOLD 10.0 #define SAMPLE_CORRECTION_PERCENT_MAX 10 #define AUDIO_DIFF_AVG_NB 20 #define FF_ALLOC_EVENT (SDL_USEREVENT) #define FF_REFRESH_EVENT (SDL_USEREVENT + 1) #define FF_QUIT_EVENT (SDL_USEREVENT + 2) #define VIDEO_PICTURE_QUEUE_SIZE 1 #define DEFAULT_AV_SYNC_TYPE AV_SYNC_VIDEO_MASTER typedef struct PacketQueue { AVPacketList *first_pkt, *last_pkt; int nb_packets; int size; SDL_mutex *mutex; SDL_cond *cond; } PacketQueue; typedef struct VideoPicture { SDL_Overlay *bmp; int width, height; /* source height & width */ int allocated; double pts; } VideoPicture; typedef struct VideoState { AVFormatContext *pFormatCtx; int videoStream, audioStream; int av_sync_type; double external_clock; /* external clock base */ int64_t external_clock_time; double audio_clock; AVStream *audio_st; PacketQueue audioq; uint8_t audio_buf[(AVCODEC_MAX_AUDIO_FRAME_SIZE * 3) / 2]; unsigned int audio_buf_size; unsigned int audio_buf_index; AVPacket audio_pkt; uint8_t *audio_pkt_data; int audio_pkt_size; int audio_hw_buf_size; double audio_diff_cum; /* used for AV difference average computation */ double audio_diff_avg_coef; double audio_diff_threshold; int audio_diff_avg_count; double frame_timer; double frame_last_pts; double frame_last_delay; double video_clock; ///<pts of last decoded frame / predicted pts of next decoded frame double video_current_pts; ///<current displayed pts (different from video_clock if frame fifos are used) int64_t video_current_pts_time; ///<time (av_gettime) at which we updated video_current_pts - used to have running video pts AVStream *video_st; PacketQueue videoq; VideoPicture pictq[VIDEO_PICTURE_QUEUE_SIZE]; int pictq_size, pictq_rindex, pictq_windex; SDL_mutex *pictq_mutex; SDL_cond *pictq_cond; SDL_Thread *parse_tid; SDL_Thread *video_tid; char filename[1024]; int quit; } VideoState; enum { AV_SYNC_AUDIO_MASTER, AV_SYNC_VIDEO_MASTER, AV_SYNC_EXTERNAL_MASTER, }; SDL_Surface *screen; /* Since we only have one decoding thread, the Big Struct can be global in case we need it. */ VideoState *global_video_state; void packet_queue_init(PacketQueue *q) { memset(q, 0, sizeof(PacketQueue)); q->mutex = SDL_CreateMutex(); q->cond = SDL_CreateCond(); } int packet_queue_put(PacketQueue *q, AVPacket *pkt) { AVPacketList *pkt1; if(av_dup_packet(pkt) < 0) { return -1; } pkt1 = av_malloc(sizeof(AVPacketList)); if (!pkt1) return -1; pkt1->pkt = *pkt; pkt1->next = NULL; SDL_LockMutex(q->mutex); if (!q->last_pkt) q->first_pkt = pkt1; else q->last_pkt->next = pkt1; q->last_pkt = pkt1; q->nb_packets++; q->size += pkt1->pkt.size; SDL_CondSignal(q->cond); SDL_UnlockMutex(q->mutex); return 0; } static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block) { AVPacketList *pkt1; int ret; SDL_LockMutex(q->mutex); for(;;) { if(global_video_state->quit) { ret = -1; break; } pkt1 = q->first_pkt; if (pkt1) { q->first_pkt = pkt1->next; if (!q->first_pkt) q->last_pkt = NULL; q->nb_packets--; q->size -= pkt1->pkt.size; *pkt = pkt1->pkt; av_free(pkt1); ret = 1; break; } else if (!block) { ret = 0; break; } else { SDL_CondWait(q->cond, q->mutex); } } SDL_UnlockMutex(q->mutex); return ret; } double get_audio_clock(VideoState *is) { double pts; int hw_buf_size, bytes_per_sec, n; pts = is->audio_clock; /* maintained in the audio thread */ hw_buf_size = is->audio_buf_size - is->audio_buf_index; bytes_per_sec = 0; n = is->audio_st->codec->channels * 2; if(is->audio_st) { bytes_per_sec = is->audio_st->codec->sample_rate * n; } if(bytes_per_sec) { pts -= (double)hw_buf_size / bytes_per_sec; } return pts; } double get_video_clock(VideoState *is) { double delta; delta = (av_gettime() - is->video_current_pts_time) / 1000000.0; return is->video_current_pts + delta; } double get_external_clock(VideoState *is) { return av_gettime() / 1000000.0; } double get_master_clock(VideoState *is) { if(is->av_sync_type == AV_SYNC_VIDEO_MASTER) { return get_video_clock(is); } else if(is->av_sync_type == AV_SYNC_AUDIO_MASTER) { return get_audio_clock(is); } else { return get_external_clock(is); } } /* Add or subtract samples to get a better sync, return new audio buffer size */ int synchronize_audio(VideoState *is, short *samples, int samples_size, double pts) { int n; double ref_clock; n = 2 * is->audio_st->codec->channels; if(is->av_sync_type != AV_SYNC_AUDIO_MASTER) { double diff, avg_diff; int wanted_size, min_size, max_size, nb_samples; ref_clock = get_master_clock(is); diff = get_audio_clock(is) - ref_clock; if(diff < AV_NOSYNC_THRESHOLD) { // accumulate the diffs is->audio_diff_cum = diff + is->audio_diff_avg_coef * is->audio_diff_cum; if(is->audio_diff_avg_count < AUDIO_DIFF_AVG_NB) { is->audio_diff_avg_count++; } else { avg_diff = is->audio_diff_cum * (1.0 - is->audio_diff_avg_coef); if(fabs(avg_diff) >= is->audio_diff_threshold) { wanted_size = samples_size + ((int)(diff * is->audio_st->codec->sample_rate) * n); min_size = samples_size * ((100 - SAMPLE_CORRECTION_PERCENT_MAX) / 100); max_size = samples_size * ((100 + SAMPLE_CORRECTION_PERCENT_MAX) / 100); if(wanted_size < min_size) { wanted_size = min_size; } else if (wanted_size > max_size) { wanted_size = max_size; } if(wanted_size < samples_size) { /* remove samples */ samples_size = wanted_size; } else if(wanted_size > samples_size) { uint8_t *samples_end, *q; int nb; /* add samples by copying final sample*/ nb = (samples_size - wanted_size); samples_end = (uint8_t *)samples + samples_size - n; q = samples_end + n; while(nb > 0) { memcpy(q, samples_end, n); q += n; nb -= n; } samples_size = wanted_size; } } } } else { /* difference is TOO big; reset diff stuff */ is->audio_diff_avg_count = 0; is->audio_diff_cum = 0; } } return samples_size; } int audio_decode_frame(VideoState *is, uint8_t *audio_buf, int buf_size, double *pts_ptr) { int len1, data_size, n; AVPacket *pkt = &is->audio_pkt; double pts; for(;;) { while(is->audio_pkt_size > 0) { data_size = buf_size; len1 = avcodec_decode_audio2(is->audio_st->codec, (int16_t *)audio_buf, &data_size, is->audio_pkt_data, is->audio_pkt_size); if(len1 < 0) { /* if error, skip frame */ is->audio_pkt_size = 0; break; } is->audio_pkt_data += len1; is->audio_pkt_size -= len1; if(data_size <= 0) { /* No data yet, get more frames */ continue; } pts = is->audio_clock; *pts_ptr = pts; n = 2 * is->audio_st->codec->channels; is->audio_clock += (double)data_size / (double)(n * is->audio_st->codec->sample_rate); /* We have data, return it and come back for more later */ return data_size; } if(pkt->data) av_free_packet(pkt); if(is->quit) { return -1; } /* next packet */ if(packet_queue_get(&is->audioq, pkt, 1) < 0) { return -1; } is->audio_pkt_data = pkt->data; is->audio_pkt_size = pkt->size; /* if update, update the audio clock w/pts */ if(pkt->pts != AV_NOPTS_VALUE) { is->audio_clock = av_q2d(is->audio_st->time_base)*pkt->pts; } } } void audio_callback(void *userdata, Uint8 *stream, int len) { VideoState *is = (VideoState *)userdata; int len1, audio_size; double pts; while(len > 0) { if(is->audio_buf_index >= is->audio_buf_size) { /* We have already sent all our data; get more */ audio_size = audio_decode_frame(is, is->audio_buf, sizeof(is->audio_buf), &pts); if(audio_size < 0) { /* If error, output silence */ is->audio_buf_size = 1024; memset(is->audio_buf, 0, is->audio_buf_size); } else { audio_size = synchronize_audio(is, (int16_t *)is->audio_buf, audio_size, pts); is->audio_buf_size = audio_size; } is->audio_buf_index = 0; } len1 = is->audio_buf_size - is->audio_buf_index; if(len1 > len) len1 = len; memcpy(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1); len -= len1; stream += len1; is->audio_buf_index += len1; } } static Uint32 sdl_refresh_timer_cb(Uint32 interval, void *opaque) { SDL_Event event; event.type = FF_REFRESH_EVENT; event.user.data1 = opaque; SDL_PushEvent(&event); return 0; /* 0 means stop timer */ } /* schedule a video refresh in 'delay' ms */ static void schedule_refresh(VideoState *is, int delay) { SDL_AddTimer(delay, sdl_refresh_timer_cb, is); } void video_display(VideoState *is) { SDL_Rect rect; VideoPicture *vp; AVPicture pict; float aspect_ratio; int w, h, x, y; int i; vp = &is->pictq[is->pictq_rindex]; if(vp->bmp) { if(is->video_st->codec->sample_aspect_ratio.num == 0) { aspect_ratio = 0; } else { aspect_ratio = av_q2d(is->video_st->codec->sample_aspect_ratio) * is->video_st->codec->width / is->video_st->codec->height; } if(aspect_ratio <= 0.0) { aspect_ratio = (float)is->video_st->codec->width / (float)is->video_st->codec->height; } h = screen->h; w = ((int)rint(h * aspect_ratio)) & -3; if(w > screen->w) { w = screen->w; h = ((int)rint(w / aspect_ratio)) & -3; } x = (screen->w - w) / 2; y = (screen->h - h) / 2; rect.x = x; rect.y = y; rect.w = w; rect.h = h; SDL_DisplayYUVOverlay(vp->bmp, &rect); } } void video_refresh_timer(void *userdata) { VideoState *is = (VideoState *)userdata; VideoPicture *vp; double actual_delay, delay, sync_threshold, ref_clock, diff; if(is->video_st) { if(is->pictq_size == 0) { schedule_refresh(is, 1); } else { vp = &is->pictq[is->pictq_rindex]; is->video_current_pts = vp->pts; is->video_current_pts_time = av_gettime(); delay = vp->pts - is->frame_last_pts; /* the pts from last time */ if(delay <= 0 || delay >= 1.0) { /* if incorrect delay, use previous one */ delay = is->frame_last_delay; } /* save for next time */ is->frame_last_delay = delay; is->frame_last_pts = vp->pts; /* update delay to sync to audio if not master source */ if(is->av_sync_type != AV_SYNC_VIDEO_MASTER) { ref_clock = get_master_clock(is); diff = vp->pts - ref_clock; /* Skip or repeat the frame. Take delay into account FFPlay still doesn't "know if this is the best guess." */ sync_threshold = (delay > AV_SYNC_THRESHOLD) ? delay : AV_SYNC_THRESHOLD; if(fabs(diff) < AV_NOSYNC_THRESHOLD) { if(diff <= -sync_threshold) { delay = 0; } else if(diff >= sync_threshold) { delay = 2 * delay; } } } is->frame_timer += delay; /* computer the REAL delay */ actual_delay = is->frame_timer - (av_gettime() / 1000000.0); if(actual_delay < 0.010) { /* Really it should skip the picture instead */ actual_delay = 0.010; } schedule_refresh(is, (int)(actual_delay * 1000 + 0.5)); /* show the picture! */ video_display(is); /* update queue for next picture! */ if(++is->pictq_rindex == VIDEO_PICTURE_QUEUE_SIZE) { is->pictq_rindex = 0; } SDL_LockMutex(is->pictq_mutex); is->pictq_size--; SDL_CondSignal(is->pictq_cond); SDL_UnlockMutex(is->pictq_mutex); } } else { schedule_refresh(is, 100); } } void alloc_picture(void *userdata) { VideoState *is = (VideoState *)userdata; VideoPicture *vp; vp = &is->pictq[is->pictq_windex]; if(vp->bmp) { // we already have one make another, bigger/smaller SDL_FreeYUVOverlay(vp->bmp); } // Allocate a place to put our YUV image on that screen vp->bmp = SDL_CreateYUVOverlay(is->video_st->codec->width, is->video_st->codec->height, SDL_YV12_OVERLAY, screen); vp->width = is->video_st->codec->width; vp->height = is->video_st->codec->height; SDL_LockMutex(is->pictq_mutex); vp->allocated = 1; SDL_CondSignal(is->pictq_cond); SDL_UnlockMutex(is->pictq_mutex); } int queue_picture(VideoState *is, AVFrame *pFrame, double pts) { VideoPicture *vp; int dst_pix_fmt; AVPicture pict; /* wait until we have space for a new pic */ SDL_LockMutex(is->pictq_mutex); while(is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE && !is->quit) { SDL_CondWait(is->pictq_cond, is->pictq_mutex); } SDL_UnlockMutex(is->pictq_mutex); if(is->quit) return -1; // windex is set to 0 initially vp = &is->pictq[is->pictq_windex]; /* allocate or resize the buffer! */ if(!vp->bmp || vp->width != is->video_st->codec->width || vp->height != is->video_st->codec->height) { SDL_Event event; vp->allocated = 0; /* we have to do it in the main thread */ event.type = FF_ALLOC_EVENT; event.user.data1 = is; SDL_PushEvent(&event); /* wait until we have a picture allocated */ SDL_LockMutex(is->pictq_mutex); while(!vp->allocated && !is->quit) { SDL_CondWait(is->pictq_cond, is->pictq_mutex); } SDL_UnlockMutex(is->pictq_mutex); if(is->quit) { return -1; } } /* We have a place to put our picture on the queue */ /* If we are skipping a frame, do we set this to null but still return vp->allocated = 1? */ if(vp->bmp) { SDL_LockYUVOverlay(vp->bmp); dst_pix_fmt = PIX_FMT_YUV420P; /* point pict at the queue */ pict.data[0] = vp->bmp->pixels[0]; pict.data[1] = vp->bmp->pixels[2]; pict.data[2] = vp->bmp->pixels[1]; pict.linesize[0] = vp->bmp->pitches[0]; pict.linesize[1] = vp->bmp->pitches[2]; pict.linesize[2] = vp->bmp->pitches[1]; // Convert the image into YUV format that SDL uses img_convert(&pict, dst_pix_fmt, (AVPicture *)pFrame, is->video_st->codec->pix_fmt, is->video_st->codec->width, is->video_st->codec->height); SDL_UnlockYUVOverlay(vp->bmp); vp->pts = pts; /* now we inform our display thread that we have a pic ready */ if(++is->pictq_windex == VIDEO_PICTURE_QUEUE_SIZE) { is->pictq_windex = 0; } SDL_LockMutex(is->pictq_mutex); is->pictq_size++; SDL_UnlockMutex(is->pictq_mutex); } return 0; } double synchronize_video(VideoState *is, AVFrame *src_frame, double pts) { double frame_delay; if(pts != 0) { /* if we have pts, set video clock to it */ is->video_clock = pts; } else { /* if we aren't given a pts, set it to the clock */ pts = is->video_clock; } /* update the video clock */ frame_delay = av_q2d(is->video_st->codec->time_base); /* if we are repeating a frame, adjust clock accordingly */ frame_delay += src_frame->repeat_pict * (frame_delay * 0.5); is->video_clock += frame_delay; return pts; } uint64_t global_video_pkt_pts = AV_NOPTS_VALUE; /* These are called whenever we allocate a frame * buffer. We use this to store the global_pts in * a frame at the time it is allocated. */ int our_get_buffer(struct AVCodecContext *c, AVFrame *pic) { int ret = avcodec_default_get_buffer(c, pic); uint64_t *pts = av_malloc(sizeof(uint64_t)); *pts = global_video_pkt_pts; pic->opaque = pts; return ret; } void our_release_buffer(struct AVCodecContext *c, AVFrame *pic) { if(pic) av_freep(&pic->opaque); avcodec_default_release_buffer(c, pic); } int video_thread(void *arg) { VideoState *is = (VideoState *)arg; AVPacket pkt1, *packet = &pkt1; int len1, frameFinished; AVFrame *pFrame; double pts; pFrame = avcodec_alloc_frame(); for(;;) { if(packet_queue_get(&is->videoq, packet, 1) < 0) { // means we quit getting packets break; } pts = 0; // Save global pts to be stored in pFrame in first call global_video_pkt_pts = packet->pts; // Decode video frame len1 = avcodec_decode_video(is->video_st->codec, pFrame, &frameFinished, packet->data, packet->size); if(packet->dts == AV_NOPTS_VALUE && pFrame->opaque && *(uint64_t*)pFrame->opaque != AV_NOPTS_VALUE) { pts = *(uint64_t *)pFrame->opaque; } else if(packet->dts != AV_NOPTS_VALUE) { pts = packet->dts; } else { pts = 0; } pts *= av_q2d(is->video_st->time_base); // Did we get a video frame? if(frameFinished) { pts = synchronize_video(is, pFrame, pts); if(queue_picture(is, pFrame, pts) < 0) { break; } } av_free_packet(packet); } av_free(pFrame); return 0; } int stream_component_open(VideoState *is, int stream_index) { AVFormatContext *pFormatCtx = is->pFormatCtx; AVCodecContext *codecCtx; AVCodec *codec; SDL_AudioSpec wanted_spec, spec; if(stream_index < 0 || stream_index >= pFormatCtx->nb_streams) { return -1; } // Get a pointer to the codec context for the video stream codecCtx = pFormatCtx->streams[stream_index]->codec; if(codecCtx->codec_type == CODEC_TYPE_AUDIO) { // Set audio settings from codec info wanted_spec.freq = codecCtx->sample_rate; wanted_spec.format = AUDIO_S16SYS; wanted_spec.channels = codecCtx->channels; wanted_spec.silence = 0; wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE; wanted_spec.callback = audio_callback; wanted_spec.userdata = is; if(SDL_OpenAudio(&wanted_spec, &spec) < 0) { fprintf(stderr, "SDL_OpenAudio: %s\n", SDL_GetError()); return -1; } is->audio_hw_buf_size = spec.size; } codec = avcodec_find_decoder(codecCtx->codec_id); if(!codec || (avcodec_open(codecCtx, codec) < 0)) { fprintf(stderr, "Unsupported codec!\n"); return -1; } switch(codecCtx->codec_type) { case CODEC_TYPE_AUDIO: is->audioStream = stream_index; is->audio_st = pFormatCtx->streams[stream_index]; is->audio_buf_size = 0; is->audio_buf_index = 0; /* averaging filter for audio sync */ is->audio_diff_avg_coef = exp(log(0.01 / AUDIO_DIFF_AVG_NB)); is->audio_diff_avg_count = 0; /* Correct audio only if larger error than this */ is->audio_diff_threshold = 2.0 * SDL_AUDIO_BUFFER_SIZE / codecCtx->sample_rate; memset(&is->audio_pkt, 0, sizeof(is->audio_pkt)); packet_queue_init(&is->audioq); SDL_PauseAudio(0); break; case CODEC_TYPE_VIDEO: is->videoStream = stream_index; is->video_st = pFormatCtx->streams[stream_index]; is->frame_timer = (double)av_gettime() / 1000000.0; is->frame_last_delay = 40e-3; is->video_current_pts_time = av_gettime(); packet_queue_init(&is->videoq); is->video_tid = SDL_CreateThread(video_thread, is); codecCtx->get_buffer = our_get_buffer; codecCtx->release_buffer = our_release_buffer; break; default: break; } } int decode_interrupt_cb(void) { return (global_video_state && global_video_state->quit); } int decode_thread(void *arg) { VideoState *is = (VideoState *)arg; AVFormatContext *pFormatCtx; AVPacket pkt1, *packet = &pkt1; int video_index = -1; int audio_index = -1; int i; is->videoStream=-1; is->audioStream=-1; global_video_state = is; // will interrupt blocking functions if we quit! url_set_interrupt_cb(decode_interrupt_cb); // Open video file if(av_open_input_file(&pFormatCtx, is->filename, NULL, 0, NULL)!=0) return -1; // Couldn't open file is->pFormatCtx = pFormatCtx; // Retrieve stream information if(av_find_stream_info(pFormatCtx)<0) return -1; // Couldn't find stream information // Dump information about file onto standard error dump_format(pFormatCtx, 0, is->filename, 0); // Find the first video stream for(i=0; i<pFormatCtx->nb_streams; i++) { if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO && video_index < 0) { video_index=i; } if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_AUDIO && audio_index < 0) { audio_index=i; } } if(audio_index >= 0) { stream_component_open(is, audio_index); } if(video_index >= 0) { stream_component_open(is, video_index); } if(is->videoStream < 0 || is->audioStream < 0) { fprintf(stderr, "%s: could not open codecs\n", is->filename); goto fail; } // main decode loop for(;;) { if(is->quit) { break; } // seek stuff goes here if(is->audioq.size > MAX_AUDIOQ_SIZE || is->videoq.size > MAX_VIDEOQ_SIZE) { SDL_Delay(10); continue; } if(av_read_frame(is->pFormatCtx, packet) < 0) { if(url_ferror(&pFormatCtx->pb) == 0) { SDL_Delay(100); /* no error; wait for user input */ continue; } else { break; } } // Is this a packet from the video stream? if(packet->stream_index == is->videoStream) { packet_queue_put(&is->videoq, packet); } else if(packet->stream_index == is->audioStream) { packet_queue_put(&is->audioq, packet); } else { av_free_packet(packet); } } /* all done - wait for it */ while(!is->quit) { SDL_Delay(100); } fail: { SDL_Event event; event.type = FF_QUIT_EVENT; event.user.data1 = is; SDL_PushEvent(&event); } return 0; } int main(int argc, char *argv[]) { SDL_Event event; VideoState *is; is = av_mallocz(sizeof(VideoState)); if(argc < 2) { fprintf(stderr, "Usage: test <file>\n"); exit(1); } // Register all formats and codecs av_register_all(); if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) { fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError()); exit(1); } // Make a screen to put our video #ifndef __DARWIN__ screen = SDL_SetVideoMode(640, 480, 0, 0); #else screen = SDL_SetVideoMode(640, 480, 24, 0); #endif if(!screen) { fprintf(stderr, "SDL: could not set video mode - exiting\n"); exit(1); } pstrcpy(is->filename, sizeof(is->filename), argv[1]); is->pictq_mutex = SDL_CreateMutex(); is->pictq_cond = SDL_CreateCond(); schedule_refresh(is, 40); is->av_sync_type = DEFAULT_AV_SYNC_TYPE; is->parse_tid = SDL_CreateThread(decode_thread, is); if(!is->parse_tid) { av_free(is); return -1; } for(;;) { SDL_WaitEvent(&event); switch(event.type) { case FF_QUIT_EVENT: case SDL_QUIT: is->quit = 1; SDL_Quit(); exit(0); break; case FF_ALLOC_EVENT: alloc_picture(event.user.data1); break; case FF_REFRESH_EVENT: video_refresh_timer(event.user.data1); break; default: break; } } return 0; }
lopesivan/ffmpeg-with-c-and-cpp
tutorial/ffmpegtutorial/tutorial06.c
C
gpl-3.0
24,098
/* * Copyright (C) 2015-2018 Département de l'Instruction Publique (DIP-SEM) * * Copyright (C) 2013 Open Education Foundation * * Copyright (C) 2010-2013 Groupement d'Intérêt Public pour * l'Education Numérique en Afrique (GIP ENA) * * This file is part of OpenBoard. * * OpenBoard is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3 of the License, * with a specific linking exception for the OpenSSL project's * "OpenSSL" library (or with modified versions of it that use the * same license as the "OpenSSL" library). * * OpenBoard 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 OpenBoard. If not, see <http://www.gnu.org/licenses/>. */ #ifndef UBIDLETIMER_H_ #define UBIDLETIMER_H_ #include <QObject> #include <QDateTime> class QEvent; class UBIdleTimer : public QObject { Q_OBJECT public: UBIdleTimer(QObject *parent = 0); virtual ~UBIdleTimer(); protected: bool eventFilter(QObject *obj, QEvent *event); virtual void timerEvent(QTimerEvent *event); private: QDateTime mLastInputEventTime; bool mCursorIsHidden; }; #endif /* UBIDLETIMER_H_ */
DIP-SEM/OpenBoard
src/core/UBIdleTimer.h
C
gpl-3.0
1,533
/***************************************************************************** * * PROJECT: Multi Theft Auto v1.0 * LICENSE: See LICENSE in the top level directory * FILE: mods/deathmatch/logic/CPlayerStats.h * PURPOSE: Player statistics class * * Multi Theft Auto is available from http://www.multitheftauto.com/ * *****************************************************************************/ class CPlayerStats; #pragma once #include <vector> using namespace std; struct sStat { unsigned short id; float value; }; class CPlayerStats { public: ~CPlayerStats(); bool GetStat(unsigned short usID, float& fValue); void SetStat(unsigned short usID, float fValue); vector<sStat*>::const_iterator IterBegin() { return m_List.begin(); } vector<sStat*>::const_iterator IterEnd() { return m_List.end(); } unsigned short GetSize() { return static_cast<unsigned short>(m_List.size()); } private: vector<sStat*> m_List; };
qaisjp/mtasa-blue
Server/mods/deathmatch/logic/CPlayerStats.h
C
gpl-3.0
1,066
'''Test the analysis.signal module.''' from __future__ import absolute_import, print_function, division import pytest import numpy as np import gridcells.analysis.signal as asignal from gridcells.analysis.signal import (local_extrema, local_maxima, local_minima, ExtremumTypes, LocalExtrema) RTOL = 1e-10 def _data_generator(n_items, sz): '''Generate pairs of test vectors.''' it = 0 while it < n_items: N1 = np.random.randint(sz) + 1 N2 = np.random.randint(sz) + 1 if N1 == 0 and N2 == 0: continue a1 = np.random.rand(N1) a2 = np.random.rand(N2) yield (a1, a2) it += 1 class TestCorrelation(object): ''' Test the analysis.signal.corr function (and effectively the core of the autoCorrelation) function. ''' maxN = 500 maxLoops = 1000 def test_onesided(self): '''Test the one-sided version of ``corr``.''' for a1, a2 in _data_generator(self.maxLoops, self.maxN): c_cpp = asignal.corr(a1, a2, mode='onesided') c_np = np.correlate(a1, a2, mode='full')[::-1][a1.size - 1:] np.testing.assert_allclose(c_cpp, c_np, rtol=RTOL) def test_twosided(self): '''Test the two-sided version of ``corr``.''' for a1, a2 in _data_generator(self.maxLoops, self.maxN): c_cpp = asignal.corr(a1, a2, mode='twosided') c_np = np.correlate(a1, a2, mode='full')[::-1] np.testing.assert_allclose(c_cpp, c_np, rtol=RTOL) def test_range(self): '''Test the ranged version of ``corr``.''' # Half the range of both signals for a1, a2 in _data_generator(self.maxLoops, self.maxN): if a1.size <= 1 or a2.size <= 1: continue lag_start = - (a1.size // 2) lag_end = a2.size // 2 c_np_centre = a1.size - 1 c_cpp = asignal.corr(a1, a2, mode='range', lag_start=lag_start, lag_end=lag_end) c_np = np.correlate(a1, a2, mode='full')[::-1] np.testing.assert_allclose( c_cpp, c_np[c_np_centre + lag_start:c_np_centre + lag_end + 1], rtol=RTOL) def test_zero_len(self): '''Test that an exception is raised when inputs have zero length.''' a1 = np.array([]) a2 = np.arange(10) # corr(a1, a2) lag_start = 0 lag_end = 0 for mode in ("onesided", "twosided", "range"): with pytest.raises(TypeError): asignal.corr(a1, a2, mode, lag_start, lag_end) with pytest.raises(TypeError): asignal.corr(a2, a1, mode, lag_start, lag_end) with pytest.raises(TypeError): asignal.corr(a1, a1, mode, lag_start, lag_end) def test_non_double(self): '''Test the corr function when dtype is not double.''' a1 = np.array([1, 2, 3], dtype=int) asignal.corr(a1, a1, mode='twosided') class TestAutoCorrelation(object): '''Test the acorr function.''' maxN = 500 maxLoops = 1000 def test_default_params(self): '''Test default parameters.''' a = np.arange(10) c_cpp = asignal.acorr(a) c_np = np.correlate(a, a, mode='full')[::-1][a.size - 1:] np.testing.assert_allclose(c_cpp, c_np, rtol=RTOL) def test_onesided(self): '''Test the one-sided version of ``corr``.''' a = np.arange(10) c_cpp = asignal.acorr(a, mode='onesided', max_lag=5) c_np = np.correlate(a, a, mode='full')[::-1][a.size - 1:a.size - 1 + 6] np.testing.assert_allclose(c_cpp, c_np, rtol=RTOL) def test_twosided(self): '''Test the two-sided version of ``corr``.''' a = np.arange(10) c_cpp = asignal.acorr(a, mode='twosided', max_lag=5) c_np = np.correlate(a, a, mode='full')[::-1][a.size - 6:a.size + 5] np.testing.assert_allclose(c_cpp, c_np, rtol=RTOL) def test_norm(self): '''Test normalization.''' # Simple array a = np.arange(10) c_cpp = asignal.acorr(a, mode='twosided', norm=True) c_np = np.correlate(a, a, mode='full')[::-1] np.testing.assert_allclose(c_cpp, c_np / np.max(c_np), rtol=RTOL) # A zero array will return zero zero_array = np.zeros(13) c_cpp = asignal.acorr(zero_array, mode='twosided', norm=True) assert np.all(c_cpp == 0.) def generate_sin(n_half_cycles, resolution=100): '''Generate a sine function with a number of (full) half cycles. Note that the positions of the extrema might be shifted +/- 1 with respect to the actual real sin because of possible rounding errors. Parameters ---------- n_half_cycles : int Number of half cycles to generate. Does not have to be even. resolution : int Number of data points for each half cycle. ''' if n_half_cycles < 1: raise ValueError() if resolution < 1: raise ValueError() f = 1. / (2 * resolution) t = np.arange(n_half_cycles * resolution, dtype=float) sig = np.sin(2 * np.pi * f * t) extrema_positions = np.array(np.arange(n_half_cycles) * resolution + resolution / 2, dtype=int) extrema_types = [] current_type = ExtremumTypes.MAX for _ in range(n_half_cycles): extrema_types.append(current_type) if current_type is ExtremumTypes.MAX: current_type = ExtremumTypes.MIN else: current_type = ExtremumTypes.MAX return (sig, extrema_positions, np.array(extrema_types)) class TestLocalExtrema(object): '''Test computation of local extrema.''' def test_local_extrema(self): for n_extrema in [1, 2, 51]: sig, extrema_idx, extrema_types = generate_sin(n_extrema) extrema = local_extrema(sig) assert len(extrema) == n_extrema assert np.all(extrema_idx[extrema_types == ExtremumTypes.MIN] == extrema.get_type(ExtremumTypes.MIN)) assert np.all(extrema_idx[extrema_types == ExtremumTypes.MAX] == extrema.get_type(ExtremumTypes.MAX)) def test_zero_array(self): for func in [local_extrema, local_maxima, local_minima]: extrema = func(np.empty(0)) assert len(extrema) == 0 def test_single_item(self): '''This should return a zero length array.''' for func in [local_extrema, local_maxima, local_minima]: extrema = func(np.array([1.])) assert len(extrema) == 0 def test_maxima(self): # One maximum only for n_extrema in [1, 2]: sig, extrema_idx, extrema_types = generate_sin(n_extrema) maxima = local_maxima(sig) assert len(maxima) == 1 assert np.all(extrema_idx[extrema_types == ExtremumTypes.MAX] == maxima) # 2 maxima for n_extrema in [3, 4]: sig, extrema_idx, extrema_types = generate_sin(n_extrema) maxima = local_maxima(sig) assert len(maxima) == 2 assert np.all(extrema_idx[extrema_types == ExtremumTypes.MAX] == maxima) def test_minima(self): # Only one maximum so should return empty n_extrema = 1 sig, extrema_idx, extrema_types = generate_sin(n_extrema) minima = local_minima(sig) assert len(minima) == 0 assert np.all(extrema_idx[extrema_types == ExtremumTypes.MIN] == minima) # One maximum and minimum n_extrema = 2 sig, extrema_idx, extrema_types = generate_sin(n_extrema) minima = local_minima(sig) assert len(minima) == 1 assert np.all(extrema_idx[extrema_types == ExtremumTypes.MIN] == minima) # 2 minima for n_extrema in [4, 5]: sig, extrema_idx, extrema_types = generate_sin(n_extrema) minima = local_minima(sig) assert len(minima) == 2 assert np.all(extrema_idx[extrema_types == ExtremumTypes.MIN] == minima) class TestLocalExtremaClass(object): '''Test the local extremum object.''' def test_empty(self): extrema = LocalExtrema([], []) assert len(extrema) == 0 assert len(extrema.get_type(ExtremumTypes.MIN)) == 0 # FIXME def test_inconsistent_inputs(self): with pytest.raises(IndexError): extrema = LocalExtrema([], [1]) with pytest.raises(IndexError): extrema = LocalExtrema(np.arange(10), [1]) def test_single_type(self): N = 10 test_vector = np.arange(N) for tested_type in ExtremumTypes: extrema = LocalExtrema(test_vector, [tested_type] * N) assert len(extrema) == N for current_type in ExtremumTypes: retrieved = extrema.get_type(current_type) if current_type is tested_type: assert len(retrieved) == N assert np.all(retrieved == test_vector) else: assert len(retrieved) == 0 def test_mixed_types(self): N = 10 test_vector = np.arange(10) test_types = np.ones(N) * ExtremumTypes.MIN test_types[0:10:2] = ExtremumTypes.MAX extrema = LocalExtrema(test_vector, test_types) assert len(extrema) == N retrieved_min = extrema.get_type(ExtremumTypes.MIN) assert np.all(retrieved_min == test_vector[1:10:2]) retrieved_max = extrema.get_type(ExtremumTypes.MAX) assert np.all(retrieved_max == test_vector[0:10:2]) # Should not find any other types for current_type in ExtremumTypes: if (current_type is not ExtremumTypes.MIN and current_type is not ExtremumTypes.MAX): assert len(extrema.get_type(current_type)) == 0
lsolanka/gridcells
tests/unit/test_analysis_signal.py
Python
gpl-3.0
10,163
<?php //require_once 'PEAR.php'; // commented by yogatama for use in gtfw //require_once 'oleread.inc'; /////// //define('Spreadsheet_Excel_Reader_HAVE_ICONV', function_exists('iconv')); //define('Spreadsheet_Excel_Reader_HAVE_MB', function_exists('mb_convert_encoding')); define('Spreadsheet_Excel_Reader_BIFF8', 0x600); define('Spreadsheet_Excel_Reader_BIFF7', 0x500); define('Spreadsheet_Excel_Reader_WorkbookGlobals', 0x5); define('Spreadsheet_Excel_Reader_Worksheet', 0x10); define('Spreadsheet_Excel_Reader_Type_BOF', 0x809); define('Spreadsheet_Excel_Reader_Type_EOF', 0x0a); define('Spreadsheet_Excel_Reader_Type_BOUNDSHEET', 0x85); define('Spreadsheet_Excel_Reader_Type_DIMENSION', 0x200); define('Spreadsheet_Excel_Reader_Type_ROW', 0x208); define('Spreadsheet_Excel_Reader_Type_DBCELL', 0xd7); define('Spreadsheet_Excel_Reader_Type_FILEPASS', 0x2f); define('Spreadsheet_Excel_Reader_Type_NOTE', 0x1c); define('Spreadsheet_Excel_Reader_Type_TXO', 0x1b6); define('Spreadsheet_Excel_Reader_Type_RK', 0x7e); define('Spreadsheet_Excel_Reader_Type_RK2', 0x27e); define('Spreadsheet_Excel_Reader_Type_MULRK', 0xbd); define('Spreadsheet_Excel_Reader_Type_MULBLANK', 0xbe); define('Spreadsheet_Excel_Reader_Type_INDEX', 0x20b); define('Spreadsheet_Excel_Reader_Type_SST', 0xfc); define('Spreadsheet_Excel_Reader_Type_EXTSST', 0xff); define('Spreadsheet_Excel_Reader_Type_CONTINUE', 0x3c); define('Spreadsheet_Excel_Reader_Type_LABEL', 0x204); define('Spreadsheet_Excel_Reader_Type_LABELSST', 0xfd); define('Spreadsheet_Excel_Reader_Type_NUMBER', 0x203); define('Spreadsheet_Excel_Reader_Type_NAME', 0x18); define('Spreadsheet_Excel_Reader_Type_ARRAY', 0x221); define('Spreadsheet_Excel_Reader_Type_STRING', 0x207); define('Spreadsheet_Excel_Reader_Type_FORMULA', 0x406); define('Spreadsheet_Excel_Reader_Type_FORMULA2', 0x6); define('Spreadsheet_Excel_Reader_Type_FORMAT', 0x41e); define('Spreadsheet_Excel_Reader_Type_XF', 0xe0); define('Spreadsheet_Excel_Reader_Type_BOOLERR', 0x205); define('Spreadsheet_Excel_Reader_Type_UNKNOWN', 0xffff); define('Spreadsheet_Excel_Reader_Type_NINETEENFOUR', 0x22); define('Spreadsheet_Excel_Reader_Type_MERGEDCELLS', 0xE5); define('Spreadsheet_Excel_Reader_utcOffsetDays' , 25569); define('Spreadsheet_Excel_Reader_utcOffsetDays1904', 24107); define('Spreadsheet_Excel_Reader_msInADay', 24 * 60 * 60); //define('Spreadsheet_Excel_Reader_DEF_NUM_FORMAT', "%.2f"); define('Spreadsheet_Excel_Reader_DEF_NUM_FORMAT', "%s"); // function file_get_contents for PHP < 4.3.0 // Thanks Marian Steinbach for this function if (!function_exists('file_get_contents')) { function file_get_contents($filename, $use_include_path = 0) { $data = ''; $file = @fopen($filename, "rb", $use_include_path); if ($file) { while (!feof($file)) $data .= fread($file, 1024); fclose($file); } else { // There was a problem opening the file $data = FALSE; } return $data; } } //class Spreadsheet_Excel_Reader extends PEAR { class Spreadsheet_Excel_Reader { var $boundsheets = array(); var $formatRecords = array(); var $sst = array(); var $sheets = array(); var $data; var $pos; var $_ole; var $_defaultEncoding; var $_defaultFormat = Spreadsheet_Excel_Reader_DEF_NUM_FORMAT; var $_columnsFormat = array(); var $_rowoffset = 1; var $_coloffset = 1; var $dateFormats = array ( 0xe => "d/m/Y", 0xf => "d-M-Y", 0x10 => "d-M", 0x11 => "M-Y", 0x12 => "h:i a", 0x13 => "h:i:s a", 0x14 => "H:i", 0x15 => "H:i:s", 0x16 => "d/m/Y H:i", 0x2d => "i:s", 0x2e => "H:i:s", 0x2f => "i:s.S"); var $numberFormats = array( 0x1 => "%1.0f", // "0" 0x2 => "%1.2f", // "0.00", 0x3 => "%1.0f", //"#,##0", 0x4 => "%1.2f", //"#,##0.00", 0x5 => "%1.0f", /*"$#,##0;($#,##0)",*/ 0x6 => '$%1.0f', /*"$#,##0;($#,##0)",*/ 0x7 => '$%1.2f', //"$#,##0.00;($#,##0.00)", 0x8 => '$%1.2f', //"$#,##0.00;($#,##0.00)", 0x9 => '%1.0f%%', // "0%" 0xa => '%1.2f%%', // "0.00%" 0xb => '%1.2f', // 0.00E00", 0x25 => '%1.0f', // "#,##0;(#,##0)", 0x26 => '%1.0f', //"#,##0;(#,##0)", 0x27 => '%1.2f', //"#,##0.00;(#,##0.00)", 0x28 => '%1.2f', //"#,##0.00;(#,##0.00)", 0x29 => '%1.0f', //"#,##0;(#,##0)", 0x2a => '$%1.0f', //"$#,##0;($#,##0)", 0x2b => '%1.2f', //"#,##0.00;(#,##0.00)", 0x2c => '$%1.2f', //"$#,##0.00;($#,##0.00)", 0x30 => '%1.0f'); //"##0.0E0"; function Spreadsheet_Excel_Reader(){ $this->_ole =& new OLERead(); $this->setUTFEncoder('iconv'); } function setOutputEncoding($Encoding){ $this->_defaultEncoding = $Encoding; } /** * $encoder = 'iconv' or 'mb' * set iconv if you would like use 'iconv' for encode UTF-16LE to your encoding * set mb if you would like use 'mb_convert_encoding' for encode UTF-16LE to your encoding */ function setUTFEncoder($encoder = 'iconv'){ $this->_encoderFunction = ''; if ($encoder == 'iconv'){ $this->_encoderFunction = function_exists('iconv') ? 'iconv' : ''; }elseif ($encoder == 'mb') { $this->_encoderFunction = function_exists('mb_convert_encoding') ? 'mb_convert_encoding' : ''; } } function setRowColOffset($iOffset){ $this->_rowoffset = $iOffset; $this->_coloffset = $iOffset; } function setDefaultFormat($sFormat){ $this->_defaultFormat = $sFormat; } function setColumnFormat($column, $sFormat){ $this->_columnsFormat[$column] = $sFormat; } function read($sFileName) { $errlevel = error_reporting(); //error_reporting($errlevel ^ E_NOTICE); $res = $this->_ole->read($sFileName); // oops, something goes wrong (Darko Miljanovic) if($res === false) { // check error code if($this->_ole->error == 1) { // bad file die('The filename ' . $sFileName . ' is not readable'); } // check other error codes here (eg bad fileformat, etc...) } $this->data = $this->_ole->getWorkBook(); /* $res = $this->_ole->read($sFileName); if ($this->isError($res)) { // var_dump($res); return $this->raiseError($res); } $total = $this->_ole->ppsTotal(); for ($i = 0; $i < $total; $i++) { if ($this->_ole->isFile($i)) { $type = unpack("v", $this->_ole->getData($i, 0, 2)); if ($type[''] == 0x0809) { // check if it's a BIFF stream $this->_index = $i; $this->data = $this->_ole->getData($i, 0, $this->_ole->getDataLength($i)); break; } } } if ($this->_index === null) { return $this->raiseError("$file doesn't seem to be an Excel file"); } */ //var_dump($this->data); //echo "data =".$this->data; $this->pos = 0; //$this->readRecords(); $this->_parse(); error_reporting($errlevel); } function _parse(){ $pos = 0; $code = ord($this->data[$pos]) | ord($this->data[$pos+1])<<8; $length = ord($this->data[$pos+2]) | ord($this->data[$pos+3])<<8; $version = ord($this->data[$pos + 4]) | ord($this->data[$pos + 5])<<8; $substreamType = ord($this->data[$pos + 6]) | ord($this->data[$pos + 7])<<8; //echo "Start parse code=".base_convert($code,10,16)." version=".base_convert($version,10,16)." substreamType=".base_convert($substreamType,10,16).""."\n"; if (($version != Spreadsheet_Excel_Reader_BIFF8) && ($version != Spreadsheet_Excel_Reader_BIFF7)) { return false; } if ($substreamType != Spreadsheet_Excel_Reader_WorkbookGlobals){ return false; } //print_r($rec); $pos += $length + 4; $code = ord($this->data[$pos]) | ord($this->data[$pos+1])<<8; $length = ord($this->data[$pos+2]) | ord($this->data[$pos+3])<<8; while ($code != Spreadsheet_Excel_Reader_Type_EOF){ switch ($code) { case Spreadsheet_Excel_Reader_Type_SST: //echo "Type_SST\n"; $spos = $pos + 4; $limitpos = $spos + $length; $uniqueStrings = $this->_GetInt4d($this->data, $spos+4); $spos += 8; for ($i = 0; $i < $uniqueStrings; $i++) { // Read in the number of characters if ($spos == $limitpos) { $opcode = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; $conlength = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; if ($opcode != 0x3c) { return -1; } $spos += 4; $limitpos = $spos + $conlength; } $numChars = ord($this->data[$spos]) | (ord($this->data[$spos+1]) << 8); //echo "i = $i pos = $pos numChars = $numChars "; $spos += 2; $optionFlags = ord($this->data[$spos]); $spos++; $asciiEncoding = (($optionFlags & 0x01) == 0) ; $extendedString = ( ($optionFlags & 0x04) != 0); // See if string contains formatting information $richString = ( ($optionFlags & 0x08) != 0); if ($richString) { // Read in the crun $formattingRuns = ord($this->data[$spos]) | (ord($this->data[$spos+1]) << 8); $spos += 2; } if ($extendedString) { // Read in cchExtRst $extendedRunLength = $this->_GetInt4d($this->data, $spos); $spos += 4; } $len = ($asciiEncoding)? $numChars : $numChars*2; if ($spos + $len < $limitpos) { $retstr = substr($this->data, $spos, $len); $spos += $len; }else{ // found countinue $retstr = substr($this->data, $spos, $limitpos - $spos); $bytesRead = $limitpos - $spos; $charsLeft = $numChars - (($asciiEncoding) ? $bytesRead : ($bytesRead / 2)); $spos = $limitpos; while ($charsLeft > 0){ $opcode = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; $conlength = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; if ($opcode != 0x3c) { return -1; } $spos += 4; $limitpos = $spos + $conlength; $option = ord($this->data[$spos]); $spos += 1; if ($asciiEncoding && ($option == 0)) { $len = min($charsLeft, $limitpos - $spos); // min($charsLeft, $conlength); $retstr .= substr($this->data, $spos, $len); $charsLeft -= $len; $asciiEncoding = true; }elseif (!$asciiEncoding && ($option != 0)){ $len = min($charsLeft * 2, $limitpos - $spos); // min($charsLeft, $conlength); $retstr .= substr($this->data, $spos, $len); $charsLeft -= $len/2; $asciiEncoding = false; }elseif (!$asciiEncoding && ($option == 0)) { // Bummer - the string starts off as Unicode, but after the // continuation it is in straightforward ASCII encoding $len = min($charsLeft, $limitpos - $spos); // min($charsLeft, $conlength); for ($j = 0; $j < $len; $j++) { $retstr .= $this->data[$spos + $j].chr(0); } $charsLeft -= $len; $asciiEncoding = false; }else{ $newstr = ''; for ($j = 0; $j < strlen($retstr); $j++) { $newstr = $retstr[$j].chr(0); } $retstr = $newstr; $len = min($charsLeft * 2, $limitpos - $spos); // min($charsLeft, $conlength); $retstr .= substr($this->data, $spos, $len); $charsLeft -= $len/2; $asciiEncoding = false; //echo "Izavrat\n"; } $spos += $len; } } $retstr = ($asciiEncoding) ? $retstr : $this->_encodeUTF16($retstr); // echo "Str $i = $retstr\n"; if ($richString){ $spos += 4 * $formattingRuns; } // For extended strings, skip over the extended string data if ($extendedString) { $spos += $extendedRunLength; } //if ($retstr == 'Derby'){ // echo "bb\n"; //} $this->sst[]=$retstr; } /*$continueRecords = array(); while ($this->getNextCode() == Type_CONTINUE) { $continueRecords[] = &$this->nextRecord(); } //echo " 1 Type_SST\n"; $this->shareStrings = new SSTRecord($r, $continueRecords); //print_r($this->shareStrings->strings); */ // echo 'SST read: '.($time_end-$time_start)."\n"; break; case Spreadsheet_Excel_Reader_Type_FILEPASS: return false; break; case Spreadsheet_Excel_Reader_Type_NAME: //echo "Type_NAME\n"; break; case Spreadsheet_Excel_Reader_Type_FORMAT: $indexCode = ord($this->data[$pos+4]) | ord($this->data[$pos+5]) << 8; if ($version == Spreadsheet_Excel_Reader_BIFF8) { $numchars = ord($this->data[$pos+6]) | ord($this->data[$pos+7]) << 8; if (ord($this->data[$pos+8]) == 0){ $formatString = substr($this->data, $pos+9, $numchars); } else { $formatString = substr($this->data, $pos+9, $numchars*2); } } else { $numchars = ord($this->data[$pos+6]); $formatString = substr($this->data, $pos+7, $numchars*2); } $this->formatRecords[$indexCode] = $formatString; // echo "Type.FORMAT\n"; break; case Spreadsheet_Excel_Reader_Type_XF: //global $dateFormats, $numberFormats; $indexCode = ord($this->data[$pos+6]) | ord($this->data[$pos+7]) << 8; //echo "\nType.XF ".count($this->formatRecords['xfrecords'])." $indexCode "; if (array_key_exists($indexCode, $this->dateFormats)) { //echo "isdate ".$dateFormats[$indexCode]; $this->formatRecords['xfrecords'][] = array( 'type' => 'date', 'format' => $this->dateFormats[$indexCode] ); }elseif (array_key_exists($indexCode, $this->numberFormats)) { //echo "isnumber ".$this->numberFormats[$indexCode]; $this->formatRecords['xfrecords'][] = array( 'type' => 'number', 'format' => $this->numberFormats[$indexCode] ); }else{ $isdate = FALSE; if ($indexCode > 0){ if (isset($this->formatRecords[$indexCode])) $formatstr = $this->formatRecords[$indexCode]; //echo '.other.'; //echo "\ndate-time=$formatstr=\n"; if ($formatstr) if (preg_match("/[^hmsday\/\-:\s]/i", $formatstr) == 0) { // found day and time format $isdate = TRUE; $formatstr = str_replace('mm', 'i', $formatstr); $formatstr = str_replace('h', 'H', $formatstr); //echo "\ndate-time $formatstr \n"; } } if ($isdate){ $this->formatRecords['xfrecords'][] = array( 'type' => 'date', 'format' => $formatstr, ); }else{ $this->formatRecords['xfrecords'][] = array( 'type' => 'other', 'format' => '', 'code' => $indexCode ); } } //echo "\n"; break; case Spreadsheet_Excel_Reader_Type_NINETEENFOUR: //echo "Type.NINETEENFOUR\n"; $this->nineteenFour = (ord($this->data[$pos+4]) == 1); break; case Spreadsheet_Excel_Reader_Type_BOUNDSHEET: //echo "Type.BOUNDSHEET\n"; $rec_offset = $this->_GetInt4d($this->data, $pos+4); $rec_typeFlag = ord($this->data[$pos+8]); $rec_visibilityFlag = ord($this->data[$pos+9]); $rec_length = ord($this->data[$pos+10]); if ($version == Spreadsheet_Excel_Reader_BIFF8){ $chartype = ord($this->data[$pos+11]); if ($chartype == 0){ $rec_name = substr($this->data, $pos+12, $rec_length); } else { $rec_name = $this->_encodeUTF16(substr($this->data, $pos+12, $rec_length*2)); } }elseif ($version == Spreadsheet_Excel_Reader_BIFF7){ $rec_name = substr($this->data, $pos+11, $rec_length); } $this->boundsheets[] = array('name'=>$rec_name, 'offset'=>$rec_offset); break; } //echo "Code = ".base_convert($r['code'],10,16)."\n"; $pos += $length + 4; $code = ord($this->data[$pos]) | ord($this->data[$pos+1])<<8; $length = ord($this->data[$pos+2]) | ord($this->data[$pos+3])<<8; //$r = &$this->nextRecord(); //echo "1 Code = ".base_convert($r['code'],10,16)."\n"; } foreach ($this->boundsheets as $key=>$val){ $this->sn = $key; $this->_parsesheet($val['offset']); } return true; } function _parsesheet($spos){ $cont = true; // read BOF $code = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; $length = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; $version = ord($this->data[$spos + 4]) | ord($this->data[$spos + 5])<<8; $substreamType = ord($this->data[$spos + 6]) | ord($this->data[$spos + 7])<<8; if (($version != Spreadsheet_Excel_Reader_BIFF8) && ($version != Spreadsheet_Excel_Reader_BIFF7)) { return -1; } if ($substreamType != Spreadsheet_Excel_Reader_Worksheet){ return -2; } //echo "Start parse code=".base_convert($code,10,16)." version=".base_convert($version,10,16)." substreamType=".base_convert($substreamType,10,16).""."\n"; $spos += $length + 4; //var_dump($this->formatRecords); //echo "code $code $length"; while($cont) { //echo "mem= ".memory_get_usage()."\n"; // $r = &$this->file->nextRecord(); $lowcode = ord($this->data[$spos]); if ($lowcode == Spreadsheet_Excel_Reader_Type_EOF) break; $code = $lowcode | ord($this->data[$spos+1])<<8; $length = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; $spos += 4; $this->sheets[$this->sn]['maxrow'] = $this->_rowoffset - 1; $this->sheets[$this->sn]['maxcol'] = $this->_coloffset - 1; //echo "Code=".base_convert($code,10,16)." $code\n"; unset($this->rectype); $this->multiplier = 1; // need for format with % switch ($code) { case Spreadsheet_Excel_Reader_Type_DIMENSION: //echo 'Type_DIMENSION '; if (!isset($this->numRows)) { if (($length == 10) || ($version == Spreadsheet_Excel_Reader_BIFF7)){ $this->sheets[$this->sn]['numRows'] = ord($this->data[$spos+2]) | ord($this->data[$spos+3]) << 8; $this->sheets[$this->sn]['numCols'] = ord($this->data[$spos+6]) | ord($this->data[$spos+7]) << 8; } else { $this->sheets[$this->sn]['numRows'] = ord($this->data[$spos+4]) | ord($this->data[$spos+5]) << 8; $this->sheets[$this->sn]['numCols'] = ord($this->data[$spos+10]) | ord($this->data[$spos+11]) << 8; } } //echo 'numRows '.$this->numRows.' '.$this->numCols."\n"; break; case Spreadsheet_Excel_Reader_Type_MERGEDCELLS: $cellRanges = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; for ($i = 0; $i < $cellRanges; $i++) { $fr = ord($this->data[$spos + 8*$i + 2]) | ord($this->data[$spos + 8*$i + 3])<<8; $lr = ord($this->data[$spos + 8*$i + 4]) | ord($this->data[$spos + 8*$i + 5])<<8; $fc = ord($this->data[$spos + 8*$i + 6]) | ord($this->data[$spos + 8*$i + 7])<<8; $lc = ord($this->data[$spos + 8*$i + 8]) | ord($this->data[$spos + 8*$i + 9])<<8; //$this->sheets[$this->sn]['mergedCells'][] = array($fr + 1, $fc + 1, $lr + 1, $lc + 1); if ($lr - $fr > 0) { $this->sheets[$this->sn]['cellsInfo'][$fr+1][$fc+1]['rowspan'] = $lr - $fr + 1; } if ($lc - $fc > 0) { $this->sheets[$this->sn]['cellsInfo'][$fr+1][$fc+1]['colspan'] = $lc - $fc + 1; } } //echo "Merged Cells $cellRanges $lr $fr $lc $fc\n"; break; case Spreadsheet_Excel_Reader_Type_RK: case Spreadsheet_Excel_Reader_Type_RK2: //echo 'Spreadsheet_Excel_Reader_Type_RK'."\n"; $row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; $column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; $rknum = $this->_GetInt4d($this->data, $spos + 6); $numValue = $this->_GetIEEE754($rknum); //echo $numValue." "; if ($this->isDate($spos)) { list($string, $raw) = $this->createDate($numValue); }else{ $raw = $numValue; if (isset($this->_columnsFormat[$column + 1])){ $this->curformat = $this->_columnsFormat[$column + 1]; } $string = sprintf($this->curformat, $numValue * $this->multiplier); //$this->addcell(RKRecord($r)); } $this->addcell($row, $column, $string, $raw); //echo "Type_RK $row $column $string $raw {$this->curformat}\n"; break; case Spreadsheet_Excel_Reader_Type_LABELSST: $row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; $column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; $xfindex = ord($this->data[$spos+4]) | ord($this->data[$spos+5])<<8; $index = $this->_GetInt4d($this->data, $spos + 6); //var_dump($this->sst); $this->addcell($row, $column, $this->sst[$index]); //echo "LabelSST $row $column $string\n"; break; case Spreadsheet_Excel_Reader_Type_MULRK: $row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; $colFirst = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; $colLast = ord($this->data[$spos + $length - 2]) | ord($this->data[$spos + $length - 1])<<8; $columns = $colLast - $colFirst + 1; $tmppos = $spos+4; for ($i = 0; $i < $columns; $i++) { $numValue = $this->_GetIEEE754($this->_GetInt4d($this->data, $tmppos + 2)); if ($this->isDate($tmppos-4)) { list($string, $raw) = $this->createDate($numValue); }else{ $raw = $numValue; if (isset($this->_columnsFormat[$colFirst + $i + 1])){ $this->curformat = $this->_columnsFormat[$colFirst + $i + 1]; } $string = sprintf($this->curformat, $numValue * $this->multiplier); } //$rec['rknumbers'][$i]['xfindex'] = ord($rec['data'][$pos]) | ord($rec['data'][$pos+1]) << 8; $tmppos += 6; $this->addcell($row, $colFirst + $i, $string, $raw); //echo "MULRK $row ".($colFirst + $i)." $string\n"; } //MulRKRecord($r); // Get the individual cell records from the multiple record //$num = ; break; case Spreadsheet_Excel_Reader_Type_NUMBER: $row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; $column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; $tmp = unpack("ddouble", substr($this->data, $spos + 6, 8)); // It machine machine dependent if ($this->isDate($spos)) { list($string, $raw) = $this->createDate($tmp['double']); // $this->addcell(DateRecord($r, 1)); }else{ //$raw = $tmp['']; if (isset($this->_columnsFormat[$column + 1])){ $this->curformat = $this->_columnsFormat[$column + 1]; } $raw = $this->createNumber($spos); $string = sprintf($this->curformat, $raw * $this->multiplier); // $this->addcell(NumberRecord($r)); } $this->addcell($row, $column, $string, $raw); //echo "Number $row $column $string\n"; break; case Spreadsheet_Excel_Reader_Type_FORMULA: case Spreadsheet_Excel_Reader_Type_FORMULA2: $row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; $column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; if ((ord($this->data[$spos+6])==0) && (ord($this->data[$spos+12])==255) && (ord($this->data[$spos+13])==255)) { //String formula. Result follows in a STRING record //echo "FORMULA $row $column Formula with a string<br>\n"; } elseif ((ord($this->data[$spos+6])==1) && (ord($this->data[$spos+12])==255) && (ord($this->data[$spos+13])==255)) { //Boolean formula. Result is in +2; 0=false,1=true } elseif ((ord($this->data[$spos+6])==2) && (ord($this->data[$spos+12])==255) && (ord($this->data[$spos+13])==255)) { //Error formula. Error code is in +2; } elseif ((ord($this->data[$spos+6])==3) && (ord($this->data[$spos+12])==255) && (ord($this->data[$spos+13])==255)) { //Formula result is a null string. } else { // result is a number, so first 14 bytes are just like a _NUMBER record $tmp = unpack("ddouble", substr($this->data, $spos + 6, 8)); // It machine machine dependent if ($this->isDate($spos)) { list($string, $raw) = $this->createDate($tmp['double']); // $this->addcell(DateRecord($r, 1)); }else{ //$raw = $tmp['']; if (isset($this->_columnsFormat[$column + 1])){ $this->curformat = $this->_columnsFormat[$column + 1]; } $raw = $this->createNumber($spos); $string = sprintf($this->curformat, $raw * $this->multiplier); // $this->addcell(NumberRecord($r)); } $this->addcell($row, $column, $string, $raw); //echo "Number $row $column $string\n"; } break; case Spreadsheet_Excel_Reader_Type_BOOLERR: $row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; $column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; $string = ord($this->data[$spos+6]); $this->addcell($row, $column, $string); //echo 'Type_BOOLERR '."\n"; break; case Spreadsheet_Excel_Reader_Type_ROW: case Spreadsheet_Excel_Reader_Type_DBCELL: case Spreadsheet_Excel_Reader_Type_MULBLANK: break; case Spreadsheet_Excel_Reader_Type_LABEL: $row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8; $column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; $this->addcell($row, $column, substr($this->data, $spos + 8, ord($this->data[$spos + 6]) | ord($this->data[$spos + 7])<<8)); // $this->addcell(LabelRecord($r)); break; case Spreadsheet_Excel_Reader_Type_EOF: $cont = false; break; default: //echo ' unknown :'.base_convert($r['code'],10,16)."\n"; break; } $spos += $length; } if (!isset($this->sheets[$this->sn]['numRows'])) $this->sheets[$this->sn]['numRows'] = $this->sheets[$this->sn]['maxrow']; if (!isset($this->sheets[$this->sn]['numCols'])) $this->sheets[$this->sn]['numCols'] = $this->sheets[$this->sn]['maxcol']; } function isDate($spos){ //$xfindex = GetInt2d(, 4); $xfindex = ord($this->data[$spos+4]) | ord($this->data[$spos+5]) << 8; //echo 'check is date '.$xfindex.' '.$this->formatRecords['xfrecords'][$xfindex]['type']."\n"; //var_dump($this->formatRecords['xfrecords'][$xfindex]); if ($this->formatRecords['xfrecords'][$xfindex]['type'] == 'date') { $this->curformat = $this->formatRecords['xfrecords'][$xfindex]['format']; $this->rectype = 'date'; return true; } else { if ($this->formatRecords['xfrecords'][$xfindex]['type'] == 'number') { $this->curformat = $this->formatRecords['xfrecords'][$xfindex]['format']; $this->rectype = 'number'; if (($xfindex == 0x9) || ($xfindex == 0xa)){ $this->multiplier = 100; } }else{ $this->curformat = $this->_defaultFormat; $this->rectype = 'unknown'; } return false; } } function createDate($numValue){ if ($numValue > 1){ $utcDays = $numValue - ($this->nineteenFour ? Spreadsheet_Excel_Reader_utcOffsetDays1904 : Spreadsheet_Excel_Reader_utcOffsetDays); $utcValue = round($utcDays * Spreadsheet_Excel_Reader_msInADay); $string = date ($this->curformat, $utcValue); $raw = $utcValue; }else{ $raw = $numValue; $hours = floor($numValue * 24); $mins = floor($numValue * 24 * 60) - $hours * 60; $secs = floor($numValue * Spreadsheet_Excel_Reader_msInADay) - $hours * 60 * 60 - $mins * 60; $string = date ($this->curformat, mktime($hours, $mins, $secs)); } return array($string, $raw); } function createNumber($spos){ $rknumhigh = $this->_GetInt4d($this->data, $spos + 10); $rknumlow = $this->_GetInt4d($this->data, $spos + 6); //for ($i=0; $i<8; $i++) { echo ord($this->data[$i+$spos+6]) . " "; } echo "<br>"; $sign = ($rknumhigh & 0x80000000) >> 31; $exp = ($rknumhigh & 0x7ff00000) >> 20; $mantissa = (0x100000 | ($rknumhigh & 0x000fffff)); $mantissalow1 = ($rknumlow & 0x80000000) >> 31; $mantissalow2 = ($rknumlow & 0x7fffffff); $value = $mantissa / pow( 2 , (20- ($exp - 1023))); if ($mantissalow1 != 0) $value += 1 / pow (2 , (21 - ($exp - 1023))); $value += $mantissalow2 / pow (2 , (52 - ($exp - 1023))); //echo "Sign = $sign, Exp = $exp, mantissahighx = $mantissa, mantissalow1 = $mantissalow1, mantissalow2 = $mantissalow2<br>\n"; if ($sign) {$value = -1 * $value;} return $value; } function addcell($row, $col, $string, $raw = ''){ //echo "ADD cel $row-$col $string\n"; $this->sheets[$this->sn]['maxrow'] = max($this->sheets[$this->sn]['maxrow'], $row + $this->_rowoffset); $this->sheets[$this->sn]['maxcol'] = max($this->sheets[$this->sn]['maxcol'], $col + $this->_coloffset); $this->sheets[$this->sn]['cells'][$row + $this->_rowoffset][$col + $this->_coloffset] = $string; if ($raw) $this->sheets[$this->sn]['cellsInfo'][$row + $this->_rowoffset][$col + $this->_coloffset]['raw'] = $raw; if (isset($this->rectype)) $this->sheets[$this->sn]['cellsInfo'][$row + $this->_rowoffset][$col + $this->_coloffset]['type'] = $this->rectype; } function _GetIEEE754($rknum){ if (($rknum & 0x02) != 0) { $value = $rknum >> 2; } else { //mmp // first comment out the previously existing 7 lines of code here // $tmp = unpack("d", pack("VV", 0, ($rknum & 0xfffffffc))); // //$value = $tmp['']; // if (array_key_exists(1, $tmp)) { // $value = $tmp[1]; // } else { // $value = $tmp['']; // } // I got my info on IEEE754 encoding from // http://research.microsoft.com/~hollasch/cgindex/coding/ieeefloat.html // The RK format calls for using only the most significant 30 bits of the // 64 bit floating point value. The other 34 bits are assumed to be 0 // So, we use the upper 30 bits of $rknum as follows... $sign = ($rknum & 0x80000000) >> 31; $exp = ($rknum & 0x7ff00000) >> 20; $mantissa = (0x100000 | ($rknum & 0x000ffffc)); $value = $mantissa / pow( 2 , (20- ($exp - 1023))); if ($sign) {$value = -1 * $value;} //end of changes by mmp } if (($rknum & 0x01) != 0) { $value /= 100; } return $value; } function _encodeUTF16($string){ $result = $string; if ($this->_defaultEncoding){ switch ($this->_encoderFunction){ case 'iconv' : $result = iconv('UTF-16LE', $this->_defaultEncoding, $string); break; case 'mb_convert_encoding' : $result = mb_convert_encoding($string, $this->_defaultEncoding, 'UTF-16LE' ); break; } } return $result; } function _GetInt4d($data, $pos) { $value = ord($data[$pos]) | (ord($data[$pos+1]) << 8) | (ord($data[$pos+2]) << 16) | (ord($data[$pos+3]) << 24); if ($value>=4294967294) { $value=-2; } if ($value >= 4000000000 && $value < 4294967294) // Add these lines { $value = -2 - 4294967294 + $value; } // End add lines return $value; } } ?>
4n6g4/gtsdm
malra/gtfw_base3.2/main/lib/ExcelReader/reader.php
PHP
gpl-3.0
41,610
<?php /** --------------------------------------------------------------------- * app/helpers/htmlFormHelpers.php : miscellaneous functions * ---------------------------------------------------------------------- * CollectiveAccess * Open-source collections management software * ---------------------------------------------------------------------- * * Software by Whirl-i-Gig (http://www.whirl-i-gig.com) * Copyright 2008-2019 Whirl-i-Gig * * For more information visit http://www.CollectiveAccess.org * * This program is free software; you may redistribute it and/or modify it under * the terms of the provided license as published by Whirl-i-Gig * * CollectiveAccess is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * This source code is free and modifiable under the terms of * GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See * the "license.txt" file for details, or visit the CollectiveAccess web site at * http://www.CollectiveAccess.org * * @package CollectiveAccess * @subpackage utils * @license http://www.gnu.org/copyleft/gpl.html GNU Public License version 3 * * ---------------------------------------------------------------------- */ /** * */ # ------------------------------------------------------------------------------------------------ /** * Creates an HTML <select> form element * * @param string $ps_name Name of the element * @param array $pa_content Associative array with keys as display options and values as option values. If the 'contentArrayUsesKeysForValues' is set then keys use interpreted as option values and values as display options. * @param array $pa_attributes Optional associative array of <select> tag options; keys are attribute names and values are attribute values * @param array $pa_options Optional associative array of options. Valid options are: * value = the default value of the element * values = an array of values for the element, when the <select> allows multiple selections * disabledOptions = an associative array indicating whether options are disabled or not; keys are option *values*, values are boolean (true=disabled; false=enabled) * contentArrayUsesKeysForValues = normally the keys of the $pa_content array are used as display options and the values as option values. Setting 'contentArrayUsesKeysForValues' to true will reverse the interpretation, using keys as option values. * useOptionsForValues = set values to be the same as option text. [Default is false] * width = width of select in characters or pixels. If specifying pixels use "px" as the units (eg. 100px) * colors = * @return string HTML code representing the drop-down list */ function caHTMLSelect($ps_name, $pa_content, $pa_attributes=null, $pa_options=null) { if (!is_array($pa_content)) { $pa_content = array(); } if (is_array($va_dim = caParseFormElementDimension(isset($pa_options['width']) ? $pa_options['width'] : null))) { if ($va_dim['type'] == 'pixels') { $pa_attributes['style'] = "width: ".$va_dim['dimension']."px; ".$pa_attributes['style']; } else { // Approximate character width using 1 character = 6 pixels of width $pa_attributes['style'] = "width: ".($va_dim['dimension'] * 6)."px; ".$pa_attributes['style']; } } if (is_array($va_dim = caParseFormElementDimension(isset($pa_options['height']) ? $pa_options['height'] : null))) { if ($va_dim['type'] == 'pixels') { $pa_attributes['style'] = "height: ".$va_dim['dimension']."px; ".$pa_attributes['style']; } else { // Approximate character width using 1 character = 6 pixels of width $pa_attributes['size'] = $va_dim['dimension']; } } $vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options); $vs_element = "<select name='{$ps_name}' {$vs_attr_string}>\n"; $vs_selected_val = isset($pa_options['value']) ? $pa_options['value'] : null; if (is_array($pa_options['values']) && $vs_selected_val) { $vs_selected_val = null; } $va_selected_vals = isset($pa_options['values']) ? $pa_options['values'] : array(); $va_disabled_options = isset($pa_options['disabledOptions']) ? $pa_options['disabledOptions'] : array(); $vb_content_is_list = caIsIndexedArray($pa_content); $va_colors = array(); if (isset($pa_options['colors']) && is_array($pa_options['colors'])) { $va_colors = $pa_options['colors']; } $vb_use_options_for_values = caGetOption('useOptionsForValues', $pa_options, false); $vb_uses_color = false; if (isset($pa_options['contentArrayUsesKeysForValues']) && $pa_options['contentArrayUsesKeysForValues']) { foreach($pa_content as $vs_val => $vs_opt) { if ($vb_use_options_for_values) { $vs_val = preg_replace("!^[\s]+!", "", preg_replace("![\s]+$!", "", str_replace("&nbsp;", "", $vs_opt))); } if ($COLOR = ($vs_color = $va_colors[$vs_val]) ? " data-color='#{$vs_color}'" : '') { $vb_uses_color = true; } if (is_null($vs_selected_val) || !($SELECTED = (((string)$vs_selected_val === (string)$vs_val) && strlen($vs_selected_val)) ? ' selected="1"' : '')) { $SELECTED = (is_array($va_selected_vals) && in_array($vs_val, $va_selected_vals)) ? ' selected="1"' : ''; } $DISABLED = (isset($va_disabled_options[$vs_val]) && $va_disabled_options[$vs_val]) ? ' disabled="1"' : ''; $vs_element .= "<option value='".htmlspecialchars($vs_val, ENT_QUOTES, 'UTF-8')."'{$SELECTED}{$DISABLED}{$COLOR}>".$vs_opt."</option>\n"; } } else { if ($vb_content_is_list) { foreach($pa_content as $vs_val) { if ($COLOR = ($vs_color = $va_colors[$vs_val]) ? " data-color='#{$vs_color}'" : '') { $vb_uses_color = true; } if (is_null($vs_selected_val) || !($SELECTED = ((string)$vs_selected_val === (string)$vs_val) ? ' selected="1"' : '')) { $SELECTED = (is_array($va_selected_vals) && in_array($vs_val, $va_selected_vals)) ? ' selected="1"' : ''; } $DISABLED = (isset($va_disabled_options[$vs_val]) && $va_disabled_options[$vs_val]) ? ' disabled="1"' : ''; $vs_element .= "<option value='".htmlspecialchars($vs_val, ENT_QUOTES, 'UTF-8')."'{$SELECTED}{$DISABLED}{$COLOR}>".$vs_val."</option>\n"; } } else { foreach($pa_content as $vs_opt => $vs_val) { if ($vb_use_options_for_values) { $vs_val = preg_replace("!^[\s]+!", "", preg_replace("![\s]+$!", "", str_replace("&nbsp;", "", $vs_opt))); } if ($COLOR = ($vs_color = $va_colors[$vs_val]) ? " data-color='#{$vs_color}'" : '') { $vb_uses_color = true; } if (is_null($vs_selected_val) || !($SELECTED = ((string)$vs_selected_val === (string)$vs_val) ? ' selected="1"' : '')) { $SELECTED = (is_array($va_selected_vals) && in_array($vs_val, $va_selected_vals)) ? ' selected="1"' : ''; } $DISABLED = (isset($va_disabled_options[$vs_val]) && $va_disabled_options[$vs_val]) ? ' disabled="1"' : ''; $vs_element .= "<option value='".htmlspecialchars($vs_val, ENT_QUOTES, 'UTF-8')."'{$SELECTED}{$DISABLED}{$COLOR}>".$vs_opt."</option>\n"; } } } $vs_element .= "</select>\n"; if ($vb_uses_color && isset($pa_attributes['id']) && $pa_attributes['id']) { $vs_element .= "<script type='text/javascript'>jQuery(document).ready(function() { var f; jQuery('#".$pa_attributes['id']."').on('change', f=function() { var c = jQuery('#".$pa_attributes['id']."').find('option:selected').data('color'); jQuery('#".$pa_attributes['id']."').css('background-color', c ? c : '#fff'); return false;}); f(); });</script>"; } return $vs_element; } # ------------------------------------------------------------------------------------------------ /** * Render an HTML text form element (<input type="text"> or <textarea> depending upon height). * * @param string $ps_name The name of the rendered form element * @param array $pa_attributes An array of attributes to include in the rendered HTML form element. If you need to set class, id, alt or other attributes, set them here. * @param array Options include: * width = Width of element in pixels (number with "px" suffix) or characters (number with no suffix) [Default is null] * height = Height of element in pixels (number with "px" suffix) or characters (number with no suffix) [Default is null] * usewysiwygeditor = Use rich text editor (CKEditor) for text element. Only available when the height of the text element is multi-line. [Default is false] * cktoolbar = app.conf directive name to pull CKEditor toolbar spec from. [Default is wysiwyg_editor_toolbar] * contentUrl = URL to use to load content when CKEditor is use with CA-specific plugins. [Default is null] * textAreaTagName = * @return string */ function caHTMLTextInput($ps_name, $pa_attributes=null, $pa_options=null) { $vb_is_textarea = false; $va_styles = array(); $vb_use_wysiwyg_editor = caGetOption('usewysiwygeditor', $pa_options, false); $vn_width = $vn_height = null; if (is_array($va_dim = caParseFormElementDimension( (isset($pa_options['width']) ? $pa_options['width'] : (isset($pa_attributes['size']) ? $pa_attributes['size'] : (isset($pa_attributes['width']) ? $pa_attributes['width'] : null) ) ) ))) { if ($va_dim['type'] == 'pixels') { $va_styles[] = "width: ".($vn_width = $va_dim['dimension'])."px;"; unset($pa_attributes['width']); unset($pa_attributes['size']); unset($pa_attributes['cols']); } else { // width is in characters $pa_attributes['size'] = $va_dim['dimension']; $vn_width = $va_dim['dimension'] * 6; } } if (!$vn_width) $vn_width = 300; if (is_array($va_dim = caParseFormElementDimension( (isset($pa_options['height']) ? $pa_options['height'] : (isset($pa_attributes['height']) ? $pa_attributes['height'] : null) ) ))) { if ($va_dim['type'] == 'pixels') { $va_styles[] = "height: ".($vn_height = $va_dim['dimension'])."px;"; unset($pa_attributes['height']); unset($pa_attributes['rows']); $vb_is_textarea = true; } else { // height is in characters if (($pa_attributes['rows'] = $va_dim['dimension']) > 1) { $vb_is_textarea = true; } $vn_height = $va_dim['dimension'] * 12; } } else { if (($pa_attributes['rows'] = (isset($pa_attributes['height']) && $pa_attributes['height']) ? $pa_attributes['height'] : 1) > 1) { $vb_is_textarea = true; } } if (!$vn_height) $vn_height = 300; $pa_attributes['style'] = join(" ", $va_styles); // WYSIWYG editor requires an DOM ID so generate one if none is explicitly set if ($vb_use_wysiwyg_editor && !isset($pa_attributes['id'])) { $pa_attributes['id'] = "{$ps_name}_element"; } if ($vb_is_textarea) { $tag_name = caGetOption('textAreaTagName', $pa_options, 'textarea'); $vs_value = $pa_attributes['value']; if ($pa_attributes['size']) { $pa_attributes['cols'] = $pa_attributes['size']; } unset($pa_attributes['size']); unset($pa_attributes['value']); $vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options); $vs_element = "<{$tag_name} name='{$ps_name}' wrap='soft' {$vs_attr_string}>".$vs_value."</{$tag_name}>\n"; } else { $pa_attributes['size'] = !$pa_attributes['size'] ? $pa_attributes['width'] : $pa_attributes['size']; $vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options); $vs_element = "<input name='{$ps_name}' {$vs_attr_string} type='text'/>\n"; } if ($vb_use_wysiwyg_editor) { AssetLoadManager::register("ckeditor"); $o_config = Configuration::load(); if(!is_array($va_toolbar_config = $o_config->getAssoc(caGetOption('cktoolbar', $pa_options, 'wysiwyg_editor_toolbar')))) { $va_toolbar_config = []; } $vs_content_url = caGetOption('contentUrl', $pa_options, ''); $va_lookup_urls = caGetOption('lookupUrls', $pa_options, null); $vs_element .= "<script type='text/javascript'>jQuery(document).ready(function() { var ckEditor = CKEDITOR.replace( '".$pa_attributes['id']."', { toolbar : ".json_encode(array_values($va_toolbar_config)).", width: '{$vn_width}px', height: '{$vn_height}px', toolbarLocation: 'top', enterMode: CKEDITOR.ENTER_BR, contentUrl: '{$vs_content_url}', lookupUrls: ".json_encode($va_lookup_urls)." }); ckEditor.on('instanceReady', function(){ ckEditor.document.on( 'keydown', function(e) {if (caUI && caUI.utils) { caUI.utils.showUnsavedChangesWarning(true); } }); }); }); </script>"; } return $vs_element; } # ------------------------------------------------------------------------------------------------ function caHTMLHiddenInput($ps_name, $pa_attributes=null, $pa_options=null) { $vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options); $vs_element = "<input name='{$ps_name}' {$vs_attr_string} type='hidden'/>\n"; return $vs_element; } # ------------------------------------------------------------------------------------------------ /** * Creates set of radio buttons * * $ps_name - name of the element * $pa_content - associative array with keys as display options and values as option values * $pa_attributes - optional associative array of <input> tag options applied to each radio button; keys are attribute names and values are attribute values * $pa_options - optional associative array of options. Valid options are: * value = the default value of the element * disabledOptions = an associative array indicating whether options are disabled or not; keys are option *values*, values are boolean (true=disabled; false=enabled) */ function caHTMLRadioButtonsInput($ps_name, $pa_content, $pa_attributes=null, $pa_options=null) { $vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options); $vs_selected_val = isset($pa_options['value']) ? $pa_options['value'] : null; $va_disabled_options = isset($pa_options['disabledOptions']) ? $pa_options['disabledOptions'] : array(); $vb_content_is_list = (array_key_exists(0, $pa_content)) ? true : false; $vs_id = isset($pa_attributes['id']) ? $pa_attributes['id'] : null; unset($pa_attributes['id']); $vn_i = 0; if ($vb_content_is_list) { foreach($pa_content as $vs_val) { $vs_id_attr = ($vs_id) ? 'id="'.$vs_id.'_'.$vn_i.'"' : ''; $SELECTED = ($vs_selected_val == $vs_val) ? ' selected="1"' : ''; $DISABLED = (isset($va_disabled_options[$vs_val]) && $va_disabled_options[$vs_val]) ? ' disabled="1"' : ''; $vs_element .= "<input type='radio' name='{$ps_name}' {$vs_id_attr} value='".htmlspecialchars($vs_val, ENT_QUOTES, 'UTF-8')."'{$SELECTED}{$DISABLED}> ".$vs_val."\n"; $vn_i++; } } else { foreach($pa_content as $vs_opt => $vs_val) { $vs_id_attr = ($vs_id) ? 'id="'.$vs_id.'_'.$vn_i.'"' : ''; $SELECTED = ($vs_selected_val == $vs_val) ? ' selected="1"' : ''; $DISABLED = (isset($va_disabled_options[$vs_val]) && $va_disabled_options[$vs_val]) ? ' disabled="1"' : ''; $vs_element .= "<input type='radio' name='{$ps_name}' {$vs_id_attr} value='".htmlspecialchars($vs_val, ENT_QUOTES, 'UTF-8')."'{$SELECTED}{$DISABLED}> ".$vs_opt."\n"; $vn_i++; } } return $vs_element; } # ------------------------------------------------------------------------------------------------ /** * Create a single radio button * * $ps_name - name of the element * $pa_attributes - optional associative array of <input> tag options applied to the radio button; keys are attribute names and values are attribute values * $pa_options - optional associative array of options. Valid options are: * checked = if true, value will be selected by default * disabled = boolean indicating if radio button is enabled or not (true=disabled; false=enabled) */ function caHTMLRadioButtonInput($ps_name, $pa_attributes=null, $pa_options=null) { if(caGetOption('checked', $pa_options, false)) { $pa_attributes['checked'] = 1; } if(caGetOption('disabled', $pa_options, false)) { $pa_attributes['disabled'] = 1; } $vs_attr_string = _caHTMLMakeAttributeString($pa_attributes); // standard check box $vs_element = "<input name='{$ps_name}' {$vs_attr_string} type='radio'/>\n"; return $vs_element; } # ------------------------------------------------------------------------------------------------ /** * Creates a checkbox * * $ps_name - name of the element * $pa_attributes - optional associative array of <input> tag options applied to the checkbox; keys are attribute names and values are attribute values * $pa_options - optional associative array of options. Valid options are: * value = the default value of the element * disabled = boolean indicating if checkbox is enabled or not (true=disabled; false=enabled) * returnValueIfUnchecked = boolean indicating if checkbox should return value in request if unchecked; default is false */ function caHTMLCheckboxInput($ps_name, $pa_attributes=null, $pa_options=null) { if (array_key_exists('checked', $pa_attributes) && !$pa_attributes['checked']) { unset($pa_attributes['checked']); } if (array_key_exists('CHECKED', $pa_attributes) && !$pa_attributes['CHECKED']) { unset($pa_attributes['CHECKED']); } if(caGetOption('disabled', $pa_options, false)) { $pa_attributes['disabled'] = 1; } $vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options); if (isset($pa_options['returnValueIfUnchecked']) && $pa_options['returnValueIfUnchecked']) { // javascript-y check box that returns form value even if unchecked $vs_element = "<input name='{$ps_name}' {$vs_attr_string} type='checkbox'/>\n"; unset($pa_attributes['id']); $pa_attributes['value'] = $pa_options['returnValueIfUnchecked']; $vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options); $vs_element = "<input name='{$ps_name}' {$vs_attr_string} type='hidden'/>\n". $vs_element; } else { // standard check box $vs_element = "<input name='{$ps_name}' {$vs_attr_string} type='checkbox'/>\n"; } return $vs_element; } # ------------------------------------------------------------------------------------------------ function caHTMLLink($ps_content, $pa_attributes=null, $pa_options=null) { $vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options); $vs_element = "<a {$vs_attr_string}>{$ps_content}</a>"; return $vs_element; } # ------------------------------------------------------------------------------------------------ /** * Generates an HTML <img> or Tilepic embed tag with supplied URL and attributes * * @param $ps_url string The image URL * @param $pa_options array Options include: * scaleCSSWidthTo = width in pixels to *style* via CSS the returned image to. Does not actually alter the image. Aspect ratio of the image is preserved, with the combination of scaleCSSWidthTo and scaleCSSHeightTo being taken as a bounding box for the image. Only applicable to standard <img> tags. Tilepic display size cannot be styled using CSS; use the "width" and "height" options instead. * scaleCSSHeightTo = height in pixels to *style* via CSS the returned image to. * * @return string */ function caHTMLImage($ps_url, $pa_options=null) { if (!is_array($pa_options)) { $pa_options = array(); } $va_attributes = array('src' => $ps_url); foreach(array('name', 'id', 'width', 'height', 'vspace', 'hspace', 'alt', 'title', 'usemap', 'align', 'border', 'class', 'style') as $vs_attr) { if (isset($pa_options[$vs_attr])) { $va_attributes[$vs_attr] = $pa_options[$vs_attr]; } } // Allow data-* attributes foreach($pa_options as $vs_k => $vs_v) { if (substr($vs_k, 0, 5) == 'data-') { $va_attributes[$vs_k] = $vs_v; } } $vn_scale_css_width_to = caGetOption('scaleCSSWidthTo', $pa_options, null); $vn_scale_css_height_to = caGetOption('scaleCSSHeightTo', $pa_options, null); if ($vn_scale_css_width_to || $vn_scale_css_height_to) { if (!$vn_scale_css_width_to) { $vn_scale_css_width_to = $vn_scale_css_height_to; } if (!$vn_scale_css_height_to) { $vn_scale_css_height_to = $vn_scale_css_width_to; } $va_scaled_dimensions = caFitImageDimensions($va_attributes['width'], $va_attributes['height'], $vn_scale_css_width_to, $vn_scale_css_height_to); $va_attributes['width'] = $va_scaled_dimensions['width'].'px'; $va_attributes['height'] = $va_scaled_dimensions['height'].'px'; } $vs_attr_string = _caHTMLMakeAttributeString($va_attributes, $pa_options); if(preg_match("/\.tpc\$/", $ps_url)) { # # Tilepic # $vn_width = (int)$pa_options["width"]; $vn_height = (int)$pa_options["height"]; $vn_tile_width = caGetOption('tile_width', $pa_options, 256, array('castTo'=>'int')); $vn_tile_height = caGetOption('tile_height', $pa_options, 256, array('castTo'=>'int')); // Tiles must be square. if ($vn_tile_width != $vn_tile_height){ $vn_tile_height = $vn_tile_width; } $vn_layers = (int)$pa_options["layers"]; if (!($vs_id_name = (string)$pa_options["idname"])) { $vs_id_name = (string)$pa_options["id"]; } $vn_viewer_width = $pa_options["viewer_width"]; $vn_viewer_height = $pa_options["viewer_height"]; $vs_annotation_load_url = caGetOption("annotation_load_url", $pa_options, null); $vs_annotation_save_url = caGetOption("annotation_save_url", $pa_options, null); $vs_help_load_url = caGetOption("help_load_url", $pa_options, null); $vb_read_only = caGetOption("read_only", $pa_options, null); $vs_annotation_editor_panel = caGetOption("annotationEditorPanel", $pa_options, null); $vs_annotation_editor_url = caGetOption("annotationEditorUrl", $pa_options, null); $vs_viewer_base_url = caGetOption("viewer_base_url", $pa_options, __CA_URL_ROOT__); $o_config = Configuration::load(); if (!$vn_viewer_width || !$vn_viewer_height) { $vn_viewer_width = (int)$o_config->get("tilepic_viewer_width"); if (!$vn_viewer_width) { $vn_viewer_width = 500; } $vn_viewer_height = (int)$o_config->get("tilepic_viewer_height"); if (!$vn_viewer_height) { $vn_viewer_height = 500; } } $vs_error_tag = caGetOption("alt_image_tag", $pa_options, ''); $vn_viewer_width_with_units = $vn_viewer_width; $vn_viewer_height_with_units = $vn_viewer_height; if (preg_match('!^[\d]+$!', $vn_viewer_width)) { $vn_viewer_width_with_units .= 'px'; } if (preg_match('!^[\d]+$!', $vn_viewer_height)) { $vn_viewer_height_with_units .= 'px'; } if(!is_array($va_viewer_opts_from_app_config = $o_config->getAssoc('image_viewer_options'))) { $va_viewer_opts_from_app_config = array(); } $va_opts = array_merge(array( 'id' => "{$vs_id_name}_viewer", 'src' => "{$vs_viewer_base_url}/viewers/apps/tilepic.php?p={$ps_url}&t=", 'annotationLoadUrl' => $vs_annotation_load_url, 'annotationSaveUrl' => $vs_annotation_save_url, 'annotationEditorPanel' => $vs_annotation_editor_panel, 'annotationEditorUrl' => $vs_annotation_editor_url, 'annotationEditorLink' => _t('More...'), 'helpLoadUrl' => $vs_help_load_url, 'lockAnnotations' => ($vb_read_only ? true : false), 'showAnnotationTools' => ($vb_read_only ? false : true) ), $va_viewer_opts_from_app_config); $va_opts['info'] = array( 'width' => $vn_width, 'height' => $vn_height, // Set tile size using function options. 'tilesize'=> $vn_tile_width, 'levels' => $vn_layers ); $vs_tag = " <div id='{$vs_id_name}' style='width:{$vn_viewer_width_with_units}; height: {$vn_viewer_height_with_units}; position: relative; z-index: 0;'> {$vs_error_tag} </div> <script type='text/javascript'> var elem = document.createElement('canvas'); if (elem.getContext && elem.getContext('2d')) { jQuery(document).ready(function() { jQuery('#{$vs_id_name}').tileviewer(".json_encode($va_opts)."); }); } </script>\n"; return $vs_tag; } else { # # Standard image # if (!isset($pa_options["width"])) $pa_options["width"] = 100; if (!isset($pa_options["height"])) $pa_options["height"] = 100; if (($ps_url) && ($pa_options["width"] > 0) && ($pa_options["height"] > 0)) { $vs_element = "<img {$vs_attr_string} />"; } else { $vs_element = ""; } } return $vs_element; } # ------------------------------------------------------------------------------------------------ /** * Create string for use in HTML tags out of attribute array. * * @param array $pa_attributes * @param array $pa_options Optional array of options. Supported options are: * dontConvertAttributeQuotesToEntities = if true, attribute values are not passed through htmlspecialchars(); if you set this be sure to only use single quotes in your attribute values or escape all double quotes since double quotes are used to enclose tem */ function _caHTMLMakeAttributeString($pa_attributes, $pa_options=null) { $va_attr_settings = array(); if (is_array($pa_attributes)) { foreach($pa_attributes as $vs_attr => $vs_attr_val) { if (is_array($vs_attr_val)) { $vs_attr_val = join(" ", $vs_attr_val); } if (is_object($vs_attr_val)) { continue; } if (isset($pa_options['dontConvertAttributeQuotesToEntities']) && $pa_options['dontConvertAttributeQuotesToEntities']) { $va_attr_settings[] = $vs_attr.'="'.$vs_attr_val.'"'; } else { $va_attr_settings[] = $vs_attr.'=\''.htmlspecialchars($vs_attr_val, ENT_QUOTES, 'UTF-8').'\''; } } } return join(' ', $va_attr_settings); } # ------------------------------------------------------------------------------------------------ /** * Takes an HTML form field ($ps_field), a text label ($ps_table), and DOM ID to wrap the label in ($ps_id) * and a block of help/descriptive text ($ps_description) and returns a formatted block of HTML with * a jQuery-based tool tip attached. Formatting is performed using the format defined in app.conf * by the 'form_element_display_format' config directive unless overridden by a format passed in * the optional $ps_format parameter. * * Note that $ps_description is also optional. If it is omitted or passed blank then no tooltip is attached */ function caHTMLMakeLabeledFormElement($ps_field, $ps_label, $ps_id, $ps_description='', $ps_format='', $pb_emit_tooltip=true) { $o_config = Configuration::load(); if (!$ps_format) { $ps_format = $o_config->get('form_element_display_format'); } $vs_formatted_element = str_replace("^LABEL",'<span id="'.$ps_id.'">'.$ps_label.'</span>', $ps_format); $vs_formatted_element = str_replace("^ELEMENT", $ps_field, $vs_formatted_element); $vs_formatted_element = str_replace("^EXTRA", '', $vs_formatted_element); if ($ps_description && $pb_emit_tooltip) { TooltipManager::add('#'.$ps_id, "<h3>{$ps_label}</h3>{$ps_description}"); } return $vs_formatted_element; } # ------------------------------------------------------------------------------------------------
collectiveaccess/providence
app/helpers/htmlFormHelpers.php
PHP
gpl-3.0
27,259
namespace MissionPlanner.GCSViews { partial class InitialSetup { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(InitialSetup)); this.backstageView = new MissionPlanner.Controls.BackstageView.BackstageView(); this.backstageViewPagefw = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.initialSetupBindingSource = new System.Windows.Forms.BindingSource(this.components); this.configFirmware1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigFirmware(); this.backstageViewPagefwdisabled = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configFirmwareDisabled1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigFirmwareDisabled(); this.backstageViewPagewizard = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configWizard1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigWizard(); this.backstageViewPagemand = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configMandatory1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigMandatory(); this.backstageViewPagetradheli = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configTradHeli1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigTradHeli(); this.backstageViewPageframetype = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configFrameType1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigFrameType(); this.backstageViewPageaccel = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configAccelerometerCalibration = new MissionPlanner.GCSViews.ConfigurationView.ConfigAccelerometerCalibration(); this.backstageViewPagecompass = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configHWCompass1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWCompass(); this.backstageViewPageradio = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configRadioInput1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigRadioInput(); this.backstageViewPageESC = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configESC1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigESCCalibration(); this.backstageViewPageflmode = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configFlightModes1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigFlightModes(); this.backstageViewPagefs = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configFailSafe1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigFailSafe(); this.backstageViewPageopt = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configOptional1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigOptional(); this.backstageViewPageSikradio = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this._3DRradio1 = new MissionPlanner.Sikradio(); this.backstageViewPagebatmon = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configBatteryMonitoring1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigBatteryMonitoring(); this.backstageViewPageBatt2 = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configBatteryMonitoring21 = new MissionPlanner.GCSViews.ConfigurationView.ConfigBatteryMonitoring2(); this.backstageViewPagecompassmot = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configCompassMot1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigCompassMot(); this.backstageViewPagesonar = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.ConfigHWRangeFinder1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWRangeFinder(); this.backstageViewPageairspeed = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configHWAirspeed1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWAirspeed(); this.backstageViewPageoptflow = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configHWOptFlow1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWOptFlow(); this.backstageViewPageosd = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configHWOSD1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWOSD(); this.backstageViewPagegimbal = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configMount1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigMount(); this.backstageViewPageAntTrack = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.tracker1 = new MissionPlanner.Antenna.Tracker(); this.backstageViewPageMotorTest = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configMotor1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigMotorTest(); this.backstageViewPagehwbt = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configHWBT1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWBT(); this.backstageViewPageParachute = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); this.configHWPa1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWParachute(); this.backstageViewPageinstfw = new MissionPlanner.Controls.BackstageView.BackstageViewPage(); ((System.ComponentModel.ISupportInitialize)(this.initialSetupBindingSource)).BeginInit(); this.SuspendLayout(); // // backstageView // resources.ApplyResources(this.backstageView, "backstageView"); this.backstageView.HighlightColor1 = System.Drawing.SystemColors.Highlight; this.backstageView.HighlightColor2 = System.Drawing.SystemColors.MenuHighlight; this.backstageView.Name = "backstageView"; this.backstageView.Pages.Add(this.backstageViewPagefw); this.backstageView.Pages.Add(this.backstageViewPagefwdisabled); this.backstageView.Pages.Add(this.backstageViewPagewizard); this.backstageView.Pages.Add(this.backstageViewPagemand); this.backstageView.Pages.Add(this.backstageViewPagetradheli); this.backstageView.Pages.Add(this.backstageViewPageframetype); this.backstageView.Pages.Add(this.backstageViewPageaccel); this.backstageView.Pages.Add(this.backstageViewPagecompass); this.backstageView.Pages.Add(this.backstageViewPageradio); this.backstageView.Pages.Add(this.backstageViewPageESC); this.backstageView.Pages.Add(this.backstageViewPageflmode); this.backstageView.Pages.Add(this.backstageViewPagefs); this.backstageView.Pages.Add(this.backstageViewPageopt); this.backstageView.Pages.Add(this.backstageViewPageSikradio); this.backstageView.Pages.Add(this.backstageViewPagebatmon); this.backstageView.Pages.Add(this.backstageViewPageBatt2); this.backstageView.Pages.Add(this.backstageViewPagecompassmot); this.backstageView.Pages.Add(this.backstageViewPagesonar); this.backstageView.Pages.Add(this.backstageViewPageairspeed); this.backstageView.Pages.Add(this.backstageViewPageoptflow); this.backstageView.Pages.Add(this.backstageViewPageosd); this.backstageView.Pages.Add(this.backstageViewPagegimbal); this.backstageView.Pages.Add(this.backstageViewPageAntTrack); this.backstageView.Pages.Add(this.backstageViewPageMotorTest); this.backstageView.Pages.Add(this.backstageViewPagehwbt); this.backstageView.Pages.Add(this.backstageViewPageParachute); this.backstageView.WidthMenu = 172; // // backstageViewPagefw // this.backstageViewPagefw.Advanced = false; this.backstageViewPagefw.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isDisConnected", true)); this.backstageViewPagefw.LinkText = "Install Firmware"; this.backstageViewPagefw.Page = this.configFirmware1; this.backstageViewPagefw.Parent = null; this.backstageViewPagefw.Show = true; this.backstageViewPagefw.Spacing = 30; resources.ApplyResources(this.backstageViewPagefw, "backstageViewPagefw"); // // initialSetupBindingSource // this.initialSetupBindingSource.DataSource = typeof(MissionPlanner.GCSViews.InitialSetup); // // configFirmware1 // resources.ApplyResources(this.configFirmware1, "configFirmware1"); this.configFirmware1.Name = "configFirmware1"; // // backstageViewPagefwdisabled // this.backstageViewPagefwdisabled.Advanced = false; this.backstageViewPagefwdisabled.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isConnected", true)); this.backstageViewPagefwdisabled.LinkText = "Install Firmware"; this.backstageViewPagefwdisabled.Page = this.configFirmwareDisabled1; this.backstageViewPagefwdisabled.Parent = null; this.backstageViewPagefwdisabled.Show = true; this.backstageViewPagefwdisabled.Spacing = 30; resources.ApplyResources(this.backstageViewPagefwdisabled, "backstageViewPagefwdisabled"); // // configFirmwareDisabled1 // resources.ApplyResources(this.configFirmwareDisabled1, "configFirmwareDisabled1"); this.configFirmwareDisabled1.Name = "configFirmwareDisabled1"; // // backstageViewPagewizard // this.backstageViewPagewizard.Advanced = false; this.backstageViewPagewizard.LinkText = "Wizard"; this.backstageViewPagewizard.Page = this.configWizard1; this.backstageViewPagewizard.Parent = null; this.backstageViewPagewizard.Show = true; this.backstageViewPagewizard.Spacing = 30; resources.ApplyResources(this.backstageViewPagewizard, "backstageViewPagewizard"); // // configWizard1 // resources.ApplyResources(this.configWizard1, "configWizard1"); this.configWizard1.Name = "configWizard1"; // // backstageViewPagemand // this.backstageViewPagemand.Advanced = false; this.backstageViewPagemand.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isConnected", true)); this.backstageViewPagemand.LinkText = "Mandatory Hardware"; this.backstageViewPagemand.Page = this.configMandatory1; this.backstageViewPagemand.Parent = null; this.backstageViewPagemand.Show = true; this.backstageViewPagemand.Spacing = 30; resources.ApplyResources(this.backstageViewPagemand, "backstageViewPagemand"); // // configMandatory1 // resources.ApplyResources(this.configMandatory1, "configMandatory1"); this.configMandatory1.Name = "configMandatory1"; // // backstageViewPagetradheli // this.backstageViewPagetradheli.Advanced = false; this.backstageViewPagetradheli.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isHeli", true)); this.backstageViewPagetradheli.LinkText = "Heli Setup"; this.backstageViewPagetradheli.Page = this.configTradHeli1; this.backstageViewPagetradheli.Parent = this.backstageViewPagemand; this.backstageViewPagetradheli.Show = true; this.backstageViewPagetradheli.Spacing = 30; resources.ApplyResources(this.backstageViewPagetradheli, "backstageViewPagetradheli"); // // configTradHeli1 // resources.ApplyResources(this.configTradHeli1, "configTradHeli1"); this.configTradHeli1.Name = "configTradHeli1"; // // backstageViewPageframetype // this.backstageViewPageframetype.Advanced = false; this.backstageViewPageframetype.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isCopter", true)); this.backstageViewPageframetype.LinkText = "Frame Type"; this.backstageViewPageframetype.Page = this.configFrameType1; this.backstageViewPageframetype.Parent = this.backstageViewPagemand; this.backstageViewPageframetype.Show = true; this.backstageViewPageframetype.Spacing = 30; resources.ApplyResources(this.backstageViewPageframetype, "backstageViewPageframetype"); // // configFrameType1 // resources.ApplyResources(this.configFrameType1, "configFrameType1"); this.configFrameType1.Name = "configFrameType1"; // // backstageViewPageaccel // this.backstageViewPageaccel.Advanced = false; this.backstageViewPageaccel.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isConnected", true)); this.backstageViewPageaccel.LinkText = "Accel Calibration"; this.backstageViewPageaccel.Page = this.configAccelerometerCalibration; this.backstageViewPageaccel.Parent = this.backstageViewPagemand; this.backstageViewPageaccel.Show = true; this.backstageViewPageaccel.Spacing = 30; resources.ApplyResources(this.backstageViewPageaccel, "backstageViewPageaccel"); // // configAccelerometerCalibration // resources.ApplyResources(this.configAccelerometerCalibration, "configAccelerometerCalibration"); this.configAccelerometerCalibration.Name = "configAccelerometerCalibration"; // // backstageViewPagecompass // this.backstageViewPagecompass.Advanced = false; this.backstageViewPagecompass.LinkText = "Compass"; this.backstageViewPagecompass.Page = this.configHWCompass1; this.backstageViewPagecompass.Parent = this.backstageViewPagemand; this.backstageViewPagecompass.Show = true; this.backstageViewPagecompass.Spacing = 30; resources.ApplyResources(this.backstageViewPagecompass, "backstageViewPagecompass"); // // configHWCompass1 // resources.ApplyResources(this.configHWCompass1, "configHWCompass1"); this.configHWCompass1.Name = "configHWCompass1"; // // backstageViewPageradio // this.backstageViewPageradio.Advanced = false; this.backstageViewPageradio.LinkText = "Radio Calibration"; this.backstageViewPageradio.Page = this.configRadioInput1; this.backstageViewPageradio.Parent = this.backstageViewPagemand; this.backstageViewPageradio.Show = true; this.backstageViewPageradio.Spacing = 30; resources.ApplyResources(this.backstageViewPageradio, "backstageViewPageradio"); // // configRadioInput1 // resources.ApplyResources(this.configRadioInput1, "configRadioInput1"); this.configRadioInput1.Name = "configRadioInput1"; // // backstageViewPageESC // this.backstageViewPageESC.Advanced = false; this.backstageViewPageESC.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isCopter", true)); this.backstageViewPageESC.LinkText = "ESC Calibration"; this.backstageViewPageESC.Page = this.configESC1; this.backstageViewPageESC.Parent = this.backstageViewPagemand; this.backstageViewPageESC.Show = false; this.backstageViewPageESC.Spacing = 30; resources.ApplyResources(this.backstageViewPageESC, "backstageViewPageESC"); // // configESC1 // resources.ApplyResources(this.configESC1, "configESC1"); this.configESC1.Name = "configESC1"; // // backstageViewPageflmode // this.backstageViewPageflmode.Advanced = false; this.backstageViewPageflmode.LinkText = "Flight Modes"; this.backstageViewPageflmode.Page = this.configFlightModes1; this.backstageViewPageflmode.Parent = this.backstageViewPagemand; this.backstageViewPageflmode.Show = true; this.backstageViewPageflmode.Spacing = 30; resources.ApplyResources(this.backstageViewPageflmode, "backstageViewPageflmode"); // // configFlightModes1 // resources.ApplyResources(this.configFlightModes1, "configFlightModes1"); this.configFlightModes1.Name = "configFlightModes1"; // // backstageViewPagefs // this.backstageViewPagefs.Advanced = false; this.backstageViewPagefs.LinkText = "FailSafe"; this.backstageViewPagefs.Page = this.configFailSafe1; this.backstageViewPagefs.Parent = this.backstageViewPagemand; this.backstageViewPagefs.Show = true; this.backstageViewPagefs.Spacing = 30; resources.ApplyResources(this.backstageViewPagefs, "backstageViewPagefs"); // // configFailSafe1 // resources.ApplyResources(this.configFailSafe1, "configFailSafe1"); this.configFailSafe1.Name = "configFailSafe1"; // // backstageViewPageopt // this.backstageViewPageopt.Advanced = false; this.backstageViewPageopt.LinkText = "Optional Hardware"; this.backstageViewPageopt.Page = this.configOptional1; this.backstageViewPageopt.Parent = null; this.backstageViewPageopt.Show = true; this.backstageViewPageopt.Spacing = 30; resources.ApplyResources(this.backstageViewPageopt, "backstageViewPageopt"); // // configOptional1 // resources.ApplyResources(this.configOptional1, "configOptional1"); this.configOptional1.Name = "configOptional1"; // // backstageViewPageSikradio // this.backstageViewPageSikradio.Advanced = false; this.backstageViewPageSikradio.LinkText = "Sik Radio"; this.backstageViewPageSikradio.Page = this._3DRradio1; this.backstageViewPageSikradio.Parent = this.backstageViewPageopt; this.backstageViewPageSikradio.Show = true; this.backstageViewPageSikradio.Spacing = 30; resources.ApplyResources(this.backstageViewPageSikradio, "backstageViewPageSikradio"); // // _3DRradio1 // resources.ApplyResources(this._3DRradio1, "_3DRradio1"); this._3DRradio1.Name = "_3DRradio1"; // // backstageViewPagebatmon // this.backstageViewPagebatmon.Advanced = false; this.backstageViewPagebatmon.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isConnected", true)); this.backstageViewPagebatmon.LinkText = "Battery Monitor"; this.backstageViewPagebatmon.Page = this.configBatteryMonitoring1; this.backstageViewPagebatmon.Parent = this.backstageViewPageopt; this.backstageViewPagebatmon.Show = true; this.backstageViewPagebatmon.Spacing = 30; resources.ApplyResources(this.backstageViewPagebatmon, "backstageViewPagebatmon"); // // configBatteryMonitoring1 // resources.ApplyResources(this.configBatteryMonitoring1, "configBatteryMonitoring1"); this.configBatteryMonitoring1.Name = "configBatteryMonitoring1"; // // backstageViewPageBatt2 // this.backstageViewPageBatt2.Advanced = false; this.backstageViewPageBatt2.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isConnected", true)); this.backstageViewPageBatt2.LinkText = "Battery Monitor 2"; this.backstageViewPageBatt2.Page = this.configBatteryMonitoring21; this.backstageViewPageBatt2.Parent = this.backstageViewPageopt; this.backstageViewPageBatt2.Show = true; this.backstageViewPageBatt2.Spacing = 30; resources.ApplyResources(this.backstageViewPageBatt2, "backstageViewPageBatt2"); // // configBatteryMonitoring21 // resources.ApplyResources(this.configBatteryMonitoring21, "configBatteryMonitoring21"); this.configBatteryMonitoring21.Name = "configBatteryMonitoring21"; // // backstageViewPagecompassmot // this.backstageViewPagecompassmot.Advanced = false; this.backstageViewPagecompassmot.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isCopter", true)); this.backstageViewPagecompassmot.LinkText = "Compass/Motor Calib"; this.backstageViewPagecompassmot.Page = this.configCompassMot1; this.backstageViewPagecompassmot.Parent = this.backstageViewPageopt; this.backstageViewPagecompassmot.Show = true; this.backstageViewPagecompassmot.Spacing = 30; resources.ApplyResources(this.backstageViewPagecompassmot, "backstageViewPagecompassmot"); // // configCompassMot1 // resources.ApplyResources(this.configCompassMot1, "configCompassMot1"); this.configCompassMot1.Name = "configCompassMot1"; // // backstageViewPagesonar // this.backstageViewPagesonar.Advanced = false; this.backstageViewPagesonar.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isConnected", true)); this.backstageViewPagesonar.LinkText = "Sonar"; this.backstageViewPagesonar.Page = this.ConfigHWRangeFinder1; this.backstageViewPagesonar.Parent = this.backstageViewPageopt; this.backstageViewPagesonar.Show = true; this.backstageViewPagesonar.Spacing = 30; resources.ApplyResources(this.backstageViewPagesonar, "backstageViewPagesonar"); // // ConfigHWRangeFinder1 // resources.ApplyResources(this.ConfigHWRangeFinder1, "ConfigHWRangeFinder1"); this.ConfigHWRangeFinder1.Name = "ConfigHWRangeFinder1"; // // backstageViewPageairspeed // this.backstageViewPageairspeed.Advanced = false; this.backstageViewPageairspeed.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isConnected", true)); this.backstageViewPageairspeed.LinkText = "Airspeed"; this.backstageViewPageairspeed.Page = this.configHWAirspeed1; this.backstageViewPageairspeed.Parent = this.backstageViewPageopt; this.backstageViewPageairspeed.Show = true; this.backstageViewPageairspeed.Spacing = 30; resources.ApplyResources(this.backstageViewPageairspeed, "backstageViewPageairspeed"); // // configHWAirspeed1 // resources.ApplyResources(this.configHWAirspeed1, "configHWAirspeed1"); this.configHWAirspeed1.Name = "configHWAirspeed1"; // // backstageViewPageoptflow // this.backstageViewPageoptflow.Advanced = false; this.backstageViewPageoptflow.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isConnected", true)); this.backstageViewPageoptflow.LinkText = "Optical Flow"; this.backstageViewPageoptflow.Page = this.configHWOptFlow1; this.backstageViewPageoptflow.Parent = this.backstageViewPageopt; this.backstageViewPageoptflow.Show = true; this.backstageViewPageoptflow.Spacing = 30; resources.ApplyResources(this.backstageViewPageoptflow, "backstageViewPageoptflow"); // // configHWOptFlow1 // resources.ApplyResources(this.configHWOptFlow1, "configHWOptFlow1"); this.configHWOptFlow1.Name = "configHWOptFlow1"; // // backstageViewPageosd // this.backstageViewPageosd.Advanced = false; this.backstageViewPageosd.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isConnected", true)); this.backstageViewPageosd.LinkText = "OSD"; this.backstageViewPageosd.Page = this.configHWOSD1; this.backstageViewPageosd.Parent = this.backstageViewPageopt; this.backstageViewPageosd.Show = true; this.backstageViewPageosd.Spacing = 30; resources.ApplyResources(this.backstageViewPageosd, "backstageViewPageosd"); // // configHWOSD1 // resources.ApplyResources(this.configHWOSD1, "configHWOSD1"); this.configHWOSD1.Name = "configHWOSD1"; // // backstageViewPagegimbal // this.backstageViewPagegimbal.Advanced = false; this.backstageViewPagegimbal.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isConnected", true)); this.backstageViewPagegimbal.LinkText = "Camera Gimbal"; this.backstageViewPagegimbal.Page = this.configMount1; this.backstageViewPagegimbal.Parent = this.backstageViewPageopt; this.backstageViewPagegimbal.Show = true; this.backstageViewPagegimbal.Spacing = 30; resources.ApplyResources(this.backstageViewPagegimbal, "backstageViewPagegimbal"); // // configMount1 // resources.ApplyResources(this.configMount1, "configMount1"); this.configMount1.Name = "configMount1"; // // backstageViewPageAntTrack // this.backstageViewPageAntTrack.Advanced = false; this.backstageViewPageAntTrack.LinkText = "Antenna tracker"; this.backstageViewPageAntTrack.Page = this.tracker1; this.backstageViewPageAntTrack.Parent = this.backstageViewPageopt; this.backstageViewPageAntTrack.Show = true; this.backstageViewPageAntTrack.Spacing = 30; resources.ApplyResources(this.backstageViewPageAntTrack, "backstageViewPageAntTrack"); // // tracker1 // this.tracker1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(38)))), ((int)(((byte)(39)))), ((int)(((byte)(40))))); resources.ApplyResources(this.tracker1, "tracker1"); this.tracker1.ForeColor = System.Drawing.Color.White; this.tracker1.Name = "tracker1"; // // backstageViewPageMotorTest // this.backstageViewPageMotorTest.Advanced = false; this.backstageViewPageMotorTest.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isCopter", true)); this.backstageViewPageMotorTest.LinkText = "Motor Test"; this.backstageViewPageMotorTest.Page = this.configMotor1; this.backstageViewPageMotorTest.Parent = this.backstageViewPageopt; this.backstageViewPageMotorTest.Show = true; this.backstageViewPageMotorTest.Spacing = 30; resources.ApplyResources(this.backstageViewPageMotorTest, "backstageViewPageMotorTest"); // // configMotor1 // resources.ApplyResources(this.configMotor1, "configMotor1"); this.configMotor1.Name = "configMotor1"; // // backstageViewPagehwbt // this.backstageViewPagehwbt.Advanced = false; this.backstageViewPagehwbt.LinkText = "Bluetooth Setup"; this.backstageViewPagehwbt.Page = this.configHWBT1; this.backstageViewPagehwbt.Parent = this.backstageViewPageopt; this.backstageViewPagehwbt.Show = true; this.backstageViewPagehwbt.Spacing = 30; resources.ApplyResources(this.backstageViewPagehwbt, "backstageViewPagehwbt"); // // configHWBT1 // resources.ApplyResources(this.configHWBT1, "configHWBT1"); this.configHWBT1.Name = "configHWBT1"; // // backstageViewPageParachute // this.backstageViewPageParachute.Advanced = false; this.backstageViewPageParachute.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isCopter", true)); this.backstageViewPageParachute.LinkText = "Parachute"; this.backstageViewPageParachute.Page = this.configHWPa1; this.backstageViewPageParachute.Parent = this.backstageViewPageopt; this.backstageViewPageParachute.Show = true; this.backstageViewPageParachute.Spacing = 30; resources.ApplyResources(this.backstageViewPageParachute, "backstageViewPageParachute"); // // configHWPa1 // resources.ApplyResources(this.configHWPa1, "configHWPa1"); this.configHWPa1.Name = "configHWPa1"; // // backstageViewPageinstfw // this.backstageViewPageinstfw.Advanced = false; this.backstageViewPageinstfw.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isDisConnected", true)); this.backstageViewPageinstfw.LinkText = "Install Firmware"; this.backstageViewPageinstfw.Page = this.configFirmware1; this.backstageViewPageinstfw.Parent = null; this.backstageViewPageinstfw.Show = false; this.backstageViewPageinstfw.Spacing = 30; resources.ApplyResources(this.backstageViewPageinstfw, "backstageViewPageinstfw"); // // InitialSetup // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.Controls.Add(this.backstageView); this.Controls.Add(this.configAccelerometerCalibration); this.Controls.Add(this.configHWBT1); this.Controls.Add(this.configBatteryMonitoring21); this.MinimumSize = new System.Drawing.Size(1000, 450); this.Name = "InitialSetup"; resources.ApplyResources(this, "$this"); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.HardwareConfig_FormClosing); this.Load += new System.EventHandler(this.HardwareConfig_Load); ((System.ComponentModel.ISupportInitialize)(this.initialSetupBindingSource)).EndInit(); this.ResumeLayout(false); } #endregion internal Controls.BackstageView.BackstageView backstageView; private ConfigurationView.ConfigFirmware configFirmware1; private ConfigurationView.ConfigFirmwareDisabled configFirmwareDisabled1; private ConfigurationView.ConfigWizard configWizard1; private ConfigurationView.ConfigMandatory configMandatory1; private ConfigurationView.ConfigOptional configOptional1; private ConfigurationView.ConfigTradHeli configTradHeli1; private ConfigurationView.ConfigFrameType configFrameType1; private ConfigurationView.ConfigHWCompass configHWCompass1; private ConfigurationView.ConfigRadioInput configRadioInput1; private ConfigurationView.ConfigFlightModes configFlightModes1; private ConfigurationView.ConfigFailSafe configFailSafe1; private Sikradio _3DRradio1; private ConfigurationView.ConfigBatteryMonitoring configBatteryMonitoring1; private ConfigurationView.ConfigHWRangeFinder ConfigHWRangeFinder1; private ConfigurationView.ConfigHWAirspeed configHWAirspeed1; private ConfigurationView.ConfigHWOptFlow configHWOptFlow1; private ConfigurationView.ConfigHWOSD configHWOSD1; private ConfigurationView.ConfigMount configMount1; private ConfigurationView.ConfigMotorTest configMotor1; private Antenna.Tracker tracker1; private Controls.BackstageView.BackstageViewPage backstageViewPageinstfw; private Controls.BackstageView.BackstageViewPage backstageViewPagewizard; private Controls.BackstageView.BackstageViewPage backstageViewPagemand; private Controls.BackstageView.BackstageViewPage backstageViewPageopt; private Controls.BackstageView.BackstageViewPage backstageViewPagetradheli; private Controls.BackstageView.BackstageViewPage backstageViewPageframetype; private Controls.BackstageView.BackstageViewPage backstageViewPagecompass; private Controls.BackstageView.BackstageViewPage backstageViewPageradio; private Controls.BackstageView.BackstageViewPage backstageViewPageflmode; private Controls.BackstageView.BackstageViewPage backstageViewPagefs; private Controls.BackstageView.BackstageViewPage backstageViewPageSikradio; private Controls.BackstageView.BackstageViewPage backstageViewPagebatmon; private Controls.BackstageView.BackstageViewPage backstageViewPagesonar; private Controls.BackstageView.BackstageViewPage backstageViewPageairspeed; private Controls.BackstageView.BackstageViewPage backstageViewPageoptflow; private Controls.BackstageView.BackstageViewPage backstageViewPageosd; private Controls.BackstageView.BackstageViewPage backstageViewPagegimbal; private Controls.BackstageView.BackstageViewPage backstageViewPageAntTrack; private Controls.BackstageView.BackstageViewPage backstageViewPagefwdisabled; private Controls.BackstageView.BackstageViewPage backstageViewPagefw; private System.Windows.Forms.BindingSource initialSetupBindingSource; private Controls.BackstageView.BackstageViewPage backstageViewPagecompassmot; private ConfigurationView.ConfigCompassMot configCompassMot1; private Controls.BackstageView.BackstageViewPage backstageViewPageMotorTest; private Controls.BackstageView.BackstageViewPage backstageViewPageaccel; private ConfigurationView.ConfigAccelerometerCalibration configAccelerometerCalibration; private Controls.BackstageView.BackstageViewPage backstageViewPagehwbt; private ConfigurationView.ConfigHWBT configHWBT1; private Controls.BackstageView.BackstageViewPage backstageViewPageParachute; private ConfigurationView.ConfigHWParachute configHWPa1; private Controls.BackstageView.BackstageViewPage backstageViewPageESC; private ConfigurationView.ConfigESCCalibration configESC1; private Controls.BackstageView.BackstageViewPage backstageViewPageBatt2; private ConfigurationView.ConfigBatteryMonitoring2 configBatteryMonitoring21; } }
brianlsharp/MissionPlanner
GCSViews/InitialSetup.Designer.cs
C#
gpl-3.0
38,120
/* FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd. All rights reserved VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception. *************************************************************************** >>! NOTE: The modification to the GPL is included to allow you to !<< >>! distribute a combined work that includes FreeRTOS without being !<< >>! obliged to provide the source code for proprietary components !<< >>! outside of the FreeRTOS kernel. !<< *************************************************************************** FreeRTOS 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. Full license text is available on the following link: http://www.freertos.org/a00114.html *************************************************************************** * * * FreeRTOS provides completely free yet professionally developed, * * robust, strictly quality controlled, supported, and cross * * platform software that is more than just the market leader, it * * is the industry's de facto standard. * * * * Help yourself get started quickly while simultaneously helping * * to support the FreeRTOS project by purchasing a FreeRTOS * * tutorial book, reference manual, or both: * * http://www.FreeRTOS.org/Documentation * * * *************************************************************************** http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading the FAQ page "My application does not run, what could be wrong?". Have you defined configASSERT()? http://www.FreeRTOS.org/support - In return for receiving this top quality embedded software for free we request you assist our global community by participating in the support forum. http://www.FreeRTOS.org/training - Investing in training allows your team to be as productive as possible as early as possible. Now you can receive FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers Ltd, and the world's leading authority on the world's leading RTOS. http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, including FreeRTOS+Trace - an indispensable productivity tool, a DOS compatible FAT file system, and our tiny thread aware UDP/IP stack. http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS licenses offer ticketed support, indemnification and commercial middleware. http://www.SafeRTOS.com - High Integrity Systems also provide a safety engineered and independently SIL3 certified version for use in safety and mission critical applications that require provable dependability. 1 tab == 4 spaces! */ #ifndef FREERTOS_CONFIG_H #define FREERTOS_CONFIG_H /*----------------------------------------------------------- * Application specific definitions. * * These definitions should be adjusted for your particular hardware and * application requirements. * * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. * * See http://www.freertos.org/a00110.html. *----------------------------------------------------------*/ /* For definition of BOARD_MCK. */ #ifndef __IAR_SYSTEMS_ASM__ /* Prevent chip.h being included when this file is included from the IAR port layer assembly file. */ #include "board.h" #endif #define configUSE_PREEMPTION 1 #define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 #define configUSE_QUEUE_SETS 1 #define configUSE_IDLE_HOOK 0 #define configUSE_TICK_HOOK 1 #define configCPU_CLOCK_HZ ( BOARD_MCK << 1UL ) #define configTICK_RATE_HZ ( 1000 ) #define configMAX_PRIORITIES ( 5 ) #define configMINIMAL_STACK_SIZE ( ( unsigned short ) 130 ) #define configTOTAL_HEAP_SIZE ( ( size_t ) ( 46 * 1024 ) ) #define configMAX_TASK_NAME_LEN ( 10 ) #define configUSE_TRACE_FACILITY 1 #define configUSE_16_BIT_TICKS 0 #define configIDLE_SHOULD_YIELD 1 #define configUSE_MUTEXES 1 #define configQUEUE_REGISTRY_SIZE 8 #define configCHECK_FOR_STACK_OVERFLOW 2 #define configUSE_RECURSIVE_MUTEXES 1 #define configUSE_MALLOC_FAILED_HOOK 1 #define configUSE_APPLICATION_TASK_TAG 0 #define configUSE_COUNTING_SEMAPHORES 1 /* The full demo always has tasks to run so the tick will never be turned off. The blinky demo will use the default tickless idle implementation to turn the tick off. */ #define configUSE_TICKLESS_IDLE 0 /* Run time stats gathering definitions. */ #define configGENERATE_RUN_TIME_STATS 0 /* This demo makes use of one or more example stats formatting functions. These format the raw data provided by the uxTaskGetSystemState() function in to human readable ASCII form. See the notes in the implementation of vTaskList() within FreeRTOS/Source/tasks.c for limitations. */ #define configUSE_STATS_FORMATTING_FUNCTIONS 1 /* Co-routine definitions. */ #define configUSE_CO_ROUTINES 0 #define configMAX_CO_ROUTINE_PRIORITIES ( 2 ) /* Software timer definitions. */ #define configUSE_TIMERS 1 #define configTIMER_TASK_PRIORITY ( configMAX_PRIORITIES - 1 ) #define configTIMER_QUEUE_LENGTH 5 #define configTIMER_TASK_STACK_DEPTH ( configMINIMAL_STACK_SIZE * 2 ) /* Set the following definitions to 1 to include the API function, or zero to exclude the API function. */ #define INCLUDE_vTaskPrioritySet 1 #define INCLUDE_uxTaskPriorityGet 1 #define INCLUDE_vTaskDelete 1 #define INCLUDE_vTaskCleanUpResources 1 #define INCLUDE_vTaskSuspend 1 #define INCLUDE_vTaskDelayUntil 1 #define INCLUDE_vTaskDelay 1 #define INCLUDE_eTaskGetState 1 #define INCLUDE_xTimerPendFunctionCall 1 /* Cortex-M specific definitions. */ #ifdef __NVIC_PRIO_BITS /* __BVIC_PRIO_BITS will be specified when CMSIS is being used. */ #define configPRIO_BITS __NVIC_PRIO_BITS #else #define configPRIO_BITS 3 /* 7 priority levels */ #endif /* The lowest interrupt priority that can be used in a call to a "set priority" function. */ #define configLIBRARY_LOWEST_INTERRUPT_PRIORITY 0x07 /* The highest interrupt priority that can be used by any interrupt service routine that makes calls to interrupt safe FreeRTOS API functions. DO NOT CALL INTERRUPT SAFE FREERTOS API FUNCTIONS FROM ANY INTERRUPT THAT HAS A HIGHER PRIORITY THAN THIS! (higher priorities are lower numeric values. */ #define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 4 /* Interrupt priorities used by the kernel port layer itself. These are generic to all Cortex-M ports, and do not rely on any particular library functions. */ #define configKERNEL_INTERRUPT_PRIORITY ( configLIBRARY_LOWEST_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) ) /* !!!! configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to zero !!!! See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html. */ #define configMAX_SYSCALL_INTERRUPT_PRIORITY ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) ) /* Normal assert() semantics without relying on the provision of an assert.h header file. */ #define configASSERT( x ) if( ( x ) == 0 ) { taskDISABLE_INTERRUPTS(); for( ;; ); } /* Definitions that map the FreeRTOS port interrupt handlers to their CMSIS standard names. */ #define xPortPendSVHandler PendSV_Handler #define vPortSVCHandler SVC_Handler #define xPortSysTickHandler SysTick_Handler #endif /* FREERTOS_CONFIG_H */
RobsonRojas/frertos-udemy
FreeRTOSv9.0.0/FreeRTOS/Demo/CORTEX_M7_SAMV71_Xplained_IAR_Keil/FreeRTOSConfig.h
C
gpl-3.0
8,732
/* RetroArch - A frontend for libretro. * Copyright (C) 2010-2014 - Hans-Kristian Arntzen * Copyright (C) 2011-2017 - Daniel De Matteis * Copyright (C) 2016-2019 - Brad Parker * * RetroArch 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 Found- * ation, either version 3 of the License, or (at your option) any later version. * * RetroArch 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 RetroArch. * If not, see <http://www.gnu.org/licenses/>. */ /* SIXEL context. */ #ifdef HAVE_CONFIG_H #include "../../config.h" #endif #include "../../configuration.h" #include "../../dynamic.h" #include "../../retroarch.h" #include "../../verbosity.h" #include "../../ui/ui_companion_driver.h" #if defined(_WIN32) && !defined(_XBOX) #include "../common/win32_common.h" #endif static enum gfx_ctx_api sixel_ctx_api = GFX_CTX_NONE; static void gfx_ctx_sixel_check_window(void *data, bool *quit, bool *resize, unsigned *width, unsigned *height, bool is_shutdown) { } static bool gfx_ctx_sixel_set_resize(void *data, unsigned width, unsigned height) { (void)data; (void)width; (void)height; return false; } static void gfx_ctx_sixel_update_window_title(void *data, void *data2) { const settings_t *settings = config_get_ptr(); video_frame_info_t *video_info = (video_frame_info_t*)data2; #if defined(_WIN32) && !defined(_XBOX) const ui_window_t *window = ui_companion_driver_get_window_ptr(); char title[128]; title[0] = '\0'; if (settings->bools.video_memory_show) { uint64_t mem_bytes_used = frontend_driver_get_used_memory(); uint64_t mem_bytes_total = frontend_driver_get_total_memory(); char mem[128]; mem[0] = '\0'; snprintf( mem, sizeof(mem), " || MEM: %.2f/%.2fMB", mem_bytes_used / (1024.0f * 1024.0f), mem_bytes_total / (1024.0f * 1024.0f)); strlcat(video_info->fps_text, mem, sizeof(video_info->fps_text)); } video_driver_get_window_title(title, sizeof(title)); if (window && title[0]) window->set_title(&main_window, title); #endif } static void gfx_ctx_sixel_get_video_size(void *data, unsigned *width, unsigned *height) { (void)data; } static void *gfx_ctx_sixel_init( video_frame_info_t *video_info, void *video_driver) { (void)video_driver; return (void*)"sixel"; } static void gfx_ctx_sixel_destroy(void *data) { (void)data; } static bool gfx_ctx_sixel_set_video_mode(void *data, video_frame_info_t *video_info, unsigned width, unsigned height, bool fullscreen) { return true; } static void gfx_ctx_sixel_input_driver(void *data, const char *joypad_name, input_driver_t **input, void **input_data) { (void)data; #ifdef HAVE_UDEV *input_data = input_udev.init(joypad_name); if (*input_data) { *input = &input_udev; return; } #endif *input = NULL; *input_data = NULL; } static bool gfx_ctx_sixel_has_focus(void *data) { return true; } static bool gfx_ctx_sixel_suppress_screensaver(void *data, bool enable) { return true; } static bool gfx_ctx_sixel_get_metrics(void *data, enum display_metric_types type, float *value) { return false; } static enum gfx_ctx_api gfx_ctx_sixel_get_api(void *data) { return sixel_ctx_api; } static bool gfx_ctx_sixel_bind_api(void *data, enum gfx_ctx_api api, unsigned major, unsigned minor) { (void)data; return true; } static void gfx_ctx_sixel_show_mouse(void *data, bool state) { (void)data; } static void gfx_ctx_sixel_swap_interval(void *data, int interval) { (void)data; (void)interval; } static void gfx_ctx_sixel_set_flags(void *data, uint32_t flags) { (void)data; (void)flags; } static uint32_t gfx_ctx_sixel_get_flags(void *data) { uint32_t flags = 0; return flags; } static void gfx_ctx_sixel_swap_buffers(void *data, void *data2) { (void)data; } const gfx_ctx_driver_t gfx_ctx_sixel = { gfx_ctx_sixel_init, gfx_ctx_sixel_destroy, gfx_ctx_sixel_get_api, gfx_ctx_sixel_bind_api, gfx_ctx_sixel_swap_interval, gfx_ctx_sixel_set_video_mode, gfx_ctx_sixel_get_video_size, NULL, /* get_refresh_rate */ NULL, /* get_video_output_size */ NULL, /* get_video_output_prev */ NULL, /* get_video_output_next */ gfx_ctx_sixel_get_metrics, NULL, gfx_ctx_sixel_update_window_title, gfx_ctx_sixel_check_window, gfx_ctx_sixel_set_resize, gfx_ctx_sixel_has_focus, gfx_ctx_sixel_suppress_screensaver, true, /* has_windowed */ gfx_ctx_sixel_swap_buffers, gfx_ctx_sixel_input_driver, NULL, NULL, NULL, gfx_ctx_sixel_show_mouse, "sixel", gfx_ctx_sixel_get_flags, gfx_ctx_sixel_set_flags, NULL, NULL, NULL };
RobLoach/RetroArch
gfx/drivers_context/sixel_ctx.c
C
gpl-3.0
5,106
<!-- title: "Install Netdata on FreeNAS" custom_edit_url: https://github.com/netdata/netdata/edit/master/packaging/installer/methods/freenas.md --> # Install Netdata on FreeNAS On FreeNAS-Corral-RELEASE (>=10.0.3 and <11.3), Netdata is pre-installed. To use Netdata, the service will need to be enabled and started from the FreeNAS [CLI](https://github.com/freenas/cli). To enable the Netdata service: ```sh service netdata config set enable=true ``` To start the Netdata service: ```sh service netdata start ```
vlvkobal/netdata
packaging/installer/methods/freenas.md
Markdown
gpl-3.0
522
/* * This file is part of EasyRPG Player. * * EasyRPG Player 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. * * EasyRPG Player 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 EasyRPG Player. If not, see <http://www.gnu.org/licenses/>. */ // Headers #include "audio.h" #include "system.h" #include "baseui.h" AudioInterface& Audio() { static EmptyAudio default_; return DisplayUi? DisplayUi->GetAudio() : default_; }
Lobomon/Player-for-QT
src/audio.cpp
C++
gpl-3.0
882
/* * Vortex OpenSplice * * This software and documentation are Copyright 2006 to TO_YEAR ADLINK * Technology Limited, its affiliated companies and licensors. All rights * reserved. * * Licensed under the ADLINK Software License Agreement Rev 2.7 2nd October * 2014 (the "License"); you may not use this file except in compliance with * the License. * You may obtain a copy of the License at: * $OSPL_HOME/LICENSE * * See the License for the specific language governing permissions and * limitations under the License. * */ /** \file os/linux/code/os_time.c * \brief Linux time management * * Implements time management for Linux * by including the generic Linux implementation */ #include "../linux/code/os_time.c"
PrismTech/opensplice
src/abstraction/os/lynxos5/code/os_time.c
C
gpl-3.0
802
"""Add timetable related tables Revision ID: 33a1d6f25951 Revises: 225d0750c216 Create Date: 2015-11-25 14:05:51.856236 """ import sqlalchemy as sa from alembic import op from indico.core.db.sqlalchemy import PyIntEnum, UTCDateTime from indico.modules.events.timetable.models.entries import TimetableEntryType # revision identifiers, used by Alembic. revision = '33a1d6f25951' down_revision = '225d0750c216' def upgrade(): # Break op.create_table( 'breaks', sa.Column('id', sa.Integer(), nullable=False), sa.Column('title', sa.String(), nullable=False), sa.Column('description', sa.Text(), nullable=False), sa.Column('duration', sa.Interval(), nullable=False), sa.Column('text_color', sa.String(), nullable=False), sa.Column('background_color', sa.String(), nullable=False), sa.Column('room_name', sa.String(), nullable=False), sa.Column('inherit_location', sa.Boolean(), nullable=False), sa.Column('address', sa.Text(), nullable=False), sa.Column('venue_id', sa.Integer(), nullable=True, index=True), sa.Column('venue_name', sa.String(), nullable=False), sa.Column('room_id', sa.Integer(), nullable=True, index=True), sa.CheckConstraint("(room_id IS NULL) OR (venue_name = '' AND room_name = '')", name='no_custom_location_if_room'), sa.CheckConstraint("(venue_id IS NULL) OR (venue_name = '')", name='no_venue_name_if_venue_id'), sa.CheckConstraint("(room_id IS NULL) OR (venue_id IS NOT NULL)", name='venue_id_if_room_id'), sa.CheckConstraint("NOT inherit_location OR (venue_id IS NULL AND room_id IS NULL AND venue_name = '' AND " "room_name = '' AND address = '')", name='inherited_location'), sa.CheckConstraint("(text_color = '') = (background_color = '')", name='both_or_no_colors'), sa.CheckConstraint("text_color != '' AND background_color != ''", name='colors_not_empty'), sa.ForeignKeyConstraint(['room_id'], ['roombooking.rooms.id']), sa.ForeignKeyConstraint(['venue_id'], ['roombooking.locations.id']), sa.ForeignKeyConstraint(['venue_id', 'room_id'], ['roombooking.rooms.location_id', 'roombooking.rooms.id']), sa.PrimaryKeyConstraint('id'), schema='events' ) # TimetableEntry op.create_table( 'timetable_entries', sa.Column('id', sa.Integer(), nullable=False), sa.Column('event_id', sa.Integer(), nullable=False, index=True), sa.Column('parent_id', sa.Integer(), nullable=True, index=True), sa.Column('session_block_id', sa.Integer(), nullable=True, index=True, unique=True), sa.Column('contribution_id', sa.Integer(), nullable=True, index=True, unique=True), sa.Column('break_id', sa.Integer(), nullable=True, index=True, unique=True), sa.Column('type', PyIntEnum(TimetableEntryType), nullable=False), sa.Column('start_dt', UTCDateTime, nullable=False), sa.Index('ix_timetable_entries_start_dt_desc', sa.text('start_dt DESC')), sa.CheckConstraint('type != 1 OR parent_id IS NULL', name='valid_parent'), sa.CheckConstraint('type != 1 OR (contribution_id IS NULL AND break_id IS NULL AND ' 'session_block_id IS NOT NULL)', name='valid_session_block'), sa.CheckConstraint('type != 2 OR (session_block_id IS NULL AND break_id IS NULL AND ' 'contribution_id IS NOT NULL)', name='valid_contribution'), sa.CheckConstraint('type != 3 OR (contribution_id IS NULL AND session_block_id IS NULL AND ' 'break_id IS NOT NULL)', name='valid_break'), sa.ForeignKeyConstraint(['break_id'], ['events.breaks.id']), sa.ForeignKeyConstraint(['contribution_id'], ['events.contributions.id']), sa.ForeignKeyConstraint(['event_id'], ['events.events.id']), sa.ForeignKeyConstraint(['parent_id'], ['events.timetable_entries.id']), sa.ForeignKeyConstraint(['session_block_id'], ['events.session_blocks.id']), sa.PrimaryKeyConstraint('id'), schema='events' ) def downgrade(): op.drop_table('timetable_entries', schema='events') op.drop_table('breaks', schema='events')
belokop/indico_bare
migrations/versions/201511251405_33a1d6f25951_add_timetable_related_tables.py
Python
gpl-3.0
4,295
module ComboFieldTagHelper def combo_field_tag(name, value, option_tags = nil, options = {}) select_placeholder = options[:select_placeholder] || "Select existing value" input_placeholder = options[:input_placeholder] || "Enter new value" id = options[:id] klass = options[:class] || 'combo-field' required = options[:required] help = options[:help] unless options[:label] == false label_html = label_tag(options[:label] || name, nil, class: "#{'required' if required}") end select_options = { prompt: '', class: "#{klass} form-control #{'required' if required}", data: { placeholder: select_placeholder } } select_options[:id] = "#{id}_select" if id.present? select_html = select_tag name, option_tags, select_options text_field_options = { class: "form-control", placeholder: input_placeholder } text_field_options[:id] = "#{id}_text" if id.present? text_field_html = text_field_tag name, value, text_field_options if help select_html << content_tag(:small, help.html_safe, class: 'help-block') end <<-HTML.html_safe <div class='combo-field-wrapper #{klass}-wrapper'> #{label_html} <div class='combo-field-select #{klass}-select'>#{select_html}</div> <div class='combo-field-alternative'>or</div> <div class='combo-field-input #{klass}-input'> #{text_field_html} <a href='#' class='clear-input hidden'>&times;</a> </div> </div> HTML end end
TGAC/brassica
app/helpers/combo_field_tag_helper.rb
Ruby
gpl-3.0
1,529
{ "": { "domain": "ckan", "lang": "cs_CZ", "plural-forms": "nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;" }, "An Error Occurred": [ null, "Nastala chyba" ], "Are you sure you want to perform this action?": [ null, "Jste si jistí, že chcete provést tuto akci?" ], "Cancel": [ null, "Zrušit" ], "Confirm": [ null, "Potvrdit" ], "Edit": [ null, "Upravit" ], "Failed to load data API information": [ null, "Pokus o získání informací pomocí API selhal" ], "Follow": [ null, "Sledovat" ], "Hide": [ null, "Skrýt" ], "Image": [ null, "Obrázek" ], "Input is too short, must be at least one character": [ null, "Zadaný vstup je příliš krátký, musíte zadat alespoň jeden znak" ], "Link": [ null, "Odkaz" ], "Link to a URL on the internet (you can also link to an API)": [ null, "Odkaz na internetovou URL adresu (můžete také zadat odkaz na API)" ], "Loading...": [ null, "Nahrávám ..." ], "No matches found": [ null, "Nenalezena žádná shoda" ], "Please Confirm Action": [ null, "Prosím potvrďte akci" ], "Remove": [ null, "Odstranit" ], "Reorder resources": [ null, "Změnit pořadí zdrojů" ], "Reset this": [ null, "Resetovat" ], "Resource uploaded": [ null, "Zdroj nahrán" ], "Save order": [ null, "Uložit pořadí" ], "Saving...": [ null, "Ukládám..." ], "Show more": [ null, "Ukázat více" ], "Start typing…": [ null, "Začněte psát..." ], "There are unsaved modifications to this form": [ null, "Tento formulář obsahuje neuložené změny" ], "There is no API data to load for this resource": [ null, "Tento zdroj neobsahuje žádná data, která lze poskytnou přes API" ], "URL": [ null, "URL" ], "Unable to authenticate upload": [ null, "Nastala chyba autentizace při nahrávání dat" ], "Unable to get data for uploaded file": [ null, "Nelze získat data z nahraného souboru" ], "Unable to upload file": [ null, "Nelze nahrát soubor" ], "Unfollow": [ null, "Přestat sledovat" ], "Upload": [ null, "Nahrát" ], "Upload a file": [ null, "Nahrát soubor" ], "Upload a file on your computer": [ null, "Nahrát soubor na Váš počítač" ], "You are uploading a file. Are you sure you want to navigate away and stop this upload?": [ null, "Právě nahráváte soubor. Jste si opravdu jistí, že chcete tuto stránku opustit a ukončit tak nahrávání?" ], "show less": [ null, "ukázat méně" ], "show more": [ null, "ukázat více" ] }
nucleo-digital/ckan-theme-cmbd
public/base/i18n/cs_CZ.js
JavaScript
gpl-3.0
2,840
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Spectra</title> <meta name="author" content="CEERI"> <meta name="description" content="[No canvas support] spectra = []; // Graph Data Array l = 0; // The letter 'L' - NOT a one var socket = io.connect('http://172.16.5.14:7000'); // &hellip;"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <link href="/spectra/atom.xml" rel="alternate" title="Spectra" type="application/atom+xml"> <link rel="canonical" href=""> <link href="/spectra/favicon.png" rel="shortcut icon"> <link href="/spectra/stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css"> <!--[if lt IE 9]><script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]--> <script async="true" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> </head> <body> <header id="header" class="inner"><h1><a href="/spectra/">Spectra</a></h1> <nav id="main-nav"><ul class="main"> </ul> </nav> <nav id="mobile-nav"> <div class="alignleft menu"> <a class="button">Menu</a> <div class="container"><ul class="main"> </ul> </div> </div> <div class="alignright search"> <a class="button"></a> <div class="container"> <form action="http://google.com/search" method="get"> <input type="text" name="q" results="0"> <input type="hidden" name="q" value="site:172.16.5.14/spectra"> </form> </div> </div> </nav> <nav id="sub-nav" class="alignright"> <div class="social"> <a class="github" href="https://github.com/debanjum/Spectroserver" title="GitHub">GitHub</a> <a class="rss" href="/spectra/atom.xml" title="RSS">RSS</a> </div> <form class="search" action="http://google.com/search" method="get"> <input class="alignright" type="text" name="q" results="0"> <input type="hidden" name="q" value="site:172.16.5.14/spectra"> </form> </nav> <h2><a>Spectral Data Visualisation & Spectrophotometer Control</a></h2> </header> <div id="content" class="inner"> <head> <script type="text/javascript" src="http://172.16.5.14:7000/socket.io/socket.io.js"></script> <script type="text/javascript" src="/spectra/javascripts/RGraph.line.js" ></script> <script type="text/javascript" src="/spectra/javascripts/RGraph.common.core.js" ></script> <canvas id="cvs" width="1000" height="450">[No canvas support]</canvas> <script> spectra = []; // Graph Data Array l = 0; // The letter 'L' - NOT a one var socket = io.connect('http://172.16.5.14:7000'); // Pre-pad the arrays with null values for (var i=0; i<1000; ++i) { spectra.push(null); } function getGraph(id, spectra) { // After creating the chart, store it on the global window object if (!window.__rgraph_line__) { window.__rgraph_line__ = new RGraph.Line(id, spectra); window.__rgraph_line__.Set('chart.background.barcolor1', 'white'); window.__rgraph_line__.Set('chart.background.barcolor2', 'white'); window.__rgraph_line__.Set('chart.title.xaxis', 'Wavelength'); window.__rgraph_line__.Set('chart.title.yaxis', 'Voltage'); window.__rgraph_line__.Set('chart.title.vpos', 0.5); window.__rgraph_line__.Set('chart.title', 'Spectral Profile'); window.__rgraph_line__.Set('chart.title.yaxis.pos', 0.5); window.__rgraph_line__.Set('chart.title.xaxis.pos', 0.5); window.__rgraph_line__.Set('chart.colors', ['black']); window.__rgraph_line__.Set('chart.linewidth',1.5); window.__rgraph_line__.Set('chart.yaxispos', 'right'); window.__rgraph_line__.Set('chart.ymax', 3.3); window.__rgraph_line__.Set('chart.ymin', 0); window.__rgraph_line__.Set('chart.yticks', 1); window.__rgraph_line__.Set('chart.xticks', 5); window.__rgraph_line__.Set('units.post', 'V'); } return window.__rgraph_line__; } function drawGraph () { // "cache" this in a local variable var _RG = RGraph; _RG.Clear(document.getElementById("cvs")); var graph = getGraph('cvs', spectra); graph.Draw(); socket.on ('connect', function () //Connects to Node Data Server { socket.on ('data', function (msg) { var VALUE = parseFloat(msg); // Convert message to float spectra.push(VALUE); // Push to Graph Data Array var SPAN = document.getElementById('sensorvalue'); var text = document.createTextNode(VALUE); if(SPAN.childNodes.length == 0) { SPAN.appendChild(text) } else { SPAN.firstChild.nodeValue = VALUE; } if (spectra.length > 500) { spectra = _RG.array_shift(spectra); } }); }); if (document.all && _RG.isIE8()) { alert('[MSIE] Sorry, Internet Explorer 8 is not fast enough to support animated charts'); } else { window.__rgraph_line__.original_data[0] = spectra; setTimeout(drawGraph, 10); //Delay between Graph Updates } } drawGraph(); socket.on( 'sff', function() { } ); function initspec(start,stop) { drawGraph(); socket.emit('initspec', start, stop ); } function scanspec() { socket.emit('scanspec'); } function resetspec() { socket.emit('resetspec'); } function save(start,stop,spectra) { socket.emit('savespec', start, stop, spectra ); } function openspec(openw) { drawGraph(); socket.emit('openspec', openw ); } </script> </head> <body> <div role="main"> Analog Out: <span id="sensorvalue"></span> </div> <form name="input" action="" method="post"> Start Wavelength: <input type="text" name="startwave" id="startw" ><br /> Stop Wavelength: <input type="text" name="stopwave" id="stopw" ><br /> Open Spectra <input type="value" name="openwave" id="openw" ><br /> <input type="button" value="reset" onClick=resetspec()> <input type="button" value="intialise" onClick=initspec(startw.value,stopw.value)> <input type="button" value="scan" onClick=scanspec()> <input type="button" value="save" onClick=save(startw.value,stopw.value,spectra)> <input type="button" value="open" onClick=openspec(openw.value)> </form> </body> </div> <footer id="footer" class="inner">Copyright &copy; 2014 CEERI <span class="credit">Powered by <a href="http://octopress.org">Octopress</a></span> </footer> <script src="/spectra/javascripts/slash.js"></script> <script src="/spectra/javascripts/jquery.fancybox.pack.js"></script> <script type="text/javascript"> (function($){ $('.fancybox').fancybox(); })(jQuery); </script> <!-- Delete or comment this line to disable Fancybox --> </body> </html>
lrmodesgh/Spectroserver
spectra/index.html
HTML
gpl-3.0
6,866
> **Note**: this project is hosted on a [public repository](https://github.com/hhkaos/awesome-arcgis) where anyone can contribute. Learn how to [contribute in less than a minute](https://github.com/hhkaos/awesome-arcgis/blob/master/CONTRIBUTING.md#contributions). # Scene services <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> **Table of contents** - [Training](#training) - [Videos](#videos) - [Resources](#resources) - [Utils](#utils) - [News](#news) <!-- END doctoc generated TOC please keep comment here to allow auto update --> ## Training ### Videos |Event|Title|Length| |---|---|---| ## Resources Probably not all the resources are in this list, please use the [ArcGIS Search](https://esri-es.github.io/arcgis-search/) tool looking for: ["scene service"](https://esri-es.github.io/arcgis-search/?search="scene service"&utm_campaign=awesome-list&utm_source=awesome-list&utm_medium=page). ## Utils ## News
hhkaos/awesome-arcgis
arcgis/content/data-storage/service-types/scene-service/README.md
Markdown
gpl-3.0
1,034
package net.einsteinsci.betterbeginnings.items; import net.einsteinsci.betterbeginnings.register.IBBName; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; import java.util.HashSet; import java.util.Set; public abstract class ItemKnife extends ItemTool implements IBBName { public static final float DAMAGE = 3.0f; public ItemKnife(ToolMaterial material) { super(DAMAGE, material, getBreakable()); } public static Set getBreakable() { Set<Block> s = new HashSet<>(); // s.add(Blocks.log); // s.add(Blocks.log2); // s.add(Blocks.planks); s.add(Blocks.pumpkin); s.add(Blocks.lit_pumpkin); s.add(Blocks.melon_block); s.add(Blocks.clay); s.add(Blocks.grass); s.add(Blocks.mycelium); s.add(Blocks.leaves); s.add(Blocks.leaves2); s.add(Blocks.brown_mushroom_block); s.add(Blocks.red_mushroom_block); s.add(Blocks.glass); s.add(Blocks.glass_pane); s.add(Blocks.soul_sand); s.add(Blocks.stained_glass); s.add(Blocks.stained_glass_pane); s.add(Blocks.cactus); return s; } @Override public boolean shouldRotateAroundWhenRendering() { return true; } @Override public int getHarvestLevel(ItemStack stack, String toolClass) { return toolMaterial.getHarvestLevel(); } @Override public Set<String> getToolClasses(ItemStack stack) { Set<String> res = new HashSet<>(); res.add("knife"); return res; } // ...which also requires this... @Override public ItemStack getContainerItem(ItemStack itemStack) { ItemStack result = itemStack.copy(); result.setItemDamage(itemStack.getItemDamage() + 1); return result; } // Allows durability-based crafting. @Override public boolean hasContainerItem(ItemStack stack) { return true; } @Override public abstract String getName(); }
Leviathan143/betterbeginnings
src/main/java/net/einsteinsci/betterbeginnings/items/ItemKnife.java
Java
gpl-3.0
1,851
/* Copyright (c) 2008, 2009 * Juergen Weigert (jnweiger@immd4.informatik.uni-erlangen.de) * Michael Schroeder (mlschroe@immd4.informatik.uni-erlangen.de) * Micah Cowan (micah@cowan.name) * Sadrul Habib Chowdhury (sadrul@users.sourceforge.net) * Copyright (c) 1993-2002, 2003, 2005, 2006, 2007 * Juergen Weigert (jnweiger@immd4.informatik.uni-erlangen.de) * Michael Schroeder (mlschroe@immd4.informatik.uni-erlangen.de) * Copyright (c) 1987 Oliver Laumann * * 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, 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 (see the file COPYING); if not, see * http://www.gnu.org/licenses/, or contact Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA * **************************************************************** */ #include <sys/types.h> #include <sys/socket.h> #include <fcntl.h> #include <netdb.h> #include <stdio.h> #include "config.h" #ifdef BUILTIN_TELNET #include "screen.h" extern Window *fore; extern Layer *flayer; extern int visual_bell; extern char screenterm[]; extern int af; static void TelReply(Window *, char *, int); static void TelDocmd(Window *, int, int); static void TelDosub(Window *); // why TEL_DEFPORT has " #define TEL_DEFPORT "23" #define TEL_CONNECTING (-2) #define TC_IAC 255 #define TC_DONT 254 #define TC_DO 253 #define TC_WONT 252 #define TC_WILL 251 #define TC_SB 250 #define TC_BREAK 243 #define TC_SE 240 #define TC_S "S b swWdDc" #define TO_BINARY 0 #define TO_ECHO 1 #define TO_SGA 3 #define TO_TM 6 #define TO_TTYPE 24 #define TO_NAWS 31 #define TO_TSPEED 32 #define TO_LFLOW 33 #define TO_LINEMODE 34 #define TO_XDISPLOC 35 #define TO_NEWENV 39 #define TO_S "be c t wsf xE E" static unsigned char tn_init[] = { TC_IAC, TC_DO, TO_SGA, TC_IAC, TC_WILL, TO_TTYPE, TC_IAC, TC_WILL, TO_NAWS, TC_IAC, TC_WILL, TO_LFLOW, }; static void tel_connev_fn(Event *ev, char *data) { Window *p = (Window *)data; if (connect(p->w_ptyfd, (struct sockaddr *)&p->w_telsa, sizeof(p->w_telsa)) && errno != EISCONN) { char buf[1024]; buf[0] = ' '; strncpy(buf + 1, strerror(errno), sizeof(buf) - 2); buf[sizeof(buf) - 1] = 0; WriteString(p, buf, strlen(buf)); WindowDied(p, 0, 0); return; } WriteString(p, "connected.\r\n", 12); evdeq(&p->w_telconnev); p->w_telstate = 0; } int TelOpenAndConnect(Window *p) { int fd, on = 1; char buf[256]; struct addrinfo hints, *res0, *res; if (!(p->w_cmdargs[1])) { Msg(0, "Usage: screen //telnet host [port]"); return -1; } memset(&hints, 0, sizeof(hints)); hints.ai_family = af; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; if (getaddrinfo(p->w_cmdargs[1], p->w_cmdargs[2] ? p->w_cmdargs[2] : TEL_DEFPORT, &hints, &res0)) { Msg(0, "unknown host: %s", p->w_cmdargs[1]); return -1; } for (res = res0; res; res = res->ai_next) { if ((fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1) { if (res->ai_next) continue; else { Msg(errno, "TelOpenAndConnect: socket"); freeaddrinfo(res0); return -1; } } if (setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on))) Msg(errno, "TelOpenAndConnect: setsockopt SO_OOBINLINE"); if (p->w_cmdargs[2] && strcmp(p->w_cmdargs[2], TEL_DEFPORT)) snprintf(buf, 256, "Trying %s %s...", p->w_cmdargs[1], p->w_cmdargs[2]); else snprintf(buf, 256, "Trying %s...", p->w_cmdargs[1]); WriteString(p, buf, strlen(buf)); if (connect(fd, res->ai_addr, res->ai_addrlen)) { if (errno == EINPROGRESS) { p->w_telstate = TEL_CONNECTING; p->w_telconnev.fd = fd; p->w_telconnev.handler = tel_connev_fn; p->w_telconnev.data = (char *)p; p->w_telconnev.type = EV_WRITE; p->w_telconnev.priority = 1; evenq(&p->w_telconnev); } else { close(fd); if (res->ai_next) continue; else { Msg(errno, "TelOpenAndConnect: connect"); freeaddrinfo(res0); return -1; } } } else WriteString(p, "connected.\r\n", 12); if (!(p->w_cmdargs[2] && strcmp(p->w_cmdargs[2], TEL_DEFPORT))) TelReply(p, (char *)tn_init, sizeof(tn_init)); p->w_ptyfd = fd; memcpy(&p->w_telsa, &res->ai_addr, sizeof(res->ai_addr)); freeaddrinfo(res0); return 0; } return -1; } int TelIsline(Window *p) { return !fore->w_telropts[TO_SGA]; } void TelProcessLine(char **bufpp, int *lenp) { int echo = !fore->w_telropts[TO_ECHO]; unsigned char c; char *tb; int tl; char *buf = *bufpp; int l = *lenp; while (l--) { c = *(unsigned char *)buf++; if (fore->w_telbufl + 2 >= IOSIZE) { WBell(fore, visual_bell); continue; } if (c == '\r') { if (echo) WriteString(fore, "\r\n", 2); fore->w_telbuf[fore->w_telbufl++] = '\r'; fore->w_telbuf[fore->w_telbufl++] = '\n'; tb = fore->w_telbuf; tl = fore->w_telbufl; LayProcess(&tb, &tl); fore->w_telbufl = 0; continue; } if (c == '\b' && fore->w_telbufl > 0) { if (echo) { WriteString(fore, (char *)&c, 1); WriteString(fore, " ", 1); WriteString(fore, (char *)&c, 1); } fore->w_telbufl--; } if ((c >= 0x20 && c <= 0x7e) || c >= 0xa0) { if (echo) WriteString(fore, (char *)&c, 1); fore->w_telbuf[fore->w_telbufl++] = c; } } *lenp = 0; } int DoTelnet(char *buf, int *lenp, int f) { int echo = !fore->w_telropts[TO_ECHO]; int cmode = fore->w_telropts[TO_SGA]; int bin = fore->w_telropts[TO_BINARY]; char *p = buf, *sbuf; int trunc = 0; int c; int l = *lenp; sbuf = p; while (l-- > 0) { c = *(unsigned char *)p++; if (c == TC_IAC || (c == '\r' && (l == 0 || *p != '\n') && cmode && !bin)) { if (cmode && echo) { WriteString(fore, sbuf, p - sbuf); sbuf = p; } if (f-- <= 0) { trunc++; l--; } if (l < 0) { p--; /* drop char */ break; } if (l) bcopy(p, p + 1, l); if (c == TC_IAC) *p++ = c; else if (c == '\r') *p++ = 0; else if (c == '\n') { p[-1] = '\r'; *p++ = '\n'; } } } *lenp = p - buf; return trunc; } /* modifies data in-place, returns new length */ int TelIn(Window *p, char *buf, int len, int free) { char *rp, *wp; int c; rp = wp = buf; while (len-- > 0) { c = *(unsigned char *)rp++; if (p->w_telstate >= TC_WILL && p->w_telstate <= TC_DONT) { TelDocmd(p, p->w_telstate, c); p->w_telstate = 0; continue; } if (p->w_telstate == TC_SB || p->w_telstate == TC_SE) { if (p->w_telstate == TC_SE && c == TC_IAC) p->w_telsubidx--; if (p->w_telstate == TC_SE && c == TC_SE) { p->w_telsubidx--; TelDosub(p); p->w_telstate = 0; continue; } if (p->w_telstate == TC_SB && c == TC_IAC) p->w_telstate = TC_SE; else p->w_telstate = TC_SB; p->w_telsubbuf[p->w_telsubidx] = c; if (p->w_telsubidx < sizeof(p->w_telsubbuf) - 1) p->w_telsubidx++; continue; } if (p->w_telstate == TC_IAC) { if ((c >= TC_WILL && c <= TC_DONT) || c == TC_SB) { p->w_telsubidx = 0; p->w_telstate = c; continue; } p->w_telstate = 0; if (c != TC_IAC) continue; } else if (c == TC_IAC) { p->w_telstate = c; continue; } if (p->w_telstate == '\r') { p->w_telstate = 0; if (c == 0) continue; /* suppress trailing \0 */ } else if (c == '\n' && !p->w_telropts[TO_SGA]) { /* oops... simulate terminal line mode: insert \r */ if (wp + 1 == rp) { if (free-- > 0) { if (len) bcopy(rp, rp + 1, len); rp++; *wp++ = '\r'; } } else *wp++ = '\r'; } if (c == '\r') p->w_telstate = c; *wp++ = c; } return wp - buf; } static void TelReply(Window *p, char *str, int len) { if (len <= 0) return; if (p->w_inlen + len > IOSIZE) { Msg(0, "Warning: telnet protocol overrun!"); return; } bcopy(str, p->w_inbuf + p->w_inlen, len); p->w_inlen += len; } static void TelDocmd(Window *p, int cmd, int opt) { unsigned char b[3]; int repl = 0; switch (cmd) { case TC_WILL: if (p->w_telropts[opt] || opt == TO_TM) return; repl = TC_DONT; if (opt == TO_ECHO || opt == TO_SGA || opt == TO_BINARY) { p->w_telropts[opt] = 1; /* setcon(); */ repl = TC_DO; } break; case TC_WONT: if (!p->w_telropts[opt] || opt == TO_TM) return; repl = TC_DONT; p->w_telropts[opt] = 0; break; case TC_DO: if (p->w_telmopts[opt]) return; repl = TC_WONT; if (opt == TO_TTYPE || opt == TO_SGA || opt == TO_BINARY || opt == TO_NAWS || opt == TO_TM || opt == TO_LFLOW) { repl = TC_WILL; p->w_telmopts[opt] = 1; } p->w_telmopts[TO_TM] = 0; break; case TC_DONT: if (!p->w_telmopts[opt]) return; repl = TC_WONT; p->w_telmopts[opt] = 0; break; } b[0] = TC_IAC; b[1] = repl; b[2] = opt; TelReply(p, (char *)b, 3); if (cmd == TC_DO && opt == TO_NAWS) TelWindowSize(p); } static void TelDosub(Window *p) { char trepl[20 + 6 + 1]; int l; switch (p->w_telsubbuf[0]) { case TO_TTYPE: if (p->w_telsubidx != 2 || p->w_telsubbuf[1] != 1) return; l = strlen(screenterm); if (l >= 20) break; sprintf(trepl, "%c%c%c%c%s%c%c", TC_IAC, TC_SB, TO_TTYPE, 0, screenterm, TC_IAC, TC_SE); TelReply(p, trepl, l + 6); break; case TO_LFLOW: if (p->w_telsubidx != 2) return; break; default: break; } } void TelBreak(Window *p) { static unsigned char tel_break[] = { TC_IAC, TC_BREAK }; TelReply(p, (char *)tel_break, 2); } void TelWindowSize(Window *p) { char s[20], trepl[20], *t; int i; if (p->w_width == 0 || p->w_height == 0 || !p->w_telmopts[TO_NAWS]) return; sprintf(s, "%c%c%c%c%c%c%c%c%c", TC_SB, TC_SB, TO_NAWS, p->w_width / 256, p->w_width & 255, p->w_height / 256, p->w_height & 255, TC_SE, TC_SE); t = trepl; for (i = 0; i < 9; i++) if ((unsigned char)(*t++ = s[i]) == TC_IAC) *t++ = TC_IAC; trepl[0] = TC_IAC; t[-2] = TC_IAC; TelReply(p, trepl, t - trepl); } static char tc_s[] = TC_S; static char to_s[] = TO_S; void TelStatus(Window *p, char *buf, int l) { int i; *buf++ = '['; for (i = 0; to_s[i]; i++) { if (to_s[i] == ' ' || p->w_telmopts[i] == 0) continue; *buf++ = to_s[i]; } *buf++ = ':'; for (i = 0; to_s[i]; i++) { if (to_s[i] == ' ' || p->w_telropts[i] == 0) continue; *buf++ = to_s[i]; } if (p->w_telstate == TEL_CONNECTING) buf[-1] = 'C'; else if (p->w_telstate && p->w_telstate != '\r') { *buf++ = ':'; *buf++ = tc_s[p->w_telstate - TC_SE]; } *buf++ = ']'; *buf = 0; return; } #endif /* BUILTIN_TELNET */
maire/screen
src/teln.c
C
gpl-3.0
11,094
/****************************************************************************/ /// @file GUILaneSpeedTrigger.h /// @author Daniel Krajzewicz /// @author Jakob Erdmann /// @author Michael Behrisch /// @date Mon, 26.04.2004 /// @version $Id: GUILaneSpeedTrigger.h 13107 2012-12-02 13:57:34Z behrisch $ /// // Changes the speed allowed on a set of lanes (gui version) /****************************************************************************/ // SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/ // Copyright (C) 2001-2012 DLR (http://www.dlr.de/) and contributors /****************************************************************************/ // // This file is part of SUMO. // SUMO 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. // /****************************************************************************/ #ifndef GUILaneSpeedTrigger_h #define GUILaneSpeedTrigger_h // =========================================================================== // included modules // =========================================================================== #ifdef _MSC_VER #include <windows_config.h> #else #include <config.h> #endif #include <vector> #include <string> #include <microsim/trigger/MSLaneSpeedTrigger.h> #include <utils/gui/globjects/GUIGlObject_AbstractAdd.h> #include <utils/gui/globjects/GUIGLObjectPopupMenu.h> #include <utils/foxtools/FXRealSpinDial.h> #include <gui/GUIManipulator.h> // =========================================================================== // class definitions // =========================================================================== /** * @class GUILaneSpeedTrigger * @brief Changes the speed allowed on a set of lanes (gui version) * * This is the gui-version of the MSLaneSpeedTrigger-object */ class GUILaneSpeedTrigger : public MSLaneSpeedTrigger, public GUIGlObject_AbstractAdd { public: /** @brief Constructor * @param[in] idStorage The gl-id storage for giving this object an gl-id * @param[in] id The id of the lane speed trigger * @param[in] destLanes List of lanes affected by this speed trigger * @param[in] file Name of the file to read the speeds to set from */ GUILaneSpeedTrigger(const std::string& id, const std::vector<MSLane*>& destLanes, const std::string& file); /** destructor */ ~GUILaneSpeedTrigger(); /// @name inherited from GUIGlObject //@{ /** @brief Returns an own popup-menu * * @param[in] app The application needed to build the popup-menu * @param[in] parent The parent window needed to build the popup-menu * @return The built popup-menu * @see GUIGlObject::getPopUpMenu */ GUIGLObjectPopupMenu* getPopUpMenu(GUIMainWindow& app, GUISUMOAbstractView& parent); /** @brief Returns an own parameter window * * @param[in] app The application needed to build the parameter window * @param[in] parent The parent window needed to build the parameter window * @return The built parameter window * @see GUIGlObject::getParameterWindow */ GUIParameterTableWindow* getParameterWindow(GUIMainWindow& app, GUISUMOAbstractView& parent); /** @brief Returns the boundary to which the view shall be centered in order to show the object * * @return The boundary the object is within * @see GUIGlObject::getCenteringBoundary */ Boundary getCenteringBoundary() const; /** @brief Draws the object * @param[in] s The settings for the current view (may influence drawing) * @see GUIGlObject::drawGL */ void drawGL(const GUIVisualizationSettings& s) const; //@} GUIManipulator* openManipulator(GUIMainWindow& app, GUISUMOAbstractView& parent); public: class GUILaneSpeedTriggerPopupMenu : public GUIGLObjectPopupMenu { FXDECLARE(GUILaneSpeedTriggerPopupMenu) public: GUILaneSpeedTriggerPopupMenu(GUIMainWindow& app, GUISUMOAbstractView& parent, GUIGlObject& o); ~GUILaneSpeedTriggerPopupMenu(); /** @brief Called if the object's manipulator shall be shown */ long onCmdOpenManip(FXObject*, FXSelector, void*); protected: GUILaneSpeedTriggerPopupMenu() { } }; class GUIManip_LaneSpeedTrigger : public GUIManipulator { FXDECLARE(GUIManip_LaneSpeedTrigger) public: enum { MID_USER_DEF = FXDialogBox::ID_LAST, MID_PRE_DEF, MID_OPTION, MID_CLOSE, ID_LAST }; /// Constructor GUIManip_LaneSpeedTrigger(GUIMainWindow& app, const std::string& name, GUILaneSpeedTrigger& o, int xpos, int ypos); /// Destructor virtual ~GUIManip_LaneSpeedTrigger(); long onCmdOverride(FXObject*, FXSelector, void*); long onCmdClose(FXObject*, FXSelector, void*); long onCmdUserDef(FXObject*, FXSelector, void*); long onUpdUserDef(FXObject*, FXSelector, void*); long onCmdPreDef(FXObject*, FXSelector, void*); long onUpdPreDef(FXObject*, FXSelector, void*); long onCmdChangeOption(FXObject*, FXSelector, void*); private: GUIMainWindow* myParent; FXint myChosenValue; FXDataTarget myChosenTarget; SUMOReal mySpeed; FXDataTarget mySpeedTarget; FXRealSpinDial* myUserDefinedSpeed; FXComboBox* myPredefinedValues; GUILaneSpeedTrigger* myObject; protected: GUIManip_LaneSpeedTrigger() { } }; private: /// Definition of a positions container typedef std::vector<Position> PosCont; /// Definition of a rotation container typedef std::vector<SUMOReal> RotCont; private: /// The positions in full-geometry mode PosCont myFGPositions; /// The rotations in full-geometry mode RotCont myFGRotations; /// The boundary of this rerouter Boundary myBoundary; /// The information whether the speed shall be shown in m/s or km/h bool myShowAsKMH; /// Storage for last value to avoid string recomputation mutable SUMOReal myLastValue; /// Storage for speed string to avoid recomputation mutable std::string myLastValueString; }; #endif /****************************************************************************/
rudhir-upretee/SUMO_Src
src/guisim/GUILaneSpeedTrigger.h
C
gpl-3.0
6,731
/****************************************************************************/ /// @file MSEdge.cpp /// @author Christian Roessel /// @author Jakob Erdmann /// @author Christoph Sommer /// @author Daniel Krajzewicz /// @author Laura Bieker /// @author Michael Behrisch /// @author Sascha Krieg /// @date Tue, 06 Mar 2001 /// @version $Id: MSEdge.cpp 13107 2012-12-02 13:57:34Z behrisch $ /// // A road/street connecting two junctions /****************************************************************************/ // SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/ // Copyright (C) 2001-2012 DLR (http://www.dlr.de/) and contributors /****************************************************************************/ // // This file is part of SUMO. // SUMO 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. // /****************************************************************************/ // =========================================================================== // included modules // =========================================================================== #ifdef _MSC_VER #include <windows_config.h> #else #include <config.h> #endif #include <algorithm> #include <iostream> #include <cassert> #include <utils/common/StringTokenizer.h> #include <utils/options/OptionsCont.h> #include "MSEdge.h" #include "MSLane.h" #include "MSLaneChanger.h" #include "MSGlobals.h" #include "MSVehicle.h" #include "MSEdgeWeightsStorage.h" #ifdef HAVE_INTERNAL #include <mesosim/MELoop.h> #include <mesosim/MESegment.h> #include <mesosim/MEVehicle.h> #endif #ifdef CHECK_MEMORY_LEAKS #include <foreign/nvwa/debug_new.h> #endif // CHECK_MEMORY_LEAKS // =========================================================================== // static member definitions // =========================================================================== MSEdge::DictType MSEdge::myDict; std::vector<MSEdge*> MSEdge::myEdges; // =========================================================================== // member method definitions // =========================================================================== MSEdge::MSEdge(const std::string& id, int numericalID, const EdgeBasicFunction function, const std::string& streetName) : Named(id), myNumericalID(numericalID), myLanes(0), myLaneChanger(0), myFunction(function), myVaporizationRequests(0), myLastFailedInsertionTime(-1), myStreetName(streetName) {} MSEdge::~MSEdge() { delete myLaneChanger; for (AllowedLanesCont::iterator i1 = myAllowed.begin(); i1 != myAllowed.end(); i1++) { delete(*i1).second; } for (ClassedAllowedLanesCont::iterator i2 = myClassedAllowed.begin(); i2 != myClassedAllowed.end(); i2++) { for (AllowedLanesCont::iterator i1 = (*i2).second.begin(); i1 != (*i2).second.end(); i1++) { delete(*i1).second; } } delete myLanes; // Note: Lanes are delete using MSLane::clear(); } void MSEdge::initialize(std::vector<MSLane*>* lanes) { assert(myFunction == EDGEFUNCTION_DISTRICT || lanes != 0); myLanes = lanes; if (myLanes && myLanes->size() > 1 && myFunction != EDGEFUNCTION_INTERNAL) { myLaneChanger = new MSLaneChanger(myLanes, OptionsCont::getOptions().getBool("lanechange.allow-swap")); } } void MSEdge::closeBuilding() { myAllowed[0] = new std::vector<MSLane*>(); for (std::vector<MSLane*>::iterator i = myLanes->begin(); i != myLanes->end(); ++i) { myAllowed[0]->push_back(*i); const MSLinkCont& lc = (*i)->getLinkCont(); for (MSLinkCont::const_iterator j = lc.begin(); j != lc.end(); ++j) { MSLane* toL = (*j)->getLane(); if (toL != 0) { MSEdge& to = toL->getEdge(); // if (std::find(mySuccessors.begin(), mySuccessors.end(), &to) == mySuccessors.end()) { mySuccessors.push_back(&to); } if (std::find(to.myPredeccesors.begin(), to.myPredeccesors.end(), this) == to.myPredeccesors.end()) { to.myPredeccesors.push_back(this); } // if (myAllowed.find(&to) == myAllowed.end()) { myAllowed[&to] = new std::vector<MSLane*>(); } myAllowed[&to]->push_back(*i); } #ifdef HAVE_INTERNAL_LANES toL = (*j)->getViaLane(); if (toL != 0) { MSEdge& to = toL->getEdge(); to.myPredeccesors.push_back(this); } #endif } } std::sort(mySuccessors.begin(), mySuccessors.end(), by_id_sorter()); rebuildAllowedLanes(); } void MSEdge::rebuildAllowedLanes() { // clear myClassedAllowed. // it will be rebuilt on demand for (ClassedAllowedLanesCont::iterator i2 = myClassedAllowed.begin(); i2 != myClassedAllowed.end(); i2++) { for (AllowedLanesCont::iterator i1 = (*i2).second.begin(); i1 != (*i2).second.end(); i1++) { delete(*i1).second; } } myClassedAllowed.clear(); // rebuild myMinimumPermissions and myCombinedPermissions myMinimumPermissions = SVCFreeForAll; myCombinedPermissions = 0; for (std::vector<MSLane*>::iterator i = myLanes->begin(); i != myLanes->end(); ++i) { myMinimumPermissions &= (*i)->getPermissions(); myCombinedPermissions |= (*i)->getPermissions(); } } // ------------ Access to the edge's lanes MSLane* MSEdge::leftLane(const MSLane* const lane) const { std::vector<MSLane*>::iterator laneIt = find(myLanes->begin(), myLanes->end(), lane); if (laneIt == myLanes->end() || laneIt == myLanes->end() - 1) { return 0; } return *(laneIt + 1); } MSLane* MSEdge::rightLane(const MSLane* const lane) const { std::vector<MSLane*>::iterator laneIt = find(myLanes->begin(), myLanes->end(), lane); if (laneIt == myLanes->end() || laneIt == myLanes->begin()) { return 0; } return *(laneIt - 1); } const std::vector<MSLane*>* MSEdge::allowedLanes(const MSEdge& destination, SUMOVehicleClass vclass) const { return allowedLanes(&destination, vclass); } const std::vector<MSLane*>* MSEdge::allowedLanes(SUMOVehicleClass vclass) const { return allowedLanes(0, vclass); } const std::vector<MSLane*>* MSEdge::getAllowedLanesWithDefault(const AllowedLanesCont& c, const MSEdge* dest) const { AllowedLanesCont::const_iterator it = c.find(dest); if (it == c.end()) { return 0; } return it->second; } const std::vector<MSLane*>* MSEdge::allowedLanes(const MSEdge* destination, SUMOVehicleClass vclass) const { if ((myMinimumPermissions & vclass) == vclass) { // all lanes allow vclass return getAllowedLanesWithDefault(myAllowed, destination); } // look up cached result in myClassedAllowed ClassedAllowedLanesCont::const_iterator i = myClassedAllowed.find(vclass); if (i != myClassedAllowed.end()) { // can use cached value const AllowedLanesCont& c = (*i).second; return getAllowedLanesWithDefault(c, destination); } else { // this vclass is requested for the first time. rebuild all destinations // go through connected edges for (AllowedLanesCont::const_iterator i1 = myAllowed.begin(); i1 != myAllowed.end(); ++i1) { const MSEdge* edge = i1->first; const std::vector<MSLane*>* lanes = i1->second; myClassedAllowed[vclass][edge] = new std::vector<MSLane*>(); // go through lanes approaching current edge for (std::vector<MSLane*>::const_iterator i2 = lanes->begin(); i2 != lanes->end(); ++i2) { // allows the current vehicle class? if ((*i2)->allowsVehicleClass(vclass)) { // -> may be used myClassedAllowed[vclass][edge]->push_back(*i2); } } // assert that 0 is returned if no connection is allowed for a class if (myClassedAllowed[vclass][edge]->size() == 0) { delete myClassedAllowed[vclass][edge]; myClassedAllowed[vclass][edge] = 0; } } return myClassedAllowed[vclass][destination]; } } // ------------ SUMOTime MSEdge::incVaporization(SUMOTime) { ++myVaporizationRequests; return 0; } SUMOTime MSEdge::decVaporization(SUMOTime) { --myVaporizationRequests; return 0; } MSLane* MSEdge::getFreeLane(const std::vector<MSLane*>* allowed, const SUMOVehicleClass vclass) const { if (allowed == 0) { allowed = allowedLanes(vclass); } MSLane* res = 0; if (allowed != 0) { unsigned int noCars = INT_MAX; for (std::vector<MSLane*>::const_iterator i = allowed->begin(); i != allowed->end(); ++i) { if ((*i)->getVehicleNumber() < noCars) { res = (*i); noCars = (*i)->getVehicleNumber(); } } } return res; } MSLane* MSEdge::getDepartLane(const MSVehicle& veh) const { switch (veh.getParameter().departLaneProcedure) { case DEPART_LANE_GIVEN: if ((int) myLanes->size() <= veh.getParameter().departLane || !(*myLanes)[veh.getParameter().departLane]->allowsVehicleClass(veh.getVehicleType().getVehicleClass())) { return 0; } return (*myLanes)[veh.getParameter().departLane]; case DEPART_LANE_RANDOM: return RandHelper::getRandomFrom(*allowedLanes(veh.getVehicleType().getVehicleClass())); case DEPART_LANE_FREE: return getFreeLane(0, veh.getVehicleType().getVehicleClass()); case DEPART_LANE_ALLOWED_FREE: if (veh.getRoute().size() == 1) { return getFreeLane(0, veh.getVehicleType().getVehicleClass()); } else { return getFreeLane(allowedLanes(**(veh.getRoute().begin() + 1)), veh.getVehicleType().getVehicleClass()); } case DEPART_LANE_BEST_FREE: { const std::vector<MSVehicle::LaneQ>& bl = veh.getBestLanes(false, (*myLanes)[0]); SUMOReal bestLength = -1; for (std::vector<MSVehicle::LaneQ>::const_iterator i = bl.begin(); i != bl.end(); ++i) { if ((*i).length > bestLength) { bestLength = (*i).length; } } std::vector<MSLane*>* bestLanes = new std::vector<MSLane*>(); for (std::vector<MSVehicle::LaneQ>::const_iterator i = bl.begin(); i != bl.end(); ++i) { if ((*i).length == bestLength) { bestLanes->push_back((*i).lane); } } MSLane* ret = getFreeLane(bestLanes, veh.getVehicleType().getVehicleClass()); delete bestLanes; return ret; } case DEPART_LANE_DEFAULT: default: break; } if (!(*myLanes)[0]->allowsVehicleClass(veh.getVehicleType().getVehicleClass())) { return 0; } return (*myLanes)[0]; } bool MSEdge::insertVehicle(SUMOVehicle& v, SUMOTime time) const { // when vaporizing, no vehicles are inserted... if (isVaporizing()) { return false; } #ifdef HAVE_INTERNAL if (MSGlobals::gUseMesoSim) { const SUMOVehicleParameter& pars = v.getParameter(); SUMOReal pos = 0.0; switch (pars.departPosProcedure) { case DEPART_POS_GIVEN: if (pars.departPos >= 0.) { pos = pars.departPos; } else { pos = pars.departPos + getLength(); } if (pos < 0 || pos > getLength()) { WRITE_WARNING("Invalid departPos " + toString(pos) + " given for vehicle '" + v.getID() + "'. Inserting at lane end instead."); pos = getLength(); } break; case DEPART_POS_RANDOM: case DEPART_POS_RANDOM_FREE: pos = RandHelper::rand(getLength()); break; default: break; } bool result = false; MESegment* segment = MSGlobals::gMesoNet->getSegmentForEdge(*this, pos); MEVehicle* veh = static_cast<MEVehicle*>(&v); if (pars.departPosProcedure == DEPART_POS_FREE) { while (segment != 0 && !result) { result = segment->initialise(veh, time); segment = segment->getNextSegment(); } } else { result = segment->initialise(veh, time); } return result; } #else UNUSED_PARAMETER(time); #endif MSLane* insertionLane = getDepartLane(static_cast<MSVehicle&>(v)); return insertionLane != 0 && insertionLane->insertVehicle(static_cast<MSVehicle&>(v)); } void MSEdge::changeLanes(SUMOTime t) { if (myFunction == EDGEFUNCTION_INTERNAL) { return; } assert(myLaneChanger != 0); myLaneChanger->laneChange(t); } #ifdef HAVE_INTERNAL_LANES const MSEdge* MSEdge::getInternalFollowingEdge(MSEdge* followerAfterInternal) const { //@todo to be optimized for (std::vector<MSLane*>::const_iterator i = myLanes->begin(); i != myLanes->end(); ++i) { MSLane* l = *i; const MSLinkCont& lc = l->getLinkCont(); for (MSLinkCont::const_iterator j = lc.begin(); j != lc.end(); ++j) { MSLink* link = *j; if (&link->getLane()->getEdge() == followerAfterInternal) { if (link->getViaLane() != 0) { return &link->getViaLane()->getEdge(); } else { return 0; // network without internal links } } } } return 0; } #endif SUMOReal MSEdge::getCurrentTravelTime(SUMOReal minSpeed) const { assert(minSpeed > 0); SUMOReal v = 0; #ifdef HAVE_INTERNAL if (MSGlobals::gUseMesoSim) { MESegment* first = MSGlobals::gMesoNet->getSegmentForEdge(*this); unsigned segments = 0; do { v += first->getMeanSpeed(); first = first->getNextSegment(); segments++; } while (first != 0); v /= (SUMOReal) segments; } else { #endif for (std::vector<MSLane*>::iterator i = myLanes->begin(); i != myLanes->end(); ++i) { v += (*i)->getMeanSpeed(); } v /= (SUMOReal) myLanes->size(); #ifdef HAVE_INTERNAL } #endif v = MAX2(minSpeed, v); return getLength() / v; } bool MSEdge::dictionary(const std::string& id, MSEdge* ptr) { DictType::iterator it = myDict.find(id); if (it == myDict.end()) { // id not in myDict. myDict[id] = ptr; if (ptr->getNumericalID() != -1) { while ((int)myEdges.size() < ptr->getNumericalID() + 1) { myEdges.push_back(0); } myEdges[ptr->getNumericalID()] = ptr; } return true; } return false; } MSEdge* MSEdge::dictionary(const std::string& id) { DictType::iterator it = myDict.find(id); if (it == myDict.end()) { // id not in myDict. return 0; } return it->second; } MSEdge* MSEdge::dictionary(size_t id) { assert(myEdges.size() > id); return myEdges[id]; } size_t MSEdge::dictSize() { return myDict.size(); } size_t MSEdge::numericalDictSize() { return myEdges.size(); } void MSEdge::clear() { for (DictType::iterator i = myDict.begin(); i != myDict.end(); ++i) { delete(*i).second; } myDict.clear(); } void MSEdge::insertIDs(std::vector<std::string>& into) { for (DictType::iterator i = myDict.begin(); i != myDict.end(); ++i) { into.push_back((*i).first); } } void MSEdge::parseEdgesList(const std::string& desc, std::vector<const MSEdge*>& into, const std::string& rid) { if (desc[0] == BinaryFormatter::BF_ROUTE) { std::istringstream in(desc, std::ios::binary); char c; in >> c; FileHelpers::readEdgeVector(in, into, rid); } else { StringTokenizer st(desc); parseEdgesList(st.getVector(), into, rid); } } void MSEdge::parseEdgesList(const std::vector<std::string>& desc, std::vector<const MSEdge*>& into, const std::string& rid) { for (std::vector<std::string>::const_iterator i = desc.begin(); i != desc.end(); ++i) { const MSEdge* edge = MSEdge::dictionary(*i); // check whether the edge exists if (edge == 0) { throw ProcessError("The edge '" + *i + "' within the route " + rid + " is not known." + "\n The route can not be build."); } into.push_back(edge); } } SUMOReal MSEdge::getDistanceTo(const MSEdge* other) const { if (getLanes().size() > 0 && other->getLanes().size() > 0) { return getLanes()[0]->getShape()[-1].distanceTo2D(other->getLanes()[0]->getShape()[0]); } else { return 0; // optimism is just right for astar } } SUMOReal MSEdge::getLength() const { return getLanes()[0]->getLength(); } SUMOReal MSEdge::getSpeedLimit() const { // @note lanes might have different maximum speeds in theory return getLanes()[0]->getSpeedLimit(); } SUMOReal MSEdge::getVehicleMaxSpeed(const SUMOVehicle* const veh) const { // @note lanes might have different maximum speeds in theory return getLanes()[0]->getVehicleMaxSpeed(veh); } /****************************************************************************/
rudhir-upretee/SUMO_Src
src/microsim/MSEdge.cpp
C++
gpl-3.0
17,842
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * OPCODE - Optimized Collision Detection * Copyright (C) 2001 Pierre Terdiman * Homepage: http://www.codercorner.com/Opcode.htm */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Contains base volume collider class. * \file OPC_VolumeCollider.h * \author Pierre Terdiman * \date June, 2, 2001 */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Include Guard #ifndef __OPC_VOLUMECOLLIDER_H__ #define __OPC_VOLUMECOLLIDER_H__ struct VolumeCache { VolumeCache() : Model(null) {} ~VolumeCache() {} IceCore::Container TouchedPrimitives; //!< Indices of touched primitives const BaseModel* Model; //!< Owner }; class VolumeCollider : public Collider { public: // Constructor / Destructor VolumeCollider(); virtual ~VolumeCollider() = 0; // Collision report /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Gets the number of touched primitives after a collision query. * \see GetContactStatus() * \see GetTouchedPrimitives() * \return the number of touched primitives */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// inline_ udword GetNbTouchedPrimitives() const { return mTouchedPrimitives ? mTouchedPrimitives->GetNbEntries() : 0; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Gets the list of touched primitives after a collision query. * \see GetContactStatus() * \see GetNbTouchedPrimitives() * \return the list of touched primitives (primitive indices) */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// inline_ const udword* GetTouchedPrimitives() const { return mTouchedPrimitives ? mTouchedPrimitives->GetEntries() : null; } // Stats /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Stats: gets the number of Volume-BV overlap tests after a collision query. * \see GetNbVolumePrimTests() * \return the number of Volume-BV tests performed during last query */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// inline_ udword GetNbVolumeBVTests() const { return mNbVolumeBVTests; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Stats: gets the number of Volume-Triangle overlap tests after a collision query. * \see GetNbVolumeBVTests() * \return the number of Volume-Triangle tests performed during last query */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// inline_ udword GetNbVolumePrimTests() const { return mNbVolumePrimTests; } // Settings /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Validates current settings. You should call this method after all the settings / callbacks have been defined for a collider. * \return null if everything is ok, else a string describing the problem */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// override(Collider) const char* ValidateSettings(); protected: // Touched primitives IceCore::Container* mTouchedPrimitives; //!< List of touched primitives // Precompured scale cache IceMaths::Point mLocalScale; //!< Collision model's local scale (stripped off from its matrix) // Dequantization coeffs IceMaths::Point mCenterCoeff; IceMaths::Point mExtentsCoeff; // Stats udword mNbVolumeBVTests; //!< Number of Volume-BV tests udword mNbVolumePrimTests; //!< Number of Volume-Primitive tests // Internal methods void _Dump(const AABBCollisionNode* node); void _Dump(const AABBNoLeafNode* node); void _Dump(const AABBQuantizedNode* node); void _Dump(const AABBQuantizedNoLeafNode* node); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Initializes a query */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// override(Collider) inline_ void InitQuery() { // Reset stats & contact status mNbVolumeBVTests = 0; mNbVolumePrimTests = 0; Collider::InitQuery(); } inline_ BOOL IsCacheValid(VolumeCache& cache) { // We're going to do a volume-vs-model query. if(cache.Model!=mCurrentModel) { // Cached list was for another model so we can't keep it // Keep track of new owner and reset cache cache.Model = mCurrentModel; return FALSE; } else { // Same models, no problem return TRUE; } } }; #endif // __OPC_VOLUMECOLLIDER_H__
mpreisler/ember
src/components/ogre/ogreopcode/include/Opcode/OPC_VolumeCollider.h
C
gpl-3.0
7,411
<!DOCTYPE html> <!-- Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.7 Version: 4.7.1 Author: KeenThemes Website: http://www.keenthemes.com/ Contact: support@keenthemes.com Follow: www.twitter.com/keenthemes Dribbble: www.dribbble.com/keenthemes Like: www.facebook.com/keenthemes Purchase: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes Renew Support: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes License: You must have a valid license purchased only from themeforest(the above link) in order to legally use the theme for your project. --> <!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]--> <!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]--> <!--[if !IE]><!--> <html lang="en"> <!--<![endif]--> <!-- BEGIN HEAD --> <head> <meta charset="utf-8" /> <title>Metronic Admin Theme #3 | Fixed Top Bar</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta content="width=device-width, initial-scale=1" name="viewport" /> <meta content="Preview page of Metronic Admin Theme #3 for " name="description" /> <meta content="" name="author" /> <!-- BEGIN GLOBAL MANDATORY STYLES --> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css" /> <link href="../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" /> <link href="../assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css" /> <link href="../assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link href="../assets/global/plugins/bootstrap-switch/css/bootstrap-switch.min.css" rel="stylesheet" type="text/css" /> <!-- END GLOBAL MANDATORY STYLES --> <!-- BEGIN THEME GLOBAL STYLES --> <link href="../assets/global/css/components-rounded.min.css" rel="stylesheet" id="style_components" type="text/css" /> <link href="../assets/global/css/plugins.min.css" rel="stylesheet" type="text/css" /> <!-- END THEME GLOBAL STYLES --> <!-- BEGIN THEME LAYOUT STYLES --> <link href="../assets/layouts/layout3/css/layout.min.css" rel="stylesheet" type="text/css" /> <link href="../assets/layouts/layout3/css/themes/default.min.css" rel="stylesheet" type="text/css" id="style_color" /> <link href="../assets/layouts/layout3/css/custom.min.css" rel="stylesheet" type="text/css" /> <!-- END THEME LAYOUT STYLES --> <link rel="shortcut icon" href="favicon.ico" /> </head> <!-- END HEAD --> <body class="page-container-bg-solid page-header-top-fixed"> <div class="page-wrapper"> <div class="page-wrapper-row"> <div class="page-wrapper-top"> <!-- BEGIN HEADER --> <div class="page-header"> <!-- BEGIN HEADER TOP --> <div class="page-header-top"> <div class="container"> <!-- BEGIN LOGO --> <div class="page-logo"> <a href="index.html"> <img src="../assets/layouts/layout3/img/logo-default.jpg" alt="logo" class="logo-default"> </a> </div> <!-- END LOGO --> <!-- BEGIN RESPONSIVE MENU TOGGLER --> <a href="javascript:;" class="menu-toggler"></a> <!-- END RESPONSIVE MENU TOGGLER --> <!-- BEGIN TOP NAVIGATION MENU --> <div class="top-menu"> <ul class="nav navbar-nav pull-right"> <!-- BEGIN NOTIFICATION DROPDOWN --> <!-- DOC: Apply "dropdown-hoverable" class after "dropdown" and remove data-toggle="dropdown" data-hover="dropdown" data-close-others="true" attributes to enable hover dropdown mode --> <!-- DOC: Remove "dropdown-hoverable" and add data-toggle="dropdown" data-hover="dropdown" data-close-others="true" attributes to the below A element with dropdown-toggle class --> <li class="dropdown dropdown-extended dropdown-notification dropdown-dark" id="header_notification_bar"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-bell"></i> <span class="badge badge-default">7</span> </a> <ul class="dropdown-menu"> <li class="external"> <h3>You have <strong>12 pending</strong> tasks</h3> <a href="app_todo.html">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 250px;" data-handle-color="#637283"> <li> <a href="javascript:;"> <span class="time">just now</span> <span class="details"> <span class="label label-sm label-icon label-success"> <i class="fa fa-plus"></i> </span> New user registered. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">3 mins</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Server #12 overloaded. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">10 mins</span> <span class="details"> <span class="label label-sm label-icon label-warning"> <i class="fa fa-bell-o"></i> </span> Server #2 not responding. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">14 hrs</span> <span class="details"> <span class="label label-sm label-icon label-info"> <i class="fa fa-bullhorn"></i> </span> Application error. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">2 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Database overloaded 68%. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">3 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> A user IP blocked. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">4 days</span> <span class="details"> <span class="label label-sm label-icon label-warning"> <i class="fa fa-bell-o"></i> </span> Storage Server #4 not responding dfdfdfd. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">5 days</span> <span class="details"> <span class="label label-sm label-icon label-info"> <i class="fa fa-bullhorn"></i> </span> System Error. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">9 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Storage server failed. </span> </a> </li> </ul> </li> </ul> </li> <!-- END NOTIFICATION DROPDOWN --> <!-- BEGIN TODO DROPDOWN --> <li class="dropdown dropdown-extended dropdown-tasks dropdown-dark" id="header_task_bar"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-calendar"></i> <span class="badge badge-default">3</span> </a> <ul class="dropdown-menu extended tasks"> <li class="external"> <h3>You have <strong>12 pending</strong> tasks</h3> <a href="app_todo_2.html">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283"> <li> <a href="javascript:;"> <span class="task"> <span class="desc">New release v1.2 </span> <span class="percent">30%</span> </span> <span class="progress"> <span style="width: 40%;" class="progress-bar progress-bar-success" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">40% Complete</span> </span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Application deployment</span> <span class="percent">65%</span> </span> <span class="progress"> <span style="width: 65%;" class="progress-bar progress-bar-danger" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">65% Complete</span> </span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Mobile app release</span> <span class="percent">98%</span> </span> <span class="progress"> <span style="width: 98%;" class="progress-bar progress-bar-success" aria-valuenow="98" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">98% Complete</span> </span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Database migration</span> <span class="percent">10%</span> </span> <span class="progress"> <span style="width: 10%;" class="progress-bar progress-bar-warning" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">10% Complete</span> </span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Web server upgrade</span> <span class="percent">58%</span> </span> <span class="progress"> <span style="width: 58%;" class="progress-bar progress-bar-info" aria-valuenow="58" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">58% Complete</span> </span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Mobile development</span> <span class="percent">85%</span> </span> <span class="progress"> <span style="width: 85%;" class="progress-bar progress-bar-success" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">85% Complete</span> </span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">New UI release</span> <span class="percent">38%</span> </span> <span class="progress progress-striped"> <span style="width: 38%;" class="progress-bar progress-bar-important" aria-valuenow="18" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">38% Complete</span> </span> </span> </a> </li> </ul> </li> </ul> </li> <!-- END TODO DROPDOWN --> <li class="droddown dropdown-separator"> <span class="separator"></span> </li> <!-- BEGIN INBOX DROPDOWN --> <li class="dropdown dropdown-extended dropdown-inbox dropdown-dark" id="header_inbox_bar"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <span class="circle">3</span> <span class="corner"></span> </a> <ul class="dropdown-menu"> <li class="external"> <h3>You have <strong>7 New</strong> Messages</h3> <a href="app_inbox.html">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283"> <li> <a href="#"> <span class="photo"> <img src="../assets/layouts/layout3/img/avatar2.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Lisa Wong </span> <span class="time">Just Now </span> </span> <span class="message"> Vivamus sed auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href="#"> <span class="photo"> <img src="../assets/layouts/layout3/img/avatar3.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Richard Doe </span> <span class="time">16 mins </span> </span> <span class="message"> Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href="#"> <span class="photo"> <img src="../assets/layouts/layout3/img/avatar1.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Bob Nilson </span> <span class="time">2 hrs </span> </span> <span class="message"> Vivamus sed nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href="#"> <span class="photo"> <img src="../assets/layouts/layout3/img/avatar2.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Lisa Wong </span> <span class="time">40 mins </span> </span> <span class="message"> Vivamus sed auctor 40% nibh congue nibh... </span> </a> </li> <li> <a href="#"> <span class="photo"> <img src="../assets/layouts/layout3/img/avatar3.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Richard Doe </span> <span class="time">46 mins </span> </span> <span class="message"> Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> </ul> </li> </ul> </li> <!-- END INBOX DROPDOWN --> <!-- BEGIN USER LOGIN DROPDOWN --> <li class="dropdown dropdown-user dropdown-dark"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <img alt="" class="img-circle" src="../assets/layouts/layout3/img/avatar9.jpg"> <span class="username username-hide-mobile">Nick</span> </a> <ul class="dropdown-menu dropdown-menu-default"> <li> <a href="page_user_profile_1.html"> <i class="icon-user"></i> My Profile </a> </li> <li> <a href="app_calendar.html"> <i class="icon-calendar"></i> My Calendar </a> </li> <li> <a href="app_inbox.html"> <i class="icon-envelope-open"></i> My Inbox <span class="badge badge-danger"> 3 </span> </a> </li> <li> <a href="app_todo_2.html"> <i class="icon-rocket"></i> My Tasks <span class="badge badge-success"> 7 </span> </a> </li> <li class="divider"> </li> <li> <a href="page_user_lock_1.html"> <i class="icon-lock"></i> Lock Screen </a> </li> <li> <a href="page_user_login_1.html"> <i class="icon-key"></i> Log Out </a> </li> </ul> </li> <!-- END USER LOGIN DROPDOWN --> <!-- BEGIN QUICK SIDEBAR TOGGLER --> <li class="dropdown dropdown-extended quick-sidebar-toggler"> <span class="sr-only">Toggle Quick Sidebar</span> <i class="icon-logout"></i> </li> <!-- END QUICK SIDEBAR TOGGLER --> </ul> </div> <!-- END TOP NAVIGATION MENU --> </div> </div> <!-- END HEADER TOP --> <!-- BEGIN HEADER MENU --> <div class="page-header-menu"> <div class="container"> <!-- BEGIN HEADER SEARCH BOX --> <form class="search-form" action="page_general_search.html" method="GET"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search" name="query"> <span class="input-group-btn"> <a href="javascript:;" class="btn submit"> <i class="icon-magnifier"></i> </a> </span> </div> </form> <!-- END HEADER SEARCH BOX --> <!-- BEGIN MEGA MENU --> <!-- DOC: Apply "hor-menu-light" class after the "hor-menu" class below to have a horizontal menu with white background --> <!-- DOC: Remove data-hover="dropdown" and data-close-others="true" attributes below to disable the dropdown opening on mouse hover --> <div class="hor-menu "> <ul class="nav navbar-nav"> <li aria-haspopup="true" class="menu-dropdown classic-menu-dropdown "> <a href="javascript:;"> Dashboard <span class="arrow"></span> </a> <ul class="dropdown-menu pull-left"> <li aria-haspopup="true" class=" "> <a href="index.html" class="nav-link "> <i class="icon-bar-chart"></i> Default Dashboard <span class="badge badge-success">1</span> </a> </li> <li aria-haspopup="true" class=" "> <a href="dashboard_2.html" class="nav-link "> <i class="icon-bulb"></i> Dashboard 2 </a> </li> <li aria-haspopup="true" class=" "> <a href="dashboard_3.html" class="nav-link "> <i class="icon-graph"></i> Dashboard 3 <span class="badge badge-danger">3</span> </a> </li> </ul> </li> <li aria-haspopup="true" class="menu-dropdown mega-menu-dropdown "> <a href="javascript:;"> UI Features <span class="arrow"></span> </a> <ul class="dropdown-menu" style="min-width: 710px"> <li> <div class="mega-menu-content"> <div class="row"> <div class="col-md-4"> <ul class="mega-menu-submenu"> <li> <a href="ui_colors.html"> Color Library </a> </li> <li> <a href="ui_metronic_grid.html"> Metronic Grid System </a> </li> <li> <a href="ui_general.html"> General Components </a> </li> <li> <a href="ui_buttons.html"> Buttons </a> </li> <li> <a href="ui_buttons_spinner.html"> Spinner Buttons </a> </li> <li> <a href="ui_confirmations.html"> Popover Confirmations </a> </li> <li> <a href="ui_sweetalert.html"> Bootstrap Sweet Alerts </a> </li> <li> <a href="ui_icons.html"> Font Icons </a> </li> <li> <a href="ui_socicons.html"> Social Icons </a> </li> <li> <a href="ui_typography.html"> Typography </a> </li> <li> <a href="ui_tabs_accordions_navs.html"> Tabs, Accordions & Navs </a> </li> <li> <a href="ui_tree.html"> Tree View </a> </li> <li> <a href="maps_google.html"> Google Maps </a> </li> </ul> </div> <div class="col-md-4"> <ul class="mega-menu-submenu"> <li> <a href="maps_vector.html"> Vector Maps </a> </li> <li> <a href="ui_timeline.html"> Timeline 1 </a> </li> <li> <a href="ui_timeline_2.html"> Timeline 2 </a> </li> <li> <a href="ui_timeline_horizontal.html"> Horizontal Timeline </a> </li> <li> <a href="ui_page_progress_style_1.html"> Page Progress Bar - Flash </a> </li> <li> <a href="ui_page_progress_style_2.html"> Page Progress Bar - Big Counter </a> </li> <li> <a href="ui_blockui.html"> Block UI </a> </li> <li> <a href="ui_bootstrap_growl.html"> Bootstrap Growl Notifications </a> </li> <li> <a href="ui_notific8.html"> Notific8 Notifications </a> </li> <li> <a href="ui_toastr.html"> Toastr Notifications </a> </li> <li> <a href="ui_bootbox.html"> Bootbox Dialogs </a> </li> </ul> </div> <div class="col-md-4"> <ul class="mega-menu-submenu"> <li> <a href="ui_alerts_api.html"> Metronic Alerts API </a> </li> <li> <a href="ui_session_timeout.html"> Session Timeout </a> </li> <li> <a href="ui_idle_timeout.html"> User Idle Timeout </a> </li> <li> <a href="ui_modals.html"> Modals </a> </li> <li> <a href="ui_extended_modals.html"> Extended Modals </a> </li> <li> <a href="ui_tiles.html"> Tiles </a> </li> <li> <a href="ui_datepaginator.html"> Date Paginator </a> </li> <li> <a href="ui_nestable.html"> Nestable List </a> </li> </ul> </div> </div> </div> </li> </ul> </li> <li aria-haspopup="true" class="menu-dropdown classic-menu-dropdown active"> <a href="javascript:;"> Layouts <span class="arrow"></span> </a> <ul class="dropdown-menu pull-left"> <li aria-haspopup="true" class=" "> <a href="layout_mega_menu_light.html" class="nav-link "> Light Mega Menu </a> </li> <li aria-haspopup="true" class=" "> <a href="layout_top_bar_light.html" class="nav-link "> Light Top Bar Dropdowns </a> </li> <li aria-haspopup="true" class=" "> <a href="layout_fluid_page.html" class="nav-link "> Fluid Page </a> </li> <li aria-haspopup="true" class=" active"> <a href="layout_top_bar_fixed.html" class="nav-link active"> Fixed Top Bar </a> </li> <li aria-haspopup="true" class=" "> <a href="layout_mega_menu_fixed.html" class="nav-link "> Fixed Mega Menu </a> </li> <li aria-haspopup="true" class=" "> <a href="layout_disabled_menu.html" class="nav-link "> Disabled Menu Links </a> </li> <li aria-haspopup="true" class=" "> <a href="layout_blank_page.html" class="nav-link "> Blank Page </a> </li> </ul> </li> <li aria-haspopup="true" class="menu-dropdown mega-menu-dropdown mega-menu-full"> <a href="javascript:;"> Components <span class="arrow"></span> </a> <ul class="dropdown-menu" style="min-width: "> <li> <div class="mega-menu-content"> <div class="row"> <div class="col-md-3"> <ul class="mega-menu-submenu"> <li> <h3>Components 1</h3> </li> <li> <a href="components_date_time_pickers.html"> Date & Time Pickers </a> </li> <li> <a href="components_color_pickers.html"> Color Pickers </a> </li> <li> <a href="components_select2.html"> Select2 Dropdowns </a> </li> <li> <a href="components_bootstrap_multiselect_dropdown.html"> Bootstrap Multiselect Dropdowns </a> </li> <li> <a href="components_bootstrap_select.html"> Bootstrap Select </a> </li> <li> <a href="components_multi_select.html"> Bootstrap Multiple Select </a> </li> </ul> </div> <div class="col-md-3"> <ul class="mega-menu-submenu"> <li> <h3>Components 2</h3> </li> <li> <a href="components_bootstrap_select_splitter.html"> Select Splitter </a> </li> <li> <a href="components_clipboard.html"> Clipboard </a> </li> <li> <a href="components_typeahead.html"> Typeahead Autocomplete </a> </li> <li> <a href="components_bootstrap_tagsinput.html"> Bootstrap Tagsinput </a> </li> <li> <a href="components_bootstrap_switch.html"> Bootstrap Switch </a> </li> <li> <a href="components_bootstrap_maxlength.html"> Bootstrap Maxlength </a> </li> </ul> </div> <div class="col-md-3"> <ul class="mega-menu-submenu"> <li> <h3>Components 3</h3> </li> <li> <a href="components_bootstrap_fileinput.html"> Bootstrap File Input </a> </li> <li> <a href="components_bootstrap_touchspin.html"> Bootstrap Touchspin </a> </li> <li> <a href="components_form_tools.html"> Form Widgets & Tools </a> </li> <li> <a href="components_context_menu.html"> Context Menu </a> </li> <li> <a href="components_editors.html"> Markdown & WYSIWYG Editors </a> </li> </ul> </div> <div class="col-md-3"> <ul class="mega-menu-submenu"> <li> <h3>Components 4</h3> </li> <li> <a href="components_code_editors.html"> Code Editors </a> </li> <li> <a href="components_ion_sliders.html"> Ion Range Sliders </a> </li> <li> <a href="components_noui_sliders.html"> NoUI Range Sliders </a> </li> <li> <a href="components_knob_dials.html"> Knob Circle Dials </a> </li> </ul> </div> </div> </div> </li> </ul> </li> <li aria-haspopup="true" class="menu-dropdown classic-menu-dropdown "> <a href="javascript:;"> More <span class="arrow"></span> </a> <ul class="dropdown-menu pull-left"> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle "> <i class="icon-settings"></i> Form Stuff <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li aria-haspopup="true" class=" "> <a href="form_controls.html" class="nav-link "> Bootstrap Form <br>Controls </a> </li> <li aria-haspopup="true" class=" "> <a href="form_controls_md.html" class="nav-link "> Material Design <br>Form Controls </a> </li> <li aria-haspopup="true" class=" "> <a href="form_validation.html" class="nav-link "> Form Validation </a> </li> <li aria-haspopup="true" class=" "> <a href="form_validation_states_md.html" class="nav-link "> Material Design <br>Form Validation States </a> </li> <li aria-haspopup="true" class=" "> <a href="form_validation_md.html" class="nav-link "> Material Design <br>Form Validation </a> </li> <li aria-haspopup="true" class=" "> <a href="form_layouts.html" class="nav-link "> Form Layouts </a> </li> <li aria-haspopup="true" class=" "> <a href="form_repeater.html" class="nav-link "> Form Repeater </a> </li> <li aria-haspopup="true" class=" "> <a href="form_input_mask.html" class="nav-link "> Form Input Mask </a> </li> <li aria-haspopup="true" class=" "> <a href="form_editable.html" class="nav-link "> Form X-editable </a> </li> <li aria-haspopup="true" class=" "> <a href="form_wizard.html" class="nav-link "> Form Wizard </a> </li> <li aria-haspopup="true" class=" "> <a href="form_icheck.html" class="nav-link "> iCheck Controls </a> </li> <li aria-haspopup="true" class=" "> <a href="form_image_crop.html" class="nav-link "> Image Cropping </a> </li> <li aria-haspopup="true" class=" "> <a href="form_fileupload.html" class="nav-link "> Multiple File Upload </a> </li> <li aria-haspopup="true" class=" "> <a href="form_dropzone.html" class="nav-link "> Dropzone File Upload </a> </li> </ul> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle "> <i class="icon-briefcase"></i> Tables <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li aria-haspopup="true" class=" "> <a href="table_static_basic.html" class="nav-link "> Basic Tables </a> </li> <li aria-haspopup="true" class=" "> <a href="table_static_responsive.html" class="nav-link "> Responsive Tables </a> </li> <li aria-haspopup="true" class=" "> <a href="table_bootstrap.html" class="nav-link "> Bootstrap Tables </a> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle"> Datatables <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li class=""> <a href="table_datatables_managed.html" class="nav-link "> Managed Datatables </a> </li> <li class=""> <a href="table_datatables_buttons.html" class="nav-link "> Buttons Extension </a> </li> <li class=""> <a href="table_datatables_colreorder.html" class="nav-link "> Colreorder Extension </a> </li> <li class=""> <a href="table_datatables_rowreorder.html" class="nav-link "> Rowreorder Extension </a> </li> <li class=""> <a href="table_datatables_scroller.html" class="nav-link "> Scroller Extension </a> </li> <li class=""> <a href="table_datatables_fixedheader.html" class="nav-link "> FixedHeader Extension </a> </li> <li class=""> <a href="table_datatables_responsive.html" class="nav-link "> Responsive Extension </a> </li> <li class=""> <a href="table_datatables_editable.html" class="nav-link "> Editable Datatables </a> </li> <li class=""> <a href="table_datatables_ajax.html" class="nav-link "> Ajax Datatables </a> </li> </ul> </li> </ul> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="?p=" class="nav-link nav-toggle "> <i class="icon-wallet"></i> Portlets <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li aria-haspopup="true" class=" "> <a href="portlet_boxed.html" class="nav-link "> Boxed Portlets </a> </li> <li aria-haspopup="true" class=" "> <a href="portlet_light.html" class="nav-link "> Light Portlets </a> </li> <li aria-haspopup="true" class=" "> <a href="portlet_solid.html" class="nav-link "> Solid Portlets </a> </li> <li aria-haspopup="true" class=" "> <a href="portlet_ajax.html" class="nav-link "> Ajax Portlets </a> </li> <li aria-haspopup="true" class=" "> <a href="portlet_draggable.html" class="nav-link "> Draggable Portlets </a> </li> </ul> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="?p=" class="nav-link nav-toggle "> <i class="icon-settings"></i> Elements <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li aria-haspopup="true" class=" "> <a href="elements_steps.html" class="nav-link "> Steps </a> </li> <li aria-haspopup="true" class=" "> <a href="elements_lists.html" class="nav-link "> Lists </a> </li> <li aria-haspopup="true" class=" "> <a href="elements_ribbons.html" class="nav-link "> Ribbons </a> </li> <li aria-haspopup="true" class=" "> <a href="elements_overlay.html" class="nav-link "> Overlays </a> </li> <li aria-haspopup="true" class=" "> <a href="elements_cards.html" class="nav-link "> User Cards </a> </li> </ul> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle "> <i class="icon-bar-chart"></i> Charts <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li aria-haspopup="true" class=" "> <a href="charts_amcharts.html" class="nav-link "> amChart </a> </li> <li aria-haspopup="true" class=" "> <a href="charts_flotcharts.html" class="nav-link "> Flot Charts </a> </li> <li aria-haspopup="true" class=" "> <a href="charts_flowchart.html" class="nav-link "> Flow Charts </a> </li> <li aria-haspopup="true" class=" "> <a href="charts_google.html" class="nav-link "> Google Charts </a> </li> <li aria-haspopup="true" class=" "> <a href="charts_echarts.html" class="nav-link "> eCharts </a> </li> <li aria-haspopup="true" class=" "> <a href="charts_morris.html" class="nav-link "> Morris Charts </a> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle"> HighCharts <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li class=""> <a href="charts_highcharts.html" class="nav-link " target="_blank"> HighCharts </a> </li> <li class=""> <a href="charts_highstock.html" class="nav-link " target="_blank"> HighStock </a> </li> <li class=""> <a href="charts_highmaps.html" class="nav-link " target="_blank"> HighMaps </a> </li> </ul> </li> </ul> </li> </ul> </li> <li aria-haspopup="true" class="menu-dropdown classic-menu-dropdown "> <a href="javascript:;"> <i class="icon-briefcase"></i> Pages <span class="arrow"></span> </a> <ul class="dropdown-menu pull-left"> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle "> <i class="icon-basket"></i> eCommerce <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li aria-haspopup="true" class=" "> <a href="ecommerce_index.html" class="nav-link "> <i class="icon-home"></i> Dashboard </a> </li> <li aria-haspopup="true" class=" "> <a href="ecommerce_orders.html" class="nav-link "> <i class="icon-basket"></i> Orders </a> </li> <li aria-haspopup="true" class=" "> <a href="ecommerce_orders_view.html" class="nav-link "> <i class="icon-tag"></i> Order View </a> </li> <li aria-haspopup="true" class=" "> <a href="ecommerce_products.html" class="nav-link "> <i class="icon-graph"></i> Products </a> </li> <li aria-haspopup="true" class=" "> <a href="ecommerce_products_edit.html" class="nav-link "> <i class="icon-graph"></i> Product Edit </a> </li> </ul> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle "> <i class="icon-docs"></i> Apps <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li aria-haspopup="true" class=" "> <a href="app_todo.html" class="nav-link "> <i class="icon-clock"></i> Todo 1 </a> </li> <li aria-haspopup="true" class=" "> <a href="app_todo_2.html" class="nav-link "> <i class="icon-check"></i> Todo 2 </a> </li> <li aria-haspopup="true" class=" "> <a href="app_inbox.html" class="nav-link "> <i class="icon-envelope"></i> Inbox </a> </li> <li aria-haspopup="true" class=" "> <a href="app_calendar.html" class="nav-link "> <i class="icon-calendar"></i> Calendar </a> </li> <li aria-haspopup="true" class=" "> <a href="app_ticket.html" class="nav-link "> <i class="icon-notebook"></i> Support </a> </li> </ul> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle "> <i class="icon-user"></i> User <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li aria-haspopup="true" class=" "> <a href="page_user_profile_1.html" class="nav-link "> <i class="icon-user"></i> Profile 1 </a> </li> <li aria-haspopup="true" class=" "> <a href="page_user_profile_1_account.html" class="nav-link "> <i class="icon-user-female"></i> Profile 1 Account </a> </li> <li aria-haspopup="true" class=" "> <a href="page_user_profile_1_help.html" class="nav-link "> <i class="icon-user-following"></i> Profile 1 Help </a> </li> <li aria-haspopup="true" class=" "> <a href="page_user_profile_2.html" class="nav-link "> <i class="icon-users"></i> Profile 2 </a> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-notebook"></i> Login <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li class=""> <a href="page_user_login_1.html" class="nav-link " target="_blank"> Login Page 1 </a> </li> <li class=""> <a href="page_user_login_2.html" class="nav-link " target="_blank"> Login Page 2 </a> </li> <li class=""> <a href="page_user_login_3.html" class="nav-link " target="_blank"> Login Page 3 </a> </li> <li class=""> <a href="page_user_login_4.html" class="nav-link " target="_blank"> Login Page 4 </a> </li> <li class=""> <a href="page_user_login_5.html" class="nav-link " target="_blank"> Login Page 5 </a> </li> <li class=""> <a href="page_user_login_6.html" class="nav-link " target="_blank"> Login Page 6 </a> </li> </ul> </li> <li aria-haspopup="true" class=" "> <a href="page_user_lock_1.html" class="nav-link " target="_blank"> <i class="icon-lock"></i> Lock Screen 1 </a> </li> <li aria-haspopup="true" class=" "> <a href="page_user_lock_2.html" class="nav-link " target="_blank"> <i class="icon-lock-open"></i> Lock Screen 2 </a> </li> </ul> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle "> <i class="icon-social-dribbble"></i> General <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li aria-haspopup="true" class=" "> <a href="page_general_about.html" class="nav-link "> <i class="icon-info"></i> About </a> </li> <li aria-haspopup="true" class=" "> <a href="page_general_contact.html" class="nav-link "> <i class="icon-call-end"></i> Contact </a> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-notebook"></i> Portfolio <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li class=""> <a href="page_general_portfolio_1.html" class="nav-link "> Portfolio 1 </a> </li> <li class=""> <a href="page_general_portfolio_2.html" class="nav-link "> Portfolio 2 </a> </li> <li class=""> <a href="page_general_portfolio_3.html" class="nav-link "> Portfolio 3 </a> </li> <li class=""> <a href="page_general_portfolio_4.html" class="nav-link "> Portfolio 4 </a> </li> </ul> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle"> <i class="icon-magnifier"></i> Search <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li class=""> <a href="page_general_search.html" class="nav-link "> Search 1 </a> </li> <li class=""> <a href="page_general_search_2.html" class="nav-link "> Search 2 </a> </li> <li class=""> <a href="page_general_search_3.html" class="nav-link "> Search 3 </a> </li> <li class=""> <a href="page_general_search_4.html" class="nav-link "> Search 4 </a> </li> <li class=""> <a href="page_general_search_5.html" class="nav-link "> Search 5 </a> </li> </ul> </li> <li aria-haspopup="true" class=" "> <a href="page_general_pricing.html" class="nav-link "> <i class="icon-tag"></i> Pricing </a> </li> <li aria-haspopup="true" class=" "> <a href="page_general_faq.html" class="nav-link "> <i class="icon-wrench"></i> FAQ </a> </li> <li aria-haspopup="true" class=" "> <a href="page_general_blog.html" class="nav-link "> <i class="icon-pencil"></i> Blog </a> </li> <li aria-haspopup="true" class=" "> <a href="page_general_blog_post.html" class="nav-link "> <i class="icon-note"></i> Blog Post </a> </li> <li aria-haspopup="true" class=" "> <a href="page_general_invoice.html" class="nav-link "> <i class="icon-envelope"></i> Invoice </a> </li> <li aria-haspopup="true" class=" "> <a href="page_general_invoice_2.html" class="nav-link "> <i class="icon-envelope"></i> Invoice 2 </a> </li> </ul> </li> <li aria-haspopup="true" class="dropdown-submenu "> <a href="javascript:;" class="nav-link nav-toggle "> <i class="icon-settings"></i> System <span class="arrow"></span> </a> <ul class="dropdown-menu"> <li aria-haspopup="true" class=" "> <a href="page_system_coming_soon.html" class="nav-link " target="_blank"> Coming Soon </a> </li> <li aria-haspopup="true" class=" "> <a href="page_system_404_1.html" class="nav-link "> 404 Page 1 </a> </li> <li aria-haspopup="true" class=" "> <a href="page_system_404_2.html" class="nav-link " target="_blank"> 404 Page 2 </a> </li> <li aria-haspopup="true" class=" "> <a href="page_system_404_3.html" class="nav-link " target="_blank"> 404 Page 3 </a> </li> <li aria-haspopup="true" class=" "> <a href="page_system_500_1.html" class="nav-link "> 500 Page 1 </a> </li> <li aria-haspopup="true" class=" "> <a href="page_system_500_2.html" class="nav-link " target="_blank"> 500 Page 2 </a> </li> </ul> </li> </ul> </li> </ul> </div> <!-- END MEGA MENU --> </div> </div> <!-- END HEADER MENU --> </div> <!-- END HEADER --> </div> </div> <div class="page-wrapper-row full-height"> <div class="page-wrapper-middle"> <!-- BEGIN CONTAINER --> <div class="page-container"> <!-- BEGIN CONTENT --> <div class="page-content-wrapper"> <!-- BEGIN CONTENT BODY --> <!-- BEGIN PAGE HEAD--> <div class="page-head"> <div class="container"> <!-- BEGIN PAGE TITLE --> <div class="page-title"> <h1>Fixed Top Bar </h1> </div> <!-- END PAGE TITLE --> <!-- BEGIN PAGE TOOLBAR --> <div class="page-toolbar"> <!-- BEGIN THEME PANEL --> <div class="btn-group btn-theme-panel"> <a href="javascript:;" class="btn dropdown-toggle" data-toggle="dropdown"> <i class="icon-settings"></i> </a> <div class="dropdown-menu theme-panel pull-right dropdown-custom hold-on-click"> <div class="row"> <div class="col-md-6 col-sm-6 col-xs-12"> <h3>THEME COLORS</h3> <div class="row"> <div class="col-md-6 col-sm-6 col-xs-12"> <ul class="theme-colors"> <li class="theme-color theme-color-default" data-theme="default"> <span class="theme-color-view"></span> <span class="theme-color-name">Default</span> </li> <li class="theme-color theme-color-blue-hoki" data-theme="blue-hoki"> <span class="theme-color-view"></span> <span class="theme-color-name">Blue Hoki</span> </li> <li class="theme-color theme-color-blue-steel" data-theme="blue-steel"> <span class="theme-color-view"></span> <span class="theme-color-name">Blue Steel</span> </li> <li class="theme-color theme-color-yellow-orange" data-theme="yellow-orange"> <span class="theme-color-view"></span> <span class="theme-color-name">Orange</span> </li> <li class="theme-color theme-color-yellow-crusta" data-theme="yellow-crusta"> <span class="theme-color-view"></span> <span class="theme-color-name">Yellow Crusta</span> </li> </ul> </div> <div class="col-md-6 col-sm-6 col-xs-12"> <ul class="theme-colors"> <li class="theme-color theme-color-green-haze" data-theme="green-haze"> <span class="theme-color-view"></span> <span class="theme-color-name">Green Haze</span> </li> <li class="theme-color theme-color-red-sunglo" data-theme="red-sunglo"> <span class="theme-color-view"></span> <span class="theme-color-name">Red Sunglo</span> </li> <li class="theme-color theme-color-red-intense" data-theme="red-intense"> <span class="theme-color-view"></span> <span class="theme-color-name">Red Intense</span> </li> <li class="theme-color theme-color-purple-plum" data-theme="purple-plum"> <span class="theme-color-view"></span> <span class="theme-color-name">Purple Plum</span> </li> <li class="theme-color theme-color-purple-studio" data-theme="purple-studio"> <span class="theme-color-view"></span> <span class="theme-color-name">Purple Studio</span> </li> </ul> </div> </div> </div> <div class="col-md-6 col-sm-6 col-xs-12 seperator"> <h3>LAYOUT</h3> <ul class="theme-settings"> <li> Theme Style <select class="theme-setting theme-setting-style form-control input-sm input-small input-inline tooltips" data-original-title="Change theme style" data-container="body" data-placement="left"> <option value="boxed" selected="selected">Square corners</option> <option value="rounded">Rounded corners</option> </select> </li> <li> Layout <select class="theme-setting theme-setting-layout form-control input-sm input-small input-inline tooltips" data-original-title="Change layout type" data-container="body" data-placement="left"> <option value="boxed" selected="selected">Boxed</option> <option value="fluid">Fluid</option> </select> </li> <li> Top Menu Style <select class="theme-setting theme-setting-top-menu-style form-control input-sm input-small input-inline tooltips" data-original-title="Change top menu dropdowns style" data-container="body" data-placement="left"> <option value="dark" selected="selected">Dark</option> <option value="light">Light</option> </select> </li> <li> Top Menu Mode <select class="theme-setting theme-setting-top-menu-mode form-control input-sm input-small input-inline tooltips" data-original-title="Enable fixed(sticky) top menu" data-container="body" data-placement="left"> <option value="fixed">Fixed</option> <option value="not-fixed" selected="selected">Not Fixed</option> </select> </li> <li> Mega Menu Style <select class="theme-setting theme-setting-mega-menu-style form-control input-sm input-small input-inline tooltips" data-original-title="Change mega menu dropdowns style" data-container="body" data-placement="left"> <option value="dark" selected="selected">Dark</option> <option value="light">Light</option> </select> </li> <li> Mega Menu Mode <select class="theme-setting theme-setting-mega-menu-mode form-control input-sm input-small input-inline tooltips" data-original-title="Enable fixed(sticky) mega menu" data-container="body" data-placement="left"> <option value="fixed" selected="selected">Fixed</option> <option value="not-fixed">Not Fixed</option> </select> </li> </ul> </div> </div> </div> </div> <!-- END THEME PANEL --> </div> <!-- END PAGE TOOLBAR --> </div> </div> <!-- END PAGE HEAD--> <!-- BEGIN PAGE CONTENT BODY --> <div class="page-content"> <div class="container"> <!-- BEGIN PAGE BREADCRUMBS --> <ul class="page-breadcrumb breadcrumb"> <li> <a href="index.html">Home</a> <i class="fa fa-circle"></i> </li> <li> <span>Layouts</span> </li> </ul> <!-- END PAGE BREADCRUMBS --> <!-- BEGIN PAGE CONTENT INNER --> <div class="page-content-inner"> <div class="note note-info"> <p> To set fixed top bar apply <code>page-header-top-fixed</code> to the body element. </p> </div> <div class="portlet light portlet-fit "> <div class="portlet-title"> <div class="caption"> <i class=" icon-layers font-green"></i> <span class="caption-subject font-green bold uppercase">Basic Portlet</span> </div> <div class="actions"> <a class="btn btn-circle btn-icon-only btn-default" href="javascript:;"> <i class="icon-cloud-upload"></i> </a> <a class="btn btn-circle btn-icon-only btn-default" href="javascript:;"> <i class="icon-wrench"></i> </a> <a class="btn btn-circle btn-icon-only btn-default" href="javascript:;"> <i class="icon-trash"></i> </a> </div> </div> <div class="portlet-body"> <p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p> <p> This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? </p> <p> Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. </p> Thanks a ton!height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. </p> <p> I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton! </p> <p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p> <p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p> <p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p> <p> Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. </p> Thanks a ton!height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. </p> <p> I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton! </p> <p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p> <p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p> <p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p> <p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p> <p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p> <p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p> </div> </div> </div> <!-- END PAGE CONTENT INNER --> </div> </div> <!-- END PAGE CONTENT BODY --> <!-- END CONTENT BODY --> </div> <!-- END CONTENT --> <!-- BEGIN QUICK SIDEBAR --> <a href="javascript:;" class="page-quick-sidebar-toggler"> <i class="icon-login"></i> </a> <div class="page-quick-sidebar-wrapper" data-close-on-body-click="false"> <div class="page-quick-sidebar"> <ul class="nav nav-tabs"> <li class="active"> <a href="javascript:;" data-target="#quick_sidebar_tab_1" data-toggle="tab"> Users <span class="badge badge-danger">2</span> </a> </li> <li> <a href="javascript:;" data-target="#quick_sidebar_tab_2" data-toggle="tab"> Alerts <span class="badge badge-success">7</span> </a> </li> <li class="dropdown"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown"> More <i class="fa fa-angle-down"></i> </a> <ul class="dropdown-menu pull-right"> <li> <a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab"> <i class="icon-bell"></i> Alerts </a> </li> <li> <a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab"> <i class="icon-info"></i> Notifications </a> </li> <li> <a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab"> <i class="icon-speech"></i> Activities </a> </li> <li class="divider"></li> <li> <a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab"> <i class="icon-settings"></i> Settings </a> </li> </ul> </li> </ul> <div class="tab-content"> <div class="tab-pane active page-quick-sidebar-chat" id="quick_sidebar_tab_1"> <div class="page-quick-sidebar-chat-users" data-rail-color="#ddd" data-wrapper-class="page-quick-sidebar-list"> <h3 class="list-heading">Staff</h3> <ul class="media-list list-items"> <li class="media"> <div class="media-status"> <span class="badge badge-success">8</span> </div> <img class="media-object" src="../assets/layouts/layout/img/avatar3.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Bob Nilson</h4> <div class="media-heading-sub"> Project Manager </div> </div> </li> <li class="media"> <img class="media-object" src="../assets/layouts/layout/img/avatar1.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Nick Larson</h4> <div class="media-heading-sub"> Art Director </div> </div> </li> <li class="media"> <div class="media-status"> <span class="badge badge-danger">3</span> </div> <img class="media-object" src="../assets/layouts/layout/img/avatar4.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Deon Hubert</h4> <div class="media-heading-sub"> CTO </div> </div> </li> <li class="media"> <img class="media-object" src="../assets/layouts/layout/img/avatar2.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Ella Wong</h4> <div class="media-heading-sub"> CEO </div> </div> </li> </ul> <h3 class="list-heading">Customers</h3> <ul class="media-list list-items"> <li class="media"> <div class="media-status"> <span class="badge badge-warning">2</span> </div> <img class="media-object" src="../assets/layouts/layout/img/avatar6.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Lara Kunis</h4> <div class="media-heading-sub"> CEO, Loop Inc </div> <div class="media-heading-small"> Last seen 03:10 AM </div> </div> </li> <li class="media"> <div class="media-status"> <span class="label label-sm label-success">new</span> </div> <img class="media-object" src="../assets/layouts/layout/img/avatar7.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Ernie Kyllonen</h4> <div class="media-heading-sub"> Project Manager, <br> SmartBizz PTL </div> </div> </li> <li class="media"> <img class="media-object" src="../assets/layouts/layout/img/avatar8.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Lisa Stone</h4> <div class="media-heading-sub"> CTO, Keort Inc </div> <div class="media-heading-small"> Last seen 13:10 PM </div> </div> </li> <li class="media"> <div class="media-status"> <span class="badge badge-success">7</span> </div> <img class="media-object" src="../assets/layouts/layout/img/avatar9.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Deon Portalatin</h4> <div class="media-heading-sub"> CFO, H&D LTD </div> </div> </li> <li class="media"> <img class="media-object" src="../assets/layouts/layout/img/avatar10.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Irina Savikova</h4> <div class="media-heading-sub"> CEO, Tizda Motors Inc </div> </div> </li> <li class="media"> <div class="media-status"> <span class="badge badge-danger">4</span> </div> <img class="media-object" src="../assets/layouts/layout/img/avatar11.jpg" alt="..."> <div class="media-body"> <h4 class="media-heading">Maria Gomez</h4> <div class="media-heading-sub"> Manager, Infomatic Inc </div> <div class="media-heading-small"> Last seen 03:10 AM </div> </div> </li> </ul> </div> <div class="page-quick-sidebar-item"> <div class="page-quick-sidebar-chat-user"> <div class="page-quick-sidebar-nav"> <a href="javascript:;" class="page-quick-sidebar-back-to-list"> <i class="icon-arrow-left"></i>Back</a> </div> <div class="page-quick-sidebar-chat-user-messages"> <div class="post out"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Bob Nilson</a> <span class="datetime">20:15</span> <span class="body"> When could you send me the report ? </span> </div> </div> <div class="post in"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Ella Wong</a> <span class="datetime">20:15</span> <span class="body"> Its almost done. I will be sending it shortly </span> </div> </div> <div class="post out"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Bob Nilson</a> <span class="datetime">20:15</span> <span class="body"> Alright. Thanks! :) </span> </div> </div> <div class="post in"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Ella Wong</a> <span class="datetime">20:16</span> <span class="body"> You are most welcome. Sorry for the delay. </span> </div> </div> <div class="post out"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Bob Nilson</a> <span class="datetime">20:17</span> <span class="body"> No probs. Just take your time :) </span> </div> </div> <div class="post in"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Ella Wong</a> <span class="datetime">20:40</span> <span class="body"> Alright. I just emailed it to you. </span> </div> </div> <div class="post out"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Bob Nilson</a> <span class="datetime">20:17</span> <span class="body"> Great! Thanks. Will check it right away. </span> </div> </div> <div class="post in"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Ella Wong</a> <span class="datetime">20:40</span> <span class="body"> Please let me know if you have any comment. </span> </div> </div> <div class="post out"> <img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" /> <div class="message"> <span class="arrow"></span> <a href="javascript:;" class="name">Bob Nilson</a> <span class="datetime">20:17</span> <span class="body"> Sure. I will check and buzz you if anything needs to be corrected. </span> </div> </div> </div> <div class="page-quick-sidebar-chat-user-form"> <div class="input-group"> <input type="text" class="form-control" placeholder="Type a message here..."> <div class="input-group-btn"> <button type="button" class="btn green"> <i class="icon-paper-clip"></i> </button> </div> </div> </div> </div> </div> </div> <div class="tab-pane page-quick-sidebar-alerts" id="quick_sidebar_tab_2"> <div class="page-quick-sidebar-alerts-list"> <h3 class="list-heading">General</h3> <ul class="feeds list-items"> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-check"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 4 pending tasks. <span class="label label-sm label-warning "> Take action <i class="fa fa-share"></i> </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> Just now </div> </div> </li> <li> <a href="javascript:;"> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-success"> <i class="fa fa-bar-chart-o"></i> </div> </div> <div class="cont-col2"> <div class="desc"> Finance Report for year 2013 has been released. </div> </div> </div> </div> <div class="col2"> <div class="date"> 20 mins </div> </div> </a> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-danger"> <i class="fa fa-user"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 5 pending membership that requires a quick review. </div> </div> </div> </div> <div class="col2"> <div class="date"> 24 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-shopping-cart"></i> </div> </div> <div class="cont-col2"> <div class="desc"> New order received with <span class="label label-sm label-success"> Reference Number: DR23923 </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> 30 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-success"> <i class="fa fa-user"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 5 pending membership that requires a quick review. </div> </div> </div> </div> <div class="col2"> <div class="date"> 24 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-bell-o"></i> </div> </div> <div class="cont-col2"> <div class="desc"> Web server hardware needs to be upgraded. <span class="label label-sm label-warning"> Overdue </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> 2 hours </div> </div> </li> <li> <a href="javascript:;"> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-default"> <i class="fa fa-briefcase"></i> </div> </div> <div class="cont-col2"> <div class="desc"> IPO Report for year 2013 has been released. </div> </div> </div> </div> <div class="col2"> <div class="date"> 20 mins </div> </div> </a> </li> </ul> <h3 class="list-heading">System</h3> <ul class="feeds list-items"> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-check"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 4 pending tasks. <span class="label label-sm label-warning "> Take action <i class="fa fa-share"></i> </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> Just now </div> </div> </li> <li> <a href="javascript:;"> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-danger"> <i class="fa fa-bar-chart-o"></i> </div> </div> <div class="cont-col2"> <div class="desc"> Finance Report for year 2013 has been released. </div> </div> </div> </div> <div class="col2"> <div class="date"> 20 mins </div> </div> </a> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-default"> <i class="fa fa-user"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 5 pending membership that requires a quick review. </div> </div> </div> </div> <div class="col2"> <div class="date"> 24 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-shopping-cart"></i> </div> </div> <div class="cont-col2"> <div class="desc"> New order received with <span class="label label-sm label-success"> Reference Number: DR23923 </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> 30 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-success"> <i class="fa fa-user"></i> </div> </div> <div class="cont-col2"> <div class="desc"> You have 5 pending membership that requires a quick review. </div> </div> </div> </div> <div class="col2"> <div class="date"> 24 mins </div> </div> </li> <li> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-warning"> <i class="fa fa-bell-o"></i> </div> </div> <div class="cont-col2"> <div class="desc"> Web server hardware needs to be upgraded. <span class="label label-sm label-default "> Overdue </span> </div> </div> </div> </div> <div class="col2"> <div class="date"> 2 hours </div> </div> </li> <li> <a href="javascript:;"> <div class="col1"> <div class="cont"> <div class="cont-col1"> <div class="label label-sm label-info"> <i class="fa fa-briefcase"></i> </div> </div> <div class="cont-col2"> <div class="desc"> IPO Report for year 2013 has been released. </div> </div> </div> </div> <div class="col2"> <div class="date"> 20 mins </div> </div> </a> </li> </ul> </div> </div> <div class="tab-pane page-quick-sidebar-settings" id="quick_sidebar_tab_3"> <div class="page-quick-sidebar-settings-list"> <h3 class="list-heading">General Settings</h3> <ul class="list-items borderless"> <li> Enable Notifications <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="success" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> <li> Allow Tracking <input type="checkbox" class="make-switch" data-size="small" data-on-color="info" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> <li> Log Errors <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="danger" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> <li> Auto Sumbit Issues <input type="checkbox" class="make-switch" data-size="small" data-on-color="warning" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> <li> Enable SMS Alerts <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="success" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> </ul> <h3 class="list-heading">System Settings</h3> <ul class="list-items borderless"> <li> Security Level <select class="form-control input-inline input-sm input-small"> <option value="1">Normal</option> <option value="2" selected>Medium</option> <option value="e">High</option> </select> </li> <li> Failed Email Attempts <input class="form-control input-inline input-sm input-small" value="5" /> </li> <li> Secondary SMTP Port <input class="form-control input-inline input-sm input-small" value="3560" /> </li> <li> Notify On System Error <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="danger" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> <li> Notify On SMTP Error <input type="checkbox" class="make-switch" checked data-size="small" data-on-color="warning" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li> </ul> <div class="inner-content"> <button class="btn btn-success"> <i class="icon-settings"></i> Save Changes</button> </div> </div> </div> </div> </div> </div> <!-- END QUICK SIDEBAR --> </div> <!-- END CONTAINER --> </div> </div> <div class="page-wrapper-row"> <div class="page-wrapper-bottom"> <!-- BEGIN FOOTER --> <!-- BEGIN PRE-FOOTER --> <div class="page-prefooter"> <div class="container"> <div class="row"> <div class="col-md-3 col-sm-6 col-xs-12 footer-block"> <h2>About</h2> <p> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam dolore. </p> </div> <div class="col-md-3 col-sm-6 col-xs12 footer-block"> <h2>Subscribe Email</h2> <div class="subscribe-form"> <form action="javascript:;"> <div class="input-group"> <input type="text" placeholder="mail@email.com" class="form-control"> <span class="input-group-btn"> <button class="btn" type="submit">Submit</button> </span> </div> </form> </div> </div> <div class="col-md-3 col-sm-6 col-xs-12 footer-block"> <h2>Follow Us On</h2> <ul class="social-icons"> <li> <a href="javascript:;" data-original-title="rss" class="rss"></a> </li> <li> <a href="javascript:;" data-original-title="facebook" class="facebook"></a> </li> <li> <a href="javascript:;" data-original-title="twitter" class="twitter"></a> </li> <li> <a href="javascript:;" data-original-title="googleplus" class="googleplus"></a> </li> <li> <a href="javascript:;" data-original-title="linkedin" class="linkedin"></a> </li> <li> <a href="javascript:;" data-original-title="youtube" class="youtube"></a> </li> <li> <a href="javascript:;" data-original-title="vimeo" class="vimeo"></a> </li> </ul> </div> <div class="col-md-3 col-sm-6 col-xs-12 footer-block"> <h2>Contacts</h2> <address class="margin-bottom-40"> Phone: 800 123 3456 <br> Email: <a href="mailto:info@metronic.com">info@metronic.com</a> </address> </div> </div> </div> </div> <!-- END PRE-FOOTER --> <!-- BEGIN INNER FOOTER --> <div class="page-footer"> <div class="container"> 2016 &copy; Metronic Theme By <a target="_blank" href="http://keenthemes.com">Keenthemes</a> &nbsp;|&nbsp; <a href="http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes" title="Purchase Metronic just for 27$ and get lifetime updates for free" target="_blank">Purchase Metronic!</a> </div> </div> <div class="scroll-to-top"> <i class="icon-arrow-up"></i> </div> <!-- END INNER FOOTER --> <!-- END FOOTER --> </div> </div> </div> <!-- BEGIN QUICK NAV --> <nav class="quick-nav"> <a class="quick-nav-trigger" href="#0"> <span aria-hidden="true"></span> </a> <ul> <li> <a href="https://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes" target="_blank" class="active"> <span>Purchase Metronic</span> <i class="icon-basket"></i> </a> </li> <li> <a href="https://themeforest.net/item/metronic-responsive-admin-dashboard-template/reviews/4021469?ref=keenthemes" target="_blank"> <span>Customer Reviews</span> <i class="icon-users"></i> </a> </li> <li> <a href="http://keenthemes.com/showcast/" target="_blank"> <span>Showcase</span> <i class="icon-user"></i> </a> </li> <li> <a href="http://keenthemes.com/metronic-theme/changelog/" target="_blank"> <span>Changelog</span> <i class="icon-graph"></i> </a> </li> </ul> <span aria-hidden="true" class="quick-nav-bg"></span> </nav> <div class="quick-nav-overlay"></div> <!-- END QUICK NAV --> <!--[if lt IE 9]> <script src="../assets/global/plugins/respond.min.js"></script> <script src="../assets/global/plugins/excanvas.min.js"></script> <script src="../assets/global/plugins/ie8.fix.min.js"></script> <![endif]--> <!-- BEGIN CORE PLUGINS --> <script src="../assets/global/plugins/jquery.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/js.cookie.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script> <!-- END CORE PLUGINS --> <!-- BEGIN THEME GLOBAL SCRIPTS --> <script src="../assets/global/scripts/app.min.js" type="text/javascript"></script> <!-- END THEME GLOBAL SCRIPTS --> <!-- BEGIN THEME LAYOUT SCRIPTS --> <script src="../assets/layouts/layout3/scripts/layout.min.js" type="text/javascript"></script> <script src="../assets/layouts/layout3/scripts/demo.min.js" type="text/javascript"></script> <script src="../assets/layouts/global/scripts/quick-sidebar.min.js" type="text/javascript"></script> <script src="../assets/layouts/global/scripts/quick-nav.min.js" type="text/javascript"></script> <!-- END THEME LAYOUT SCRIPTS --> </body> </html>
FernandoUnix/AcessoRestrito
metronic_v4.7.1/theme/admin_3_rounded/layout_top_bar_fixed.html
HTML
gpl-3.0
194,270
package es.ucm.fdi.emf.model.ed2.diagram.sheet; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import org.eclipse.gmf.runtime.notation.View; import org.eclipse.jface.viewers.BaseLabelProvider; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.graphics.Image; import es.ucm.fdi.emf.model.ed2.diagram.navigator.Ed2NavigatorGroup; import es.ucm.fdi.emf.model.ed2.diagram.part.Ed2VisualIDRegistry; import es.ucm.fdi.emf.model.ed2.diagram.providers.Ed2ElementTypes; /** * @generated */ public class Ed2SheetLabelProvider extends BaseLabelProvider implements ILabelProvider { /** * @generated */ public String getText(Object element) { element = unwrap(element); if (element instanceof Ed2NavigatorGroup) { return ((Ed2NavigatorGroup) element).getGroupName(); } IElementType etype = getElementType(getView(element)); return etype == null ? "" : etype.getDisplayName(); } /** * @generated */ public Image getImage(Object element) { IElementType etype = getElementType(getView(unwrap(element))); return etype == null ? null : Ed2ElementTypes.getImage(etype); } /** * @generated */ private Object unwrap(Object element) { if (element instanceof IStructuredSelection) { return ((IStructuredSelection) element).getFirstElement(); } return element; } /** * @generated */ private View getView(Object element) { if (element instanceof View) { return (View) element; } if (element instanceof IAdaptable) { return (View) ((IAdaptable) element).getAdapter(View.class); } return null; } /** * @generated */ private IElementType getElementType(View view) { // For intermediate views climb up the containment hierarchy to find the one associated with an element type. while (view != null) { int vid = Ed2VisualIDRegistry.getVisualID(view); IElementType etype = Ed2ElementTypes.getElementType(vid); if (etype != null) { return etype; } view = view.eContainer() instanceof View ? (View) view.eContainer() : null; } return null; } }
RubenM13/E-EDD-2.0
es.ucm.fdi.ed2.emf.diagram/src/es/ucm/fdi/emf/model/ed2/diagram/sheet/Ed2SheetLabelProvider.java
Java
gpl-3.0
2,246
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Universal charset detector code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 2001 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # Shy Shalom - original C code # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### import constants, sys from charsetgroupprober import CharSetGroupProber from sbcharsetprober import SingleByteCharSetProber from langcyrillicmodel import Win1251CyrillicModel, Koi8rModel, Latin5CyrillicModel, MacCyrillicModel, Ibm866Model, Ibm855Model from langgreekmodel import Latin7GreekModel, Win1253GreekModel from langbulgarianmodel import Latin5BulgarianModel, Win1251BulgarianModel from langhungarianmodel import Latin2HungarianModel, Win1250HungarianModel from langthaimodel import TIS620ThaiModel from langhebrewmodel import Win1255HebrewModel from hebrewprober import HebrewProber class SBCSGroupProber(CharSetGroupProber): def __init__(self): CharSetGroupProber.__init__(self) self._mProbers = [ \ SingleByteCharSetProber(Win1251CyrillicModel), SingleByteCharSetProber(Koi8rModel), SingleByteCharSetProber(Latin5CyrillicModel), SingleByteCharSetProber(MacCyrillicModel), SingleByteCharSetProber(Ibm866Model), SingleByteCharSetProber(Ibm855Model), SingleByteCharSetProber(Latin7GreekModel), SingleByteCharSetProber(Win1253GreekModel), SingleByteCharSetProber(Latin5BulgarianModel), SingleByteCharSetProber(Win1251BulgarianModel), SingleByteCharSetProber(Latin2HungarianModel), SingleByteCharSetProber(Win1250HungarianModel), SingleByteCharSetProber(TIS620ThaiModel), ] hebrewProber = HebrewProber() logicalHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, constants.False, hebrewProber) visualHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, constants.True, hebrewProber) hebrewProber.set_model_probers(logicalHebrewProber, visualHebrewProber) self._mProbers.extend([hebrewProber, logicalHebrewProber, visualHebrewProber]) self.reset()
disabler/isida3
lib/chardet/sbcsgroupprober.py
Python
gpl-3.0
2,948
# frozen_string_literal: true # How minitest plugins. See https://github.com/simplecov-ruby/simplecov/pull/756 for why we need this. # https://github.com/seattlerb/minitest#writing-extensions module Minitest def self.plugin_simplecov_init(_options) if defined?(SimpleCov) SimpleCov.external_at_exit = true Minitest.after_run do SimpleCov.at_exit_behavior end end end end
BeGe78/esood
vendor/bundle/ruby/3.0.0/gems/simplecov-0.21.2/lib/minitest/simplecov_plugin.rb
Ruby
gpl-3.0
411
//*************************************************************************** // // Copyright (c) 1999 - 2006 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //*************************************************************************** /** @file FileScanner.cpp This module defines ... */ //*************************************************************************** // Defines //*************************************************************************** //*************************************************************************** // Includes //*************************************************************************** #include "FileScanner.h" #include "IFXException.h" #include "IFXMatrix4x4.h" #include "Color.h" #include "Quat.h" #include "Point.h" #include "Int3.h" #include "Int2.h" #include "MetaDataList.h" #include "Tokens.h" #include <ctype.h> #include <wchar.h> using namespace U3D_IDTF; //*************************************************************************** // Constants //*************************************************************************** //*************************************************************************** // Enumerations //*************************************************************************** //*************************************************************************** // Classes, structures and types //*************************************************************************** //*************************************************************************** // Global data //*************************************************************************** //*************************************************************************** // Local data //*************************************************************************** //*************************************************************************** // Local function prototypes //*************************************************************************** //*************************************************************************** // Public methods //*************************************************************************** FileScanner::FileScanner() { m_currentCharacter[0] = 0; m_currentCharacter[1] = 0; m_used = TRUE; } FileScanner::~FileScanner() { } IFXRESULT FileScanner::Initialize( const IFXCHAR* pFileName ) { IFXRESULT result = IFX_OK; result = m_file.Initialize( pFileName ); if( IFXSUCCESS( result ) ) m_currentCharacter[0] = m_file.ReadCharacter(); return result; } IFXRESULT FileScanner::Scan( IFXString* pToken, U32 scanLine ) { // try to use fscanf IFXRESULT result = IFX_OK; if( NULL != pToken ) { if( scanLine ) SkipBlanks(); else SkipSpaces(); if( TRUE == IsEndOfFile() ) result = IFX_E_EOF; else { U8 i = 0; U8 buffer[MAX_STRING_LENGTH] = {0}; while( 0 == IsSpace( GetCurrentCharacter() ) && !IsEndOfFile() ) { buffer[i++] = GetCurrentCharacter(); NextCharacter(); } result = pToken->Assign(buffer); } } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT FileScanner::ScanString( IFXString* pString ) { IFXRESULT result = IFX_OK; if( NULL == pString ) result = IFX_E_INVALID_POINTER; if( IFXSUCCESS( result ) ) { SkipSpaces(); if( '"' == GetCurrentCharacter() ) { // found string, skip first quote NextCharacter(); U32 i = 0; U8 scanBuffer[MAX_STRING_LENGTH+2]; while( '"' != GetCurrentCharacter() && i < MAX_STRING_LENGTH ) { if( '\\' == GetCurrentCharacter()) { NextCharacter(); U8 currentCharacter = GetCurrentCharacter(); switch (currentCharacter) { case '\\': scanBuffer[i++] = '\\'; break; case 'n': scanBuffer[i++] = '\n'; break; case 't': scanBuffer[i++] = '\t'; break; case 'r': scanBuffer[i++] = '\r'; break; case '"': scanBuffer[i++] = '"'; break; default: scanBuffer[i++] = currentCharacter; } } else scanBuffer[i++] = GetCurrentCharacter(); NextCharacter(); } NextCharacter(); // skip last double quote scanBuffer[i] = 0; /// @todo: Converter Unicode support // convert one byte string to unicode pString->Assign( scanBuffer ); } else { result = IFX_E_STRING_NOT_FOUND; } } return result; } IFXRESULT FileScanner::ScanFloat( F32* pNumber ) { IFXRESULT result = IFX_OK; if( NULL == pNumber ) result = IFX_E_INVALID_POINTER; if( IFXSUCCESS( result ) ) { //this F32 format is preferred #ifdef F32_EXPONENTIAL IFXString buffer; U32 fpos; result = m_file.GetPosition( &fpos ); if( IFXSUCCESS( result ) ) result = Scan( &buffer, 1 ); if( IFXSUCCESS( result ) ) { I32 scanResult = swscanf( buffer.Raw(), L"%g", pNumber ); if( 0 == scanResult || EOF == scanResult ) { result = IFX_E_FLOAT_NOT_FOUND; // new token found, not float // do not allow client to continue scan for new tokens m_used = TRUE; m_currentToken = buffer; fpos--; m_file.SetPosition( fpos ); NextCharacter(); } } #else I32 sign = 1; U32 value = 0; SkipBlanks(); if( '-' == GetCurrentCharacter() ) { sign = -1; NextCharacter(); } if( '-' == GetCurrentCharacter() || '+' == GetCurrentCharacter() ) NextCharacter(); while( isdigit( GetCurrentCharacter() ) ) { value = ( value*10 ) + ( GetCurrentCharacter() - '0' ); NextCharacter(); } // there should be fraction part of float if( '.' == GetCurrentCharacter() ) { F32 fraction = 0.0f; F32 divisor = 10.0f; if( '.' == GetCurrentCharacter() ) NextCharacter(); while( isdigit( GetCurrentCharacter() ) ) { fraction += ( GetCurrentCharacter() - '0' ) / divisor; divisor *=10.0f; NextCharacter(); } *pNumber = static_cast<float>(value); *pNumber += fraction; *pNumber *= sign; } else { result = IFX_E_FLOAT_NOT_FOUND; } #endif } return result; } IFXRESULT FileScanner::ScanInteger( I32* pNumber ) { IFXRESULT result = IFX_OK; IFXString buffer; if( NULL == pNumber ) result = IFX_E_INVALID_POINTER; if( IFXSUCCESS( result ) ) { I32 sign = 1; I32 value = 0; SkipSpaces(); if( '-' == GetCurrentCharacter() ) { sign = -1; } if( '-' == GetCurrentCharacter() || '+' == GetCurrentCharacter() ) { NextCharacter(); } while( isdigit( GetCurrentCharacter() ) ) { value = (value*10) + (GetCurrentCharacter() - '0'); NextCharacter(); } *pNumber = value * sign; } return result; } IFXRESULT FileScanner::ScanHex( I32* pNumber ) { IFXRESULT result = IFX_OK; IFXString buffer; if( NULL == pNumber ) result = IFX_E_INVALID_POINTER; if( IFXSUCCESS( result ) ) result = Scan( &buffer ); if( IFXSUCCESS( result ) ) { buffer.ForceUppercase(); int scanResult = swscanf( buffer.Raw(), L"%X", pNumber ); if( 0 == scanResult || EOF == scanResult ) { result = IFX_E_INT_NOT_FOUND; } } return result; } IFXRESULT FileScanner::ScanTM( IFXMatrix4x4* pMatrix ) { IFXRESULT result = IFX_OK; F32 matrix[16]; U32 i; for( i = 0; i < 16 && IFXSUCCESS( result ); ++i ) { result = ScanFloat( &matrix[i] ); if( 0 == (i + 1)%4 ) { // skip end of line SkipSpaces(); } } if( IFXSUCCESS( result ) ) { *pMatrix = matrix; SkipSpaces(); } return result; } IFXRESULT FileScanner::ScanColor( Color* pColor ) { IFXRESULT result = IFX_OK; F32 red = 0.0f, green = 0.0f, blue = 0.0f, alpha = 0.0f; result = ScanFloat( &red ); if( IFXSUCCESS( result ) ) result = ScanFloat( &green ); if( IFXSUCCESS( result ) ) result = ScanFloat( &blue ); if( IFXSUCCESS( result ) ) { result = ScanFloat( &alpha ); if( IFXSUCCESS( result ) ) { // 4 component color IFXVector4 color( red, green, blue, alpha ); pColor->SetColor( color ); } else if( IFX_E_FLOAT_NOT_FOUND == result ) { // 3 component color IFXVector4 color( red, green, blue ); pColor->SetColor( color ); result = IFX_OK; } SkipSpaces(); } return result; } IFXRESULT FileScanner::ScanQuat( Quat* pQuat ) { IFXRESULT result = IFX_OK; F32 w = 0.0f, x = 0.0f, y = 0.0f, z = 0.0f; result = ScanFloat( &w ); if( IFXSUCCESS( result ) ) result = ScanFloat( &x ); if( IFXSUCCESS( result ) ) result = ScanFloat( &y ); if( IFXSUCCESS( result ) ) { result = ScanFloat( &z ); if( IFXSUCCESS( result ) ) { IFXVector4 quat( w, x, y, z ); pQuat->SetQuat( quat ); SkipSpaces(); } } return result; } IFXRESULT FileScanner::ScanPoint( Point* pPoint ) { IFXRESULT result = IFX_OK; F32 x = 0.0f, y = 0.0f, z = 0.0f; result = ScanFloat( &x ); if( IFXSUCCESS( result ) ) result = ScanFloat( &y ); if( IFXSUCCESS( result ) ) result = ScanFloat( &z ); if( IFXSUCCESS( result ) ) { IFXVector3 point( x, y, z ); pPoint->SetPoint( point ); SkipSpaces(); } return result; } IFXRESULT FileScanner::ScanVector4( IFXVector4* pVector4 ) { IFXRESULT result = IFX_OK; F32 x = 0.0f, y = 0.0f, z = 0.0f, w = 0.0f; result = ScanFloat( &x ); if( IFXSUCCESS( result ) ) result = ScanFloat( &y ); if( IFXSUCCESS( result ) ) result = ScanFloat( &z ); if( IFXSUCCESS( result ) ) result = ScanFloat( &w ); if( IFXSUCCESS( result ) ) { pVector4->Set( x, y, z, w ); SkipSpaces(); } return result; } IFXRESULT FileScanner::ScanInt3( Int3* pData ) { IFXRESULT result = IFX_OK; I32 x = 0, y = 0, z = 0; result = ScanInteger( &x ); if( IFXSUCCESS( result ) ) result = ScanInteger( &y ); if( IFXSUCCESS( result ) ) result = ScanInteger( &z ); if( IFXSUCCESS( result ) ) { pData->SetData( x, y, z ); SkipSpaces(); } return result; } IFXRESULT FileScanner::ScanInt2( Int2* pData ) { IFXRESULT result = IFX_OK; I32 x = 0, y = 0; result = ScanInteger( &x ); if( IFXSUCCESS( result ) ) result = ScanInteger( &y ); if( IFXSUCCESS( result ) ) { pData->SetData( x, y ); SkipSpaces(); } return result; } IFXRESULT FileScanner::ScanToken( const IFXCHAR* pToken ) { // try to use fscanf IFXRESULT result = IFX_OK; if( NULL != pToken ) { if( TRUE == m_used ) { // previous token was successfuly used and we can scan next SkipSpaces(); if( TRUE == IsEndOfFile() ) result = IFX_E_EOF; else { U8 buffer[MAX_STRING_LENGTH]; U32 i = 0; if( IDTF_END_BLOCK != GetCurrentCharacter() ) { while( ( 0 == IsSpace( GetCurrentCharacter() ) ) && !IsEndOfFile() && i < MAX_STRING_LENGTH ) { buffer[i++] = GetCurrentCharacter(); NextCharacter(); } buffer[i] = 0; /// @todo: Converter unicode support m_currentToken.Assign( buffer ); } else { // block terminator found // do not allow client to continue scan for new tokens m_used = FALSE; } } } /// @todo: Converter Unicode support // convert one byte token to unicode IFXString token( pToken ); if( m_currentToken != token ) { m_used = FALSE; result = IFX_E_TOKEN_NOT_FOUND; } else m_used = TRUE; } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT FileScanner::ScanStringToken( const IFXCHAR* pToken, IFXString* pValue ) { IFXRESULT result = IFX_OK; if( NULL != pToken && NULL != pValue ) { result = ScanToken( pToken ); if( IFXSUCCESS( result ) ) result = ScanString( pValue ); } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT FileScanner::ScanIntegerToken( const IFXCHAR* pToken, I32* pValue ) { IFXRESULT result = IFX_OK; if( NULL != pToken && NULL != pValue ) { result = ScanToken( pToken ); if( IFXSUCCESS( result ) ) result = ScanInteger( pValue ); } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT FileScanner::ScanHexToken( const IFXCHAR* pToken, I32* pValue ) { IFXRESULT result = IFX_OK; if( NULL != pToken && NULL != pValue ) { result = ScanToken( pToken ); if( IFXSUCCESS( result ) ) result = ScanHex( pValue ); } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT FileScanner::ScanFloatToken( const IFXCHAR* pToken, F32* pValue ) { IFXRESULT result = IFX_OK; if( NULL != pToken && NULL != pValue ) { result = ScanToken( pToken ); if( IFXSUCCESS( result ) ) result = ScanFloat( pValue ); } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT FileScanner::ScanTMToken( const IFXCHAR* pToken, IFXMatrix4x4* pValue ) { IFXRESULT result = IFX_OK; if( NULL != pToken && NULL != pValue ) { result = ScanToken( pToken ); if( IFXSUCCESS( result ) ) result = FindBlockStarter(); if( IFXSUCCESS( result ) ) result = ScanTM( pValue ); if( IFXSUCCESS( result ) ) result = FindBlockTerminator(); } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT FileScanner::ScanColorToken( const IFXCHAR* pToken, Color* pValue ) { IFXRESULT result = IFX_OK; if( NULL != pToken && NULL != pValue ) { result = ScanToken( pToken ); if( IFXSUCCESS( result ) ) result = ScanColor( pValue ); } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT FileScanner::ScanQuatToken( const IFXCHAR* pToken, Quat* pValue ) { IFXRESULT result = IFX_OK; if( NULL != pToken && NULL != pValue ) { result = ScanToken( pToken ); if( IFXSUCCESS( result ) ) result = ScanQuat( pValue ); } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT FileScanner::ScanPointToken( const IFXCHAR* pToken, Point* pValue ) { IFXRESULT result = IFX_OK; if( NULL != pToken && NULL != pValue ) { result = ScanToken( pToken ); if( IFXSUCCESS( result ) ) result = ScanPoint( pValue ); } else result = IFX_E_INVALID_POINTER; return result; } IFXRESULT FileScanner::FindBlockStarter() { IFXRESULT result = IFX_OK; SkipSpaces(); if( TRUE == IsEndOfFile() ) result = IFX_E_EOF; else { if( GetCurrentCharacter() == IDTF_BEGIN_BLOCK ) { NextCharacter(); SkipSpaces(); } else result = IFX_E_STARTER_NOT_FOUND; } return result; } IFXRESULT FileScanner::FindBlockTerminator() { IFXRESULT result = IFX_OK; SkipSpaces(); if( TRUE == IsEndOfFile() ) result = IFX_E_EOF; else { if( GetCurrentCharacter() == IDTF_END_BLOCK ) { // block terminator found // allow client to scan for next token m_used = TRUE; NextCharacter(); } else result = IFX_E_TERMINATOR_NOT_FOUND; } return result; } //*************************************************************************** // Protected methods //*************************************************************************** BOOL FileScanner::IsSpace( I8 character ) { return isspace( character ); } BOOL FileScanner::IsEndOfFile() { return m_file.IsEndOfFile(); } void FileScanner::SkipSpaces() { while( 0 != isspace( GetCurrentCharacter() ) && !m_file.IsEndOfFile() ) NextCharacter(); } void FileScanner::SkipBlanks() { while( ( ' ' == GetCurrentCharacter() || '\t' == GetCurrentCharacter() ) && !m_file.IsEndOfFile() ) NextCharacter(); } U8 FileScanner::NextCharacter() { return m_currentCharacter[0] = m_file.ReadCharacter(); } //*************************************************************************** // Private methods //*************************************************************************** //*************************************************************************** // Global functions //*************************************************************************** //*************************************************************************** // Local functions //***************************************************************************
cnr-isti-vclab/meshlab
src/external/u3d/src/IDTF/FileScanner.cpp
C++
gpl-3.0
16,279
// Copyright (c) 2017 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. // // --------------------------------------------------------------------------- // // This file was generated by the CEF translator tool. If making changes by // hand only do so within the body of existing method and function // implementations. See the translator.README.txt file in the tools directory // for more information. // // $hash=517c8bf7f36b294cbbcb0a52dcc9b1d1922986ce$ // #ifndef CEF_LIBCEF_DLL_CTOCPP_DOMNODE_CTOCPP_H_ #define CEF_LIBCEF_DLL_CTOCPP_DOMNODE_CTOCPP_H_ #pragma once #if !defined(WRAPPING_CEF_SHARED) #error This file can be included wrapper-side only #endif #include "include/capi/cef_dom_capi.h" #include "include/cef_dom.h" #include "libcef_dll/ctocpp/ctocpp_ref_counted.h" // Wrap a C structure with a C++ class. // This class may be instantiated and accessed wrapper-side only. class CefDOMNodeCToCpp : public CefCToCppRefCounted<CefDOMNodeCToCpp, CefDOMNode, cef_domnode_t> { public: CefDOMNodeCToCpp(); // CefDOMNode methods. Type GetType() OVERRIDE; bool IsText() OVERRIDE; bool IsElement() OVERRIDE; bool IsEditable() OVERRIDE; bool IsFormControlElement() OVERRIDE; CefString GetFormControlElementType() OVERRIDE; bool IsSame(CefRefPtr<CefDOMNode> that) OVERRIDE; CefString GetName() OVERRIDE; CefString GetValue() OVERRIDE; bool SetValue(const CefString& value) OVERRIDE; CefString GetAsMarkup() OVERRIDE; CefRefPtr<CefDOMDocument> GetDocument() OVERRIDE; CefRefPtr<CefDOMNode> GetParent() OVERRIDE; CefRefPtr<CefDOMNode> GetPreviousSibling() OVERRIDE; CefRefPtr<CefDOMNode> GetNextSibling() OVERRIDE; bool HasChildren() OVERRIDE; CefRefPtr<CefDOMNode> GetFirstChild() OVERRIDE; CefRefPtr<CefDOMNode> GetLastChild() OVERRIDE; CefString GetElementTagName() OVERRIDE; bool HasElementAttributes() OVERRIDE; bool HasElementAttribute(const CefString& attrName) OVERRIDE; CefString GetElementAttribute(const CefString& attrName) OVERRIDE; void GetElementAttributes(AttributeMap& attrMap) OVERRIDE; bool SetElementAttribute(const CefString& attrName, const CefString& value) OVERRIDE; CefString GetElementInnerText() OVERRIDE; CefRect GetElementBounds() OVERRIDE; }; #endif // CEF_LIBCEF_DLL_CTOCPP_DOMNODE_CTOCPP_H_
Julusian/CasparCG-Server
dependencies64/cef/win32/libcef_dll/ctocpp/domnode_ctocpp.h
C
gpl-3.0
2,433
local pi = math.pi local player_in_bed = 0 local is_sp = minetest.is_singleplayer() local enable_respawn = minetest.setting_getbool("enable_bed_respawn") if enable_respawn == nil then enable_respawn = true end -- Helper functions local function get_look_yaw(pos) local n = minetest.get_node(pos) if n.param2 == 1 then return pi / 2, n.param2 elseif n.param2 == 3 then return -pi / 2, n.param2 elseif n.param2 == 0 then return pi, n.param2 else return 0, n.param2 end end local function is_night_skip_enabled() local enable_night_skip = minetest.setting_getbool("enable_bed_night_skip") if enable_night_skip == nil then enable_night_skip = true end return enable_night_skip end local function check_in_beds(players) local in_bed = beds.player if not players then players = minetest.get_connected_players() end for n, player in ipairs(players) do local name = player:get_player_name() if not in_bed[name] then return false end end return #players > 0 end local function lay_down(player, pos, bed_pos, state, skip) local name = player:get_player_name() local hud_flags = player:hud_get_flags() if not player or not name then return end -- stand up if state ~= nil and not state then local p = beds.pos[name] or nil if beds.player[name] ~= nil then beds.player[name] = nil player_in_bed = player_in_bed - 1 end -- skip here to prevent sending player specific changes (used for leaving players) if skip then return end if p then player:setpos(p) end -- physics, eye_offset, etc player:set_eye_offset({x = 0, y = 0, z = 0}, {x = 0, y = 0, z = 0}) player:set_look_yaw(math.random(1, 180) / 100) default.player_attached[name] = false player:set_physics_override(1, 1, 1) hud_flags.wielditem = true default.player_set_animation(player, "stand" , 30) -- lay down else beds.player[name] = 1 beds.pos[name] = pos player_in_bed = player_in_bed + 1 -- physics, eye_offset, etc player:set_eye_offset({x = 0, y = -13, z = 0}, {x = 0, y = 0, z = 0}) local yaw, param2 = get_look_yaw(bed_pos) player:set_look_yaw(yaw) local dir = minetest.facedir_to_dir(param2) local p = {x = bed_pos.x + dir.x / 2, y = bed_pos.y, z = bed_pos.z + dir.z / 2} player:set_physics_override(0, 0, 0) player:setpos(p) default.player_attached[name] = true hud_flags.wielditem = false default.player_set_animation(player, "lay" , 0) end player:hud_set_flags(hud_flags) end local function update_formspecs(finished) local ges = #minetest.get_connected_players() local form_n = "" local is_majority = (ges / 2) < player_in_bed if finished then form_n = beds.formspec .. "label[2.7,11; Good morning.]" else form_n = beds.formspec .. "label[2.2,11;" .. tostring(player_in_bed) .. " of " .. tostring(ges) .. " players are in bed]" if is_majority and is_night_skip_enabled() then form_n = form_n .. "button_exit[2,8;4,0.75;force;Force night skip]" end end for name,_ in pairs(beds.player) do minetest.show_formspec(name, "beds_form", form_n) end end -- Public functions function beds.kick_players() for name, _ in pairs(beds.player) do local player = minetest.get_player_by_name(name) lay_down(player, nil, nil, false) end end function beds.skip_night() minetest.set_timeofday(0.23) beds.set_spawns() end function beds.on_rightclick(pos, player) local name = player:get_player_name() local ppos = player:getpos() local tod = minetest.get_timeofday() if tod > 0.2 and tod < 0.805 then if beds.player[name] then lay_down(player, nil, nil, false) end minetest.chat_send_player(name, "You can only sleep at night.") return end -- move to bed if not beds.player[name] then lay_down(player, ppos, pos) else lay_down(player, nil, nil, false) end if not is_sp then update_formspecs(false) end -- skip the night and let all players stand up if check_in_beds() then minetest.after(2, function() if not is_sp then update_formspecs(is_night_skip_enabled()) end if is_night_skip_enabled() then beds.skip_night() beds.kick_players() end end) end end -- Callbacks minetest.register_on_joinplayer(function(player) beds.read_spawns() end) -- respawn player at bed if enabled and valid position is found minetest.register_on_respawnplayer(function(player) if not enable_respawn then return false end local name = player:get_player_name() local pos = beds.spawn[name] or nil if pos then player:setpos(pos) return true end end) minetest.register_on_leaveplayer(function(player) local name = player:get_player_name() lay_down(player, nil, nil, false, true) beds.player[name] = nil if check_in_beds() then minetest.after(2, function() update_formspecs(is_night_skip_enabled()) if is_night_skip_enabled() then beds.skip_night() beds.kick_players() end end) end end) minetest.register_on_player_receive_fields(function(player, formname, fields) if formname ~= "beds_form" then return end if fields.quit or fields.leave then lay_down(player, nil, nil, false) update_formspecs(false) end if fields.force then update_formspecs(is_night_skip_enabled()) if is_night_skip_enabled() then beds.skip_night() beds.kick_players() end end end)
linushsao/sky_islands_game-linus
mods/beds/functions.lua
Lua
gpl-3.0
5,266
.color-picker { -moz-box-shadow: 1px 1px 15px rgba(0, 0, 0, 0.3); -webkit-box-shadow: 1px 1px 15px rgba(0, 0, 0, 0.3); box-shadow: 1px 1px 15px rgba(0, 0, 0, 0.3); -moz-border-radius: 0 0 5px 5px; -webkit-border-radius: 0 0 5px 5px; border-radius: 0 0 5px 5px; } .color-picker-title-bar, .color-picker-closer { position: absolute; top: -22px; color: white; padding: 5px 15px 3px; -moz-border-radius: 5px 5px 0 0; -webkit-border-radius: 5px 5px 0 0; border-radius: 5px 5px 0 0; } .color-picker-title-bar { left: 0; width: 245px; height: 15px; } .color-picker-value { position: absolute; top: -22px; } .color-picker-color { position: absolute; top: -17px; left: 15px; width: 12px; height: 12px; border: 1px solid #ccc; } .color-picker-hex { position: absolute; top: -16px; left: 33px; color: white; font-size: 10px; } .color-picker-closer { right: 0px; cursor: pointer; } .color-picker img { display: block; margin: 0; padding: 0; border: 0; } .color-picker div { float: left; } .color-picker-sv { position: relative; background-repeat: none; margin-right: 20px; width: 200px; height: 200px; } .color-picker-h { position: relative; background-repeat: none; width: 25px; height: 200px; } .color-picker-h-slider { position: absolute; left: -14px; top: -5px; width: 44px; height: 12px; } .color-picker-sv-slider { position: absolute; left: -8px; top: -8px; width: 17px; height: 17px; }
projectestac/intraweb
intranet/javascript/picky_color/picky_color.css
CSS
gpl-3.0
1,612
/* str*()-like functions for raw memory "lines" (non-NUL terminated strings). * * Especially when we're parsing input in an ESL_BUFFER, we need to be * able to parse non-writable raw memory buffers. Because an * ESL_BUFFER may have memory mapped a file, we cannot assume that the * input is NUL-terminated, and we can't even assume it's writable (so * we can't NUL-terminate it ourselves). These functions provide * a set of utilities for parsing raw memory (in terms of a char * pointer * and a length in bytes; <char *p>, <esl_pos_t n> by convention). * * Contents: * 1. The esl_mem*() API. * 2. Unit tests. * 3. Test driver. * 4. Copyright and license. */ #include "esl_config.h" #include <string.h> #include <ctype.h> #include "easel.h" /***************************************************************** *# 1. The esl_mem*() API. *****************************************************************/ /* Function: esl_mem_strtoi32() * Synopsis: Convert a chunk of text memory to an int32_t. * * Purpose: Convert the text starting at <p> to an <int32_t>, converting * no more than <n> characters (the valid length of non-<NUL> * terminated memory buffer <p>). Interpret the text as * base <base> (2 or 10, for example). <base> must be 2..36, * or 0. 0 is treated specially as base 8, 10, or 16, autodetected * according to the leading characters of the number format. * * Any leading whitespace is skipped. The next letter may * be a '-' for a negative number. If <base> is 0 or 16, * the next two characters may be "0x", in which case hex base * 16 is assumed. Else if <base> is 0 and the next * character is '0', octal base 8 is assumed. All subsequent * characters are converted to a number, until an invalid * character is reached. Upper or lower case letters are * accepted, starting at A or a, for bases over 10. For * example, In base 16, characters A-F or a-f are accepted. * The base of the representation is limited to 36 because * 'Z' or 'z' represents 35. * * The converted value is optionally returned in <*opt_val>. * The number of characters parsed (up to the first invalid * character, or <n>, whichever comes first) is optionally * returned in <*opt_nc>. The caller can reposition a parser * to <p + *opt_nc> to exactly skip past the parsed number. * * If no valid digit is found (including pathological cases * of leader-only, such as "0x" or "-"), then return <eslEINVAL>, * and <*opt_nc> and <*opt_val> are both 0. * * This syntax is essentially identical to <strtol()>, * except that we can operate on a non-NUL-terminated * memory buffer of maximum length <n>, rather than on a * NUL-terminated string. * * Args: p - pointer to text buffer to convert to int32_t * n - maximum number of chars to parse in <p>: p[0..n-1] are valid. * base - integer base. Often 10, 2, 8, or 16. Must be * <2..36>, or 0. 0 means base 8, 10, or 16 depending on * autodetected format. * *opt_nc - optRETURN: number of valid chars parsed from p. * First invalid char is p[*opt_nc]. * *opt_val - optRETURN: parsed value. * * Returns: <eslOK> on success. * * <eslEFORMAT> if no valid integer digits are found. Now * <*opt_val> and <*opt_nc> are 0. * * <eslERANGE> on an overflow error. In this case * <*opt_val> is <INT32_MAX> or <INT32_MIN> for an * overflow or underflow, respectively. <*opt_nc> is * set to the number of characters parsed INCLUDING * the digit that caused the overflow. * * Throws: <eslEINVAL> if <base> isn't in range <0..36>. Now * <*opt_nc> and <*opt_val> are 0. * * Note: An example of why you need this instead of * strtol(): suppose you've mmap()'ed a file to memory, * and it ends in ... "12345". You can't strtol the * end of the mmap'ed memory buffer because it is not * a NUL-terminated string. (Same goes anywhere in the file, * though elsewhere in the file you could overwrite * a NUL where you need it. At EOF of an mmap'ed() buffer, * you can't even do that.) * * sscanf() doesn't work either - I don't see a way to * limit it to a buffer of at most <n> chars. * * I could copy <p> to a temporary allocated string that I * NUL-terminate, then use strtol() or suchlike, but that's * just as awful as what I've done here (rewriting * strtol()). Plus, here I get complete control of the integer * type (<int32_t>) whereas strtol() gives me the less satisfying * <long>. */ int esl_mem_strtoi32(char *p, esl_pos_t n, int base, int *opt_nc, int32_t *opt_val) { esl_pos_t i = 0; int32_t sign = 1; int32_t currval = 0; int32_t digit = 0; int ndigits = 0; if (base < 0 || base == 1 || base > 36) ESL_EXCEPTION(eslEINVAL, "base must be 2..36 or 0"); while (i < n && isspace(p[i])) i++; /* skip leading whitespace */ if (i < n && p[i] == '-') { sign = -1; i++; } if ((base == 0 || base == 16) && i < n-1 && p[i] == '0' && p[i+1] == 'x') { i += 2; base = 16; } else if (base == 0 && i < n && p[i] == '0') { i += 1; base = 8; } else if (base == 0) { base = 10; } for (ndigits = 0; i < n; i++, ndigits++) { if (isdigit(p[i])) digit = p[i] - '0'; else if (isupper(p[i])) digit = 10 + (p[i] - 'A'); else if (islower(p[i])) digit = 10 + (p[i] - 'a'); else break; if (digit >= base) break; if (sign == 1) { if (currval > (INT32_MAX - digit) / base) { if (opt_val) *opt_val = INT32_MAX; if (opt_nc) *opt_nc = i+1; return eslERANGE; } currval = currval * base + digit; } else { if (currval < (INT32_MIN + digit) / base) { if (opt_val) *opt_val = INT32_MIN; if (opt_nc) *opt_nc = i+1; return eslERANGE; } currval = currval * base - digit; } } if (opt_nc) { *opt_nc = (ndigits ? i : 0); } if (opt_val) { *opt_val = currval; } return (ndigits ? eslOK : eslEFORMAT); } /* Function: esl_memnewline() * Synopsis: Find next newline in memory. * * Purpose: Given a memory buffer <*m> of <n> bytes, delimit a * next line by finding the next newline character(s). * Store the number of bytes in the line (exclusive of * the newline character(s)) in <*ret_nline>. Store * the number of bytes in the newline in <*ret_nterm>. * * If no newline is found, <nline=n> and <nterm=0>, and the * return status is <eslEOD>. * * Currently we assume newlines are either UNIX-style \verb+\n+ * or Windows-style \verb+\r\n+, in this implementation. * * Caller should not rely on this, though. Caller may only * assume that a newline is an arbitrary one- or two-byte * code. * * For example, if <*m> = \verb+"line one\r\nline two"+, <nline> * is 8 and <nterm> is 2. If <*m> = \verb+"try two\ntry three"+, * <nline> is 7 and <nterm> is 1. If <*m> = "attempt * four", <nline> is 12 and <nterm> is 0. * * In cases where the caller may have an incompletely read * buffer, it should be careful of cases where one possible * newline may be a prefix of another; for example, suppose * a file has \verb+"line one\r\nline two"+, but we only input the * buffer \verb+"line one\r"+ at first. The \verb+"\r"+ looks like an old * MacOS newline. Now we read more input, and we think the * buffer is \verb+"\nline two"+. Now we think the \verb+"\n"+ is a UNIX * newline. The result is that we read two newlines where * there's only one. Instead, caller should check for the * case of nterm==1 at the end of its buffer, and try to * extend the buffer. See <esl_buffer_GetLine()> for an * example. * * Args: m - ptr to memory buffer * n - length of p in bytes * *ret_nline - length of line found starting at p[0], exclusive of newline; up to n * *ret_nterm - # of bytes in newline code: 1 or 2, or 0 if no newline found * * Returns: <eslOK> on success. Now <*ret_nline> is the number of * bytes in the next line (exclusive of newline) and * <*ret_nterm> is the number of bytes in the newline code * (1 or 2). Thus the next line is <m[0..nline-1]>, and * the line after this starts at <m[nline+nterm]>. * * <eslEOD> if no newline is found. Now <*ret_nline> is <n>, * and <*ret_nterm> is 0. * * Xref: http://en.wikipedia.org/wiki/Newline */ int esl_memnewline(const char *m, esl_pos_t n, esl_pos_t *ret_nline, int *ret_nterm) { char *ptr = memchr(m, '\n', n); if (ptr == NULL) { *ret_nline = n; *ret_nterm = 0; } else if (ptr > m && *(ptr-1) == '\r') { *ret_nline = ptr-m-1; *ret_nterm = 2; } else { *ret_nline = ptr-m; *ret_nterm = 1; } return eslOK; } /* Function: esl_memtok() * Synopsis: Get next delimited token from a line. * * Purpose: Given references to a line and its length, <*p> and <*n>, * find the next token delimited by any of the characters * in the string <delim>. Set <*ret_tok> to point at the * start of the token, and <*ret_toklen> to its length. * Increment <*p> to point to the next non-delim character * that follows, and decrement <*n> by the same, * so that <*p> and <*n> are ready for another * call to <esl_memtok()>. * * Three differences between <esl_strtok()> and <esl_memtok()>: * first, <esl_strtok()> expects a NUL-terminated string, * whereas <esl_memtok()>'s line does not need to be * NUL-terminated; second, <esl_memtok()> does not modify * the string, whereas <esl_strtok()> writes NUL bytes * to delimit tokens; third, <esl_memtok()> skips trailing * <delim> characters as well as leading ones. * * Args: *p - pointer to line; * will be incremented to next byte after token. * *n - pointer to line length, in bytes; * will be decremented * delim - delimiter chars (example: " \t\r\n") * *ret_tok - RETURN: ptr to token found in <*p> * *ret_toklen - RETURN: length of token * * Returns: <eslOK> if a delimited token is found. * <eslEOL> if not; now <*ret_tok> is <NULL> and <*ret_toklen> is <0>. * */ int esl_memtok(char **p, esl_pos_t *n, const char *delim, char **ret_tok, esl_pos_t *ret_toklen) { char *s = *p; esl_pos_t so, xo, eo; for (so = 0; so < *n; so++) if (strchr(delim, s[so]) == NULL) break; for (xo = so; xo < *n; xo++) if (strchr(delim, s[xo]) != NULL) break; for (eo = xo; eo < *n; eo++) if (strchr(delim, s[eo]) == NULL) break; if (so == *n) { *ret_tok = NULL; *ret_toklen = 0; return eslEOL; } else { *p += eo; *n -= eo; *ret_tok = s + so; *ret_toklen = xo - so; return eslOK; } } /* Function: esl_memspn() * Synopsis: Finds length of prefix consisting only of given chars * * Purpose: For line <p> of length <n>, return the length of * a prefix that consists only of characters in the * string <allow>. * * A commonly used idiom for "buffer is all whitespace" * is <esl_memspn(p, n, " \t\r\n") == n>. */ esl_pos_t esl_memspn(char *p, esl_pos_t n, const char *allow) { esl_pos_t so; for (so = 0; so < n; so++) if (strchr(allow, p[so]) == NULL) break; return so; } /* Function: esl_memcspn() * Synopsis: Finds length of prefix consisting of anything other than given chars * * Purpose: For line <p> of length <n>, return the length of * a prefix that consists only of characters NOT in the * string <disallow>. */ esl_pos_t esl_memcspn(char *p, esl_pos_t n, const char *disallow) { esl_pos_t so; for (so = 0; so < n; so++) if (strchr(disallow, p[so]) != NULL) break; return so; } /* Function: esl_memstrcmp() * Synopsis: Compare a memory line and string for equality. * * Purpose: Compare line <p> of length <n> to a NUL-terminated * string <s>, and return TRUE if they are exactly * equal: <strlen(s) == n> and <p[0..n-1] == s[0..n-1]>. * Else, return FALSE. */ int esl_memstrcmp(const char *p, esl_pos_t n, const char *s) { esl_pos_t pos; if (p == NULL && n == 0 && (s == NULL || s[0] == '\0')) return TRUE; if (!p || !s) return FALSE; for (pos = 0; pos < n && s[pos] != '\0'; pos++) if (p[pos] != s[pos]) return FALSE; if (pos != n) return FALSE; if (s[pos] != '\0') return FALSE; return TRUE; } /* Function: esl_memstrpfx() * Synopsis: Return TRUE if memory line starts with string. * * Purpose: Compare line <p> of length <n> to a NUL-terminated * string <s>. Return TRUE if the prefix of <p> exactly * matches <s> up to its NUL sentinel byte. Else, * return FALSE. */ int esl_memstrpfx(const char *p, esl_pos_t n, const char *s) { esl_pos_t pos; if (!p || !s) return FALSE; for (pos = 0; pos < n && s[pos] != '\0'; pos++) if (p[pos] != s[pos]) return FALSE; if (s[pos] != '\0') return FALSE; return TRUE; } /* Function: esl_memstrcontains() * Synopsis: Return TRUE if memory line matches a string. * * Purpose: Compare line <p> of length <n> to NUL-terminated * string <s>. Return <TRUE> if <p> contains an exact * match to <s> at any position. */ int esl_memstrcontains(const char *p, esl_pos_t n, const char *s) { esl_pos_t s0, pos; if (! p || ! s) return FALSE; for (s0 = 0; s0 < n; s0++) { for (pos = 0; s0+pos < n && s[pos] != '\0'; pos++) if (p[s0+pos] != s[pos]) break; if (s[pos] == '\0') return TRUE; } return FALSE; } /* Function: esl_memstrdup() * Synopsis: Duplicate a memory line as a NUL-terminated string. * * Purpose: Given memory line <p> of length <n>, duplicate it * as a NUL-terminated string; return the new string * in <*ret_s>. * * Returns: <eslOK> on success. * * Throws: <eslEMEM> on allocation failure; now <*ret_s> is <NULL>. */ int esl_memstrdup(const char *p, esl_pos_t n, char **ret_s) { char *s = NULL; int status; if (! p) { *ret_s = NULL; return eslOK; } ESL_ALLOC(s, sizeof(char) * (n+1)); memcpy(s, p, n); s[n] = '\0'; *ret_s = s; return eslOK; ERROR: *ret_s = NULL; return status; } /* Function: esl_memstrcpy() * Synopsis: Copy a memory line as a string. * * Purpose: Given memory line <p> of length <n>, copy * it to <dest> and NUL-terminate it. Caller must * be sure that <s> is already allocated for * at least <n+1> bytes. * * Returns: <eslOK> on success. */ int esl_memstrcpy(const char *p, esl_pos_t n, char *dest) { memcpy(dest, p, n); dest[n] = '\0'; return eslOK; } /* Function: esl_memtod() * Synopsis: esl_mem equivalent to strtod(). * * Purpose: Given a buffer <p> of length <n>, convert it to a * double-precision floating point value, just as * <strtod()> would do for a NUL-terminated string. * * Returns: <eslOK> on success, and <*ret_val> contains the * converted value. * * Throws: <eslEMEM> on allocation error, and <*ret_val> is 0. */ int esl_memtod(const char *p, esl_pos_t n, double *ret_val) { char fixedbuf[128]; char *bigbuf = NULL; int status; if (n < 128) { memcpy(fixedbuf, p, sizeof(char) * n); fixedbuf[n] = '\0'; *ret_val = strtod(fixedbuf, NULL); return eslOK; } else { ESL_ALLOC(bigbuf, sizeof(char) * (n+1)); memcpy(bigbuf, p, sizeof(char) * n); bigbuf[n] = '\0'; *ret_val = strtod(fixedbuf, NULL); free(bigbuf); return eslOK; } ERROR: *ret_val = 0.; return status; } /* Function: esl_memtof() * Synopsis: esl_mem equivalent to strtod(), for a float * * Purpose: Given a buffer <p> of length <n>, convert it to a * single-precision floating point value, just as * <strtod()> would do for a NUL-terminated string. * * Returns: <eslOK> on success, and <*ret_val> contains the * converted value. * * Throws: <eslEMEM> on allocation error, and <*ret_val> is 0. */ int esl_memtof(const char *p, esl_pos_t n, float *ret_val) { char fixedbuf[128]; char *bigbuf = NULL; int status; if (n < 128) { memcpy(fixedbuf, p, sizeof(char) * n); fixedbuf[n] = '\0'; *ret_val = (float) strtod(fixedbuf, NULL); return eslOK; } else { ESL_ALLOC(bigbuf, sizeof(char) * (n+1)); memcpy(bigbuf, p, sizeof(char) * n); bigbuf[n] = '\0'; *ret_val = (float) strtod(fixedbuf, NULL); free(bigbuf); return eslOK; } ERROR: *ret_val = 0.; return status; } /* Function: esl_mem_IsReal() * Synopsis: Return TRUE if <p> is a real number; else FALSE. * * Purpose: If the memory <p> of <n> bytes is convertible * to a floating point real number by the rules of * atof(), return TRUE; else return FALSE. * * Xref: easel.c::esl_str_IsReal() for string version. */ int esl_mem_IsReal(const char *p, esl_pos_t n) { int gotdecimal = 0; int gotexp = 0; int gotreal = 0; if (!p || !n) return FALSE; while (n && isspace((int) *p)) { p++; n--; } /* skip leading whitespace */ if (n && (*p == '-' || *p == '+')) { p++; n--; } /* skip leading sign */ /* Examine remainder for garbage. Allowed one '.' and * one 'e' or 'E'; if both '.' and e/E occur, '.' * must be first. */ while (n) { if (isdigit((int) (*p))) gotreal++; else if (*p == '.') { if (gotdecimal) return FALSE; /* can't have two */ if (gotexp) return FALSE; /* e/E preceded . */ else gotdecimal++; } else if (*p == 'e' || *p == 'E') { if (gotexp) return FALSE; /* can't have two */ else gotexp++; } else if (isspace((int) (*p))) break; p++; n--; } while (n && isspace((int) *p)) { p++; n--; } /* skip trailing whitespace */ return ( (n == 0 && gotreal) ? TRUE : FALSE); } /*----------------- end, esl_mem*() API ------------------------*/ /***************************************************************** * 2. Benchmark driver. *****************************************************************/ #ifdef eslMEM_BENCHMARK #include "esl_config.h" #include <stdio.h> #include "easel.h" #include "esl_buffer.h" #include "esl_getopts.h" #include "esl_stopwatch.h" static ESL_OPTIONS options[] = { /* name type default env range togs reqs incomp help docgrp */ {"-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0}, { 0,0,0,0,0,0,0,0,0,0}, }; static char usage[] = "[-options] <infile>"; static char banner[] = "benchmark driver for mem module"; int main(int argc, char **argv) { ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 1, argc, argv, banner, usage); ESL_STOPWATCH *w = esl_stopwatch_Create(); char *infile = esl_opt_GetArg(go, 1); ESL_BUFFER *bf = NULL; int64_t nlines = 0; int64_t ntokens = 0; int64_t nchar = 0; char *p, *tok; esl_pos_t n, toklen; int status; esl_stopwatch_Start(w); if ( esl_buffer_Open(infile, NULL, &bf) != eslOK) esl_fatal("open failed"); while ( (status = esl_buffer_GetLine(bf, &p, &n)) == eslOK) { nlines++; while ( (status = esl_memtok(&p, &n, " \t", &tok, &toklen)) == eslOK) { ntokens++; nchar += toklen; } if (status != eslEOL) esl_fatal("memtok failure"); } if (status != eslEOF) esl_fatal("GetLine failure"); esl_stopwatch_Stop(w); esl_stopwatch_Display(stdout, w, NULL); printf("lines = %" PRId64 "\n", nlines); printf("tokens = %" PRId64 "\n", ntokens); printf("chars = %" PRId64 "\n", nchar); esl_buffer_Close(bf); esl_stopwatch_Destroy(w); esl_getopts_Destroy(go); return 0; } #endif /*eslMEM_BENCHMARK*/ /*---------------- end, benchmark driver ------------------------*/ /***************************************************************** * 2. Unit tests *****************************************************************/ #ifdef eslMEM_TESTDRIVE static void utest_mem_strtoi32(void) { char msg[] = "esl_mem_strtoi32() unit test failed"; int nc; int32_t val; int status; if ( (status = esl_mem_strtoi32("-1234", 5, 10, &nc, &val)) != eslOK || nc != 5 || val != -1234) esl_fatal(msg); if ( (status = esl_mem_strtoi32("\t -1234", 8, 10, &nc, &val)) != eslOK || nc != 8 || val != -1234) esl_fatal(msg); if ( (status = esl_mem_strtoi32("1234", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 1234) esl_fatal(msg); if ( (status = esl_mem_strtoi32("12345", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 1234) esl_fatal(msg); if ( (status = esl_mem_strtoi32(" 0xff", 5, 0, &nc, &val)) != eslOK || nc != 5 || val != 255) esl_fatal(msg); if ( (status = esl_mem_strtoi32(" 0777", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 63) esl_fatal(msg); if ( (status = esl_mem_strtoi32("FFGG", 4, 16, &nc, &val)) != eslOK || nc != 2 || val != 255) esl_fatal(msg); if ( (status = esl_mem_strtoi32("0xffff", 6, 0, &nc, &val)) != eslOK || nc != 6 || val != 65535) esl_fatal(msg); if ( (status = esl_mem_strtoi32("0xffffff", 8, 0, &nc, &val)) != eslOK || nc != 8 || val != 16777215) esl_fatal(msg); if ( (status = esl_mem_strtoi32(" 2147483647", 11, 0, &nc, &val)) != eslOK || nc != 11 || val != INT32_MAX) esl_fatal(msg); if ( (status = esl_mem_strtoi32("-2147483648", 11, 0, &nc, &val)) != eslOK || nc != 11 || val != INT32_MIN) esl_fatal(msg); if ( (status = esl_mem_strtoi32(" 2147483648", 11, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MAX) esl_fatal(msg); if ( (status = esl_mem_strtoi32("-2147483649", 11, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MIN) esl_fatal(msg); if ( (status = esl_mem_strtoi32(" 214748364800", 13, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MAX) esl_fatal(msg); if ( (status = esl_mem_strtoi32("-214748364900", 13, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MIN) esl_fatal(msg); if ( (status = esl_mem_strtoi32(" 0x1234", 3, 16, &nc, &val)) != eslEFORMAT || nc != 0 || val != 0) esl_fatal(msg); if ( (status = esl_mem_strtoi32("09999999", 7, 0, &nc, &val)) != eslEFORMAT || nc != 0 || val != 0) esl_fatal(msg); return; } static void utest_memtok(void) { char msg[] = "esl_memtok() unit test failed"; char *teststring; esl_pos_t n; char *s; char *tok; esl_pos_t toklen; if (esl_strdup("This is\t a sentence.", -1, &teststring) != eslOK) esl_fatal(msg); s = teststring; n = strlen(teststring); if (esl_memtok(&s, &n, " ", &tok, &toklen) != eslOK) esl_fatal(msg); if (toklen != 4) esl_fatal(msg); if (memcmp(tok, "This", toklen) != 0) esl_fatal(msg); if (*s != 'i') esl_fatal(msg); if (esl_memtok(&s, &n, " \t", &tok, &toklen) != eslOK) esl_fatal(msg); if (toklen != 2) esl_fatal(msg); if (memcmp(tok, "is", toklen) != 0) esl_fatal(msg); if (*s != 'a') esl_fatal(msg); if (esl_memtok(&s, &n, "\n", &tok, &toklen) != eslOK) esl_fatal(msg); if (toklen != 11) esl_fatal(msg); if (memcmp(tok, "a sentence.", toklen) != 0) esl_fatal(msg); if (*s != '\0') esl_fatal(msg); if (n != 0) esl_fatal(msg); if (esl_memtok(&s, &n, "\n", &tok, &toklen) != eslEOL) esl_fatal(msg); if (toklen != 0) esl_fatal(msg); if (tok != NULL) esl_fatal(msg); free(teststring); return; } /* memspn, memcspn() */ static void utest_memspn_memcspn(void) { char msg[] = "memspn/memcspn unit test failed"; char test1[] = " this is a test"; char *p; esl_pos_t n; p = test1; n = 13; /* so the memory is " this is a t" */ if (esl_memspn (p, n, " \t\n\r") != 2) esl_fatal(msg); if (esl_memcspn(p, n, " \t\n\r") != 0) esl_fatal(msg); p = test1+2; n = 11; /* "this is a t" */ if (esl_memspn (p, n, " \t\n\r") != 0) esl_fatal(msg); if (esl_memcspn(p, n, " \t\n\r") != 4) esl_fatal(msg); p = test1; n = 2; if (esl_memspn (p, n, " \t\n\r") != 2) esl_fatal(msg); if (esl_memcspn(p, n, " \t\n\r") != 0) esl_fatal(msg); p = test1+2; n = 4; if (esl_memspn (p, n, " \t\n\r") != 0) esl_fatal(msg); if (esl_memcspn(p, n, " \t\n\r") != 4) esl_fatal(msg); } /* memstrcmp/memstrpfx */ static void utest_memstrcmp_memstrpfx(void) { char msg[] = "memstrcmp/memstrpfx unit test failed"; char test[] = "this is a test"; char *p; esl_pos_t n; p = test; n = strlen(p); if (! esl_memstrcmp(p, n, test)) esl_fatal(msg); if ( esl_memstrcmp(p, n, "this")) esl_fatal(msg); if (! esl_memstrpfx(p, n, "this")) esl_fatal(msg); if ( esl_memstrpfx(p, n, "that")) esl_fatal(msg); p = test; n = 2; /* now p is just "th" */ if (! esl_memstrcmp(p, n, "th")) esl_fatal(msg); if ( esl_memstrcmp(p, n, test)) esl_fatal(msg); if (! esl_memstrpfx(p, n, "th")) esl_fatal(msg); if ( esl_memstrpfx(p, n, "this")) esl_fatal(msg); /* special cases involving NULLs */ p = test; n = strlen(p); if (! esl_memstrcmp(NULL, 0, NULL)) esl_fatal(msg); if ( esl_memstrcmp(NULL, 0, test)) esl_fatal(msg); if ( esl_memstrcmp(p, n, NULL)) esl_fatal(msg); if ( esl_memstrpfx(NULL, 0, NULL)) esl_fatal(msg); if ( esl_memstrpfx(NULL, 0, "this")) esl_fatal(msg); if ( esl_memstrpfx(p, n, NULL)) esl_fatal(msg); } static void utest_memstrcontains(void) { char msg[] = "memstrcontains unit test failed"; char test[] = "CLUSTAL W (1.83) multiple sequence alignment"; char *p; esl_pos_t n; p = test; n = strlen(p); if (! esl_memstrcontains(p, n, "multiple sequence alignment")) esl_fatal(msg); if (! esl_memstrcontains(p, n, "CLUSTAL")) esl_fatal(msg); if ( esl_memstrcontains(p, n, "alignmentx")) esl_fatal(msg); } #endif /*eslMEM_TESTDRIVE*/ /*------------------ end, unit tests ----------------------------*/ /***************************************************************** * 3. Test driver *****************************************************************/ #ifdef eslMEM_TESTDRIVE #include "esl_config.h" #include <stdio.h> #include "easel.h" #include "esl_mem.h" #include "esl_getopts.h" static ESL_OPTIONS options[] = { /* name type default env range togs reqs incomp help docgrp */ {"-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0}, { 0,0,0,0,0,0,0,0,0,0}, }; static char usage[] = "[-options]"; static char banner[] = "test driver for mem module"; int main(int argc, char **argv) { ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage); utest_mem_strtoi32(); utest_memtok(); utest_memspn_memcspn(); utest_memstrcmp_memstrpfx(); utest_memstrcontains(); esl_getopts_Destroy(go); return 0; } #endif /* eslMEM_TESTDRIVE */ /*------------------ end, test driver ---------------------------*/ /***************************************************************** * @LICENSE@ * * SVN $Id$ * SVN $URL$ *****************************************************************/
Janelia-Farm-Xfam/Bio-HMM-Logo
src/easel/esl_mem.c
C
gpl-3.0
29,498
cordova.define('cordova/plugin_list', function(require, exports, module) { module.exports = [ { "file": "plugins/cordova-plugin-device/www/device.js", "id": "cordova-plugin-device.device", "pluginId": "cordova-plugin-device", "clobbers": [ "device" ] }, { "file": "plugins/cordova-plugin-device/src/browser/DeviceProxy.js", "id": "cordova-plugin-device.DeviceProxy", "pluginId": "cordova-plugin-device", "runs": true }, { "file": "plugins/cordova-plugin-device-orientation/www/CompassError.js", "id": "cordova-plugin-device-orientation.CompassError", "pluginId": "cordova-plugin-device-orientation", "clobbers": [ "CompassError" ] }, { "file": "plugins/cordova-plugin-device-orientation/www/CompassHeading.js", "id": "cordova-plugin-device-orientation.CompassHeading", "pluginId": "cordova-plugin-device-orientation", "clobbers": [ "CompassHeading" ] }, { "file": "plugins/cordova-plugin-device-orientation/www/compass.js", "id": "cordova-plugin-device-orientation.compass", "pluginId": "cordova-plugin-device-orientation", "clobbers": [ "navigator.compass" ] }, { "file": "plugins/cordova-plugin-device-orientation/src/browser/CompassProxy.js", "id": "cordova-plugin-device-orientation.CompassProxy", "pluginId": "cordova-plugin-device-orientation", "runs": true }, { "file": "plugins/cordova-plugin-dialogs/www/notification.js", "id": "cordova-plugin-dialogs.notification", "pluginId": "cordova-plugin-dialogs", "merges": [ "navigator.notification" ] }, { "file": "plugins/cordova-plugin-dialogs/www/browser/notification.js", "id": "cordova-plugin-dialogs.notification_browser", "pluginId": "cordova-plugin-dialogs", "merges": [ "navigator.notification" ] }, { "file": "plugins/cordova-plugin-network-information/www/network.js", "id": "cordova-plugin-network-information.network", "pluginId": "cordova-plugin-network-information", "clobbers": [ "navigator.connection", "navigator.network.connection" ] }, { "file": "plugins/cordova-plugin-network-information/www/Connection.js", "id": "cordova-plugin-network-information.Connection", "pluginId": "cordova-plugin-network-information", "clobbers": [ "Connection" ] }, { "file": "plugins/cordova-plugin-network-information/src/browser/network.js", "id": "cordova-plugin-network-information.NetworkInfoProxy", "pluginId": "cordova-plugin-network-information", "runs": true }, { "file": "plugins/cordova-plugin-splashscreen/www/splashscreen.js", "id": "cordova-plugin-splashscreen.SplashScreen", "pluginId": "cordova-plugin-splashscreen", "clobbers": [ "navigator.splashscreen" ] }, { "file": "plugins/cordova-plugin-splashscreen/src/browser/SplashScreenProxy.js", "id": "cordova-plugin-splashscreen.SplashScreenProxy", "pluginId": "cordova-plugin-splashscreen", "runs": true }, { "file": "plugins/cordova-plugin-statusbar/www/statusbar.js", "id": "cordova-plugin-statusbar.statusbar", "pluginId": "cordova-plugin-statusbar", "clobbers": [ "window.StatusBar" ] }, { "file": "plugins/cordova-plugin-statusbar/src/browser/statusbar.js", "id": "cordova-plugin-statusbar.statusbar.Browser", "pluginId": "cordova-plugin-statusbar", "merges": [ "window.StatusBar" ] }, { "file": "plugins/phonegap-plugin-mobile-accessibility/www/mobile-accessibility.js", "id": "phonegap-plugin-mobile-accessibility.mobile-accessibility", "pluginId": "phonegap-plugin-mobile-accessibility", "clobbers": [ "window.MobileAccessibility" ] }, { "file": "plugins/phonegap-plugin-mobile-accessibility/www/MobileAccessibilityNotifications.js", "id": "phonegap-plugin-mobile-accessibility.MobileAccessibilityNotifications", "pluginId": "phonegap-plugin-mobile-accessibility", "clobbers": [ "MobileAccessibilityNotifications" ] }, { "file": "plugins/cordova-plugin-device-motion/www/Acceleration.js", "id": "cordova-plugin-device-motion.Acceleration", "pluginId": "cordova-plugin-device-motion", "clobbers": [ "Acceleration" ] }, { "file": "plugins/cordova-plugin-device-motion/www/accelerometer.js", "id": "cordova-plugin-device-motion.accelerometer", "pluginId": "cordova-plugin-device-motion", "clobbers": [ "navigator.accelerometer" ] }, { "file": "plugins/cordova-plugin-device-motion/src/browser/AccelerometerProxy.js", "id": "cordova-plugin-device-motion.AccelerometerProxy", "pluginId": "cordova-plugin-device-motion", "runs": true }, { "file": "plugins/cordova-plugin-globalization/www/GlobalizationError.js", "id": "cordova-plugin-globalization.GlobalizationError", "pluginId": "cordova-plugin-globalization", "clobbers": [ "window.GlobalizationError" ] }, { "file": "plugins/cordova-plugin-globalization/www/globalization.js", "id": "cordova-plugin-globalization.globalization", "pluginId": "cordova-plugin-globalization", "clobbers": [ "navigator.globalization" ] }, { "file": "plugins/cordova-plugin-globalization/www/browser/moment.js", "id": "cordova-plugin-globalization.moment", "pluginId": "cordova-plugin-globalization", "runs": true }, { "file": "plugins/cordova-plugin-globalization/src/browser/GlobalizationProxy.js", "id": "cordova-plugin-globalization.GlobalizationProxy", "pluginId": "cordova-plugin-globalization", "runs": true }, { "file": "plugins/cordova-plugin-inappbrowser/www/inappbrowser.js", "id": "cordova-plugin-inappbrowser.inappbrowser", "pluginId": "cordova-plugin-inappbrowser", "clobbers": [ "cordova.InAppBrowser.open", "window.open" ] }, { "file": "plugins/cordova-plugin-inappbrowser/src/browser/InAppBrowserProxy.js", "id": "cordova-plugin-inappbrowser.InAppBrowserProxy", "pluginId": "cordova-plugin-inappbrowser", "merges": [ "" ] }, { "file": "plugins/cordova-plugin-file/www/DirectoryEntry.js", "id": "cordova-plugin-file.DirectoryEntry", "pluginId": "cordova-plugin-file", "clobbers": [ "window.DirectoryEntry" ] }, { "file": "plugins/cordova-plugin-file/www/DirectoryReader.js", "id": "cordova-plugin-file.DirectoryReader", "pluginId": "cordova-plugin-file", "clobbers": [ "window.DirectoryReader" ] }, { "file": "plugins/cordova-plugin-file/www/Entry.js", "id": "cordova-plugin-file.Entry", "pluginId": "cordova-plugin-file", "clobbers": [ "window.Entry" ] }, { "file": "plugins/cordova-plugin-file/www/File.js", "id": "cordova-plugin-file.File", "pluginId": "cordova-plugin-file", "clobbers": [ "window.File" ] }, { "file": "plugins/cordova-plugin-file/www/FileEntry.js", "id": "cordova-plugin-file.FileEntry", "pluginId": "cordova-plugin-file", "clobbers": [ "window.FileEntry" ] }, { "file": "plugins/cordova-plugin-file/www/FileError.js", "id": "cordova-plugin-file.FileError", "pluginId": "cordova-plugin-file", "clobbers": [ "window.FileError" ] }, { "file": "plugins/cordova-plugin-file/www/FileReader.js", "id": "cordova-plugin-file.FileReader", "pluginId": "cordova-plugin-file", "clobbers": [ "window.FileReader" ] }, { "file": "plugins/cordova-plugin-file/www/FileSystem.js", "id": "cordova-plugin-file.FileSystem", "pluginId": "cordova-plugin-file", "clobbers": [ "window.FileSystem" ] }, { "file": "plugins/cordova-plugin-file/www/FileUploadOptions.js", "id": "cordova-plugin-file.FileUploadOptions", "pluginId": "cordova-plugin-file", "clobbers": [ "window.FileUploadOptions" ] }, { "file": "plugins/cordova-plugin-file/www/FileUploadResult.js", "id": "cordova-plugin-file.FileUploadResult", "pluginId": "cordova-plugin-file", "clobbers": [ "window.FileUploadResult" ] }, { "file": "plugins/cordova-plugin-file/www/FileWriter.js", "id": "cordova-plugin-file.FileWriter", "pluginId": "cordova-plugin-file", "clobbers": [ "window.FileWriter" ] }, { "file": "plugins/cordova-plugin-file/www/Flags.js", "id": "cordova-plugin-file.Flags", "pluginId": "cordova-plugin-file", "clobbers": [ "window.Flags" ] }, { "file": "plugins/cordova-plugin-file/www/LocalFileSystem.js", "id": "cordova-plugin-file.LocalFileSystem", "pluginId": "cordova-plugin-file", "clobbers": [ "window.LocalFileSystem" ], "merges": [ "window" ] }, { "file": "plugins/cordova-plugin-file/www/Metadata.js", "id": "cordova-plugin-file.Metadata", "pluginId": "cordova-plugin-file", "clobbers": [ "window.Metadata" ] }, { "file": "plugins/cordova-plugin-file/www/ProgressEvent.js", "id": "cordova-plugin-file.ProgressEvent", "pluginId": "cordova-plugin-file", "clobbers": [ "window.ProgressEvent" ] }, { "file": "plugins/cordova-plugin-file/www/fileSystems.js", "id": "cordova-plugin-file.fileSystems", "pluginId": "cordova-plugin-file" }, { "file": "plugins/cordova-plugin-file/www/requestFileSystem.js", "id": "cordova-plugin-file.requestFileSystem", "pluginId": "cordova-plugin-file", "clobbers": [ "window.requestFileSystem" ] }, { "file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js", "id": "cordova-plugin-file.resolveLocalFileSystemURI", "pluginId": "cordova-plugin-file", "merges": [ "window" ] }, { "file": "plugins/cordova-plugin-file/www/browser/isChrome.js", "id": "cordova-plugin-file.isChrome", "pluginId": "cordova-plugin-file", "runs": true }, { "file": "plugins/cordova-plugin-file/www/browser/Preparing.js", "id": "cordova-plugin-file.Preparing", "pluginId": "cordova-plugin-file", "runs": true }, { "file": "plugins/cordova-plugin-file/src/browser/FileProxy.js", "id": "cordova-plugin-file.browserFileProxy", "pluginId": "cordova-plugin-file", "runs": true }, { "file": "plugins/cordova-plugin-file/www/fileSystemPaths.js", "id": "cordova-plugin-file.fileSystemPaths", "pluginId": "cordova-plugin-file", "merges": [ "cordova" ], "runs": true }, { "file": "plugins/cordova-plugin-file/www/browser/FileSystem.js", "id": "cordova-plugin-file.firefoxFileSystem", "pluginId": "cordova-plugin-file", "merges": [ "window.FileSystem" ] }, { "file": "plugins/cordova-plugin-media/www/MediaError.js", "id": "cordova-plugin-media.MediaError", "pluginId": "cordova-plugin-media", "clobbers": [ "window.MediaError" ] }, { "file": "plugins/cordova-plugin-media/www/Media.js", "id": "cordova-plugin-media.Media", "pluginId": "cordova-plugin-media", "clobbers": [ "window.Media" ] }, { "file": "plugins/cordova-plugin-media/www/browser/Media.js", "id": "cordova-plugin-media.BrowserMedia", "pluginId": "cordova-plugin-media", "clobbers": [ "window.Media" ] } ]; module.exports.metadata = // TOP OF METADATA { "cordova-plugin-console": "1.0.5", "cordova-plugin-device": "1.1.4", "cordova-plugin-device-orientation": "1.0.5", "cordova-plugin-dialogs": "1.2.1", "cordova-plugin-network-information": "1.2.1", "cordova-plugin-splashscreen": "3.2.2", "cordova-plugin-statusbar": "2.1.3", "cordova-plugin-whitelist": "1.2.2", "phonegap-plugin-mobile-accessibility": "1.0.5-dev", "cordova-plugin-device-motion": "1.2.4", "cordova-plugin-globalization": "1.0.6", "cordova-plugin-inappbrowser": "1.3.0", "cordova-plugin-compat": "1.1.0", "cordova-plugin-file": "4.3.2", "cordova-plugin-media": "2.2.0" } // BOTTOM OF METADATA });
Nullpo/Kallat-Tablero
platforms/browser/www/cordova_plugins.js
JavaScript
gpl-3.0
13,698
<?php // Controller for latestdeaths. class Deaths extends Controller { public function index() { require("config.php"); $this->load->database(); if(@$_REQUEST['world'] == 0) $world = 0; else $world = (int)@$_REQUEST['world']; $world_name = ($config['worlds'] == $world); $players_deaths = $this->db->query('SELECT `player_deaths`.`id`, `player_deaths`.`date`, `player_deaths`.`level`, `players`.`name`, `players`.`world_id` FROM `player_deaths` LEFT JOIN `players` ON `player_deaths`.`player_id` = `players`.`id` ORDER BY `date` DESC LIMIT 0,'.$config['latestdeathlimit'])->result(); if (!empty($players_deaths)) { foreach ($players_deaths as $death) { $sql = $this->db->query('SELECT environment_killers.name AS monster_name, players.name AS player_name, players.deleted AS player_exists FROM killers LEFT JOIN environment_killers ON killers.id = environment_killers.kill_id LEFT JOIN player_killers ON killers.id = player_killers.kill_id LEFT JOIN players ON players.id = player_killers.player_id WHERE killers.death_id = '.$death->id.' ORDER BY killers.final_hit DESC, killers.id ASC')->result(); $players_rows = '<td><a href="?subtopic=characters&name='.urlencode($death->name).'"><b>'.$death->name.'</b></a> '; $i = 0; $count = count($death); foreach($sql as $deaths) { $i++; if($deaths->player_name != "") { if($i == 1) $players_rows .= "killed at level <b>".$death->level."</b>"; else if($i == $count) $players_rows .= " and"; else $players_rows .= ","; $players_rows .= " by "; if($deaths->monster_name != "") $players_rows .= $deaths->monster_name." summoned by "; if($deaths->player_exists == 0) $players_rows .= "<a href=\"index.php?subtopic=characters&name=".urlencode($deaths->player_name)."\">"; $players_rows .= $deaths->player_name; if($deaths->player_exists == 0) $players_rows .= "</a>"; } else { if($i == 1) $players_rows .= "died at level <b>".$death->level."</b>"; else if($i == $count) $players_rows .= " and"; else $players_rows .= ","; $players_rows .= " by ".$deaths->monster_name; } $players_rows .= "</td>"; $data['deaths'][] = array('players_rows'=>$players_rows,'date'=>$death->date,'name'=>$death->name,'player_name'=>$deaths->player_name,'monster_name'=>$deaths->monster_name,'player_exists'=>$deaths->player_exists); $players_rows = ""; } } $this->load->helper("form"); $this->load->view("deaths", $data); } else { echo "<h1>There are no players killed yet.</h1>"; } } } ?>
avuenja/modernaac
system/application/controllers/deaths.php
PHP
gpl-3.0
2,690
#!/bin/bash # # flashx.tv module # Copyright (c) 2014 Plowshare team # # This file is part of Plowshare. # # Plowshare 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. # # Plowshare 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 Plowshare. If not, see <http://www.gnu.org/licenses/>. MODULE_FLASHX_REGEXP_URL='http://\(www\.\)\?flashx\.tv/' MODULE_FLASHX_DOWNLOAD_OPTIONS="" MODULE_FLASHX_DOWNLOAD_RESUME=yes MODULE_FLASHX_DOWNLOAD_FINAL_LINK_NEEDS_COOKIE=no MODULE_FLASHX_DOWNLOAD_SUCCESSIVE_INTERVAL= MODULE_FLASHX_DOWNLOAD_FINAL_LINK_NEEDS_EXTRA= MODULE_FLASHX_PROBE_OPTIONS="" # Output a flashx file download URL # $1: cookie file # $2: flashx url # stdout: real file download link flashx_download() { local -r COOKIE_FILE=$1 local -r URL=$2 local PAGE CONFIG_URL EMBED_URL FILE_NAME FILE_URL PAGE=$(curl -c "$COOKIE_FILE" --location "$URL") || return if match 'Video not found, deleted, abused or wrong link\|Video not found, deleted or abused, sorry!' \ "$PAGE"; then return $ERR_LINK_DEAD fi if match '<h2>404 Error</h2>' "$PAGE"; then return $ERR_LINK_DEAD fi FILE_NAME=$(parse_tag '<div class=.video_title' 'div' <<< "$PAGE" | html_to_utf8) || return # On main page EMBED_URL=$(echo "$PAGE" | parse '<div class="player_container_new"' 'src="\([^"]*\)' 1) || return PAGE=$(curl -b "$COOKIE_FILE" "$EMBED_URL") || return # Inside iframe embed on main page local FORM_HTML FORM_URL FORM_HASH FORM_SEC_HASH FORM_HTML=$(grep_form_by_name "$PAGE" 'fxplayit') || return FORM_URL=$(echo "$FORM_HTML" | parse_form_action) || return FORM_HASH=$(echo "$FORM_HTML" | parse_form_input_by_name 'hash') || return FORM_SEC_HASH=$(echo "$FORM_HTML" | parse_form_input_by_name 'sechash') || return PAGE=$(curl -b "$COOKIE_FILE" \ --referer "$EMBED_URL" \ --data "hash=$FORM_HASH" \ --data "sechash=$FORM_SEC_HASH" \ --header "Cookie: refid=; vr_referrer=" \ "$(basename_url "$EMBED_URL")/player/$FORM_URL") || return # Player's response CONFIG_URL=$(echo "$PAGE" | parse '<param name="movie"' 'config=\([^"]*\)') || return PAGE=$(curl -b "$COOKIE_FILE" --location "$CONFIG_URL") || return # XML config file FILE_URL=$(parse_tag 'file' <<< "$PAGE") || return echo "$FILE_URL" echo "$FILE_NAME" } # Probe a download URL # $1: cookie file (unused here) # $2: flashx.tv url # $3: requested capability list # stdout: 1 capability per line flashx_probe() { local -r URL=$2 local -r REQ_IN=$3 local PAGE REQ_OUT FILE_NAME PAGE=$(curl --location "$URL") || return if match 'Video not found, deleted, abused or wrong link\|Video not found, deleted or abused, sorry!' \ "$PAGE"; then return $ERR_LINK_DEAD fi if match '<h2>404 Error</h2>' "$PAGE"; then return $ERR_LINK_DEAD fi REQ_OUT=c if [[ $REQ_IN = *f* ]]; then FILE_NAME=$(parse_tag '<div class="video_title"' 'div' <<< "$PAGE" | html_to_utf8) && \ echo "$FILE_NAME" && REQ_OUT="${REQ_OUT}f" fi echo $REQ_OUT }
drewc/plowshare
src/modules/flashx.sh
Shell
gpl-3.0
3,581
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2017 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU 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/>. from typing import Any, Dict, Set from snapcraft import project from snapcraft.internal.project_loader import grammar from snapcraft.internal import pluginhandler, repo from ._package_transformer import package_transformer class PartGrammarProcessor: """Process part properties that support grammar. Stage packages example: >>> from unittest import mock >>> import snapcraft >>> # Pretend that all packages are valid >>> repo = mock.Mock() >>> repo.is_valid.return_value = True >>> plugin = mock.Mock() >>> plugin.stage_packages = [{'try': ['foo']}] >>> processor = PartGrammarProcessor( ... plugin=plugin, ... properties={}, ... project=snapcraft.project.Project(), ... repo=repo) >>> processor.get_stage_packages() {'foo'} Build packages example: >>> from unittest import mock >>> import snapcraft >>> # Pretend that all packages are valid >>> repo = mock.Mock() >>> repo.is_valid.return_value = True >>> plugin = mock.Mock() >>> plugin.build_packages = [{'try': ['foo']}] >>> processor = PartGrammarProcessor( ... plugin=plugin, ... properties={}, ... project=snapcraft.project.Project(), ... repo=repo) >>> processor.get_build_packages() {'foo'} Source example: >>> from unittest import mock >>> import snapcraft >>> plugin = mock.Mock() >>> plugin.properties = {'source': [{'on amd64': 'foo'}, 'else fail']} >>> processor = PartGrammarProcessor( ... plugin=plugin, ... properties=plugin.properties, ... project=snapcraft.project.Project(), ... repo=None) >>> processor.get_source() 'foo' """ def __init__( self, *, plugin: pluginhandler.PluginHandler, properties: Dict[str, Any], project: project.Project, repo: "repo.Ubuntu" ) -> None: self._project = project self._repo = repo self._build_snap_grammar = getattr(plugin, "build_snaps", []) self.__build_snaps = set() # type: Set[str] self._build_package_grammar = getattr(plugin, "build_packages", []) self.__build_packages = set() # type: Set[str] self._stage_package_grammar = getattr(plugin, "stage_packages", []) self.__stage_packages = set() # type: Set[str] source_grammar = properties.get("source", [""]) if not isinstance(source_grammar, list): self._source_grammar = [source_grammar] else: self._source_grammar = source_grammar self.__source = "" def get_source(self) -> str: if not self.__source: # The grammar is array-based, even though we only support a single # source. processor = grammar.GrammarProcessor( self._source_grammar, self._project, lambda s: True ) source_array = processor.process() if len(source_array) > 0: self.__source = source_array.pop() return self.__source def get_build_snaps(self) -> Set[str]: if not self.__build_snaps: processor = grammar.GrammarProcessor( self._build_snap_grammar, self._project, repo.snaps.SnapPackage.is_valid_snap, ) self.__build_snaps = processor.process() return self.__build_snaps def get_build_packages(self) -> Set[str]: if not self.__build_packages: processor = grammar.GrammarProcessor( self._build_package_grammar, self._project, self._repo.build_package_is_valid, transformer=package_transformer, ) self.__build_packages = processor.process() return self.__build_packages def get_stage_packages(self) -> Set[str]: if not self.__stage_packages: processor = grammar.GrammarProcessor( self._stage_package_grammar, self._project, self._repo.is_valid, transformer=package_transformer, ) self.__stage_packages = processor.process() return self.__stage_packages
sergiusens/snapcraft
snapcraft/internal/project_loader/grammar_processing/_part_grammar_processor.py
Python
gpl-3.0
4,927
# -*- coding: utf-8 -*- # Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals # import frappe import unittest class TestEInvoiceRequestLog(unittest.TestCase): pass
frappe/erpnext
erpnext/regional/doctype/e_invoice_request_log/test_e_invoice_request_log.py
Python
gpl-3.0
241
#include <cmath> #include <cfloat> // DBL_MAX #include "Action_GIST.h" #include "CpptrajStdio.h" #include "Constants.h" #include "DataSet_MatrixFlt.h" #include "DataSet_GridFlt.h" #include "DataSet_GridDbl.h" #include "ProgressBar.h" #include "StringRoutines.h" #include "DistRoutines.h" #ifdef _OPENMP # include <omp.h> #endif const double Action_GIST::maxD_ = DBL_MAX; Action_GIST::Action_GIST() : debug_(0), numthreads_(1), #ifdef CUDA numberAtoms_(0), numberAtomTypes_(0), headAtomType_(0), solvent_(NULL), NBindex_c_(NULL), molecule_c_(NULL), paramsLJ_c_(NULL), max_c_(NULL), min_c_(NULL), result_w_c_(NULL), result_s_c_(NULL), result_O_c_(NULL), result_N_c_(NULL), #endif gridspacing_(0), gridcntr_(0.0), griddim_(0.0), gO_(0), gH_(0), Esw_(0), Eww_(0), dTStrans_(0), dTSorient_(0), dTSsix_(0), neighbor_norm_(0), dipole_(0), order_norm_(0), dipolex_(0), dipoley_(0), dipolez_(0), PME_(0), U_PME_(0), ww_Eij_(0), G_max_(0.0), CurrentParm_(0), datafile_(0), eijfile_(0), infofile_(0), fltFmt_(TextFormat::GDOUBLE), intFmt_(TextFormat::INTEGER), BULK_DENS_(0.0), temperature_(0.0), NeighborCut2_(12.25), // 3.5^2 // system_potential_energy_(0), // solute_potential_energy_(0), MAX_GRID_PT_(0), NSOLVENT_(0), N_ON_GRID_(0), nMolAtoms_(0), NFRAME_(0), max_nwat_(0), doOrder_(false), doEij_(false), skipE_(false), includeIons_(true) {} /** GIST help */ void Action_GIST::Help() const { mprintf("\t[doorder] [doeij] [skipE] [skipS] [refdens <rdval>] [temp <tval>]\n" "\t[noimage] [gridcntr <xval> <yval> <zval>] [excludeions]\n" "\t[griddim <nx> <ny> <nz>] [gridspacn <spaceval>] [neighborcut <ncut>]\n" "\t[prefix <filename prefix>] [ext <grid extension>] [out <output suffix>]\n" "\t[floatfmt {double|scientific|general}] [floatwidth <fw>] [floatprec <fp>]\n" "\t[intwidth <iw>]\n" "\t[info <info suffix>]\n"); # ifdef LIBPME mprintf("\t[nopme|pme %s\n\t %s\n\t %s]\n", EwaldOptions::KeywordsCommon1(), EwaldOptions::KeywordsCommon2(), EwaldOptions::KeywordsPME()); # endif mprintf("Perform Grid Inhomogenous Solvation Theory calculation.\n" #ifdef CUDA "The option doeij is not available, when using the CUDA accelerated version,\n" "as this would need way too much memory." #endif ); } /** Init GIST action. */ Action::RetType Action_GIST::Init(ArgList& actionArgs, ActionInit& init, int debugIn) { debug_ = debugIn; # ifdef MPI if (init.TrajComm().Size() > 1) { mprinterr("Error: 'gist' action does not work with > 1 process (%i processes currently).\n", init.TrajComm().Size()); return Action::ERR; } # endif gist_init_.Start(); prefix_ = actionArgs.GetStringKey("prefix"); if (prefix_.empty()) prefix_.assign("gist"); std::string ext = actionArgs.GetStringKey("ext"); if (ext.empty()) ext.assign(".dx"); std::string gistout = actionArgs.GetStringKey("out"); if (gistout.empty()) gistout.assign(prefix_ + "-output.dat"); datafile_ = init.DFL().AddCpptrajFile( gistout, "GIST output" ); if (datafile_ == 0) return Action::ERR; // Info file: if not specified use STDOUT gistout = actionArgs.GetStringKey("info"); if (!gistout.empty()) gistout = prefix_ + "-" + gistout; infofile_ = init.DFL().AddCpptrajFile( gistout, "GIST info", DataFileList::TEXT, true ); if (infofile_ == 0) return Action::ERR; // Grid files DataFile* file_gO = init.DFL().AddDataFile( prefix_ + "-gO" + ext ); DataFile* file_gH = init.DFL().AddDataFile( prefix_ + "-gH" + ext ); DataFile* file_Esw = init.DFL().AddDataFile(prefix_ + "-Esw-dens" + ext); DataFile* file_Eww = init.DFL().AddDataFile(prefix_ + "-Eww-dens" + ext); DataFile* file_dTStrans = init.DFL().AddDataFile(prefix_ + "-dTStrans-dens" + ext); DataFile* file_dTSorient = init.DFL().AddDataFile(prefix_ + "-dTSorient-dens" + ext); DataFile* file_dTSsix = init.DFL().AddDataFile(prefix_ + "-dTSsix-dens" + ext); DataFile* file_neighbor_norm = init.DFL().AddDataFile(prefix_ + "-neighbor-norm" + ext); DataFile* file_dipole = init.DFL().AddDataFile(prefix_ + "-dipole-dens" + ext); DataFile* file_order_norm = init.DFL().AddDataFile(prefix_ + "-order-norm" + ext); DataFile* file_dipolex = init.DFL().AddDataFile(prefix_ + "-dipolex-dens" + ext); DataFile* file_dipoley = init.DFL().AddDataFile(prefix_ + "-dipoley-dens" + ext); DataFile* file_dipolez = init.DFL().AddDataFile(prefix_ + "-dipolez-dens" + ext); // Output format keywords std::string floatfmt = actionArgs.GetStringKey("floatfmt"); if (!floatfmt.empty()) { if (floatfmt == "double") fltFmt_.SetFormatType(TextFormat::DOUBLE); else if (floatfmt == "scientific") fltFmt_.SetFormatType(TextFormat::SCIENTIFIC); else if (floatfmt == "general") fltFmt_.SetFormatType(TextFormat::GDOUBLE); else { mprinterr("Error: Unrecognized format type for 'floatfmt': %s\n", floatfmt.c_str()); return Action::ERR; } } fltFmt_.SetFormatWidthPrecision( actionArgs.getKeyInt("floatwidth", 0), actionArgs.getKeyInt("floatprec", -1) ); intFmt_.SetFormatWidth( actionArgs.getKeyInt("intwidth", 0) ); // Other keywords double neighborCut = actionArgs.getKeyDouble("neighborcut", 3.5); NeighborCut2_ = neighborCut * neighborCut; includeIons_ = !actionArgs.hasKey("excludeions"); imageOpt_.InitImaging( !(actionArgs.hasKey("noimage")), actionArgs.hasKey("nonortho") ); doOrder_ = actionArgs.hasKey("doorder"); doEij_ = actionArgs.hasKey("doeij"); #ifdef CUDA if (this->doEij_) { mprinterr("Error: 'doeij' cannot be specified when using CUDA.\n"); return Action::ERR; } #endif skipE_ = actionArgs.hasKey("skipE"); if (skipE_) { if (doEij_) { mprinterr("Error: 'doeij' cannot be specified if 'skipE' is specified.\n"); return Action::ERR; } } // Parse PME options // TODO once PME output is stable, make pme true the default when LIBPME present. //# ifdef LIBPME // usePme_ = true; //# else usePme_ = false; //# endif # ifdef CUDA // Disable PME for CUDA usePme_ = false; # endif if (actionArgs.hasKey("pme")) usePme_ = true; else if (actionArgs.hasKey("nopme")) usePme_ = false; // PME and doeij are not compatible if (usePme_ && doEij_) { mprinterr("Error: 'doeij' cannot be used with PME. Specify 'nopme' to use 'doeij'\n"); return Action::ERR; } if (usePme_) { # ifdef LIBPME pmeOpts_.AllowLjPme(false); if (pmeOpts_.GetOptions(EwaldOptions::PME, actionArgs, "GIST")) { mprinterr("Error: Getting PME options for GIST failed.\n"); return Action::ERR; } # else mprinterr("Error: 'pme' with GIST requires compilation with LIBPME.\n"); return Action::ERR; # endif } DataFile* file_energy_pme = 0; DataFile* file_U_energy_pme = 0; if (usePme_) { file_energy_pme = init.DFL().AddDataFile(prefix_ + "-Water-Etot-pme-dens" + ext); file_U_energy_pme = init.DFL().AddDataFile(prefix_ + "-Solute-Etot-pme-dens"+ ext); } this->skipS_ = actionArgs.hasKey("skipS"); if (doEij_) { eijfile_ = init.DFL().AddCpptrajFile(prefix_ + "-Eww_ij.dat", "GIST Eij matrix file"); if (eijfile_ == 0) return Action::ERR; } // Set Bulk Density 55.5M BULK_DENS_ = actionArgs.getKeyDouble("refdens", 0.0334); if ( BULK_DENS_ > (0.0334*1.2) ) mprintf("Warning: water reference density is high, consider using 0.0334 for 1g/cc water density\n"); else if ( BULK_DENS_ < (0.0334*0.8) ) mprintf("Warning: water reference density is low, consider using 0.0334 for 1g/cc water density\n"); temperature_ = actionArgs.getKeyDouble("temp", 300.0); if (temperature_ < 0.0) { mprinterr("Error: Negative temperature specified.\n"); return Action::ERR; } // Grid spacing gridspacing_ = actionArgs.getKeyDouble("gridspacn", 0.50); // Grid center gridcntr_ = Vec3(0.0); if ( actionArgs.hasKey("gridcntr") ) { gridcntr_[0] = actionArgs.getNextDouble(-1); gridcntr_[1] = actionArgs.getNextDouble(-1); gridcntr_[2] = actionArgs.getNextDouble(-1); } else mprintf("Warning: No grid center values specified, using default (origin)\n"); // Grid dimensions int nx = 40; int ny = 40; int nz = 40; if ( actionArgs.hasKey("griddim") ) { nx = actionArgs.getNextInteger(-1); ny = actionArgs.getNextInteger(-1); nz = actionArgs.getNextInteger(-1); } else mprintf("Warning: No grid dimension values specified, using default (40,40,40)\n"); griddim_ = Vec3((double)nx, (double)ny, (double)nz); // Data set name std::string dsname = actionArgs.GetStringKey("name"); if (dsname.empty()) dsname = init.DSL().GenerateDefaultName("GIST"); // Set up DataSets. gO_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "gO")); gH_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "gH")); Esw_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "Esw")); Eww_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "Eww")); dTStrans_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "dTStrans")); dTSorient_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "dTSorient")); dTSsix_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "dTSsix")); neighbor_norm_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "neighbor")); dipole_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "dipole")); order_norm_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_DBL, MetaData(dsname, "order")); dipolex_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_DBL, MetaData(dsname, "dipolex")); dipoley_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_DBL, MetaData(dsname, "dipoley")); dipolez_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_DBL, MetaData(dsname, "dipolez")); if (gO_==0 || gH_==0 || Esw_==0 || Eww_==0 || dTStrans_==0 || dTSorient_==0 || dTSsix_==0 || neighbor_norm_==0 || dipole_==0 || order_norm_==0 || dipolex_==0 || dipoley_==0 || dipolez_==0) return Action::ERR; if (usePme_) { PME_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname,"PME")); U_PME_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT,MetaData(dsname,"U_PME")); if (PME_ == 0 || U_PME_ == 0) return Action::ERR; } if (doEij_) { ww_Eij_ = (DataSet_MatrixFlt*)init.DSL().AddSet(DataSet::MATRIX_FLT, MetaData(dsname, "Eij")); if (ww_Eij_ == 0) return Action::ERR; } // Allocate DataSets. TODO non-orthogonal grids as well Vec3 v_spacing( gridspacing_ ); gO_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing); MAX_GRID_PT_ = gO_->Size(); gH_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing); Esw_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing); Eww_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing); dTStrans_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing); dTSorient_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing); dTSsix_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing); neighbor_norm_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing); dipole_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing); order_norm_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing); dipolex_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing); dipoley_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing); dipolez_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing); if (usePme_) { PME_->Allocate_N_C_D(nx,ny,nz,gridcntr_,v_spacing); U_PME_->Allocate_N_C_D(nx,ny,nz,gridcntr_,v_spacing); } if (ww_Eij_ != 0) { if (ww_Eij_->AllocateTriangle( MAX_GRID_PT_ )) { mprinterr("Error: Could not allocate memory for water-water Eij matrix.\n"); return Action::ERR; } } // Add sets to files file_gO->AddDataSet( gO_ ); file_gH->AddDataSet( gH_ ); file_Esw->AddDataSet( Esw_ ); file_Eww->AddDataSet( Eww_ ); file_dTStrans->AddDataSet( dTStrans_ ); file_dTSorient->AddDataSet( dTSorient_ ); file_dTSsix->AddDataSet( dTSsix_ ); file_neighbor_norm->AddDataSet( neighbor_norm_ ); file_dipole->AddDataSet( dipole_ ); file_order_norm->AddDataSet( order_norm_ ); file_dipolex->AddDataSet( dipolex_ ); file_dipoley->AddDataSet( dipoley_ ); file_dipolez->AddDataSet( dipolez_ ); if (usePme_) { file_energy_pme->AddDataSet(PME_); file_U_energy_pme->AddDataSet(U_PME_); } // Set up grid params TODO non-orthogonal as well G_max_ = Vec3( (double)nx * gridspacing_ + 1.5, (double)ny * gridspacing_ + 1.5, (double)nz * gridspacing_ + 1.5 ); N_waters_.assign( MAX_GRID_PT_, 0 ); N_solute_atoms_.assign( MAX_GRID_PT_, 0); N_hydrogens_.assign( MAX_GRID_PT_, 0 ); voxel_xyz_.resize( MAX_GRID_PT_ ); // [] = X Y Z voxel_Q_.resize( MAX_GRID_PT_ ); // [] = W4 X4 Y4 Z4 numthreads_ = 1; # ifdef _OPENMP # pragma omp parallel { if (omp_get_thread_num() == 0) numthreads_ = omp_get_num_threads(); } # endif if (!skipE_) { E_UV_VDW_.resize( numthreads_ ); E_UV_Elec_.resize( numthreads_ ); E_VV_VDW_.resize( numthreads_ ); E_VV_Elec_.resize( numthreads_ ); neighbor_.resize( numthreads_ ); for (int thread = 0; thread != numthreads_; thread++) { E_UV_VDW_[thread].assign( MAX_GRID_PT_, 0 ); E_UV_Elec_[thread].assign( MAX_GRID_PT_, 0 ); E_VV_VDW_[thread].assign( MAX_GRID_PT_, 0 ); E_VV_Elec_[thread].assign( MAX_GRID_PT_, 0 ); neighbor_[thread].assign( MAX_GRID_PT_, 0 ); } if (usePme_) { E_pme_.assign( MAX_GRID_PT_, 0 ); U_E_pme_.assign( MAX_GRID_PT_, 0 ); //E_pme_.resize( numthreads_); //U_E_pme_.resize(numthreads_); //for (int thread = 0; thread != numthreads_; thread++) { // E_pme_[thread].assign( MAX_GRID_PT_,0); // U_E_pme_[thread].assign( MAX_GRID_PT_,0); //} } # ifdef _OPENMP if (doEij_) { // Since allocating a separate matrix for every thread will consume a lot // of memory and since the Eij matrices tend to be sparse since solute is // often present, each thread will record any interaction energies they // calculate separately and add to the Eij matrix afterwards to avoid // memory clashes. Probably not ideal if the bulk of the grid is water however. EIJ_V1_.resize( numthreads_ ); EIJ_V2_.resize( numthreads_ ); EIJ_EN_.resize( numthreads_ ); } # endif #ifdef CUDA if (this->skipE_ && this->doOrder_) { mprintf("When the keyword \"skipE\" is supplied, \"doorder\" cannot be" " chosen, as both calculations are done on the GPU at the same" " time.\nIgnoring \"doorder!\"\n"); } #endif } //Box gbox; //gbox.SetBetaLengths( 90.0, (double)nx * gridspacing_, // (double)ny * gridspacing_, // (double)nz * gridspacing_ ); //grid_.Setup_O_Box( nx, ny, nz, gO_->GridOrigin(), gbox ); //grid_.Setup_O_D( nx, ny, nz, gO_->GridOrigin(), v_spacing ); mprintf(" GIST:\n"); mprintf("\tOutput prefix= '%s', grid output extension= '%s'\n", prefix_.c_str(), ext.c_str()); mprintf("\tOutput float format string= '%s', output integer format string= '%s'\n", fltFmt_.fmt(), intFmt_.fmt()); mprintf("\tGIST info written to '%s'\n", infofile_->Filename().full()); mprintf("\tName for data sets: %s\n", dsname.c_str()); if (doOrder_) mprintf("\tDoing order calculation.\n"); else mprintf("\tSkipping order calculation.\n"); if (skipE_) mprintf("\tSkipping energy calculation.\n"); else { mprintf("\tPerforming energy calculation.\n"); if (numthreads_ > 1) mprintf("\tParallelizing energy calculation with %i threads.\n", numthreads_); if (usePme_) { mprintf("\tUsing PME.\n"); pmeOpts_.PrintOptions(); } } mprintf("\tCut off for determining solvent O-O neighbors is %f Ang\n", sqrt(NeighborCut2_)); if (includeIons_) mprintf("\tIons will be included in the solute region.\n"); else mprintf("\tIons will be excluded from the calculation.\n"); if (doEij_) { mprintf("\tComputing and printing water-water Eij matrix, output to '%s'\n", eijfile_->Filename().full()); mprintf("\tWater-water Eij matrix size is %s\n", ByteString(ww_Eij_->MemUsageInBytes(), BYTE_DECIMAL).c_str()); } else mprintf("\tSkipping water-water Eij matrix.\n"); mprintf("\tWater reference density: %6.4f molecules/Ang^3\n", BULK_DENS_); mprintf("\tSimulation temperature: %6.4f K\n", temperature_); if (imageOpt_.UseImage()) mprintf("\tDistances will be imaged.\n"); else mprintf("\tDistances will not be imaged.\n"); if (imageOpt_.ForceNonOrtho()) mprintf("\tWill use non-orthogonal imaging routines for all cell types.\n"); gO_->GridInfo(); mprintf("\tNumber of voxels: %u, voxel volume: %f Ang^3\n", MAX_GRID_PT_, gO_->Bin().VoxelVolume()); mprintf("#Please cite these papers if you use GIST results in a publication:\n" "# Steven Ramsey, Crystal Nguyen, Romelia Salomon-Ferrer, Ross C. Walker, Michael K. Gilson, and Tom Kurtzman. J. Comp. Chem. 37 (21) 2016\n" "# Crystal Nguyen, Michael K. Gilson, and Tom Young, arXiv:1108.4876v1 (2011)\n" "# Crystal N. Nguyen, Tom Kurtzman Young, and Michael K. Gilson,\n" "# J. Chem. Phys. 137, 044101 (2012)\n" "# Lazaridis, J. Phys. Chem. B 102, 3531–3541 (1998)\n" #ifdef LIBPME "#When using the PME-enhanced version of GIST, please cite:\n" "# Lieyang Chen, Anthony Cruz, Daniel R. Roe, Andy C. Simmonett, Lauren Wickstrom, Nanjie Deng, Tom Kurtzman. JCTC (2021) DOI: 10.1021/acs.jctc.0c01185\n" #endif #ifdef CUDA "#When using the GPU parallelized version of GIST, please cite:\n" "# Johannes Kraml, Anna S. Kamenik, Franz Waibl, Michael Schauperl, Klaus R. Liedl, JCTC (2019)\n" #endif ); # ifdef GIST_USE_NONORTHO_DIST2 mprintf("DEBUG: Using regular non-orthogonal distance routine.\n"); # endif gist_init_.Stop(); return Action::OK; } /// \return True if given floating point values are not equal within a tolerance static inline bool NotEqual(double v1, double v2) { return ( fabs(v1 - v2) > Constants::SMALL ); } /** Set up GIST action. */ Action::RetType Action_GIST::Setup(ActionSetup& setup) { gist_setup_.Start(); CurrentParm_ = setup.TopAddress(); // We need box info if (!setup.CoordInfo().TrajBox().HasBox()) { mprinterr("Error: Must have explicit solvent with periodic boundaries!"); return Action::ERR; } imageOpt_.SetupImaging( setup.CoordInfo().TrajBox().HasBox() ); #ifdef CUDA this->numberAtoms_ = setup.Top().Natom(); this->solvent_ = new bool[this->numberAtoms_]; #endif // Initialize PME if (usePme_) { # ifdef LIBPME if (gistPme_.Init( setup.CoordInfo().TrajBox(), pmeOpts_, debug_ )) { mprinterr("Error: GIST PME init failed.\n"); return Action::ERR; } // By default all atoms are selected for GIST PME to match up with atom_voxel_ array. if (gistPme_.Setup_PME_GIST( setup.Top(), numthreads_, NeighborCut2_ )) { mprinterr("Error: GIST PME setup/array allocation failed.\n"); return Action::ERR; } # else mprinterr("Error: GIST PME requires compilation with LIBPME.\n"); return Action::ERR; # endif } // Get molecule number for each solvent molecule //mol_nums_.clear(); O_idxs_.clear(); A_idxs_.clear(); atom_voxel_.clear(); atomIsSolute_.clear(); atomIsSolventO_.clear(); U_idxs_.clear(); // NOTE: these are just guesses O_idxs_.reserve( setup.Top().Nsolvent() ); A_idxs_.reserve( setup.Top().Natom() ); // atom_voxel_ and atomIsSolute will be indexed by atom # atom_voxel_.assign( setup.Top().Natom(), OFF_GRID_ ); atomIsSolute_.assign(setup.Top().Natom(), false); atomIsSolventO_.assign(setup.Top().Natom(), false); U_idxs_.reserve(setup.Top().Natom()-setup.Top().Nsolvent()*nMolAtoms_); unsigned int midx = 0; unsigned int NsolventAtoms = 0; unsigned int NsoluteAtoms = 0; bool isFirstSolvent = true; for (Topology::mol_iterator mol = setup.Top().MolStart(); mol != setup.Top().MolEnd(); ++mol, ++midx) { if (mol->IsSolvent()) { // NOTE: We assume the oxygen is the first atom! int o_idx = mol->MolUnit().Front(); #ifdef CUDA this->headAtomType_ = setup.Top()[o_idx].TypeIndex(); #endif // Check that molecule has correct # of atoms unsigned int molNumAtoms = (unsigned int)mol->NumAtoms(); if (nMolAtoms_ == 0) { nMolAtoms_ = molNumAtoms; mprintf("\tEach solvent molecule has %u atoms\n", nMolAtoms_); } else if (molNumAtoms != nMolAtoms_) { mprinterr("Error: All solvent molecules must have same # atoms.\n" "Error: Molecule '%s' has %u atoms, expected %u.\n", setup.Top().TruncResNameNum( setup.Top()[o_idx].ResNum() ).c_str(), molNumAtoms, nMolAtoms_); return Action::ERR; } //mol_nums_.push_back( midx ); // TODO needed? // Check that first atom is actually Oxygen if (setup.Top()[o_idx].Element() != Atom::OXYGEN) { mprinterr("Error: Molecule '%s' is not water or does not have oxygen atom.\n", setup.Top().TruncResNameNum( setup.Top()[o_idx].ResNum() ).c_str()); return Action::ERR; } O_idxs_.push_back( o_idx ); atomIsSolventO_[o_idx] = true; // Check that the next two atoms are Hydrogens if (setup.Top()[o_idx+1].Element() != Atom::HYDROGEN || setup.Top()[o_idx+2].Element() != Atom::HYDROGEN) { mprinterr("Error: Molecule '%s' does not have hydrogen atoms.\n", setup.Top().TruncResNameNum( setup.Top()[o_idx].ResNum() ).c_str()); return Action::ERR; } // Save all atom indices for energy calc, including extra points for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) { A_idxs_.push_back( o_idx + IDX ); atomIsSolute_[A_idxs_.back()] = false; // The identity of the atom is water atom_voxel_[A_idxs_.back()] = OFF_GRID_; #ifdef CUDA this->molecule_.push_back( setup.Top()[o_idx + IDX ].MolNum() ); this->charges_.push_back( setup.Top()[o_idx + IDX ].Charge() ); this->atomTypes_.push_back( setup.Top()[o_idx + IDX ].TypeIndex() ); this->solvent_[ o_idx + IDX ] = true; #endif } NsolventAtoms += nMolAtoms_; // If first solvent molecule, save charges. If not, check that charges match. if (isFirstSolvent) { double q_sum = 0.0; Q_.reserve( nMolAtoms_ ); for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) { Q_.push_back( setup.Top()[o_idx+IDX].Charge() ); q_sum += Q_.back(); //mprintf("DEBUG: Q= %20.10E q_sum= %20.10E\n", setup.Top()[o_idx+IDX].Charge(), q_sum); } // Sanity checks. // NOTE: We know indices 1 and 2 are hydrogens (with 0 being oxygen); this is checked above. if (NotEqual(Q_[1], Q_[2])) mprintf("Warning: Charges on water hydrogens do not match (%g, %g).\n", Q_[1], Q_[2]); if (fabs( q_sum ) > 0.0) mprintf("Warning: Charges on water do not sum to 0 (%g)\n", q_sum); //mprintf("DEBUG: Water charges: O=%g H1=%g H2=%g\n", q_O_, q_H1_, q_H2_); } else { for (unsigned int IDX = 0; IDX < nMolAtoms_; IDX++) { double q_atom = setup.Top()[o_idx+IDX].Charge(); if (NotEqual(Q_[IDX], q_atom)) { mprintf("Warning: Charge on water '%s' (%g) does not match first water (%g).\n", setup.Top().TruncResAtomName( o_idx+IDX ).c_str(), q_atom, Q_[IDX]); } } } isFirstSolvent = false; } else { // This is a non-solvent molecule. Save atom indices. May want to exclude // if only 1 atom (probably ion). if (mol->NumAtoms() > 1 || includeIons_) { for (Unit::const_iterator seg = mol->MolUnit().segBegin(); seg != mol->MolUnit().segEnd(); ++seg) { for (int u_idx = seg->Begin(); u_idx != seg->End(); ++u_idx) { A_idxs_.push_back( u_idx ); atomIsSolute_[A_idxs_.back()] = true; // the identity of the atom is solute NsoluteAtoms++; U_idxs_.push_back( u_idx ); // store the solute atom index for locating voxel index #ifdef CUDA this->molecule_.push_back( setup.Top()[ u_idx ].MolNum() ); this->charges_.push_back( setup.Top()[ u_idx ].Charge() ); this->atomTypes_.push_back( setup.Top()[ u_idx ].TypeIndex() ); this->solvent_[ u_idx ] = false; #endif } } } } } NSOLVENT_ = O_idxs_.size(); mprintf("\t%zu solvent molecules, %u solvent atoms, %u solute atoms (%zu total).\n", O_idxs_.size(), NsolventAtoms, NsoluteAtoms, A_idxs_.size()); if (doOrder_ && NSOLVENT_ < 5) { mprintf("Warning: Less than 5 solvent molecules. Cannot perform order calculation.\n"); doOrder_ = false; } // Allocate space for saving indices of water atoms that are on the grid // Estimate how many solvent molecules can possibly fit onto the grid. // Add some extra voxels as a buffer. double max_voxels = (double)MAX_GRID_PT_ + (1.10 * (double)MAX_GRID_PT_); double totalVolume = max_voxels * gO_->Bin().VoxelVolume(); double max_mols = totalVolume * BULK_DENS_; //mprintf("\tEstimating grid can fit a max of %.0f solvent molecules (w/ 10%% buffer).\n", // max_mols); OnGrid_idxs_.reserve( (size_t)max_mols * (size_t)nMolAtoms_ ); N_ON_GRID_ = 0; if (!skipE_) { if (imageOpt_.ImagingEnabled()) mprintf("\tImaging enabled for energy distance calculations.\n"); else mprintf("\tNo imaging will be performed for energy distance calculations.\n"); } #ifdef CUDA NonbondParmType nb = setup.Top().Nonbond(); this->NBIndex_ = nb.NBindex(); this->numberAtomTypes_ = nb.Ntypes(); for (unsigned int i = 0; i < nb.NBarray().size(); ++i) { this->lJParamsA_.push_back( (float) nb.NBarray().at(i).A() ); this->lJParamsB_.push_back( (float) nb.NBarray().at(i).B() ); } try { allocateCuda(((void**)&this->NBindex_c_), this->NBIndex_.size() * sizeof(int)); allocateCuda((void**)&this->max_c_, 3 * sizeof(float)); allocateCuda((void**)&this->min_c_, 3 * sizeof(float)); allocateCuda((void**)&this->result_w_c_, this->numberAtoms_ * sizeof(float)); allocateCuda((void**)&this->result_s_c_, this->numberAtoms_ * sizeof(float)); allocateCuda((void**)&this->result_O_c_, this->numberAtoms_ * 4 * sizeof(int)); allocateCuda((void**)&this->result_N_c_, this->numberAtoms_ * sizeof(int)); } catch (CudaException &e) { mprinterr("Error: Could not allocate memory on GPU!\n"); this->freeGPUMemory(); return Action::ERR; } try { this->copyToGPU(); } catch (CudaException &e) { return Action::ERR; } #endif gist_setup_.Stop(); return Action::OK; } const Vec3 Action_GIST::x_lab_ = Vec3(1.0, 0.0, 0.0); const Vec3 Action_GIST::y_lab_ = Vec3(0.0, 1.0, 0.0); const Vec3 Action_GIST::z_lab_ = Vec3(0.0, 0.0, 1.0); const double Action_GIST::QFAC_ = Constants::ELECTOAMBER * Constants::ELECTOAMBER; const int Action_GIST::OFF_GRID_ = -1; /* Calculate the charge-charge, vdw interaction using pme, frame by frame * */ void Action_GIST::NonbondEnergy_pme(Frame const& frameIn) { # ifdef LIBPME // Two energy terms for the whole system //double ene_pme_all = 0.0; //double ene_vdw_all = 0.0; // pointer to the E_pme_, where has the voxel-wise pme energy for water double* E_pme_grid = &E_pme_[0]; // pointer to U_E_pme_, where has the voxel-wise pme energy for solute double* U_E_pme_grid = &U_E_pme_[0]; gistPme_.CalcNonbondEnergy_GIST(frameIn, atom_voxel_, atomIsSolute_, atomIsSolventO_, E_UV_VDW_, E_UV_Elec_, E_VV_VDW_, E_VV_Elec_, neighbor_); // system_potential_energy_ += ene_pme_all + ene_vdw_all; // Water energy on the GIST grid double pme_sum = 0.0; for (unsigned int gidx=0; gidx < N_ON_GRID_; gidx++ ) { int a = OnGrid_idxs_[gidx]; // index of the atom of on-grid solvent; int a_voxel = atom_voxel_[a]; // index of the voxel double nonbond_energy = gistPme_.E_of_atom(a); pme_sum += nonbond_energy; E_pme_grid[a_voxel] += nonbond_energy; } // Solute energy on the GIST grid double solute_on_grid_sum = 0.0; // To sum up the potential energy on solute atoms that on the grid for (unsigned int uidx=0; uidx < U_onGrid_idxs_.size(); uidx++ ) { int u = U_onGrid_idxs_[uidx]; // index of the solute atom on the grid int u_voxel = atom_voxel_[u]; double u_nonbond_energy = gistPme_.E_of_atom(u); solute_on_grid_sum += u_nonbond_energy; U_E_pme_grid[u_voxel] += u_nonbond_energy; } /* // Total solute energy double solute_sum = 0.0; for (unsigned int uidx=0; uidx < U_idxs_.size(); uidx++) { int u = U_idxs_[uidx]; double u_nonbond_energy = gistPme_.E_of_atom(u); solute_sum += u_nonbond_energy; solute_potential_energy_ += u_nonbond_energy; // used to calculated the ensemble energy for all solute, will print out in terminal } */ //mprintf("The total potential energy on water atoms: %f \n", pme_sum); # else /*LIBPME */ mprinterr("Error: Compiled without LIBPME\n"); return; # endif /*LIBPME */ } /** Non-bonded energy calc. */ void Action_GIST::Ecalc(double rij2, double q1, double q2, NonbondType const& LJ, double& Evdw, double& Eelec) { double rij = sqrt(rij2); // VDW double r2 = 1.0 / rij2; double r6 = r2 * r2 * r2; double r12 = r6 * r6; double f12 = LJ.A() * r12; // A/r^12 double f6 = LJ.B() * r6; // B/r^6 Evdw = f12 - f6; // (A/r^12)-(B/r^6) // Coulomb double qiqj = QFAC_ * q1 * q2; Eelec = qiqj / rij; } /** Calculate the energy between all solute/solvent atoms and solvent atoms * on the grid. This is done after the intial GIST calculations * so that all waters have voxels assigned in atom_voxel_. * NOTE: This routine modifies the coordinates in OnGrid_XYZ_ when the cell * has nonorthogonal shape in order to properly satsify the minimum * image convention, so any calculations that rely on the on grid * coordinates (like Order()) must be done *BEFORE* this routine. */ void Action_GIST::NonbondEnergy(Frame const& frameIn, Topology const& topIn) { // Set up imaging info. if (imageOpt_.ImagingType() == ImageOption::NONORTHO) { // Wrap on-grid water coords back to primary cell TODO openmp double* ongrid_xyz = &OnGrid_XYZ_[0]; int maxXYZ = (int)OnGrid_XYZ_.size(); int idx; # ifdef _OPENMP # pragma omp parallel private(idx) { # pragma omp for # endif for (idx = 0; idx < maxXYZ; idx += 3) { double* XYZ = ongrid_xyz + idx; // Convert to frac coords frameIn.BoxCrd().FracCell().TimesVec( XYZ, XYZ ); // Wrap to primary cell XYZ[0] = XYZ[0] - floor(XYZ[0]); XYZ[1] = XYZ[1] - floor(XYZ[1]); XYZ[2] = XYZ[2] - floor(XYZ[2]); // Convert back to Cartesian frameIn.BoxCrd().UnitCell().TransposeMult( XYZ, XYZ ); } # ifdef _OPENMP } # endif } // mprintf("DEBUG: NSolventAtoms= %zu NwatAtomsOnGrid= %u\n", O_idxs_.size()*nMolAtoms_, N_ON_GRID_); double* E_UV_VDW = &(E_UV_VDW_[0][0]); double* E_UV_Elec = &(E_UV_Elec_[0][0]); double* E_VV_VDW = &(E_VV_VDW_[0][0]); double* E_VV_Elec = &(E_VV_Elec_[0][0]); float* Neighbor = &(neighbor_[0][0]); double Evdw, Eelec; int aidx; int maxAidx = (int)A_idxs_.size(); // Loop over all solute + solvent atoms # ifdef _OPENMP int mythread; Iarray* eij_v1 = 0; Iarray* eij_v2 = 0; Farray* eij_en = 0; # pragma omp parallel private(aidx, mythread, E_UV_VDW, E_UV_Elec, E_VV_VDW, E_VV_Elec, Neighbor, Evdw, Eelec, eij_v1, eij_v2, eij_en) { mythread = omp_get_thread_num(); E_UV_VDW = &(E_UV_VDW_[mythread][0]); E_UV_Elec = &(E_UV_Elec_[mythread][0]); E_VV_VDW = &(E_VV_VDW_[mythread][0]); E_VV_Elec = &(E_VV_Elec_[mythread][0]); Neighbor = (&neighbor_[mythread][0]); if (doEij_) { eij_v1 = &(EIJ_V1_[mythread]); eij_v2 = &(EIJ_V2_[mythread]); eij_en = &(EIJ_EN_[mythread]); eij_v1->clear(); eij_v2->clear(); eij_en->clear(); } # pragma omp for # endif for (aidx = 0; aidx < maxAidx; aidx++) { int a1 = A_idxs_[aidx]; // Index of atom1 int a1_voxel = atom_voxel_[a1]; // Voxel of atom1 int a1_mol = topIn[ a1 ].MolNum(); // Molecule # of atom 1 Vec3 A1_XYZ( frameIn.XYZ( a1 ) ); // Coord of atom1 double qA1 = topIn[ a1 ].Charge(); // Charge of atom1 bool a1IsO = atomIsSolventO_[a1]; std::vector<Vec3> vImages; if (imageOpt_.ImagingType() == ImageOption::NONORTHO) { // Convert to frac coords Vec3 vFrac = frameIn.BoxCrd().FracCell() * A1_XYZ; // Wrap to primary unit cell vFrac[0] = vFrac[0] - floor(vFrac[0]); vFrac[1] = vFrac[1] - floor(vFrac[1]); vFrac[2] = vFrac[2] - floor(vFrac[2]); // Calculate all images of this atom vImages.reserve(27); for (int ix = -1; ix != 2; ix++) for (int iy = -1; iy != 2; iy++) for (int iz = -1; iz != 2; iz++) // Convert image back to Cartesian vImages.push_back( frameIn.BoxCrd().UnitCell().TransposeMult( vFrac + Vec3(ix,iy,iz) ) ); } // Loop over all solvent atoms on the grid for (unsigned int gidx = 0; gidx < N_ON_GRID_; gidx++) { int a2 = OnGrid_idxs_[gidx]; // Index of on-grid solvent int a2_mol = topIn[ a2 ].MolNum(); // Molecule # of on-grid solvent if (a1_mol != a2_mol) { int a2_voxel = atom_voxel_[a2]; // Voxel of on-grid solvent const double* A2_XYZ = (&OnGrid_XYZ_[0])+gidx*3; // Coord of on-grid solvent if (atomIsSolute_[a1]) { // Solute to on-grid solvent energy // Calculate distance //gist_nonbond_dist_.Start(); double rij2; if (imageOpt_.ImagingType() == ImageOption::NONORTHO) { # ifdef GIST_USE_NONORTHO_DIST2 rij2 = DIST2_ImageNonOrtho(A1_XYZ, A2_XYZ, frameIn.BoxCrd().UnitCell(), frameIn.BoxCrd().FracCell()); # else rij2 = maxD_; for (std::vector<Vec3>::const_iterator vCart = vImages.begin(); vCart != vImages.end(); ++vCart) { double x = (*vCart)[0] - A2_XYZ[0]; double y = (*vCart)[1] - A2_XYZ[1]; double z = (*vCart)[2] - A2_XYZ[2]; rij2 = std::min(rij2, x*x + y*y + z*z); } # endif } else if (imageOpt_.ImagingType() == ImageOption::ORTHO) rij2 = DIST2_ImageOrtho( A1_XYZ, A2_XYZ, frameIn.BoxCrd() ); else rij2 = DIST2_NoImage( A1_XYZ, A2_XYZ ); //gist_nonbond_dist_.Stop(); //gist_nonbond_UV_.Start(); // Calculate energy Ecalc( rij2, qA1, topIn[ a2 ].Charge(), topIn.GetLJparam(a1, a2), Evdw, Eelec ); E_UV_VDW[a2_voxel] += Evdw; E_UV_Elec[a2_voxel] += Eelec; //gist_nonbond_UV_.Stop(); } else { // Off-grid/on-grid solvent to on-grid solvent energy // Only do the energy calculation if not previously done or atom1 not on grid if (a2 != a1 && (a2 > a1 || a1_voxel == OFF_GRID_)) { // Calculate distance //gist_nonbond_dist_.Start(); double rij2; if (imageOpt_.ImagingType() == ImageOption::NONORTHO) { # ifdef GIST_USE_NONORTHO_DIST2 rij2 = DIST2_ImageNonOrtho(A1_XYZ, A2_XYZ, frameIn.BoxCrd().UnitCell(), frameIn.BoxCrd().FracCell()); # else rij2 = maxD_; for (std::vector<Vec3>::const_iterator vCart = vImages.begin(); vCart != vImages.end(); ++vCart) { double x = (*vCart)[0] - A2_XYZ[0]; double y = (*vCart)[1] - A2_XYZ[1]; double z = (*vCart)[2] - A2_XYZ[2]; rij2 = std::min(rij2, x*x + y*y + z*z); } # endif } else if (imageOpt_.ImagingType() == ImageOption::ORTHO) rij2 = DIST2_ImageOrtho( A1_XYZ, A2_XYZ, frameIn.BoxCrd() ); else rij2 = DIST2_NoImage( A1_XYZ, A2_XYZ ); //gist_nonbond_dist_.Stop(); //gist_nonbond_VV_.Start(); // Calculate energy Ecalc( rij2, qA1, topIn[ a2 ].Charge(), topIn.GetLJparam(a1, a2), Evdw, Eelec ); //mprintf("DEBUG1: v1= %i v2= %i EVV %i %i Vdw= %f Elec= %f\n", a2_voxel, a1_voxel, a2, a1, Evdw, Eelec); E_VV_VDW[a2_voxel] += Evdw; E_VV_Elec[a2_voxel] += Eelec; // Store water neighbor using only O-O distance bool is_O_O = (a1IsO && atomIsSolventO_[a2]); if (is_O_O && rij2 < NeighborCut2_) Neighbor[a2_voxel] += 1.0; // If water atom1 was also on the grid update its energy as well. if ( a1_voxel != OFF_GRID_ ) { E_VV_VDW[a1_voxel] += Evdw; E_VV_Elec[a1_voxel] += Eelec; if (is_O_O && rij2 < NeighborCut2_) Neighbor[a1_voxel] += 1.0; if (doEij_) { if (a1_voxel != a2_voxel) { # ifdef _OPENMP eij_v1->push_back( a1_voxel ); eij_v2->push_back( a2_voxel ); eij_en->push_back( Evdw + Eelec ); # else ww_Eij_->UpdateElement(a1_voxel, a2_voxel, Evdw + Eelec); # endif } } } //gist_nonbond_VV_.Stop(); } } } // END a1 and a2 not in same molecule } // End loop over all solvent atoms on grid } // End loop over all solvent + solute atoms # ifdef _OPENMP } // END pragma omp parallel if (doEij_) { // Add any Eijs to matrix for (unsigned int thread = 0; thread != EIJ_V1_.size(); thread++) for (unsigned int idx = 0; idx != EIJ_V1_[thread].size(); idx++) ww_Eij_->UpdateElement(EIJ_V1_[thread][idx], EIJ_V2_[thread][idx], EIJ_EN_[thread][idx]); } # endif } /** GIST order calculation. */ void Action_GIST::Order(Frame const& frameIn) { // Loop over all solvent molecules that are on the grid for (unsigned int gidx = 0; gidx < N_ON_GRID_; gidx += nMolAtoms_) { int oidx1 = OnGrid_idxs_[gidx]; int voxel1 = atom_voxel_[oidx1]; Vec3 XYZ1( (&OnGrid_XYZ_[0])+gidx*3 ); // Find coordinates for 4 closest neighbors to this water (on or off grid). // TODO set up overall grid in DoAction. // TODO initialize WAT? Vec3 WAT[4]; double d1 = maxD_; double d2 = maxD_; double d3 = maxD_; double d4 = maxD_; for (unsigned int sidx2 = 0; sidx2 < NSOLVENT_; sidx2++) { int oidx2 = O_idxs_[sidx2]; if (oidx2 != oidx1) { const double* XYZ2 = frameIn.XYZ( oidx2 ); double dist2 = DIST2_NoImage( XYZ1.Dptr(), XYZ2 ); if (dist2 < d1) { d4 = d3; d3 = d2; d2 = d1; d1 = dist2; WAT[3] = WAT[2]; WAT[2] = WAT[1]; WAT[1] = WAT[0]; WAT[0] = XYZ2; } else if (dist2 < d2) { d4 = d3; d3 = d2; d2 = dist2; WAT[3] = WAT[2]; WAT[2] = WAT[1]; WAT[1] = XYZ2; } else if (dist2 < d3) { d4 = d3; d3 = dist2; WAT[3] = WAT[2]; WAT[2] = XYZ2; } else if (dist2 < d4) { d4 = dist2; WAT[3] = XYZ2; } } } // Compute the tetrahedral order parameter double sum = 0.0; for (int mol1 = 0; mol1 < 3; mol1++) { for (int mol2 = mol1 + 1; mol2 < 4; mol2++) { Vec3 v1 = WAT[mol1] - XYZ1; Vec3 v2 = WAT[mol2] - XYZ1; double r1 = v1.Magnitude2(); double r2 = v2.Magnitude2(); double cos = (v1* v2) / sqrt(r1 * r2); sum += (cos + 1.0/3)*(cos + 1.0/3); } } order_norm_->UpdateVoxel(voxel1, (1.0 - (3.0/8)*sum)); //mprintf("DBG: gidx= %u oidx1=%i voxel1= %i XYZ1={%g, %g, %g} sum= %g\n", gidx, oidx1, voxel1, XYZ1[0], XYZ1[1], XYZ1[2], sum); } // END loop over all solvent molecules } /** GIST action */ Action::RetType Action_GIST::DoAction(int frameNum, ActionFrame& frm) { gist_action_.Start(); NFRAME_++; // TODO only !skipE? N_ON_GRID_ = 0; OnGrid_idxs_.clear(); OnGrid_XYZ_.clear(); // Determine imaging type # ifdef DEBUG_GIST //mprintf("DEBUG: Is_X_Aligned_Ortho() = %i Is_X_Aligned() = %i\n", (int)frm.Frm().BoxCrd().Is_X_Aligned_Ortho(), (int)frm.Frm().BoxCrd().Is_X_Aligned()); frm.Frm().BoxCrd().UnitCell().Print("Ucell"); frm.Frm().BoxCrd().FracCell().Print("Frac"); # endif if (imageOpt_.ImagingEnabled()) imageOpt_.SetImageType( frm.Frm().BoxCrd().Is_X_Aligned_Ortho() ); # ifdef DEBUG_GIST switch (imageOpt_.ImagingType()) { case ImageOption::NO_IMAGE : mprintf("DEBUG: No Image.\n"); break; case ImageOption::ORTHO : mprintf("DEBUG: Orthogonal image.\n"); break; case ImageOption::NONORTHO : mprintf("DEBUG: Nonorthogonal image.\n"); break; } # endif // CUDA necessary information size_t bin_i, bin_j, bin_k; Vec3 const& Origin = gO_->Bin().GridOrigin(); // Loop over each solvent molecule for (unsigned int sidx = 0; sidx < NSOLVENT_; sidx++) { gist_grid_.Start(); int oidx = O_idxs_[sidx]; for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) atom_voxel_[oidx+IDX] = OFF_GRID_; const double* O_XYZ = frm.Frm().XYZ( oidx ); // Get vector of water oxygen to grid origin. Vec3 W_G( O_XYZ[0] - Origin[0], O_XYZ[1] - Origin[1], O_XYZ[2] - Origin[2] ); gist_grid_.Stop(); // Check if water oxygen is no more then 1.5 Ang from grid // NOTE: using <= to be consistent with original code if ( W_G[0] <= G_max_[0] && W_G[0] >= -1.5 && W_G[1] <= G_max_[1] && W_G[1] >= -1.5 && W_G[2] <= G_max_[2] && W_G[2] >= -1.5 ) { const double* H1_XYZ = frm.Frm().XYZ( oidx + 1 ); const double* H2_XYZ = frm.Frm().XYZ( oidx + 2 ); // Try to bin the oxygen if ( gO_->Bin().Calc( O_XYZ[0], O_XYZ[1], O_XYZ[2], bin_i, bin_j, bin_k ) ) { // Oxygen is inside the grid. Record the voxel. // NOTE hydrogens/EP always assigned to same voxel for energy purposes. int voxel = (int)gO_->CalcIndex(bin_i, bin_j, bin_k); const double* wXYZ = O_XYZ; for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) { atom_voxel_[oidx+IDX] = voxel; //OnGrid_idxs_[N_ON_GRID_+IDX] = oidx + IDX; OnGrid_idxs_.push_back( oidx+IDX ); OnGrid_XYZ_.push_back( wXYZ[0] ); OnGrid_XYZ_.push_back( wXYZ[1] ); OnGrid_XYZ_.push_back( wXYZ[2] ); wXYZ+=3; } N_ON_GRID_ += nMolAtoms_; //mprintf("DEBUG1: Water atom %i voxel %i\n", oidx, voxel); N_waters_[voxel]++; max_nwat_ = std::max( N_waters_[voxel], max_nwat_ ); // ----- EULER --------------------------- gist_euler_.Start(); // Record XYZ coords of water atoms (nonEP) in voxel TODO need EP? voxel_xyz_[voxel].push_back( O_XYZ[0] ); voxel_xyz_[voxel].push_back( O_XYZ[1] ); voxel_xyz_[voxel].push_back( O_XYZ[2] ); // Get O-HX vectors Vec3 H1_wat( H1_XYZ[0]-O_XYZ[0], H1_XYZ[1]-O_XYZ[1], H1_XYZ[2]-O_XYZ[2] ); Vec3 H2_wat( H2_XYZ[0]-O_XYZ[0], H2_XYZ[1]-O_XYZ[1], H2_XYZ[2]-O_XYZ[2] ); H1_wat.Normalize(); H2_wat.Normalize(); Vec3 ar1 = H1_wat.Cross( x_lab_ ); // ar1 = V cross U Vec3 sar = ar1; // sar = V cross U ar1.Normalize(); //mprintf("------------------------------------------\n"); //H1_wat.Print("DEBUG: H1_wat"); //x_lab_.Print("DEBUG: x_lab_"); //ar1.Print("DEBUG: ar1"); //sar.Print("DEBUG: sar"); double dp1 = x_lab_ * H1_wat; // V dot U double theta = acos(dp1); double sign = sar * H1_wat; //mprintf("DEBUG0: dp1= %f theta= %f sign= %f\n", dp1, theta, sign); // NOTE: Use SMALL instead of 0 to avoid issues with denormalization if (sign > Constants::SMALL) theta /= 2.0; else theta /= -2.0; double w1 = cos(theta); double sin_theta = sin(theta); //mprintf("DEBUG0: theta= %f w1= %f sin_theta= %f\n", theta, w1, sin_theta); double x1 = ar1[0] * sin_theta; double y1 = ar1[1] * sin_theta; double z1 = ar1[2] * sin_theta; double w2 = w1; double x2 = x1; double y2 = y1; double z2 = z1; Vec3 H_temp; H_temp[0] = ((w2*w2+x2*x2)-(y2*y2+z2*z2))*H1_wat[0]; H_temp[0] = (2*(x2*y2 + w2*z2)*H1_wat[1]) + H_temp[0]; H_temp[0] = (2*(x2*z2-w2*y2)*H1_wat[2]) + H_temp[0]; H_temp[1] = 2*(x2*y2 - w2*z2)* H1_wat[0]; H_temp[1] = ((w2*w2-x2*x2+y2*y2-z2*z2)*H1_wat[1]) + H_temp[1]; H_temp[1] = (2*(y2*z2+w2*x2)*H1_wat[2]) +H_temp[1]; H_temp[2] = 2*(x2*z2+w2*y2) *H1_wat[0]; H_temp[2] = (2*(y2*z2-w2*x2)*H1_wat[1]) + H_temp[2]; H_temp[2] = ((w2*w2-x2*x2-y2*y2+z2*z2)*H1_wat[2]) + H_temp[2]; H1_wat = H_temp; Vec3 H_temp2; H_temp2[0] = ((w2*w2+x2*x2)-(y2*y2+z2*z2))*H2_wat[0]; H_temp2[0] = (2*(x2*y2 + w2*z2)*H2_wat[1]) + H_temp2[0]; H_temp2[0] = (2*(x2*z2-w2*y2)*H2_wat[2]) +H_temp2[0]; H_temp2[1] = 2*(x2*y2 - w2*z2) *H2_wat[0]; H_temp2[1] = ((w2*w2-x2*x2+y2*y2-z2*z2)*H2_wat[1]) +H_temp2[1]; H_temp2[1] = (2*(y2*z2+w2*x2)*H2_wat[2]) +H_temp2[1]; H_temp2[2] = 2*(x2*z2+w2*y2)*H2_wat[0]; H_temp2[2] = (2*(y2*z2-w2*x2)*H2_wat[1]) +H_temp2[2]; H_temp2[2] = ((w2*w2-x2*x2-y2*y2+z2*z2)*H2_wat[2]) + H_temp2[2]; H2_wat = H_temp2; Vec3 ar2 = H_temp.Cross(H_temp2); ar2.Normalize(); double dp2 = ar2 * z_lab_; theta = acos(dp2); sar = ar2.Cross( z_lab_ ); sign = sar * H_temp; if (sign < 0) theta /= 2.0; else theta /= -2.0; double w3 = cos(theta); sin_theta = sin(theta); double x3 = x_lab_[0] * sin_theta; double y3 = x_lab_[1] * sin_theta; double z3 = x_lab_[2] * sin_theta; double w4 = w1*w3 - x1*x3 - y1*y3 - z1*z3; double x4 = w1*x3 + x1*w3 + y1*z3 - z1*y3; double y4 = w1*y3 - x1*z3 + y1*w3 + z1*x3; double z4 = w1*z3 + x1*y3 - y1*x3 + z1*w3; voxel_Q_[voxel].push_back( w4 ); voxel_Q_[voxel].push_back( x4 ); voxel_Q_[voxel].push_back( y4 ); voxel_Q_[voxel].push_back( z4 ); //mprintf("DEBUG1: sidx= %u voxel= %i wxyz4= %g %g %g %g\n", sidx, voxel, w4, x4, y4, z4); //mprintf("DEBUG2: wxyz3= %g %g %g %g wxyz2= %g %g %g %g wxyz1= %g %g %g\n", // w3, x3, y3, z3, // w2, x2, y2, z2, // w1, x1, y1, z1); // NOTE: No need for nw_angle_ here, it is same as N_waters_ gist_euler_.Stop(); // ----- DIPOLE -------------------------- gist_dipole_.Start(); //mprintf("DEBUG1: voxel %i dipole %f %f %f\n", voxel, // O_XYZ[0]*q_O_ + H1_XYZ[0]*q_H1_ + H2_XYZ[0]*q_H2_, // O_XYZ[1]*q_O_ + H1_XYZ[1]*q_H1_ + H2_XYZ[1]*q_H2_, // O_XYZ[2]*q_O_ + H1_XYZ[2]*q_H1_ + H2_XYZ[2]*q_H2_); double DPX = 0.0; double DPY = 0.0; double DPZ = 0.0; for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) { const double* XYZ = frm.Frm().XYZ( oidx+IDX ); DPX += XYZ[0] * Q_[IDX]; DPY += XYZ[1] * Q_[IDX]; DPZ += XYZ[2] * Q_[IDX]; } dipolex_->UpdateVoxel(voxel, DPX); dipoley_->UpdateVoxel(voxel, DPY); dipolez_->UpdateVoxel(voxel, DPZ); gist_dipole_.Stop(); // --------------------------------------- } // Water is at most 1.5A away from grid, so we need to check for H // even if O is outside grid. if (gO_->Bin().Calc( H1_XYZ[0], H1_XYZ[1], H1_XYZ[2], bin_i, bin_j, bin_k ) ) N_hydrogens_[ (int)gO_->CalcIndex(bin_i, bin_j, bin_k) ]++; if (gO_->Bin().Calc( H2_XYZ[0], H2_XYZ[1], H2_XYZ[2], bin_i, bin_j, bin_k ) ) N_hydrogens_[ (int)gO_->CalcIndex(bin_i, bin_j, bin_k) ]++; } // END water is within 1.5 Ang of grid } // END loop over each solvent molecule // Do solute grid assignment for PME if (usePme_) { U_onGrid_idxs_.clear(); gist_grid_.Start(); for (unsigned int s = 0; s != U_idxs_.size(); s++) { int uidx = U_idxs_[s]; // the solute atom index atom_voxel_[uidx] = OFF_GRID_; const double* u_XYZ = frm.Frm().XYZ( uidx ); // get the vector of this solute atom to the grid origin Vec3 U_G( u_XYZ[0] - Origin[0], u_XYZ[1] - Origin[1], u_XYZ[2] - Origin[2]); //size_t bin_i, bin_j, bin_k; if ( U_G[0] <= G_max_[0] && U_G[0] >= -1.5 && U_G[1] <= G_max_[1] && U_G[1] >= -1.5 && U_G[2] <= G_max_[2] && U_G[2] >- -1.5) { if ( gO_->Bin().Calc(u_XYZ[0],u_XYZ[1],u_XYZ[2],bin_i,bin_j,bin_k)) // used the gO class function to calcaute voxel index { int voxel = (int)gO_->CalcIndex(bin_i,bin_j,bin_k); atom_voxel_[uidx] = voxel; // asign the voxel index to the solute atom //U_ON_GRID_ +=1; // add +1 to the number of atom on the GIST Grid N_solute_atoms_[voxel] +=1; // add +1 to the solute atom num in this voxel U_onGrid_idxs_.push_back(uidx); // The index of the solute atom on GIST Grid } } } gist_grid_.Stop(); } # ifndef CUDA // Do order calculation if requested. // Do not do this for CUDA since CUDA nonbond routine handles the order calc. // NOTE: This has to be done before the nonbond energy calc since // the nonbond calc can modify the on-grid coordinates (for minimum // image convention when cell is non-orthogonal). gist_order_.Start(); if (doOrder_) Order(frm.Frm()); gist_order_.Stop(); # endif // Do nonbond energy calc if not skipping energy gist_nonbond_.Start(); if (!skipE_) { if (usePme_) { // PME NonbondEnergy_pme( frm.Frm() ); } else { // Non-PME # ifdef CUDA NonbondCuda(frm); # else NonbondEnergy(frm.Frm(), *CurrentParm_); # endif } } gist_nonbond_.Stop(); gist_action_.Stop(); return Action::OK; } /** Translational entropy calc between given water and all waters in voxel 2. * \param VX voxel 1 water X * \param VY voxel 1 water Y * \param VZ voxel 1 water Z * \param W4 voxel 1 water W4 * \param X4 voxel 1 water X4 * \param Y4 voxel 1 water Y4 * \param Z4 voxel 1 water Z4 * \param voxel2 Index of second voxel */ void Action_GIST::TransEntropy(float VX, float VY, float VZ, float W4, float X4, float Y4, float Z4, int voxel2, double& NNd, double& NNs) const { int nw_tot = N_waters_[voxel2]; Farray const& V_XYZ = voxel_xyz_[voxel2]; Farray const& V_Q = voxel_Q_[voxel2]; for (int n1 = 0; n1 != nw_tot; n1++) { int i1 = n1 * 3; // index into V_XYZ for n1 double dx = (double)(VX - V_XYZ[i1 ]); double dy = (double)(VY - V_XYZ[i1+1]); double dz = (double)(VZ - V_XYZ[i1+2]); double dd = dx*dx+dy*dy+dz*dz; if (dd < NNd && dd > 0) { NNd = dd; } int q1 = n1 * 4; // index into V_Q for n1 double rR = 2.0 * acos( fabs(W4 * V_Q[q1 ] + X4 * V_Q[q1+1] + Y4 * V_Q[q1+2] + Z4 * V_Q[q1+3] )); //add fabs for quaternions distance calculation double ds = rR*rR + dd; if (ds < NNs && ds > 0) { NNs = ds; } } } // Action_GIST::SumEVV() void Action_GIST::SumEVV() { if (E_VV_VDW_.size() > 1) { for (unsigned int gr_pt = 0; gr_pt != MAX_GRID_PT_; gr_pt++) { for (unsigned int thread = 1; thread < E_VV_VDW_.size(); thread++) { E_UV_VDW_[0][gr_pt] += E_UV_VDW_[thread][gr_pt]; E_UV_Elec_[0][gr_pt] += E_UV_Elec_[thread][gr_pt]; E_VV_VDW_[0][gr_pt] += E_VV_VDW_[thread][gr_pt]; E_VV_Elec_[0][gr_pt] += E_VV_Elec_[thread][gr_pt]; neighbor_[0][gr_pt] += neighbor_[thread][gr_pt]; } } } } /** Calculate average voxel energy for PME grids. */ void Action_GIST::CalcAvgVoxelEnergy_PME(double Vvox, DataSet_GridFlt& PME_dens, DataSet_GridFlt& U_PME_dens, Farray& PME_norm) const { double PME_tot =0.0; double U_PME_tot = 0.0; mprintf("\t Calculating average voxel energies: \n"); ProgressBar E_progress(MAX_GRID_PT_); for ( unsigned int gr_pt =0; gr_pt < MAX_GRID_PT_; gr_pt++) { E_progress.Update(gr_pt); int nw_total = N_waters_[gr_pt]; if (nw_total >=1) { PME_dens[gr_pt] = E_pme_[gr_pt] / (NFRAME_ * Vvox); PME_norm[gr_pt] = E_pme_[gr_pt] / nw_total; PME_tot += PME_dens[gr_pt]; }else{ PME_dens[gr_pt]=0; PME_norm[gr_pt]=0; } int ns_total = N_solute_atoms_[gr_pt]; if (ns_total >=1) { U_PME_dens[gr_pt] = U_E_pme_[gr_pt] / (NFRAME_ * Vvox); U_PME_tot += U_PME_dens[gr_pt]; }else{ U_PME_dens[gr_pt]=0; } } PME_tot *=Vvox; U_PME_tot *=Vvox; infofile_->Printf("Ensemble total water energy on the grid: %9.5f Kcal/mol \n", PME_tot); infofile_->Printf("Ensemble total solute energy on the grid: %9.5f Kcal/mol \n",U_PME_tot); // infofile_->Printf("Ensemble solute's total potential energy : %9.5f Kcal/mol \n", solute_potential_energy_ / NFRAME_); // infofile_->Printf("Ensemble system's total potential energy: %9.5f Kcal/mol \n", system_potential_energy_/NFRAME_); } /** Calculate average voxel energy for GIST grids. */ void Action_GIST::CalcAvgVoxelEnergy(double Vvox, DataSet_GridFlt& Eww_dens, DataSet_GridFlt& Esw_dens, Farray& Eww_norm, Farray& Esw_norm, DataSet_GridDbl& qtet, DataSet_GridFlt& neighbor_norm, Farray& neighbor_dens) { #ifndef CUDA Darray const& E_UV_VDW = E_UV_VDW_[0]; Darray const& E_UV_Elec = E_UV_Elec_[0]; Darray const& E_VV_VDW = E_VV_VDW_[0]; Darray const& E_VV_Elec = E_VV_Elec_[0]; #endif Farray const& Neighbor = neighbor_[0]; #ifndef CUDA // Sum values from other threads if necessary SumEVV(); #endif double Eswtot = 0.0; double Ewwtot = 0.0; mprintf("\tCalculating average voxel energies:\n"); ProgressBar E_progress( MAX_GRID_PT_ ); for (unsigned int gr_pt = 0; gr_pt < MAX_GRID_PT_; gr_pt++) { E_progress.Update( gr_pt ); //mprintf("DEBUG1: VV vdw=%f elec=%f\n", E_VV_VDW_[gr_pt], E_VV_Elec_[gr_pt]); int nw_total = N_waters_[gr_pt]; // Total number of waters that have been in this voxel. if (nw_total > 0) { #ifndef CUDA Esw_dens[gr_pt] = (E_UV_VDW[gr_pt] + E_UV_Elec[gr_pt]) / (NFRAME_ * Vvox); Esw_norm[gr_pt] = (E_UV_VDW[gr_pt] + E_UV_Elec[gr_pt]) / nw_total; Eww_dens[gr_pt] = (E_VV_VDW[gr_pt] + E_VV_Elec[gr_pt]) / (2 * NFRAME_ * Vvox); Eww_norm[gr_pt] = (E_VV_VDW[gr_pt] + E_VV_Elec[gr_pt]) / (2 * nw_total); #else double esw = this->Esw_->operator[](gr_pt); double eww = this->Eww_->operator[](gr_pt); Esw_dens[gr_pt] = esw / (this->NFRAME_ * Vvox); Esw_norm[gr_pt] = esw / nw_total; Eww_dens[gr_pt] = eww / (this->NFRAME_ * Vvox); Eww_norm[gr_pt] = eww / nw_total; #endif Eswtot += Esw_dens[gr_pt]; Ewwtot += Eww_dens[gr_pt]; } else { Esw_dens[gr_pt]=0; Esw_norm[gr_pt]=0; Eww_norm[gr_pt]=0; Eww_dens[gr_pt]=0; } // Compute the average number of water neighbor and average order parameter. if (nw_total > 0) { qtet[gr_pt] /= nw_total; //mprintf("DEBUG1: neighbor= %8.1f nw_total= %8i\n", neighbor[gr_pt], nw_total); neighbor_norm[gr_pt] = (double)Neighbor[gr_pt] / nw_total; } neighbor_dens[gr_pt] = (double)Neighbor[gr_pt] / (NFRAME_ * Vvox); } // END loop over all grid points (voxels) Eswtot *= Vvox; Ewwtot *= Vvox; infofile_->Printf("Total water-solute energy of the grid: Esw = %9.5f kcal/mol\n", Eswtot); infofile_->Printf("Total unreferenced water-water energy of the grid: Eww = %9.5f kcal/mol\n", Ewwtot); } /** Handle averaging for grids and output from GIST. */ void Action_GIST::Print() { gist_print_.Start(); double Vvox = gO_->Bin().VoxelVolume(); mprintf(" GIST OUTPUT:\n"); // The variables are kept outside, so that they are declared for later use. // Calculate orientational entropy DataSet_GridFlt& dTSorient_dens = static_cast<DataSet_GridFlt&>( *dTSorient_ ); Farray dTSorient_norm( MAX_GRID_PT_, 0.0 ); double dTSorienttot = 0; int nwtt = 0; double dTSo = 0; if (! this->skipS_) { // LOOP over all voxels mprintf("\tCalculating orientational entropy:\n"); ProgressBar oe_progress( MAX_GRID_PT_ ); for (unsigned int gr_pt = 0; gr_pt < MAX_GRID_PT_; gr_pt++) { oe_progress.Update( gr_pt ); dTSorient_dens[gr_pt] = 0; dTSorient_norm[gr_pt] = 0; int nw_total = N_waters_[gr_pt]; // Total number of waters that have been in this voxel. nwtt += nw_total; //mprintf("DEBUG1: %u nw_total %i\n", gr_pt, nw_total); if (nw_total > 1) { for (int n0 = 0; n0 < nw_total; n0++) { double NNr = 10000; int q0 = n0 * 4; // Index into voxel_Q_ for n0 for (int n1 = 0; n1 < nw_total; n1++) { if (n0 != n1) { int q1 = n1 * 4; // Index into voxel_Q_ for n1 //mprintf("DEBUG1:\t\t q1= %8i {%12.4f %12.4f %12.4f %12.4f} q0= %8i {%12.4f %12.4f %12.4f %12.4f}\n", // q1, voxel_Q_[gr_pt][q1 ], voxel_Q_[gr_pt][q1+1], voxel_Q_[gr_pt][q1+2], voxel_Q_[gr_pt][q1+3], // q0, voxel_Q_[gr_pt][q0 ], voxel_Q_[gr_pt][q0+1], voxel_Q_[gr_pt][q0+2], voxel_Q_[gr_pt][q0+3]); double rR = 2.0 * acos( fabs(voxel_Q_[gr_pt][q1 ] * voxel_Q_[gr_pt][q0 ] + voxel_Q_[gr_pt][q1+1] * voxel_Q_[gr_pt][q0+1] + voxel_Q_[gr_pt][q1+2] * voxel_Q_[gr_pt][q0+2] + voxel_Q_[gr_pt][q1+3] * voxel_Q_[gr_pt][q0+3] )); // add fabs for quaternion distance calculation //mprintf("DEBUG1:\t\t %8i %8i %g\n", n0, n1, rR); if (rR > 0 && rR < NNr) NNr = rR; } } // END inner loop over all waters for this voxel if (NNr < 9999 && NNr > 0) { double dbl = log(NNr*NNr*NNr*nw_total / (3.0*Constants::TWOPI)); //mprintf("DEBUG1: %u nw_total= %i NNr= %f dbl= %f\n", gr_pt, nw_total, NNr, dbl); dTSorient_norm[gr_pt] += dbl; dTSo += dbl; } } // END outer loop over all waters for this voxel //mprintf("DEBUG1: dTSorient_norm %f\n", dTSorient_norm[gr_pt]); dTSorient_norm[gr_pt] = Constants::GASK_KCAL * temperature_ * ((dTSorient_norm[gr_pt]/nw_total) + Constants::EULER_MASC); double dtso_norm_nw = (double)dTSorient_norm[gr_pt] * (double)nw_total; dTSorient_dens[gr_pt] = (dtso_norm_nw / (NFRAME_ * Vvox)); dTSorienttot += dTSorient_dens[gr_pt]; //mprintf("DEBUG1: %f\n", dTSorienttot); } } // END loop over all grid points (voxels) dTSorienttot *= Vvox; infofile_->Printf("Maximum number of waters found in one voxel for %d frames = %d\n", NFRAME_, max_nwat_); infofile_->Printf("Total referenced orientational entropy of the grid:" " dTSorient = %9.5f kcal/mol, Nf=%d\n", dTSorienttot, NFRAME_); } // Compute translational entropy for each voxel double dTStranstot = 0.0; double dTSt = 0.0; double dTSs = 0.0; int nwts = 0; unsigned int nx = gO_->NX(); unsigned int ny = gO_->NY(); unsigned int nz = gO_->NZ(); unsigned int addx = ny * nz; unsigned int addy = nz; unsigned int addz = 1; DataSet_GridFlt& gO = static_cast<DataSet_GridFlt&>( *gO_ ); DataSet_GridFlt& gH = static_cast<DataSet_GridFlt&>( *gH_ ); DataSet_GridFlt& dTStrans = static_cast<DataSet_GridFlt&>( *dTStrans_ ); DataSet_GridFlt& dTSsix = static_cast<DataSet_GridFlt&>( *dTSsix_ ); Farray dTStrans_norm( MAX_GRID_PT_, 0.0 ); Farray dTSsix_norm( MAX_GRID_PT_, 0.0 ); // Loop over all grid points if (! this->skipS_) mprintf("\tCalculating translational entropy:\n"); else mprintf("Calculating Densities:\n"); ProgressBar te_progress( MAX_GRID_PT_ ); for (unsigned int gr_pt = 0; gr_pt < MAX_GRID_PT_; gr_pt++) { te_progress.Update( gr_pt ); int numplane = gr_pt / addx; double W_dens = 1.0 * N_waters_[gr_pt] / (NFRAME_*Vvox); gO[gr_pt] = W_dens / BULK_DENS_; gH[gr_pt] = 1.0 * N_hydrogens_[gr_pt] / (NFRAME_*Vvox*2*BULK_DENS_); if (! this->skipS_) { int nw_total = N_waters_[gr_pt]; // Total number of waters that have been in this voxel. for (int n0 = 0; n0 < nw_total; n0++) { double NNd = 10000; double NNs = 10000; int i0 = n0 * 3; // index into voxel_xyz_ for n0 float VX = voxel_xyz_[gr_pt][i0 ]; float VY = voxel_xyz_[gr_pt][i0+1]; float VZ = voxel_xyz_[gr_pt][i0+2]; int q0 = n0 * 4; // index into voxel_Q_ for n0 float W4 = voxel_Q_[gr_pt][q0 ]; float X4 = voxel_Q_[gr_pt][q0+1]; float Y4 = voxel_Q_[gr_pt][q0+2]; float Z4 = voxel_Q_[gr_pt][q0+3]; // First do own voxel for (int n1 = 0; n1 < nw_total; n1++) { if ( n1 != n0) { int i1 = n1 * 3; // index into voxel_xyz_ for n1 double dx = (double)(VX - voxel_xyz_[gr_pt][i1 ]); double dy = (double)(VY - voxel_xyz_[gr_pt][i1+1]); double dz = (double)(VZ - voxel_xyz_[gr_pt][i1+2]); double dd = dx*dx+dy*dy+dz*dz; if (dd < NNd && dd > 0) { NNd = dd; } int q1 = n1 * 4; // index into voxel_Q_ for n1 double rR = 2 * acos( fabs(W4*voxel_Q_[gr_pt][q1 ] + X4*voxel_Q_[gr_pt][q1+1] + Y4*voxel_Q_[gr_pt][q1+2] + Z4*voxel_Q_[gr_pt][q1+3] )); //add fabs for quaternion distance calculation double ds = rR*rR + dd; if (ds < NNs && ds > 0) { NNs = ds; } } } // END self loop over all waters for this voxel //mprintf("DEBUG1: self NNd=%f NNs=%f\n", NNd, NNs); // Determine which directions are possible. bool cannotAddZ = (nz == 0 || ( gr_pt%nz == nz-1 )); bool cannotAddY = ((nz == 0 || ny-1 == 0) || ( gr_pt%(nz*(ny-1)+(numplane*addx)) < nz)); bool cannotAddX = (gr_pt >= addx * (nx-1) && gr_pt < addx * nx ); bool cannotSubZ = (nz == 0 || gr_pt%nz == 0); bool cannotSubY = ((nz == 0 || ny == 0) || (gr_pt%addx < nz)); bool cannotSubX = ((nz == 0 || ny == 0) || (gr_pt < addx)); bool boundary = ( cannotAddZ || cannotAddY || cannotAddX || cannotSubZ || cannotSubY || cannotSubX ); if (!boundary) { TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addz, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addy, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addx, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addz, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addy, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addx, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addz + addy, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addz - addy, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addz + addy, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addz - addy, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addz + addx, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addz - addx, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addz + addx, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addz - addx, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addy + addx, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addy - addx, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addy + addx, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addy - addx, NNd, NNs); // add the 8 more voxels for NNr searching TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addx + addy + addz, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addx + addy - addz, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addx - addy + addz, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addx - addy - addz, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addx + addy + addz, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addx + addy - addz, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addx - addy + addz, NNd, NNs); TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addx - addy - addz, NNd, NNs); NNd = sqrt(NNd); NNs = sqrt(NNs); if (NNd < 3 && NNd > 0/*NNd < 9999 && NNd > 0*/) { double dbl = log((NNd*NNd*NNd*NFRAME_*4*Constants::PI*BULK_DENS_)/3); dTStrans_norm[gr_pt] += dbl; dTSt += dbl; dbl = log((NNs*NNs*NNs*NNs*NNs*NNs*NFRAME_*Constants::PI*BULK_DENS_)/48); dTSsix_norm[gr_pt] += dbl; dTSs += dbl; //mprintf("DEBUG1: dbl=%f NNs=%f\n", dbl, NNs); } } } // END loop over all waters for this voxel if (dTStrans_norm[gr_pt] != 0) { nwts += nw_total; dTStrans_norm[gr_pt] = Constants::GASK_KCAL*temperature_*( (dTStrans_norm[gr_pt]/nw_total) + Constants::EULER_MASC ); dTSsix_norm[gr_pt] = Constants::GASK_KCAL*temperature_*( (dTSsix_norm[gr_pt]/nw_total) + Constants::EULER_MASC ); } double dtst_norm_nw = (double)dTStrans_norm[gr_pt] * (double)nw_total; dTStrans[gr_pt] = (dtst_norm_nw / (NFRAME_*Vvox)); double dtss_norm_nw = (double)dTSsix_norm[gr_pt] * (double)nw_total; dTSsix[gr_pt] = (dtss_norm_nw / (NFRAME_*Vvox)); dTStranstot += dTStrans[gr_pt]; } // END loop over all grid points (voxels) } if (!this->skipS_) { dTStranstot *= Vvox; double dTSst = 0.0; double dTStt = 0.0; if (nwts > 0) { dTSst = Constants::GASK_KCAL*temperature_*((dTSs/nwts) + Constants::EULER_MASC); dTStt = Constants::GASK_KCAL*temperature_*((dTSt/nwts) + Constants::EULER_MASC); } double dTSot = Constants::GASK_KCAL*temperature_*((dTSo/nwtt) + Constants::EULER_MASC); infofile_->Printf("watcount in vol = %d\n", nwtt); infofile_->Printf("watcount in subvol = %d\n", nwts); infofile_->Printf("Total referenced translational entropy of the grid:" " dTStrans = %9.5f kcal/mol, Nf=%d\n", dTStranstot, NFRAME_); infofile_->Printf("Total 6d if all one vox: %9.5f kcal/mol\n", dTSst); infofile_->Printf("Total t if all one vox: %9.5f kcal/mol\n", dTStt); infofile_->Printf("Total o if all one vox: %9.5f kcal/mol\n", dTSot); } // Compute average voxel energy. Allocate these sets even if skipping energy // to be consistent with previous output. DataSet_GridFlt& PME_dens = static_cast<DataSet_GridFlt&>( *PME_); DataSet_GridFlt& U_PME_dens = static_cast<DataSet_GridFlt&>( *U_PME_); DataSet_GridFlt& Esw_dens = static_cast<DataSet_GridFlt&>( *Esw_ ); DataSet_GridFlt& Eww_dens = static_cast<DataSet_GridFlt&>( *Eww_ ); DataSet_GridFlt& neighbor_norm = static_cast<DataSet_GridFlt&>( *neighbor_norm_ ); DataSet_GridDbl& qtet = static_cast<DataSet_GridDbl&>( *order_norm_ ); Farray Esw_norm( MAX_GRID_PT_, 0.0 ); Farray Eww_norm( MAX_GRID_PT_, 0.0 ); Farray PME_norm( MAX_GRID_PT_,0.0); Farray neighbor_dens( MAX_GRID_PT_, 0.0 ); if (!skipE_) { if (usePme_) { CalcAvgVoxelEnergy_PME(Vvox, PME_dens, U_PME_dens, PME_norm); }// else { CalcAvgVoxelEnergy(Vvox, Eww_dens, Esw_dens, Eww_norm, Esw_norm, qtet, neighbor_norm, neighbor_dens); //} } // Compute average dipole density. DataSet_GridFlt& pol = static_cast<DataSet_GridFlt&>( *dipole_ ); DataSet_GridDbl& dipolex = static_cast<DataSet_GridDbl&>( *dipolex_ ); DataSet_GridDbl& dipoley = static_cast<DataSet_GridDbl&>( *dipoley_ ); DataSet_GridDbl& dipolez = static_cast<DataSet_GridDbl&>( *dipolez_ ); for (unsigned int gr_pt = 0; gr_pt < MAX_GRID_PT_; gr_pt++) { dipolex[gr_pt] /= (Constants::DEBYE_EA * NFRAME_ * Vvox); dipoley[gr_pt] /= (Constants::DEBYE_EA * NFRAME_ * Vvox); dipolez[gr_pt] /= (Constants::DEBYE_EA * NFRAME_ * Vvox); pol[gr_pt] = sqrt( dipolex[gr_pt]*dipolex[gr_pt] + dipoley[gr_pt]*dipoley[gr_pt] + dipolez[gr_pt]*dipolez[gr_pt] ); } // Write the GIST output file. // TODO: Make a data file format? if (datafile_ != 0) { mprintf("\tWriting GIST results for each voxel:\n"); // Create the format strings. std::string fmtstr = intFmt_.Fmt() + // grid point " " + fltFmt_.Fmt() + // grid X " " + fltFmt_.Fmt() + // grid Y " " + fltFmt_.Fmt() + // grid Z " " + intFmt_.Fmt() + // # waters " " + fltFmt_.Fmt() + // gO " " + fltFmt_.Fmt() + // gH " " + fltFmt_.Fmt() + // dTStrans " " + fltFmt_.Fmt() + // dTStrans_norm " " + fltFmt_.Fmt() + // dTSorient_dens " " + fltFmt_.Fmt() + // dTSorient_norm " " + fltFmt_.Fmt() + // dTSsix " " + fltFmt_.Fmt() + // dTSsix_norm " " + fltFmt_.Fmt() + // Esw_dens " " + fltFmt_.Fmt() + // Esw_norm " " + fltFmt_.Fmt() + // Eww_dens " " + fltFmt_.Fmt(); // EWW_norm if (usePme_) { fmtstr += " " + fltFmt_.Fmt() + // PME_dens + " " + fltFmt_.Fmt(); // PME_norm } fmtstr += " " + fltFmt_.Fmt() + // dipolex " " + fltFmt_.Fmt() + // dipoley " " + fltFmt_.Fmt() + // dipolez " " + fltFmt_.Fmt() + // pol " " + fltFmt_.Fmt() + // neighbor_dens " " + fltFmt_.Fmt() + // neighbor_norm " " + fltFmt_.Fmt() + // qtet " \n"; // NEWLINE if (debug_ > 0) mprintf("DEBUG: Fmt='%s'\n", fmtstr.c_str()); const char* gistOutputVersion; if (usePme_) gistOutputVersion = "v3"; else gistOutputVersion = "v2"; // Do the header datafile_->Printf("GIST Output %s " "spacing=%.4f center=%.6f,%.6f,%.6f dims=%i,%i,%i \n" "voxel xcoord ycoord zcoord population g_O g_H" " dTStrans-dens(kcal/mol/A^3) dTStrans-norm(kcal/mol)" " dTSorient-dens(kcal/mol/A^3) dTSorient-norm(kcal/mol)" " dTSsix-dens(kcal/mol/A^3) dTSsix-norm(kcal/mol)" " Esw-dens(kcal/mol/A^3) Esw-norm(kcal/mol)" " Eww-dens(kcal/mol/A^3) Eww-norm-unref(kcal/mol)", gistOutputVersion, gridspacing_, gridcntr_[0], gridcntr_[1], gridcntr_[2], (int)griddim_[0], (int)griddim_[1], (int)griddim_[2]); if (usePme_) datafile_->Printf(" PME-dens(kcal/mol/A^3) PME-norm(kcal/mol)"); datafile_->Printf(" Dipole_x-dens(D/A^3) Dipole_y-dens(D/A^3) Dipole_z-dens(D/A^3)" " Dipole-dens(D/A^3) neighbor-dens(1/A^3) neighbor-norm order-norm\n"); // Loop over voxels ProgressBar O_progress( MAX_GRID_PT_ ); for (unsigned int gr_pt = 0; gr_pt < MAX_GRID_PT_; gr_pt++) { O_progress.Update( gr_pt ); size_t i, j, k; gO_->ReverseIndex( gr_pt, i, j, k ); Vec3 XYZ = gO_->Bin().Center( i, j, k ); if (usePme_) { datafile_->Printf(fmtstr.c_str(), gr_pt, XYZ[0], XYZ[1], XYZ[2], N_waters_[gr_pt], gO[gr_pt], gH[gr_pt], dTStrans[gr_pt], dTStrans_norm[gr_pt], dTSorient_dens[gr_pt], dTSorient_norm[gr_pt], dTSsix[gr_pt], dTSsix_norm[gr_pt], Esw_dens[gr_pt], Esw_norm[gr_pt], Eww_dens[gr_pt], Eww_norm[gr_pt], PME_dens[gr_pt], PME_norm[gr_pt], dipolex[gr_pt], dipoley[gr_pt], dipolez[gr_pt], pol[gr_pt], neighbor_dens[gr_pt], neighbor_norm[gr_pt], qtet[gr_pt]); } else { datafile_->Printf(fmtstr.c_str(), gr_pt, XYZ[0], XYZ[1], XYZ[2], N_waters_[gr_pt], gO[gr_pt], gH[gr_pt], dTStrans[gr_pt], dTStrans_norm[gr_pt], dTSorient_dens[gr_pt], dTSorient_norm[gr_pt], dTSsix[gr_pt], dTSsix_norm[gr_pt], Esw_dens[gr_pt], Esw_norm[gr_pt], Eww_dens[gr_pt], Eww_norm[gr_pt], dipolex[gr_pt], dipoley[gr_pt], dipolez[gr_pt], pol[gr_pt], neighbor_dens[gr_pt], neighbor_norm[gr_pt], qtet[gr_pt]); } } // END loop over voxels } // END datafile_ not null // Write water-water interaction energy matrix if (ww_Eij_ != 0) { DataSet_MatrixFlt& ww_Eij = static_cast<DataSet_MatrixFlt&>( *ww_Eij_ ); double fac = 1.0 / (double)(NFRAME_ * 2); for (unsigned int idx = 0; idx != ww_Eij.Size(); idx++) { if (fabs(ww_Eij[idx]) < Constants::SMALL) ww_Eij[idx] = 0.0; else { double val = (double)ww_Eij[idx]; ww_Eij[idx] = (float)(val * fac); } } // Eij matrix output, skip any zeros. for (unsigned int a = 1; a < MAX_GRID_PT_; a++) { for (unsigned int l = 0; l < a; l++) { double dbl = ww_Eij_->GetElement(a, l); if (dbl != 0) eijfile_->Printf("%10d %10d %12.5E\n", a, l, dbl); } } } gist_print_.Stop(); double total = gist_init_.Total() + gist_setup_.Total() + gist_action_.Total() + gist_print_.Total(); mprintf("\tGIST timings:\n"); gist_init_.WriteTiming(1, "Init: ", total); gist_setup_.WriteTiming(1, "Setup: ", total); gist_action_.WriteTiming(1, "Action:", total); gist_grid_.WriteTiming(2, "Grid: ", gist_action_.Total()); gist_nonbond_.WriteTiming(2, "Nonbond:", gist_action_.Total()); # ifdef LIBPME if (usePme_) gistPme_.Timing( gist_nonbond_.Total() ); # endif //gist_nonbond_dist_.WriteTiming(3, "Dist2:", gist_nonbond_.Total()); //gist_nonbond_UV_.WriteTiming(3, "UV:", gist_nonbond_.Total()); //gist_nonbond_VV_.WriteTiming(3, "VV:", gist_nonbond_.Total()); //gist_nonbond_OV_.WriteTiming(3, "OV:", gist_nonbond_.Total()); gist_euler_.WriteTiming(2, "Euler: ", gist_action_.Total()); gist_dipole_.WriteTiming(2, "Dipole: ", gist_action_.Total()); gist_order_.WriteTiming(2, "Order: ", gist_action_.Total()); gist_print_.WriteTiming(1, "Print:", total); mprintf("TIME:\tTotal: %.4f s\n", total); #ifdef CUDA this->freeGPUMemory(); #endif } #ifdef CUDA void Action_GIST::NonbondCuda(ActionFrame frm) { // Simply to get the information for the energetic calculations std::vector<float> eww_result(this->numberAtoms_); std::vector<float> esw_result(this->numberAtoms_); std::vector<std::vector<int> > order_indices; this->gist_nonbond_.Start(); float *recip = NULL; float *ucell = NULL; int boxinfo; // Check Boxinfo and write the necessary data into recip, ucell and boxinfo. switch(imageOpt_.ImagingType()) { case ImageOption::NONORTHO: recip = new float[9]; ucell = new float[9]; for (int i = 0; i < 9; ++i) { ucell[i] = (float) frm.Frm().BoxCrd().UnitCell()[i]; recip[i] = (float) frm.Frm().BoxCrd().FracCell()[i]; } boxinfo = 2; break; case ImageOption::ORTHO: recip = new float[9]; recip[0] = frm.Frm().BoxCrd().Param(Box::X); recip[1] = frm.Frm().BoxCrd().Param(Box::Y); recip[2] = frm.Frm().BoxCrd().Param(Box::Z); ucell = NULL; boxinfo = 1; break; case ImageOption::NO_IMAGE: recip = NULL; ucell = NULL; boxinfo = 0; break; default: mprinterr("Error: Unexpected box information found."); return; } std::vector<int> result_o = std::vector<int>(4 * this->numberAtoms_); std::vector<int> result_n = std::vector<int>(this->numberAtoms_); // Call the GPU Wrapper, which subsequently calls the kernel, after setup operations. // Must create arrays from the vectors, does that by getting the address of the first element of the vector. std::vector<std::vector<float> > e_result = doActionCudaEnergy(frm.Frm().xAddress(), this->NBindex_c_, this->numberAtomTypes_, this->paramsLJ_c_, this->molecule_c_, boxinfo, recip, ucell, this->numberAtoms_, this->min_c_, this->max_c_, this->headAtomType_,this->NeighborCut2_, &(result_o[0]), &(result_n[0]), this->result_w_c_, this->result_s_c_, this->result_O_c_, this->result_N_c_, this->doOrder_); eww_result = e_result.at(0); esw_result = e_result.at(1); if (this->doOrder_) { int counter = 0; for (unsigned int i = 0; i < (4 * this->numberAtoms_); i += 4) { ++counter; std::vector<int> temp; for (unsigned int j = 0; j < 4; ++j) { temp.push_back(result_o.at(i + j)); } order_indices.push_back(temp); } } delete[] recip; // Free memory delete[] ucell; // Free memory for (unsigned int sidx = 0; sidx < NSOLVENT_; sidx++) { int headAtomIndex = O_idxs_[sidx]; size_t bin_i, bin_j, bin_k; const double *vec = frm.Frm().XYZ(headAtomIndex); int voxel = -1; if (this->gO_->Bin().Calc(vec[0], vec[1], vec[2], bin_i, bin_j, bin_k)) { voxel = this->gO_->CalcIndex(bin_i, bin_j, bin_k); this->neighbor_.at(0).at(voxel) += result_n.at(headAtomIndex); // This is not nice, as it assumes that O is set before the two Hydrogens // might be the case, but is still not nice (in my opinion) for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) { this->Esw_->UpdateVoxel(voxel, esw_result.at(headAtomIndex + IDX)); this->Eww_->UpdateVoxel(voxel, eww_result.at(headAtomIndex + IDX)); } // Order calculation if (this->doOrder_) { double sum = 0; Vec3 cent( frm.Frm().xAddress() + (headAtomIndex) * 3 ); std::vector<Vec3> vectors; switch(imageOpt_.ImagingType()) { case ImageOption::NONORTHO: case ImageOption::ORTHO: { Vec3 vec(frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(0) * 3)); vectors.push_back( MinImagedVec(vec, cent, frm.Frm().BoxCrd().UnitCell(), frm.Frm().BoxCrd().FracCell())); vec = Vec3(frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(1) * 3)); vectors.push_back( MinImagedVec(vec, cent, frm.Frm().BoxCrd().UnitCell(), frm.Frm().BoxCrd().FracCell())); vec = Vec3(frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(2) * 3)); vectors.push_back( MinImagedVec(vec, cent, frm.Frm().BoxCrd().UnitCell(), frm.Frm().BoxCrd().FracCell())); vec = Vec3(frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(3) * 3)); vectors.push_back( MinImagedVec(vec, cent, frm.Frm().BoxCrd().UnitCell(), frm.Frm().BoxCrd().FracCell())); } break; default: vectors.push_back( Vec3( frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(0) * 3) ) - cent ); vectors.push_back( Vec3( frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(1) * 3) ) - cent ); vectors.push_back( Vec3( frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(2) * 3) ) - cent ); vectors.push_back( Vec3( frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(3) * 3) ) - cent ); } for (int i = 0; i < 3; ++i) { for (int j = i + 1; j < 4; ++j) { double cosThet = (vectors.at(i) * vectors.at(j)) / sqrt(vectors.at(i).Magnitude2() * vectors.at(j).Magnitude2()); sum += (cosThet + 1.0/3) * (cosThet + 1.0/3); } } this->order_norm_->UpdateVoxel(voxel, 1.0 - (3.0/8.0) * sum); } } } this->gist_nonbond_.Stop(); } /** * Frees all the Memory on the GPU. */ void Action_GIST::freeGPUMemory(void) { freeCuda(this->NBindex_c_); freeCuda(this->molecule_c_); freeCuda(this->paramsLJ_c_); freeCuda(this->max_c_); freeCuda(this->min_c_); freeCuda(this->result_w_c_); freeCuda(this->result_s_c_); freeCuda(this->result_O_c_); freeCuda(this->result_N_c_); this->NBindex_c_ = NULL; this->molecule_c_ = NULL; this->paramsLJ_c_ = NULL; this->max_c_ = NULL; this->min_c_ = NULL; this->result_w_c_= NULL; this->result_s_c_= NULL; this->result_O_c_ = NULL; this->result_N_c_ = NULL; } /** * Copies data from the CPU to the GPU. * @throws: CudaException */ void Action_GIST::copyToGPU(void) { try { copyMemoryToDevice(&(this->NBIndex_[0]), this->NBindex_c_, this->NBIndex_.size() * sizeof(int)); copyMemoryToDeviceStruct(&(this->charges_[0]), &(this->atomTypes_[0]), this->solvent_, &(this->molecule_[0]), this->numberAtoms_, &(this->molecule_c_), &(this->lJParamsA_[0]), &(this->lJParamsB_[0]), this->lJParamsA_.size(), &(this->paramsLJ_c_)); } catch (CudaException &ce) { this->freeGPUMemory(); mprinterr("Error: Could not copy data to the device.\n"); throw ce; } catch (std::exception &e) { this->freeGPUMemory(); throw e; } } #endif
hainm/cpptraj
src/Action_GIST.cpp
C++
gpl-3.0
83,454
<?php /** * Kiwitrees: Web based Family History software * Copyright (C) 2012 to 2022 kiwitrees.net * * Derived from webtrees (www.webtrees.net) * Copyright (C) 2010 to 2012 webtrees development team * * Derived from PhpGedView (phpgedview.sourceforge.net) * Copyright (C) 2002 to 2010 PGV Development Team * * Kiwitrees 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 Kiwitrees. If not, see <http://www.gnu.org/licenses/>. */ if (!defined('KT_KIWITREES')) { header('HTTP/1.0 403 Forbidden'); exit; } // add new custom_lang table self::exec( "CREATE TABLE IF NOT EXISTS `##custom_lang`(". " custom_lang_id INTEGER NOT NULL AUTO_INCREMENT,". " language VARCHAR(10) NOT NULL,". " standard_text LONGTEXT NOT NULL,". " custom_text LONGTEXT NOT NULL,". " updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,". " PRIMARY KEY (custom_lang_id)". ") COLLATE utf8_unicode_ci ENGINE=InnoDB" ); // Update the version to indicate success KT_Site::preference($schema_name, $next_version);
kiwi3685/kiwitrees
includes/db_schema/db_schema_28_29.php
PHP
gpl-3.0
1,600
<!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 (version 1.7.0_55) on Fri Mar 04 14:41:00 EST 2016 --> <title>ChanceCellInfoFormatter</title> <meta name="date" content="2016-03-04"> <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="ChanceCellInfoFormatter"; } //--> </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/ChanceCellInfoFormatter.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-files/index-1.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/CellInfoFormatter.html" title="interface in edu.towson.cis.cosc603.project2.monopoly.gui"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/FreeParkingCellInfoFormatter.html" title="class in edu.towson.cis.cosc603.project2.monopoly.gui"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?edu/towson/cis/cosc603/project2/monopoly/gui/ChanceCellInfoFormatter.html" target="_top">Frames</a></li> <li><a href="ChanceCellInfoFormatter.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:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</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">edu.towson.cis.cosc603.project2.monopoly.gui</div> <h2 title="Class ChanceCellInfoFormatter" class="title">Class ChanceCellInfoFormatter</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>edu.towson.cis.cosc603.project2.monopoly.gui.ChanceCellInfoFormatter</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/CellInfoFormatter.html" title="interface in edu.towson.cis.cosc603.project2.monopoly.gui">CellInfoFormatter</a></dd> </dl> <hr> <br> <pre>public class <span class="strong">ChanceCellInfoFormatter</span> extends java.lang.Object implements <a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/CellInfoFormatter.html" title="interface in edu.towson.cis.cosc603.project2.monopoly.gui">CellInfoFormatter</a></pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/ChanceCellInfoFormatter.html#CHANCE_CELL_LABEL">CHANCE_CELL_LABEL</a></strong></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ======== 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">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/ChanceCellInfoFormatter.html#ChanceCellInfoFormatter()">ChanceCellInfoFormatter</a></strong>()</code>&nbsp;</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">&nbsp;</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>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/ChanceCellInfoFormatter.html#format(edu.towson.cis.cosc603.project2.monopoly.IOwnable)">format</a></strong>(<a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/IOwnable.html" title="interface in edu.towson.cis.cosc603.project2.monopoly">IOwnable</a>&nbsp;cell)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>equals, 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"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field_detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="CHANCE_CELL_LABEL"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>CHANCE_CELL_LABEL</h4> <pre>public static final&nbsp;java.lang.String CHANCE_CELL_LABEL</pre> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../../constant-values.html#edu.towson.cis.cosc603.project2.monopoly.gui.ChanceCellInfoFormatter.CHANCE_CELL_LABEL">Constant Field Values</a></dd></dl> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="ChanceCellInfoFormatter()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>ChanceCellInfoFormatter</h4> <pre>public&nbsp;ChanceCellInfoFormatter()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="format(edu.towson.cis.cosc603.project2.monopoly.IOwnable)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>format</h4> <pre>public&nbsp;java.lang.String&nbsp;format(<a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/IOwnable.html" title="interface in edu.towson.cis.cosc603.project2.monopoly">IOwnable</a>&nbsp;cell)</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/CellInfoFormatter.html#format(edu.towson.cis.cosc603.project2.monopoly.IOwnable)">format</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/CellInfoFormatter.html" title="interface in edu.towson.cis.cosc603.project2.monopoly.gui">CellInfoFormatter</a></code></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><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/ChanceCellInfoFormatter.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-files/index-1.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/CellInfoFormatter.html" title="interface in edu.towson.cis.cosc603.project2.monopoly.gui"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/FreeParkingCellInfoFormatter.html" title="class in edu.towson.cis.cosc603.project2.monopoly.gui"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?edu/towson/cis/cosc603/project2/monopoly/gui/ChanceCellInfoFormatter.html" target="_top">Frames</a></li> <li><a href="ChanceCellInfoFormatter.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:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
odomin2/ait642-Dominguez-project2-
Task 13 Detect Desing Smells/Monopoly/doc/edu/towson/cis/cosc603/project2/monopoly/gui/ChanceCellInfoFormatter.html
HTML
gpl-3.0
11,799
README ====== `vcert` A web-based certificate authority mangement system built atop OpenSSL. Copyright Alan Viars 2013 Open Source License: MPL See LICENSE.txt Last Updated: November 4, 2013 About ----- `vcert` is a web-based (Django) Certificate Authority (or CA) that uses OpenSSL under the hood. The site DirectCA.org runs vcert. It was built specifically to build x509 certificates compatible with the Direct Project. It is written in Python and Django and can run atop Apache2 or other webserver. `vcert` can be used to manage a trust anchor (i.e. a registration authority or HISP) or a root CA. `vcert` supports revocation via certificate revocation lists (CRLs). A CRL is created for each trust anchor and is published to a URL. This software was designed to assist in testing for compliance with the Direct Project's Applicability Statement. Perhaps you are not working in Health IT at all and are just looking for a simple way to manage certificates. You may well be able to use this project for that purpose. CODE CONTRIBUTIONS & PULL REQUEST WELCOME! Installation Part 1 - Download and Initial Setup ------------------------------------------------ `vcert` has a number of dependencies including OpenSSL, Python, and Django. This software was tested with OpenSSL version 1.0.1, Python 2.7 and Django 1.5. SQLite is the default database and it was tested with SQLite version 3. The following instructions assume Ubuntu 13.04 is the operating system, but it is possible to use others. (If anyone wants to contribute Windows, Mac, or other operating system instructions please do so.) Here is how to get started on Ubuntu 13.04. From the terminal, start by installing OpenSSL. This is likely already installed, but installation instructions are added here for clarity. sudo apt-get install openssl Now install pip and make sure its up to date. sudo apt-get install python-pip sudo pip install --upgrade pip Install git and then clone the master repository. sudo apt-get install git-core git clone https://github.com/videntity/vcert.git Now change into the project's directory. cd vcert Let's install the necessary python libraries including Django from the project's requirements file. sudo pip install -r vcert/requirements.txt Now that Django is installed lets setup our database. Be sure and say yes when asking to create an administrative account as this will be used in the CA's administration. python manage.py syncdb A directory for OpenSSL's CA must be created. We will do so by creating a symbolic link between `/opt/ca` and `vcert/apps/certificates/ca` directories. sudo ln -s vcert/apps/certificates/ca /opt/ Now copy settings_local_example.py to settings_example.py. cp settings_local_example.py settings_example.py You can at this point try out the server at this point with `python manage.py runserver`, but your settings_local.py settings will need to be customized before everything will work as expected. Installation Part 2 - Django Settings ------------------------------------- The file `settings.py` contains default settings, where the file `settings_local.py` add and overwrites what is in `settings.py` via Python imports. One of the main changes is replacing `examaple.com` with your own domain. You'll also want to setup email settings for outgoing email notifications and setup web locations for publishing certificates and CRLs. Certificates and CRLs get published via Amazon Web Service's (AWS) Simple Storage Service (S3) and email notifications are sent via Simple Email Service (SES). The email setup is easily changed, but the certificate and CRL publishing requires S3. `vcert` assumes you create three S3 buckets with "vanity" URLs. They are `ca` for CRLs and the CA's public certificate, `pubcerts` for public certificates issued, and `privcerts` for private certificates. For illustration, if you want to host your CA on the domain `example.com`, then you would create the buckets `ca.example.com`, `privcerts.example.com` and `pubcerts.example.com`. You need to map the DNS entries accordingly to create the "vanity" URL. This is accomplished within AWS management console for S3 and in your DNS provider's website. Please see the in-line comments inside `settings_local.py` for instructions on what the various settings do. Installlation Part 3 - OpenSSL CA Configuration ----------------------------------------------- There are stil a few of items that need to be addressed: Most notably you need to do the following: Create and/or install the root CA's (or subordinate certificate's) private certificate and change settings_local.py accordingly. Here is how to generate a new CA keypair with a password on the pricate key. It assumes the domain `ca.example.com` and uses the configuration file `/opt/ca/conf/ca.example.com.cnf`. Before this next step, you will likely want to make adjustment there such the changing "example.com" to your domain, setting organizational name, city, state, and so on. Here are the step. cd /opt/ca openssl req -nodes -config conf/ca.example.com.cnf -days 7330 -x509 -newkey rsa:4096 -out public/ca.example.com.pem -outform PEM openssl rsa -des3 -in ./private/ca.example.comKey.pem -out ./private/ca.example.comKey.pem You will end up with the CA's public key in '/opt/ca/public' and the private key in '/opt/ca/private'. You need to publish the CA's public certificate and CRL somehere. `ca` (e.g. `ca.example.com`) is a reasonable place. In the above example, we used the configuration file `ca.example.com.cnf`. You can use openssl command line to create the CRL for your CA. Installation Part 4 - Setting up Cron for CRL Updates ------------------------------------------------------- In order to make the CRL updates automatic, we will use cron to execute a script to perform the update. Edit your crontab like so. crontab -r Now add the following line to your cron file. 0 */2 * * * /home/ubuntu/django-apps/vcert/scripts/buildcrl.sh >> /home/ubuntu/crl.log This assumes your `vcert` project is located at `/home/ubuntu/django-apps/vcert/`. and the output of this operation is written to `/home/ubuntu/crl.log`. Adjust these paths to fit your local environment. With this setting we are updating the CRLs every 30 minutes. Note that each "Trust Anchor" has its own CRL. Run the Application ------------------- Now you can run the `vcert` in development mode: python manage.py runserver Production Deployment --------------------- The convention is to deploy `vcert` on server named `console` (e.g. `console.example.com`). Please refer to Django's documentation for more information on deploying Django https://docs.djangoproject.com/en/dev/howto/deployment/ Security -------- `vcert` makes no security claims and is provided AS-IS with NO WARRANTY. Django has a number of security features that 'vcert' uses. It is recommended that you use a unique `SECRET_KEY` and that you host the service on HTTPS using a valid certificate. User authentication is accomplished via django's standard `auth` which uses salted and hashed passwords. In order to enable a user to act as an administraor (i.e. verify/approve certificates) you need to give access to the Django admin to said user. (`http://127.0.0.1:8000/admin` in a development configuration). You can so this in two ways: 1. Make this user a superuser (with access to all models). 2. Set the is_staff flag and enable access on the `Certificate` models. See https://docs.djangoproject.com/en/dev/topics/auth/ for more information on authentication in Django. Operation --------- `vcert` operation is quite simple. Any user with a CA account can create a new "Trust anchor". A trust anchor is the child certificate of the `vcerts` certificate with signing authority. (Remember this is configured in settings_local.py) After the Trust anchor request is made an email is sent to the CA's verifier (`CA_VERIFIER_EMAIL` in`settings_local.py`). What you do for "verification" is up to you. After the verifier verifies the information, then the verifier finds the certificate in question within the Django admin, checks the "verify" box and then clicks save. (How you do verification is up to you). When this happens, certificates are published and an email notification is sent to the person requesting the certificate. Then the user may create leaf nodes off of the Trust Archor from his or her account. These, too, go through the same verification notification and verification process before they may be accessed by the requestor. As written, `vcert` requires an invitation code to create an account. This is accomplished in the Django admin. Click the section that says "Invitations" under "Accounts", then click "Add invitation", then provide an invitation code and the email to which it should be sent. Click "Save" and an email with the code will be sent. Anyone can use the invitation code. In other words, it does not require the new user to use the email in the invitation to register. Happy CA-ing! @aviars
managai/myCert
README.md
Markdown
mpl-2.0
9,189
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% from data import Method %> <% data.new_style_struct("Text", inherited=False, gecko_name="TextReset", additional_methods=[Method("has_underline", "bool"), Method("has_overline", "bool"), Method("has_line_through", "bool")]) %> ${helpers.single_keyword("text-overflow", "clip ellipsis")} ${helpers.single_keyword("unicode-bidi", "normal embed isolate bidi-override isolate-override plaintext")} <%helpers:longhand name="${'text-decoration' if product == 'servo' else 'text-decoration-line'}" custom_cascade="${product == 'servo'}"> use cssparser::ToCss; use std::fmt; use values::computed::ComputedValueAsSpecified; impl ComputedValueAsSpecified for SpecifiedValue {} #[derive(PartialEq, Eq, Copy, Clone, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct SpecifiedValue { pub underline: bool, pub overline: bool, pub line_through: bool, // 'blink' is accepted in the parser but ignored. // Just not blinking the text is a conforming implementation per CSS 2.1. } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut space = false; if self.underline { try!(dest.write_str("underline")); space = true; } if self.overline { if space { try!(dest.write_str(" ")); } try!(dest.write_str("overline")); space = true; } if self.line_through { if space { try!(dest.write_str(" ")); } try!(dest.write_str("line-through")); } Ok(()) } } pub mod computed_value { pub type T = super::SpecifiedValue; #[allow(non_upper_case_globals)] pub const none: T = super::SpecifiedValue { underline: false, overline: false, line_through: false }; } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::none } /// none | [ underline || overline || line-through || blink ] pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { let mut result = SpecifiedValue { underline: false, overline: false, line_through: false, }; if input.try(|input| input.expect_ident_matching("none")).is_ok() { return Ok(result) } let mut blink = false; let mut empty = true; while input.try(|input| { if let Ok(ident) = input.expect_ident() { match_ignore_ascii_case! { ident, "underline" => if result.underline { return Err(()) } else { empty = false; result.underline = true }, "overline" => if result.overline { return Err(()) } else { empty = false; result.overline = true }, "line-through" => if result.line_through { return Err(()) } else { empty = false; result.line_through = true }, "blink" => if blink { return Err(()) } else { empty = false; blink = true }, _ => return Err(()) } } else { return Err(()); } Ok(()) }).is_ok() { } if !empty { Ok(result) } else { Err(()) } } % if product == "servo": fn cascade_property_custom<C: ComputedValues>( _declaration: &PropertyDeclaration, _inherited_style: &C, context: &mut computed::Context<C>, _seen: &mut PropertyBitField, _cacheable: &mut bool, _error_reporter: &mut StdBox<ParseErrorReporter + Send>) { longhands::_servo_text_decorations_in_effect::derive_from_text_decoration(context); } % endif </%helpers:longhand> ${helpers.single_keyword("text-decoration-style", "solid double dotted dashed wavy -moz-none", products="gecko")} ${helpers.predefined_type( "text-decoration-color", "CSSColor", "CSSParserColor::RGBA(RGBA { red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0 })", products="gecko")}
DDEFISHER/servo
components/style/properties/longhand/text.mako.rs
Rust
mpl-2.0
5,071
module.exports = { domain:"messages", locale_data:{ messages:{ "":{ domain:"messages", plural_forms:"nplurals=2; plural=(n != 1);", lang:"el" }, "%(addonName)s %(startSpan)sby %(authorList)s%(endSpan)s":[ "%(addonName)s %(startSpan)s από %(authorList)s%(endSpan)s" ], "Extension Metadata":[ "Μεταδεδομένα επέκτασης" ], Screenshots:[ "Στιγμιότυπα" ], "About this extension":[ "Σχετικά με την επέκταση" ], "Rate your experience":[ "Αξιολογήστε την εμπειρία σας" ], Category:[ "Κατηγορία" ], "Used by":[ "Χρήση από" ], Sentiment:[ "Αίσθηση" ], Back:[ "Πίσω" ], Submit:[ "Υποβολή" ], "Please enter some text":[ "Παρακαλώ εισάγετε κείμενο" ], "Write a review":[ "Γράψτε μια κριτική" ], "Tell the world why you think this extension is fantastic!":[ "Πείτε στον κόσμο γιατί θεωρείτε ότι αυτή η επέκταση είναι φανταστική!" ], "Privacy policy":[ "Πολιτική απορρήτου" ], "Legal notices":[ "Νομικές σημειώσεις" ], "View desktop site":[ "Προβολή ιστοσελίδας για υπολογιστές" ], "Browse in your language":[ "Περιήγηση στη γλώσσα σας" ], "Firefox Add-ons":[ "Πρόσθετα Firefox" ], "How are you enjoying your experience with %(addonName)s?":[ "Απολαμβάνετε την εμπειρία σας με το %(addonName)s;" ], "screenshot %(imageNumber)s of %(totalImages)s":[ "Στιγμιότυπο %(imageNumber)s από %(totalImages)s" ], "Average rating: %(rating)s out of 5":[ "Μέση βαθμολογία: %(rating)s από 5" ], "No ratings":[ "Καμία κριτική" ], "%(users)s user":[ "%(users)s χρήστης", "%(users)s χρήστες" ], "Log out":[ "Αποσύνδεση" ], "Log in/Sign up":[ "Σύνδεση/Εγγραφή" ], "Add-ons for Firefox":[ "Πρόσθετα για το Firefox" ], "What do you want Firefox to do?":[ "Τι θέλετε να κάνει το Firefox;" ], "Block ads":[ "Αποκλεισμός διαφημίσεων" ], Screenshot:[ "Στιγμιότυπο οθόνης" ], "Save stuff":[ "Αποθήκευση στοιχείων" ], "Shop online":[ "Διαδικτυακές αγορές" ], "Be social":[ "Κοινωνικοποίηση" ], "Share stuff":[ "Κοινή χρήση στοιχείων" ], "Browse all extensions":[ "Περιήγηση σε όλες τις επεκτάσεις" ], "How do you want Firefox to look?":[ "Τι εμφάνιση θέλετε να έχει το Firefox;" ], Wild:[ "Άγρια" ], Abstract:[ "Αφηρημένη" ], Fashionable:[ "Μοδάτη" ], Scenic:[ "Σκηνική" ], Sporty:[ "Αθλητική" ], Mystical:[ "Μυστική" ], "Browse all themes":[ "Περιήγηση σε όλα τα θέματα" ], "Downloading %(name)s.":[ "Γίνεται λήψη του %(name)s." ], "Installing %(name)s.":[ "Γίνεται εγκατάσταση του %(name)s." ], "%(name)s is installed and enabled. Click to uninstall.":[ "Το %(name)s έχει εγκατασταθεί και ενεργοποιηθεί. Κάντε κλικ για απεγκατάσταση." ], "%(name)s is disabled. Click to enable.":[ "Το %(name)s έχει απενεργοποιηθεί. Κάντε κλικ για ενεργοποίηση." ], "Uninstalling %(name)s.":[ "Γίνεται απεγκατάσταση του %(name)s." ], "%(name)s is uninstalled. Click to install.":[ "Το %(name)s έχει απεγκατασταθεί. Κάντε κλικ για εγκατάσταση." ], "Install state for %(name)s is unknown.":[ "Η κατάσταση εγκατάστασης για το %(name)s είναι άγνωστη." ], Previous:[ "Προηγούμενη" ], Next:[ "Επόμενη" ], "Page %(currentPage)s of %(totalPages)s":[ "Σελίδα %(currentPage)s από %(totalPages)s" ], "Your search for \"%(query)s\" returned %(count)s result.":[ "Η αναζήτησή σας για το \"%(query)s\" είχε %(count)s αποτέλεσμα.", "Η αναζήτησή σας για το \"%(query)s\" είχε %(count)s αποτελέσματα." ], "Searching...":[ "Αναζήτηση..." ], "No results were found for \"%(query)s\".":[ "Δεν βρέθηκε κανένα αποτέλεσμα για το \"%(query)s\"." ], "Please supply a valid search":[ "Παρακαλώ κάντε μια έγκυρη αναζήτηση" ] } }, _momentDefineLocale:function anonymous() { //! moment.js locale configuration //! locale : Greek [el] //! author : Aggelos Karalias : https://github.com/mehiel ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof define === 'function' && define.amd ? define(['../moment'], factory) : factory(global.moment) }(this, (function (moment) { 'use strict'; function isFunction(input) { return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]'; } var el = moment.defineLocale('el', { monthsNominativeEl : 'Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος'.split('_'), monthsGenitiveEl : 'Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου'.split('_'), months : function (momentToFormat, format) { if (/D/.test(format.substring(0, format.indexOf('MMMM')))) { // if there is a day number before 'MMMM' return this._monthsGenitiveEl[momentToFormat.month()]; } else { return this._monthsNominativeEl[momentToFormat.month()]; } }, monthsShort : 'Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ'.split('_'), weekdays : 'Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο'.split('_'), weekdaysShort : 'Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ'.split('_'), weekdaysMin : 'Κυ_Δε_Τρ_Τε_Πε_Πα_Σα'.split('_'), meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'μμ' : 'ΜΜ'; } else { return isLower ? 'πμ' : 'ΠΜ'; } }, isPM : function (input) { return ((input + '').toLowerCase()[0] === 'μ'); }, meridiemParse : /[ΠΜ]\.?Μ?\.?/i, longDateFormat : { LT : 'h:mm A', LTS : 'h:mm:ss A', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY h:mm A', LLLL : 'dddd, D MMMM YYYY h:mm A' }, calendarEl : { sameDay : '[Σήμερα {}] LT', nextDay : '[Αύριο {}] LT', nextWeek : 'dddd [{}] LT', lastDay : '[Χθες {}] LT', lastWeek : function () { switch (this.day()) { case 6: return '[το προηγούμενο] dddd [{}] LT'; default: return '[την προηγούμενη] dddd [{}] LT'; } }, sameElse : 'L' }, calendar : function (key, mom) { var output = this._calendarEl[key], hours = mom && mom.hours(); if (isFunction(output)) { output = output.apply(mom); } return output.replace('{}', (hours % 12 === 1 ? 'στη' : 'στις')); }, relativeTime : { future : 'σε %s', past : '%s πριν', s : 'λίγα δευτερόλεπτα', m : 'ένα λεπτό', mm : '%d λεπτά', h : 'μία ώρα', hh : '%d ώρες', d : 'μία μέρα', dd : '%d μέρες', M : 'ένας μήνας', MM : '%d μήνες', y : 'ένας χρόνος', yy : '%d χρόνια' }, ordinalParse: /\d{1,2}η/, ordinal: '%dη', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4st is the first week of the year. } }); return el; }))); } }
jasonthomas/addons-frontend
src/locale/el/amo.js
JavaScript
mpl-2.0
8,820
// Copyright Hugh Perkins 2015 hughperkins at gmail // // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. // although this looks a bit odd perhaps, this way we dont need to change the existing // qlearning api much, so dont need to break anything that works already #pragma once #include <stdexcept> #include <iostream> #include <string> #include "qlearning/QLearner.h" #include "trainers/Trainer.h" class ScenarioProxy : public Scenario { public: const int numActions; const int planes; const int size; // float *perception; // NOT owned by us, dont delete // float lastReward; // int thisAction; // bool isReset; ScenarioProxy( int numActions, int planes, int size ) : numActions(numActions), planes(planes), size(size) { } virtual int getPerceptionSize() { return size; } virtual int getPerceptionPlanes() { return planes; } virtual void getPerception( float *perception ) { // perception = this->perception; throw std::runtime_error("getPerception not implemented"); } virtual void reset() { // noop? throw std::runtime_error("reset not implemented"); } virtual int getNumActions() { // std::cout << "numActions: " << numActions << std::endl; return numActions; // throw runtime_error("getNumActions not implemented"); } virtual float act( int index ) { // this->thisAction = index; // return lastReward; throw std::runtime_error("act not implemented"); } virtual bool hasFinished() { // return isReset; throw std::runtime_error("hasFinished not implemented"); } }; // The advantage of this over the original QLearning is that it doesnt do any callbacks // so it should be super-easy to wrap, using Lua, Python, etc ... class QLearner2 { QLearner *qlearner; ScenarioProxy *scenario; NeuralNet *net; // int planes; // int size; // int numActions; public: QLearner2( Trainer *trainer, NeuralNet *net, int numActions, int planes, int size ) : net(net) { scenario = new ScenarioProxy( numActions, planes, size ); qlearner = new QLearner( trainer, scenario, net ); } ~QLearner2() { delete qlearner; delete scenario; } // QLearner2 *setPlanes( int planes ) { // this->planes = planes; // scenario->planes = planes; // return this; // } // QLearner2 *setSize( int size ) { // this->size = size; // scenario->size = size; // return this; // } // QLearner2 *setNumActions( int numActions ) { // this->numActions = numActions; // scenario->numActions = numActions; // return this; // } int step(double lastReward, bool wasReset, float *perception) { // scenario->lastReward = lastReward; // scenario->isReset = isReset; // scenario->perception = currentPerception; int action = qlearner->step( lastReward, wasReset, perception ); return action; } void setLambda( float lambda ) { qlearner->setLambda( lambda ); } void setMaxSamples( int maxSamples ) { qlearner->setMaxSamples( maxSamples ); } void setEpsilon( float epsilon ) { qlearner->setEpsilon( epsilon ); } // void setLearningRate( float learningRate ) { qlearner->setLearningRate( learningRate ); } };
pimms/DeepCL
src/qlearning/QLearner2.h
C
mpl-2.0
3,526
#include <iostream> #include <ifaddrs.h> #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <time.h> #include <syslog.h> #include <dlfcn.h> #include <sys/socket.h> #include <netdb.h> #include <string.h> #include "webserver_api_functions.h" static void termination_handler(int signum) { WebserverShutdownHandler(); } static void sig_pipe_hanler(int signum) { //printf("Sig Pipe\n"); } DEFINE_WEBSOCKET_HANDLER( "TestSocket" , TestSocket ) { switch (signal) { case WEBSOCKET_CONNECT: printf("Websocket API Connect TestSocket : %s \n", guid); break; case WEBSOCKET_DISCONNECT: printf("Websocket API Disconnect TestSocket : %s \n", guid); break; case WEBSOCKET_MSG: printf("Websocket API TestSocket Msg 1 %s\n", msg); WebsocketSendTextFrame(guid, msg, strlen(msg)); break; } } int main(int argc, char **argv) { if (signal(SIGINT, termination_handler) == SIG_IGN ) signal(SIGINT, SIG_IGN); if (signal(SIGHUP, termination_handler) == SIG_IGN ) signal(SIGHUP, SIG_IGN); if (signal(SIGTERM, termination_handler) == SIG_IGN ) signal(SIGTERM, SIG_IGN); if (signal(SIGPIPE, sig_pipe_hanler) == SIG_IGN ) signal(SIGPIPE, SIG_IGN); if (0 == WebserverInit()) { WebserverAddFileDir("", "www"); WebserverConfigSetInt("port",8080); REGISTER_WEBSOCKET_HANDLER ( TestSocket ); WebserverStart(); } WebserverShutdown(); return 0; }
lordrasmus/libcwebui
tests/config_variants/LinuxWebsocketSelect/main.cpp
C++
mpl-2.0
1,502
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* A 32-bit implementation of the NIST P-256 elliptic curve. */ #include <string.h> #include "prtypes.h" #include "mpi.h" #include "mpi-priv.h" #include "ecp.h" typedef PRUint8 u8; typedef PRUint32 u32; typedef PRUint64 u64; /* Our field elements are represented as nine, unsigned 32-bit words. Freebl's * MPI library calls them digits, but here they are called limbs, which is * GMP's terminology. * * The value of an felem (field element) is: * x[0] + (x[1] * 2**29) + (x[2] * 2**57) + ... + (x[8] * 2**228) * * That is, each limb is alternately 29 or 28-bits wide in little-endian * order. * * This means that an felem hits 2**257, rather than 2**256 as we would like. A * 28, 29, ... pattern would cause us to hit 2**256, but that causes problems * when multiplying as terms end up one bit short of a limb which would require * much bit-shifting to correct. * * Finally, the values stored in an felem are in Montgomery form. So the value * |y| is stored as (y*R) mod p, where p is the P-256 prime and R is 2**257. */ typedef u32 limb; #define NLIMBS 9 typedef limb felem[NLIMBS]; static const limb kBottom28Bits = 0xfffffff; static const limb kBottom29Bits = 0x1fffffff; /* kOne is the number 1 as an felem. It's 2**257 mod p split up into 29 and * 28-bit words. */ static const felem kOne = { 2, 0, 0, 0xffff800, 0x1fffffff, 0xfffffff, 0x1fbfffff, 0x1ffffff, 0 }; static const felem kZero = {0}; static const felem kP = { 0x1fffffff, 0xfffffff, 0x1fffffff, 0x3ff, 0, 0, 0x200000, 0xf000000, 0xfffffff }; static const felem k2P = { 0x1ffffffe, 0xfffffff, 0x1fffffff, 0x7ff, 0, 0, 0x400000, 0xe000000, 0x1fffffff }; /* kPrecomputed contains precomputed values to aid the calculation of scalar * multiples of the base point, G. It's actually two, equal length, tables * concatenated. * * The first table contains (x,y) felem pairs for 16 multiples of the base * point, G. * * Index | Index (binary) | Value * 0 | 0000 | 0G (all zeros, omitted) * 1 | 0001 | G * 2 | 0010 | 2**64G * 3 | 0011 | 2**64G + G * 4 | 0100 | 2**128G * 5 | 0101 | 2**128G + G * 6 | 0110 | 2**128G + 2**64G * 7 | 0111 | 2**128G + 2**64G + G * 8 | 1000 | 2**192G * 9 | 1001 | 2**192G + G * 10 | 1010 | 2**192G + 2**64G * 11 | 1011 | 2**192G + 2**64G + G * 12 | 1100 | 2**192G + 2**128G * 13 | 1101 | 2**192G + 2**128G + G * 14 | 1110 | 2**192G + 2**128G + 2**64G * 15 | 1111 | 2**192G + 2**128G + 2**64G + G * * The second table follows the same style, but the terms are 2**32G, * 2**96G, 2**160G, 2**224G. * * This is ~2KB of data. */ static const limb kPrecomputed[NLIMBS * 2 * 15 * 2] = { 0x11522878, 0xe730d41, 0xdb60179, 0x4afe2ff, 0x12883add, 0xcaddd88, 0x119e7edc, 0xd4a6eab, 0x3120bee, 0x1d2aac15, 0xf25357c, 0x19e45cdd, 0x5c721d0, 0x1992c5a5, 0xa237487, 0x154ba21, 0x14b10bb, 0xae3fe3, 0xd41a576, 0x922fc51, 0x234994f, 0x60b60d3, 0x164586ae, 0xce95f18, 0x1fe49073, 0x3fa36cc, 0x5ebcd2c, 0xb402f2f, 0x15c70bf, 0x1561925c, 0x5a26704, 0xda91e90, 0xcdc1c7f, 0x1ea12446, 0xe1ade1e, 0xec91f22, 0x26f7778, 0x566847e, 0xa0bec9e, 0x234f453, 0x1a31f21a, 0xd85e75c, 0x56c7109, 0xa267a00, 0xb57c050, 0x98fb57, 0xaa837cc, 0x60c0792, 0xcfa5e19, 0x61bab9e, 0x589e39b, 0xa324c5, 0x7d6dee7, 0x2976e4b, 0x1fc4124a, 0xa8c244b, 0x1ce86762, 0xcd61c7e, 0x1831c8e0, 0x75774e1, 0x1d96a5a9, 0x843a649, 0xc3ab0fa, 0x6e2e7d5, 0x7673a2a, 0x178b65e8, 0x4003e9b, 0x1a1f11c2, 0x7816ea, 0xf643e11, 0x58c43df, 0xf423fc2, 0x19633ffa, 0x891f2b2, 0x123c231c, 0x46add8c, 0x54700dd, 0x59e2b17, 0x172db40f, 0x83e277d, 0xb0dd609, 0xfd1da12, 0x35c6e52, 0x19ede20c, 0xd19e0c0, 0x97d0f40, 0xb015b19, 0x449e3f5, 0xe10c9e, 0x33ab581, 0x56a67ab, 0x577734d, 0x1dddc062, 0xc57b10d, 0x149b39d, 0x26a9e7b, 0xc35df9f, 0x48764cd, 0x76dbcca, 0xca4b366, 0xe9303ab, 0x1a7480e7, 0x57e9e81, 0x1e13eb50, 0xf466cf3, 0x6f16b20, 0x4ba3173, 0xc168c33, 0x15cb5439, 0x6a38e11, 0x73658bd, 0xb29564f, 0x3f6dc5b, 0x53b97e, 0x1322c4c0, 0x65dd7ff, 0x3a1e4f6, 0x14e614aa, 0x9246317, 0x1bc83aca, 0xad97eed, 0xd38ce4a, 0xf82b006, 0x341f077, 0xa6add89, 0x4894acd, 0x9f162d5, 0xf8410ef, 0x1b266a56, 0xd7f223, 0x3e0cb92, 0xe39b672, 0x6a2901a, 0x69a8556, 0x7e7c0, 0x9b7d8d3, 0x309a80, 0x1ad05f7f, 0xc2fb5dd, 0xcbfd41d, 0x9ceb638, 0x1051825c, 0xda0cf5b, 0x812e881, 0x6f35669, 0x6a56f2c, 0x1df8d184, 0x345820, 0x1477d477, 0x1645db1, 0xbe80c51, 0xc22be3e, 0xe35e65a, 0x1aeb7aa0, 0xc375315, 0xf67bc99, 0x7fdd7b9, 0x191fc1be, 0x61235d, 0x2c184e9, 0x1c5a839, 0x47a1e26, 0xb7cb456, 0x93e225d, 0x14f3c6ed, 0xccc1ac9, 0x17fe37f3, 0x4988989, 0x1a90c502, 0x2f32042, 0xa17769b, 0xafd8c7c, 0x8191c6e, 0x1dcdb237, 0x16200c0, 0x107b32a1, 0x66c08db, 0x10d06a02, 0x3fc93, 0x5620023, 0x16722b27, 0x68b5c59, 0x270fcfc, 0xfad0ecc, 0xe5de1c2, 0xeab466b, 0x2fc513c, 0x407f75c, 0xbaab133, 0x9705fe9, 0xb88b8e7, 0x734c993, 0x1e1ff8f, 0x19156970, 0xabd0f00, 0x10469ea7, 0x3293ac0, 0xcdc98aa, 0x1d843fd, 0xe14bfe8, 0x15be825f, 0x8b5212, 0xeb3fb67, 0x81cbd29, 0xbc62f16, 0x2b6fcc7, 0xf5a4e29, 0x13560b66, 0xc0b6ac2, 0x51ae690, 0xd41e271, 0xf3e9bd4, 0x1d70aab, 0x1029f72, 0x73e1c35, 0xee70fbc, 0xad81baf, 0x9ecc49a, 0x86c741e, 0xfe6be30, 0x176752e7, 0x23d416, 0x1f83de85, 0x27de188, 0x66f70b8, 0x181cd51f, 0x96b6e4c, 0x188f2335, 0xa5df759, 0x17a77eb6, 0xfeb0e73, 0x154ae914, 0x2f3ec51, 0x3826b59, 0xb91f17d, 0x1c72949, 0x1362bf0a, 0xe23fddf, 0xa5614b0, 0xf7d8f, 0x79061, 0x823d9d2, 0x8213f39, 0x1128ae0b, 0xd095d05, 0xb85c0c2, 0x1ecb2ef, 0x24ddc84, 0xe35e901, 0x18411a4a, 0xf5ddc3d, 0x3786689, 0x52260e8, 0x5ae3564, 0x542b10d, 0x8d93a45, 0x19952aa4, 0x996cc41, 0x1051a729, 0x4be3499, 0x52b23aa, 0x109f307e, 0x6f5b6bb, 0x1f84e1e7, 0x77a0cfa, 0x10c4df3f, 0x25a02ea, 0xb048035, 0xe31de66, 0xc6ecaa3, 0x28ea335, 0x2886024, 0x1372f020, 0xf55d35, 0x15e4684c, 0xf2a9e17, 0x1a4a7529, 0xcb7beb1, 0xb2a78a1, 0x1ab21f1f, 0x6361ccf, 0x6c9179d, 0xb135627, 0x1267b974, 0x4408bad, 0x1cbff658, 0xe3d6511, 0xc7d76f, 0x1cc7a69, 0xe7ee31b, 0x54fab4f, 0x2b914f, 0x1ad27a30, 0xcd3579e, 0xc50124c, 0x50daa90, 0xb13f72, 0xb06aa75, 0x70f5cc6, 0x1649e5aa, 0x84a5312, 0x329043c, 0x41c4011, 0x13d32411, 0xb04a838, 0xd760d2d, 0x1713b532, 0xbaa0c03, 0x84022ab, 0x6bcf5c1, 0x2f45379, 0x18ae070, 0x18c9e11e, 0x20bca9a, 0x66f496b, 0x3eef294, 0x67500d2, 0xd7f613c, 0x2dbbeb, 0xb741038, 0xe04133f, 0x1582968d, 0xbe985f7, 0x1acbc1a, 0x1a6a939f, 0x33e50f6, 0xd665ed4, 0xb4b7bd6, 0x1e5a3799, 0x6b33847, 0x17fa56ff, 0x65ef930, 0x21dc4a, 0x2b37659, 0x450fe17, 0xb357b65, 0xdf5efac, 0x15397bef, 0x9d35a7f, 0x112ac15f, 0x624e62e, 0xa90ae2f, 0x107eecd2, 0x1f69bbe, 0x77d6bce, 0x5741394, 0x13c684fc, 0x950c910, 0x725522b, 0xdc78583, 0x40eeabb, 0x1fde328a, 0xbd61d96, 0xd28c387, 0x9e77d89, 0x12550c40, 0x759cb7d, 0x367ef34, 0xae2a960, 0x91b8bdc, 0x93462a9, 0xf469ef, 0xb2e9aef, 0xd2ca771, 0x54e1f42, 0x7aaa49, 0x6316abb, 0x2413c8e, 0x5425bf9, 0x1bed3e3a, 0xf272274, 0x1f5e7326, 0x6416517, 0xea27072, 0x9cedea7, 0x6e7633, 0x7c91952, 0xd806dce, 0x8e2a7e1, 0xe421e1a, 0x418c9e1, 0x1dbc890, 0x1b395c36, 0xa1dc175, 0x1dc4ef73, 0x8956f34, 0xe4b5cf2, 0x1b0d3a18, 0x3194a36, 0x6c2641f, 0xe44124c, 0xa2f4eaa, 0xa8c25ba, 0xf927ed7, 0x627b614, 0x7371cca, 0xba16694, 0x417bc03, 0x7c0a7e3, 0x9c35c19, 0x1168a205, 0x8b6b00d, 0x10e3edc9, 0x9c19bf2, 0x5882229, 0x1b2b4162, 0xa5cef1a, 0x1543622b, 0x9bd433e, 0x364e04d, 0x7480792, 0x5c9b5b3, 0xe85ff25, 0x408ef57, 0x1814cfa4, 0x121b41b, 0xd248a0f, 0x3b05222, 0x39bb16a, 0xc75966d, 0xa038113, 0xa4a1769, 0x11fbc6c, 0x917e50e, 0xeec3da8, 0x169d6eac, 0x10c1699, 0xa416153, 0xf724912, 0x15cd60b7, 0x4acbad9, 0x5efc5fa, 0xf150ed7, 0x122b51, 0x1104b40a, 0xcb7f442, 0xfbb28ff, 0x6ac53ca, 0x196142cc, 0x7bf0fa9, 0x957651, 0x4e0f215, 0xed439f8, 0x3f46bd5, 0x5ace82f, 0x110916b6, 0x6db078, 0xffd7d57, 0xf2ecaac, 0xca86dec, 0x15d6b2da, 0x965ecc9, 0x1c92b4c2, 0x1f3811, 0x1cb080f5, 0x2d8b804, 0x19d1c12d, 0xf20bd46, 0x1951fa7, 0xa3656c3, 0x523a425, 0xfcd0692, 0xd44ddc8, 0x131f0f5b, 0xaf80e4a, 0xcd9fc74, 0x99bb618, 0x2db944c, 0xa673090, 0x1c210e1, 0x178c8d23, 0x1474383, 0x10b8743d, 0x985a55b, 0x2e74779, 0x576138, 0x9587927, 0x133130fa, 0xbe05516, 0x9f4d619, 0xbb62570, 0x99ec591, 0xd9468fe, 0x1d07782d, 0xfc72e0b, 0x701b298, 0x1863863b, 0x85954b8, 0x121a0c36, 0x9e7fedf, 0xf64b429, 0x9b9d71e, 0x14e2f5d8, 0xf858d3a, 0x942eea8, 0xda5b765, 0x6edafff, 0xa9d18cc, 0xc65e4ba, 0x1c747e86, 0xe4ea915, 0x1981d7a1, 0x8395659, 0x52ed4e2, 0x87d43b7, 0x37ab11b, 0x19d292ce, 0xf8d4692, 0x18c3053f, 0x8863e13, 0x4c146c0, 0x6bdf55a, 0x4e4457d, 0x16152289, 0xac78ec2, 0x1a59c5a2, 0x2028b97, 0x71c2d01, 0x295851f, 0x404747b, 0x878558d, 0x7d29aa4, 0x13d8341f, 0x8daefd7, 0x139c972d, 0x6b7ea75, 0xd4a9dde, 0xff163d8, 0x81d55d7, 0xa5bef68, 0xb7b30d8, 0xbe73d6f, 0xaa88141, 0xd976c81, 0x7e7a9cc, 0x18beb771, 0xd773cbd, 0x13f51951, 0x9d0c177, 0x1c49a78, }; /* Field element operations: */ /* NON_ZERO_TO_ALL_ONES returns: * 0xffffffff for 0 < x <= 2**31 * 0 for x == 0 or x > 2**31. * * x must be a u32 or an equivalent type such as limb. */ #define NON_ZERO_TO_ALL_ONES(x) ((((u32)(x) - 1) >> 31) - 1) /* felem_reduce_carry adds a multiple of p in order to cancel |carry|, * which is a term at 2**257. * * On entry: carry < 2**3, inout[0,2,...] < 2**29, inout[1,3,...] < 2**28. * On exit: inout[0,2,..] < 2**30, inout[1,3,...] < 2**29. */ static void felem_reduce_carry(felem inout, limb carry) { const u32 carry_mask = NON_ZERO_TO_ALL_ONES(carry); inout[0] += carry << 1; inout[3] += 0x10000000 & carry_mask; /* carry < 2**3 thus (carry << 11) < 2**14 and we added 2**28 in the * previous line therefore this doesn't underflow. */ inout[3] -= carry << 11; inout[4] += (0x20000000 - 1) & carry_mask; inout[5] += (0x10000000 - 1) & carry_mask; inout[6] += (0x20000000 - 1) & carry_mask; inout[6] -= carry << 22; /* This may underflow if carry is non-zero but, if so, we'll fix it in the * next line. */ inout[7] -= 1 & carry_mask; inout[7] += carry << 25; } /* felem_sum sets out = in+in2. * * On entry, in[i]+in2[i] must not overflow a 32-bit word. * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29 */ static void felem_sum(felem out, const felem in, const felem in2) { limb carry = 0; unsigned int i; for (i = 0;; i++) { out[i] = in[i] + in2[i]; out[i] += carry; carry = out[i] >> 29; out[i] &= kBottom29Bits; i++; if (i == NLIMBS) break; out[i] = in[i] + in2[i]; out[i] += carry; carry = out[i] >> 28; out[i] &= kBottom28Bits; } felem_reduce_carry(out, carry); } #define two31m3 (((limb)1) << 31) - (((limb)1) << 3) #define two30m2 (((limb)1) << 30) - (((limb)1) << 2) #define two30p13m2 (((limb)1) << 30) + (((limb)1) << 13) - (((limb)1) << 2) #define two31m2 (((limb)1) << 31) - (((limb)1) << 2) #define two31p24m2 (((limb)1) << 31) + (((limb)1) << 24) - (((limb)1) << 2) #define two30m27m2 (((limb)1) << 30) - (((limb)1) << 27) - (((limb)1) << 2) /* zero31 is 0 mod p. */ static const felem zero31 = { two31m3, two30m2, two31m2, two30p13m2, two31m2, two30m2, two31p24m2, two30m27m2, two31m2 }; /* felem_diff sets out = in-in2. * * On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29 and * in2[0,2,...] < 2**30, in2[1,3,...] < 2**29. * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */ static void felem_diff(felem out, const felem in, const felem in2) { limb carry = 0; unsigned int i; for (i = 0;; i++) { out[i] = in[i] - in2[i]; out[i] += zero31[i]; out[i] += carry; carry = out[i] >> 29; out[i] &= kBottom29Bits; i++; if (i == NLIMBS) break; out[i] = in[i] - in2[i]; out[i] += zero31[i]; out[i] += carry; carry = out[i] >> 28; out[i] &= kBottom28Bits; } felem_reduce_carry(out, carry); } /* felem_reduce_degree sets out = tmp/R mod p where tmp contains 64-bit words * with the same 29,28,... bit positions as an felem. * * The values in felems are in Montgomery form: x*R mod p where R = 2**257. * Since we just multiplied two Montgomery values together, the result is * x*y*R*R mod p. We wish to divide by R in order for the result also to be * in Montgomery form. * * On entry: tmp[i] < 2**64 * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29 */ static void felem_reduce_degree(felem out, u64 tmp[17]) { /* The following table may be helpful when reading this code: * * Limb number: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10... * Width (bits): 29| 28| 29| 28| 29| 28| 29| 28| 29| 28| 29 * Start bit: 0 | 29| 57| 86|114|143|171|200|228|257|285 * (odd phase): 0 | 28| 57| 85|114|142|171|199|228|256|285 */ limb tmp2[18], carry, x, xMask; unsigned int i; /* tmp contains 64-bit words with the same 29,28,29-bit positions as an * felem. So the top of an element of tmp might overlap with another * element two positions down. The following loop eliminates this * overlap. */ tmp2[0] = tmp[0] & kBottom29Bits; /* In the following we use "(limb) tmp[x]" and "(limb) (tmp[x]>>32)" to try * and hint to the compiler that it can do a single-word shift by selecting * the right register rather than doing a double-word shift and truncating * afterwards. */ tmp2[1] = ((limb) tmp[0]) >> 29; tmp2[1] |= (((limb) (tmp[0] >> 32)) << 3) & kBottom28Bits; tmp2[1] += ((limb) tmp[1]) & kBottom28Bits; carry = tmp2[1] >> 28; tmp2[1] &= kBottom28Bits; for (i = 2; i < 17; i++) { tmp2[i] = ((limb) (tmp[i - 2] >> 32)) >> 25; tmp2[i] += ((limb) (tmp[i - 1])) >> 28; tmp2[i] += (((limb) (tmp[i - 1] >> 32)) << 4) & kBottom29Bits; tmp2[i] += ((limb) tmp[i]) & kBottom29Bits; tmp2[i] += carry; carry = tmp2[i] >> 29; tmp2[i] &= kBottom29Bits; i++; if (i == 17) break; tmp2[i] = ((limb) (tmp[i - 2] >> 32)) >> 25; tmp2[i] += ((limb) (tmp[i - 1])) >> 29; tmp2[i] += (((limb) (tmp[i - 1] >> 32)) << 3) & kBottom28Bits; tmp2[i] += ((limb) tmp[i]) & kBottom28Bits; tmp2[i] += carry; carry = tmp2[i] >> 28; tmp2[i] &= kBottom28Bits; } tmp2[17] = ((limb) (tmp[15] >> 32)) >> 25; tmp2[17] += ((limb) (tmp[16])) >> 29; tmp2[17] += (((limb) (tmp[16] >> 32)) << 3); tmp2[17] += carry; /* Montgomery elimination of terms: * * Since R is 2**257, we can divide by R with a bitwise shift if we can * ensure that the right-most 257 bits are all zero. We can make that true * by adding multiplies of p without affecting the value. * * So we eliminate limbs from right to left. Since the bottom 29 bits of p * are all ones, then by adding tmp2[0]*p to tmp2 we'll make tmp2[0] == 0. * We can do that for 8 further limbs and then right shift to eliminate the * extra factor of R. */ for (i = 0;; i += 2) { tmp2[i + 1] += tmp2[i] >> 29; x = tmp2[i] & kBottom29Bits; xMask = NON_ZERO_TO_ALL_ONES(x); tmp2[i] = 0; /* The bounds calculations for this loop are tricky. Each iteration of * the loop eliminates two words by adding values to words to their * right. * * The following table contains the amounts added to each word (as an * offset from the value of i at the top of the loop). The amounts are * accounted for from the first and second half of the loop separately * and are written as, for example, 28 to mean a value <2**28. * * Word: 3 4 5 6 7 8 9 10 * Added in top half: 28 11 29 21 29 28 * 28 29 * 29 * Added in bottom half: 29 10 28 21 28 28 * 29 * * The value that is currently offset 7 will be offset 5 for the next * iteration and then offset 3 for the iteration after that. Therefore * the total value added will be the values added at 7, 5 and 3. * * The following table accumulates these values. The sums at the bottom * are written as, for example, 29+28, to mean a value < 2**29+2**28. * * Word: 3 4 5 6 7 8 9 10 11 12 13 * 28 11 10 29 21 29 28 28 28 28 28 * 29 28 11 28 29 28 29 28 29 28 * 29 28 21 21 29 21 29 21 * 10 29 28 21 28 21 28 * 28 29 28 29 28 29 28 * 11 10 29 10 29 10 * 29 28 11 28 11 * 29 29 * -------------------------------------------- * 30+ 31+ 30+ 31+ 30+ * 28+ 29+ 28+ 29+ 21+ * 21+ 28+ 21+ 28+ 10 * 10 21+ 10 21+ * 11 11 * * So the greatest amount is added to tmp2[10] and tmp2[12]. If * tmp2[10/12] has an initial value of <2**29, then the maximum value * will be < 2**31 + 2**30 + 2**28 + 2**21 + 2**11, which is < 2**32, * as required. */ tmp2[i + 3] += (x << 10) & kBottom28Bits; tmp2[i + 4] += (x >> 18); tmp2[i + 6] += (x << 21) & kBottom29Bits; tmp2[i + 7] += x >> 8; /* At position 200, which is the starting bit position for word 7, we * have a factor of 0xf000000 = 2**28 - 2**24. */ tmp2[i + 7] += 0x10000000 & xMask; /* Word 7 is 28 bits wide, so the 2**28 term exactly hits word 8. */ tmp2[i + 8] += (x - 1) & xMask; tmp2[i + 7] -= (x << 24) & kBottom28Bits; tmp2[i + 8] -= x >> 4; tmp2[i + 8] += 0x20000000 & xMask; tmp2[i + 8] -= x; tmp2[i + 8] += (x << 28) & kBottom29Bits; tmp2[i + 9] += ((x >> 1) - 1) & xMask; if (i+1 == NLIMBS) break; tmp2[i + 2] += tmp2[i + 1] >> 28; x = tmp2[i + 1] & kBottom28Bits; xMask = NON_ZERO_TO_ALL_ONES(x); tmp2[i + 1] = 0; tmp2[i + 4] += (x << 11) & kBottom29Bits; tmp2[i + 5] += (x >> 18); tmp2[i + 7] += (x << 21) & kBottom28Bits; tmp2[i + 8] += x >> 7; /* At position 199, which is the starting bit of the 8th word when * dealing with a context starting on an odd word, we have a factor of * 0x1e000000 = 2**29 - 2**25. Since we have not updated i, the 8th * word from i+1 is i+8. */ tmp2[i + 8] += 0x20000000 & xMask; tmp2[i + 9] += (x - 1) & xMask; tmp2[i + 8] -= (x << 25) & kBottom29Bits; tmp2[i + 9] -= x >> 4; tmp2[i + 9] += 0x10000000 & xMask; tmp2[i + 9] -= x; tmp2[i + 10] += (x - 1) & xMask; } /* We merge the right shift with a carry chain. The words above 2**257 have * widths of 28,29,... which we need to correct when copying them down. */ carry = 0; for (i = 0; i < 8; i++) { /* The maximum value of tmp2[i + 9] occurs on the first iteration and * is < 2**30+2**29+2**28. Adding 2**29 (from tmp2[i + 10]) is * therefore safe. */ out[i] = tmp2[i + 9]; out[i] += carry; out[i] += (tmp2[i + 10] << 28) & kBottom29Bits; carry = out[i] >> 29; out[i] &= kBottom29Bits; i++; out[i] = tmp2[i + 9] >> 1; out[i] += carry; carry = out[i] >> 28; out[i] &= kBottom28Bits; } out[8] = tmp2[17]; out[8] += carry; carry = out[8] >> 29; out[8] &= kBottom29Bits; felem_reduce_carry(out, carry); } /* felem_square sets out=in*in. * * On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29. * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */ static void felem_square(felem out, const felem in) { u64 tmp[17]; tmp[0] = ((u64) in[0]) * in[0]; tmp[1] = ((u64) in[0]) * (in[1] << 1); tmp[2] = ((u64) in[0]) * (in[2] << 1) + ((u64) in[1]) * (in[1] << 1); tmp[3] = ((u64) in[0]) * (in[3] << 1) + ((u64) in[1]) * (in[2] << 1); tmp[4] = ((u64) in[0]) * (in[4] << 1) + ((u64) in[1]) * (in[3] << 2) + ((u64) in[2]) * in[2]; tmp[5] = ((u64) in[0]) * (in[5] << 1) + ((u64) in[1]) * (in[4] << 1) + ((u64) in[2]) * (in[3] << 1); tmp[6] = ((u64) in[0]) * (in[6] << 1) + ((u64) in[1]) * (in[5] << 2) + ((u64) in[2]) * (in[4] << 1) + ((u64) in[3]) * (in[3] << 1); tmp[7] = ((u64) in[0]) * (in[7] << 1) + ((u64) in[1]) * (in[6] << 1) + ((u64) in[2]) * (in[5] << 1) + ((u64) in[3]) * (in[4] << 1); /* tmp[8] has the greatest value of 2**61 + 2**60 + 2**61 + 2**60 + 2**60, * which is < 2**64 as required. */ tmp[8] = ((u64) in[0]) * (in[8] << 1) + ((u64) in[1]) * (in[7] << 2) + ((u64) in[2]) * (in[6] << 1) + ((u64) in[3]) * (in[5] << 2) + ((u64) in[4]) * in[4]; tmp[9] = ((u64) in[1]) * (in[8] << 1) + ((u64) in[2]) * (in[7] << 1) + ((u64) in[3]) * (in[6] << 1) + ((u64) in[4]) * (in[5] << 1); tmp[10] = ((u64) in[2]) * (in[8] << 1) + ((u64) in[3]) * (in[7] << 2) + ((u64) in[4]) * (in[6] << 1) + ((u64) in[5]) * (in[5] << 1); tmp[11] = ((u64) in[3]) * (in[8] << 1) + ((u64) in[4]) * (in[7] << 1) + ((u64) in[5]) * (in[6] << 1); tmp[12] = ((u64) in[4]) * (in[8] << 1) + ((u64) in[5]) * (in[7] << 2) + ((u64) in[6]) * in[6]; tmp[13] = ((u64) in[5]) * (in[8] << 1) + ((u64) in[6]) * (in[7] << 1); tmp[14] = ((u64) in[6]) * (in[8] << 1) + ((u64) in[7]) * (in[7] << 1); tmp[15] = ((u64) in[7]) * (in[8] << 1); tmp[16] = ((u64) in[8]) * in[8]; felem_reduce_degree(out, tmp); } /* felem_mul sets out=in*in2. * * On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29 and * in2[0,2,...] < 2**30, in2[1,3,...] < 2**29. * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */ static void felem_mul(felem out, const felem in, const felem in2) { u64 tmp[17]; tmp[0] = ((u64) in[0]) * in2[0]; tmp[1] = ((u64) in[0]) * (in2[1] << 0) + ((u64) in[1]) * (in2[0] << 0); tmp[2] = ((u64) in[0]) * (in2[2] << 0) + ((u64) in[1]) * (in2[1] << 1) + ((u64) in[2]) * (in2[0] << 0); tmp[3] = ((u64) in[0]) * (in2[3] << 0) + ((u64) in[1]) * (in2[2] << 0) + ((u64) in[2]) * (in2[1] << 0) + ((u64) in[3]) * (in2[0] << 0); tmp[4] = ((u64) in[0]) * (in2[4] << 0) + ((u64) in[1]) * (in2[3] << 1) + ((u64) in[2]) * (in2[2] << 0) + ((u64) in[3]) * (in2[1] << 1) + ((u64) in[4]) * (in2[0] << 0); tmp[5] = ((u64) in[0]) * (in2[5] << 0) + ((u64) in[1]) * (in2[4] << 0) + ((u64) in[2]) * (in2[3] << 0) + ((u64) in[3]) * (in2[2] << 0) + ((u64) in[4]) * (in2[1] << 0) + ((u64) in[5]) * (in2[0] << 0); tmp[6] = ((u64) in[0]) * (in2[6] << 0) + ((u64) in[1]) * (in2[5] << 1) + ((u64) in[2]) * (in2[4] << 0) + ((u64) in[3]) * (in2[3] << 1) + ((u64) in[4]) * (in2[2] << 0) + ((u64) in[5]) * (in2[1] << 1) + ((u64) in[6]) * (in2[0] << 0); tmp[7] = ((u64) in[0]) * (in2[7] << 0) + ((u64) in[1]) * (in2[6] << 0) + ((u64) in[2]) * (in2[5] << 0) + ((u64) in[3]) * (in2[4] << 0) + ((u64) in[4]) * (in2[3] << 0) + ((u64) in[5]) * (in2[2] << 0) + ((u64) in[6]) * (in2[1] << 0) + ((u64) in[7]) * (in2[0] << 0); /* tmp[8] has the greatest value but doesn't overflow. See logic in * felem_square. */ tmp[8] = ((u64) in[0]) * (in2[8] << 0) + ((u64) in[1]) * (in2[7] << 1) + ((u64) in[2]) * (in2[6] << 0) + ((u64) in[3]) * (in2[5] << 1) + ((u64) in[4]) * (in2[4] << 0) + ((u64) in[5]) * (in2[3] << 1) + ((u64) in[6]) * (in2[2] << 0) + ((u64) in[7]) * (in2[1] << 1) + ((u64) in[8]) * (in2[0] << 0); tmp[9] = ((u64) in[1]) * (in2[8] << 0) + ((u64) in[2]) * (in2[7] << 0) + ((u64) in[3]) * (in2[6] << 0) + ((u64) in[4]) * (in2[5] << 0) + ((u64) in[5]) * (in2[4] << 0) + ((u64) in[6]) * (in2[3] << 0) + ((u64) in[7]) * (in2[2] << 0) + ((u64) in[8]) * (in2[1] << 0); tmp[10] = ((u64) in[2]) * (in2[8] << 0) + ((u64) in[3]) * (in2[7] << 1) + ((u64) in[4]) * (in2[6] << 0) + ((u64) in[5]) * (in2[5] << 1) + ((u64) in[6]) * (in2[4] << 0) + ((u64) in[7]) * (in2[3] << 1) + ((u64) in[8]) * (in2[2] << 0); tmp[11] = ((u64) in[3]) * (in2[8] << 0) + ((u64) in[4]) * (in2[7] << 0) + ((u64) in[5]) * (in2[6] << 0) + ((u64) in[6]) * (in2[5] << 0) + ((u64) in[7]) * (in2[4] << 0) + ((u64) in[8]) * (in2[3] << 0); tmp[12] = ((u64) in[4]) * (in2[8] << 0) + ((u64) in[5]) * (in2[7] << 1) + ((u64) in[6]) * (in2[6] << 0) + ((u64) in[7]) * (in2[5] << 1) + ((u64) in[8]) * (in2[4] << 0); tmp[13] = ((u64) in[5]) * (in2[8] << 0) + ((u64) in[6]) * (in2[7] << 0) + ((u64) in[7]) * (in2[6] << 0) + ((u64) in[8]) * (in2[5] << 0); tmp[14] = ((u64) in[6]) * (in2[8] << 0) + ((u64) in[7]) * (in2[7] << 1) + ((u64) in[8]) * (in2[6] << 0); tmp[15] = ((u64) in[7]) * (in2[8] << 0) + ((u64) in[8]) * (in2[7] << 0); tmp[16] = ((u64) in[8]) * (in2[8] << 0); felem_reduce_degree(out, tmp); } static void felem_assign(felem out, const felem in) { memcpy(out, in, sizeof(felem)); } /* felem_inv calculates |out| = |in|^{-1} * * Based on Fermat's Little Theorem: * a^p = a (mod p) * a^{p-1} = 1 (mod p) * a^{p-2} = a^{-1} (mod p) */ static void felem_inv(felem out, const felem in) { felem ftmp, ftmp2; /* each e_I will hold |in|^{2^I - 1} */ felem e2, e4, e8, e16, e32, e64; unsigned int i; felem_square(ftmp, in); /* 2^1 */ felem_mul(ftmp, in, ftmp); /* 2^2 - 2^0 */ felem_assign(e2, ftmp); felem_square(ftmp, ftmp); /* 2^3 - 2^1 */ felem_square(ftmp, ftmp); /* 2^4 - 2^2 */ felem_mul(ftmp, ftmp, e2); /* 2^4 - 2^0 */ felem_assign(e4, ftmp); felem_square(ftmp, ftmp); /* 2^5 - 2^1 */ felem_square(ftmp, ftmp); /* 2^6 - 2^2 */ felem_square(ftmp, ftmp); /* 2^7 - 2^3 */ felem_square(ftmp, ftmp); /* 2^8 - 2^4 */ felem_mul(ftmp, ftmp, e4); /* 2^8 - 2^0 */ felem_assign(e8, ftmp); for (i = 0; i < 8; i++) { felem_square(ftmp, ftmp); } /* 2^16 - 2^8 */ felem_mul(ftmp, ftmp, e8); /* 2^16 - 2^0 */ felem_assign(e16, ftmp); for (i = 0; i < 16; i++) { felem_square(ftmp, ftmp); } /* 2^32 - 2^16 */ felem_mul(ftmp, ftmp, e16); /* 2^32 - 2^0 */ felem_assign(e32, ftmp); for (i = 0; i < 32; i++) { felem_square(ftmp, ftmp); } /* 2^64 - 2^32 */ felem_assign(e64, ftmp); felem_mul(ftmp, ftmp, in); /* 2^64 - 2^32 + 2^0 */ for (i = 0; i < 192; i++) { felem_square(ftmp, ftmp); } /* 2^256 - 2^224 + 2^192 */ felem_mul(ftmp2, e64, e32); /* 2^64 - 2^0 */ for (i = 0; i < 16; i++) { felem_square(ftmp2, ftmp2); } /* 2^80 - 2^16 */ felem_mul(ftmp2, ftmp2, e16); /* 2^80 - 2^0 */ for (i = 0; i < 8; i++) { felem_square(ftmp2, ftmp2); } /* 2^88 - 2^8 */ felem_mul(ftmp2, ftmp2, e8); /* 2^88 - 2^0 */ for (i = 0; i < 4; i++) { felem_square(ftmp2, ftmp2); } /* 2^92 - 2^4 */ felem_mul(ftmp2, ftmp2, e4); /* 2^92 - 2^0 */ felem_square(ftmp2, ftmp2); /* 2^93 - 2^1 */ felem_square(ftmp2, ftmp2); /* 2^94 - 2^2 */ felem_mul(ftmp2, ftmp2, e2); /* 2^94 - 2^0 */ felem_square(ftmp2, ftmp2); /* 2^95 - 2^1 */ felem_square(ftmp2, ftmp2); /* 2^96 - 2^2 */ felem_mul(ftmp2, ftmp2, in); /* 2^96 - 3 */ felem_mul(out, ftmp2, ftmp); /* 2^256 - 2^224 + 2^192 + 2^96 - 3 */ } /* felem_scalar_3 sets out=3*out. * * On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29. * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */ static void felem_scalar_3(felem out) { limb carry = 0; unsigned int i; for (i = 0;; i++) { out[i] *= 3; out[i] += carry; carry = out[i] >> 29; out[i] &= kBottom29Bits; i++; if (i == NLIMBS) break; out[i] *= 3; out[i] += carry; carry = out[i] >> 28; out[i] &= kBottom28Bits; } felem_reduce_carry(out, carry); } /* felem_scalar_4 sets out=4*out. * * On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29. * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */ static void felem_scalar_4(felem out) { limb carry = 0, next_carry; unsigned int i; for (i = 0;; i++) { next_carry = out[i] >> 27; out[i] <<= 2; out[i] &= kBottom29Bits; out[i] += carry; carry = next_carry + (out[i] >> 29); out[i] &= kBottom29Bits; i++; if (i == NLIMBS) break; next_carry = out[i] >> 26; out[i] <<= 2; out[i] &= kBottom28Bits; out[i] += carry; carry = next_carry + (out[i] >> 28); out[i] &= kBottom28Bits; } felem_reduce_carry(out, carry); } /* felem_scalar_8 sets out=8*out. * * On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29. * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */ static void felem_scalar_8(felem out) { limb carry = 0, next_carry; unsigned int i; for (i = 0;; i++) { next_carry = out[i] >> 26; out[i] <<= 3; out[i] &= kBottom29Bits; out[i] += carry; carry = next_carry + (out[i] >> 29); out[i] &= kBottom29Bits; i++; if (i == NLIMBS) break; next_carry = out[i] >> 25; out[i] <<= 3; out[i] &= kBottom28Bits; out[i] += carry; carry = next_carry + (out[i] >> 28); out[i] &= kBottom28Bits; } felem_reduce_carry(out, carry); } /* felem_is_zero_vartime returns 1 iff |in| == 0. It takes a variable amount of * time depending on the value of |in|. */ static char felem_is_zero_vartime(const felem in) { limb carry; int i; limb tmp[NLIMBS]; felem_assign(tmp, in); /* First, reduce tmp to a minimal form. */ do { carry = 0; for (i = 0;; i++) { tmp[i] += carry; carry = tmp[i] >> 29; tmp[i] &= kBottom29Bits; i++; if (i == NLIMBS) break; tmp[i] += carry; carry = tmp[i] >> 28; tmp[i] &= kBottom28Bits; } felem_reduce_carry(tmp, carry); } while (carry); /* tmp < 2**257, so the only possible zero values are 0, p and 2p. */ return memcmp(tmp, kZero, sizeof(tmp)) == 0 || memcmp(tmp, kP, sizeof(tmp)) == 0 || memcmp(tmp, k2P, sizeof(tmp)) == 0; } /* Group operations: * * Elements of the elliptic curve group are represented in Jacobian * coordinates: (x, y, z). An affine point (x', y') is x'=x/z**2, y'=y/z**3 in * Jacobian form. */ /* point_double sets {x_out,y_out,z_out} = 2*{x,y,z}. * * See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l */ static void point_double(felem x_out, felem y_out, felem z_out, const felem x, const felem y, const felem z) { felem delta, gamma, alpha, beta, tmp, tmp2; felem_square(delta, z); felem_square(gamma, y); felem_mul(beta, x, gamma); felem_sum(tmp, x, delta); felem_diff(tmp2, x, delta); felem_mul(alpha, tmp, tmp2); felem_scalar_3(alpha); felem_sum(tmp, y, z); felem_square(tmp, tmp); felem_diff(tmp, tmp, gamma); felem_diff(z_out, tmp, delta); felem_scalar_4(beta); felem_square(x_out, alpha); felem_diff(x_out, x_out, beta); felem_diff(x_out, x_out, beta); felem_diff(tmp, beta, x_out); felem_mul(tmp, alpha, tmp); felem_square(tmp2, gamma); felem_scalar_8(tmp2); felem_diff(y_out, tmp, tmp2); } /* point_add_mixed sets {x_out,y_out,z_out} = {x1,y1,z1} + {x2,y2,1}. * (i.e. the second point is affine.) * * See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl * * Note that this function does not handle P+P, infinity+P nor P+infinity * correctly. */ static void point_add_mixed(felem x_out, felem y_out, felem z_out, const felem x1, const felem y1, const felem z1, const felem x2, const felem y2) { felem z1z1, z1z1z1, s2, u2, h, i, j, r, rr, v, tmp; felem_square(z1z1, z1); felem_sum(tmp, z1, z1); felem_mul(u2, x2, z1z1); felem_mul(z1z1z1, z1, z1z1); felem_mul(s2, y2, z1z1z1); felem_diff(h, u2, x1); felem_sum(i, h, h); felem_square(i, i); felem_mul(j, h, i); felem_diff(r, s2, y1); felem_sum(r, r, r); felem_mul(v, x1, i); felem_mul(z_out, tmp, h); felem_square(rr, r); felem_diff(x_out, rr, j); felem_diff(x_out, x_out, v); felem_diff(x_out, x_out, v); felem_diff(tmp, v, x_out); felem_mul(y_out, tmp, r); felem_mul(tmp, y1, j); felem_diff(y_out, y_out, tmp); felem_diff(y_out, y_out, tmp); } /* point_add sets {x_out,y_out,z_out} = {x1,y1,z1} + {x2,y2,z2}. * * See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl * * Note that this function does not handle P+P, infinity+P nor P+infinity * correctly. */ static void point_add(felem x_out, felem y_out, felem z_out, const felem x1, const felem y1, const felem z1, const felem x2, const felem y2, const felem z2) { felem z1z1, z1z1z1, z2z2, z2z2z2, s1, s2, u1, u2, h, i, j, r, rr, v, tmp; felem_square(z1z1, z1); felem_square(z2z2, z2); felem_mul(u1, x1, z2z2); felem_sum(tmp, z1, z2); felem_square(tmp, tmp); felem_diff(tmp, tmp, z1z1); felem_diff(tmp, tmp, z2z2); felem_mul(z2z2z2, z2, z2z2); felem_mul(s1, y1, z2z2z2); felem_mul(u2, x2, z1z1); felem_mul(z1z1z1, z1, z1z1); felem_mul(s2, y2, z1z1z1); felem_diff(h, u2, u1); felem_sum(i, h, h); felem_square(i, i); felem_mul(j, h, i); felem_diff(r, s2, s1); felem_sum(r, r, r); felem_mul(v, u1, i); felem_mul(z_out, tmp, h); felem_square(rr, r); felem_diff(x_out, rr, j); felem_diff(x_out, x_out, v); felem_diff(x_out, x_out, v); felem_diff(tmp, v, x_out); felem_mul(y_out, tmp, r); felem_mul(tmp, s1, j); felem_diff(y_out, y_out, tmp); felem_diff(y_out, y_out, tmp); } /* point_add_or_double_vartime sets {x_out,y_out,z_out} = {x1,y1,z1} + * {x2,y2,z2}. * * See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl * * This function handles the case where {x1,y1,z1}={x2,y2,z2}. */ static void point_add_or_double_vartime( felem x_out, felem y_out, felem z_out, const felem x1, const felem y1, const felem z1, const felem x2, const felem y2, const felem z2) { felem z1z1, z1z1z1, z2z2, z2z2z2, s1, s2, u1, u2, h, i, j, r, rr, v, tmp; char x_equal, y_equal; felem_square(z1z1, z1); felem_square(z2z2, z2); felem_mul(u1, x1, z2z2); felem_sum(tmp, z1, z2); felem_square(tmp, tmp); felem_diff(tmp, tmp, z1z1); felem_diff(tmp, tmp, z2z2); felem_mul(z2z2z2, z2, z2z2); felem_mul(s1, y1, z2z2z2); felem_mul(u2, x2, z1z1); felem_mul(z1z1z1, z1, z1z1); felem_mul(s2, y2, z1z1z1); felem_diff(h, u2, u1); x_equal = felem_is_zero_vartime(h); felem_sum(i, h, h); felem_square(i, i); felem_mul(j, h, i); felem_diff(r, s2, s1); y_equal = felem_is_zero_vartime(r); if (x_equal && y_equal) { point_double(x_out, y_out, z_out, x1, y1, z1); return; } felem_sum(r, r, r); felem_mul(v, u1, i); felem_mul(z_out, tmp, h); felem_square(rr, r); felem_diff(x_out, rr, j); felem_diff(x_out, x_out, v); felem_diff(x_out, x_out, v); felem_diff(tmp, v, x_out); felem_mul(y_out, tmp, r); felem_mul(tmp, s1, j); felem_diff(y_out, y_out, tmp); felem_diff(y_out, y_out, tmp); } /* copy_conditional sets out=in if mask = 0xffffffff in constant time. * * On entry: mask is either 0 or 0xffffffff. */ static void copy_conditional(felem out, const felem in, limb mask) { int i; for (i = 0; i < NLIMBS; i++) { const limb tmp = mask & (in[i] ^ out[i]); out[i] ^= tmp; } } /* select_affine_point sets {out_x,out_y} to the index'th entry of table. * On entry: index < 16, table[0] must be zero. */ static void select_affine_point(felem out_x, felem out_y, const limb *table, limb index) { limb i, j; memset(out_x, 0, sizeof(felem)); memset(out_y, 0, sizeof(felem)); for (i = 1; i < 16; i++) { limb mask = i ^ index; mask |= mask >> 2; mask |= mask >> 1; mask &= 1; mask--; for (j = 0; j < NLIMBS; j++, table++) { out_x[j] |= *table & mask; } for (j = 0; j < NLIMBS; j++, table++) { out_y[j] |= *table & mask; } } } /* select_jacobian_point sets {out_x,out_y,out_z} to the index'th entry of * table. On entry: index < 16, table[0] must be zero. */ static void select_jacobian_point(felem out_x, felem out_y, felem out_z, const limb *table, limb index) { limb i, j; memset(out_x, 0, sizeof(felem)); memset(out_y, 0, sizeof(felem)); memset(out_z, 0, sizeof(felem)); /* The implicit value at index 0 is all zero. We don't need to perform that * iteration of the loop because we already set out_* to zero. */ table += 3*NLIMBS; for (i = 1; i < 16; i++) { limb mask = i ^ index; mask |= mask >> 2; mask |= mask >> 1; mask &= 1; mask--; for (j = 0; j < NLIMBS; j++, table++) { out_x[j] |= *table & mask; } for (j = 0; j < NLIMBS; j++, table++) { out_y[j] |= *table & mask; } for (j = 0; j < NLIMBS; j++, table++) { out_z[j] |= *table & mask; } } } /* get_bit returns the bit'th bit of scalar. */ static char get_bit(const u8 scalar[32], int bit) { return ((scalar[bit >> 3]) >> (bit & 7)) & 1; } /* scalar_base_mult sets {nx,ny,nz} = scalar*G where scalar is a little-endian * number. Note that the value of scalar must be less than the order of the * group. */ static void scalar_base_mult(felem nx, felem ny, felem nz, const u8 scalar[32]) { int i, j; limb n_is_infinity_mask = -1, p_is_noninfinite_mask, mask; u32 table_offset; felem px, py; felem tx, ty, tz; memset(nx, 0, sizeof(felem)); memset(ny, 0, sizeof(felem)); memset(nz, 0, sizeof(felem)); /* The loop adds bits at positions 0, 64, 128 and 192, followed by * positions 32,96,160 and 224 and does this 32 times. */ for (i = 0; i < 32; i++) { if (i) { point_double(nx, ny, nz, nx, ny, nz); } table_offset = 0; for (j = 0; j <= 32; j += 32) { char bit0 = get_bit(scalar, 31 - i + j); char bit1 = get_bit(scalar, 95 - i + j); char bit2 = get_bit(scalar, 159 - i + j); char bit3 = get_bit(scalar, 223 - i + j); limb index = bit0 | (bit1 << 1) | (bit2 << 2) | (bit3 << 3); select_affine_point(px, py, kPrecomputed + table_offset, index); table_offset += 30 * NLIMBS; /* Since scalar is less than the order of the group, we know that * {nx,ny,nz} != {px,py,1}, unless both are zero, which we handle * below. */ point_add_mixed(tx, ty, tz, nx, ny, nz, px, py); /* The result of point_add_mixed is incorrect if {nx,ny,nz} is zero * (a.k.a. the point at infinity). We handle that situation by * copying the point from the table. */ copy_conditional(nx, px, n_is_infinity_mask); copy_conditional(ny, py, n_is_infinity_mask); copy_conditional(nz, kOne, n_is_infinity_mask); /* Equally, the result is also wrong if the point from the table is * zero, which happens when the index is zero. We handle that by * only copying from {tx,ty,tz} to {nx,ny,nz} if index != 0. */ p_is_noninfinite_mask = NON_ZERO_TO_ALL_ONES(index); mask = p_is_noninfinite_mask & ~n_is_infinity_mask; copy_conditional(nx, tx, mask); copy_conditional(ny, ty, mask); copy_conditional(nz, tz, mask); /* If p was not zero, then n is now non-zero. */ n_is_infinity_mask &= ~p_is_noninfinite_mask; } } } /* point_to_affine converts a Jacobian point to an affine point. If the input * is the point at infinity then it returns (0, 0) in constant time. */ static void point_to_affine(felem x_out, felem y_out, const felem nx, const felem ny, const felem nz) { felem z_inv, z_inv_sq; felem_inv(z_inv, nz); felem_square(z_inv_sq, z_inv); felem_mul(x_out, nx, z_inv_sq); felem_mul(z_inv, z_inv, z_inv_sq); felem_mul(y_out, ny, z_inv); } /* scalar_mult sets {nx,ny,nz} = scalar*{x,y}. */ static void scalar_mult(felem nx, felem ny, felem nz, const felem x, const felem y, const u8 scalar[32]) { int i; felem px, py, pz, tx, ty, tz; felem precomp[16][3]; limb n_is_infinity_mask, index, p_is_noninfinite_mask, mask; /* We precompute 0,1,2,... times {x,y}. */ memset(precomp, 0, sizeof(felem) * 3); memcpy(&precomp[1][0], x, sizeof(felem)); memcpy(&precomp[1][1], y, sizeof(felem)); memcpy(&precomp[1][2], kOne, sizeof(felem)); for (i = 2; i < 16; i += 2) { point_double(precomp[i][0], precomp[i][1], precomp[i][2], precomp[i / 2][0], precomp[i / 2][1], precomp[i / 2][2]); point_add_mixed(precomp[i + 1][0], precomp[i + 1][1], precomp[i + 1][2], precomp[i][0], precomp[i][1], precomp[i][2], x, y); } memset(nx, 0, sizeof(felem)); memset(ny, 0, sizeof(felem)); memset(nz, 0, sizeof(felem)); n_is_infinity_mask = -1; /* We add in a window of four bits each iteration and do this 64 times. */ for (i = 0; i < 64; i++) { if (i) { point_double(nx, ny, nz, nx, ny, nz); point_double(nx, ny, nz, nx, ny, nz); point_double(nx, ny, nz, nx, ny, nz); point_double(nx, ny, nz, nx, ny, nz); } index = scalar[31 - i / 2]; if ((i & 1) == 1) { index &= 15; } else { index >>= 4; } /* See the comments in scalar_base_mult about handling infinities. */ select_jacobian_point(px, py, pz, precomp[0][0], index); point_add(tx, ty, tz, nx, ny, nz, px, py, pz); copy_conditional(nx, px, n_is_infinity_mask); copy_conditional(ny, py, n_is_infinity_mask); copy_conditional(nz, pz, n_is_infinity_mask); p_is_noninfinite_mask = NON_ZERO_TO_ALL_ONES(index); mask = p_is_noninfinite_mask & ~n_is_infinity_mask; copy_conditional(nx, tx, mask); copy_conditional(ny, ty, mask); copy_conditional(nz, tz, mask); n_is_infinity_mask &= ~p_is_noninfinite_mask; } } /* Interface with Freebl: */ /* BYTESWAP_MP_DIGIT_TO_LE swaps the bytes of a mp_digit to * little-endian order. */ #ifdef IS_BIG_ENDIAN #ifdef __APPLE__ #include <libkern/OSByteOrder.h> #define BYTESWAP32(x) OSSwapInt32(x) #define BYTESWAP64(x) OSSwapInt64(x) #else #define BYTESWAP32(x) \ (((x) >> 24) | (((x) >> 8) & 0xff00) | (((x) & 0xff00) << 8) | ((x) << 24)) #define BYTESWAP64(x) \ (((x) >> 56) | (((x) >> 40) & 0xff00) | \ (((x) >> 24) & 0xff0000) | (((x) >> 8) & 0xff000000) | \ (((x) & 0xff000000) << 8) | (((x) & 0xff0000) << 24) | \ (((x) & 0xff00) << 40) | ((x) << 56)) #endif #ifdef MP_USE_UINT_DIGIT #define BYTESWAP_MP_DIGIT_TO_LE(x) BYTESWAP32(x) #else #define BYTESWAP_MP_DIGIT_TO_LE(x) BYTESWAP64(x) #endif #endif /* IS_BIG_ENDIAN */ #ifdef MP_USE_UINT_DIGIT static const mp_digit kRInvDigits[8] = { 0x80000000, 1, 0xffffffff, 0, 0x80000001, 0xfffffffe, 1, 0x7fffffff }; #else static const mp_digit kRInvDigits[4] = { PR_UINT64(0x180000000), 0xffffffff, PR_UINT64(0xfffffffe80000001), PR_UINT64(0x7fffffff00000001) }; #endif #define MP_DIGITS_IN_256_BITS (32/sizeof(mp_digit)) static const mp_int kRInv = { MP_ZPOS, MP_DIGITS_IN_256_BITS, MP_DIGITS_IN_256_BITS, (mp_digit*) kRInvDigits }; static const limb kTwo28 = 0x10000000; static const limb kTwo29 = 0x20000000; /* to_montgomery sets out = R*in. */ static mp_err to_montgomery(felem out, const mp_int *in, const ECGroup *group) { /* There are no MPI functions for bitshift operations and we wish to shift * in 257 bits left so we move the digits 256-bits left and then multiply * by two. */ mp_int in_shifted; int i; mp_err res; mp_init(&in_shifted); s_mp_pad(&in_shifted, MP_USED(in) + MP_DIGITS_IN_256_BITS); memcpy(&MP_DIGIT(&in_shifted, MP_DIGITS_IN_256_BITS), MP_DIGITS(in), MP_USED(in)*sizeof(mp_digit)); mp_mul_2(&in_shifted, &in_shifted); MP_CHECKOK(group->meth->field_mod(&in_shifted, &in_shifted, group->meth)); for (i = 0;; i++) { out[i] = MP_DIGIT(&in_shifted, 0) & kBottom29Bits; mp_div_d(&in_shifted, kTwo29, &in_shifted, NULL); i++; if (i == NLIMBS) break; out[i] = MP_DIGIT(&in_shifted, 0) & kBottom28Bits; mp_div_d(&in_shifted, kTwo28, &in_shifted, NULL); } CLEANUP: mp_clear(&in_shifted); return res; } /* from_montgomery sets out=in/R. */ static mp_err from_montgomery(mp_int *out, const felem in, const ECGroup *group) { mp_int result, tmp; mp_err res; int i; mp_init(&result); mp_init(&tmp); MP_CHECKOK(mp_add_d(&tmp, in[NLIMBS-1], &result)); for (i = NLIMBS-2; i >= 0; i--) { if ((i & 1) == 0) { MP_CHECKOK(mp_mul_d(&result, kTwo29, &tmp)); } else { MP_CHECKOK(mp_mul_d(&result, kTwo28, &tmp)); } MP_CHECKOK(mp_add_d(&tmp, in[i], &result)); } MP_CHECKOK(mp_mul(&result, &kRInv, out)); MP_CHECKOK(group->meth->field_mod(out, out, group->meth)); CLEANUP: mp_clear(&result); mp_clear(&tmp); return res; } /* scalar_from_mp_int sets out_scalar=n, where n < the group order. */ static void scalar_from_mp_int(u8 out_scalar[32], const mp_int *n) { /* We require that |n| is less than the order of the group and therefore it * will fit into |out_scalar|. However, these is a timing side-channel here * that we cannot avoid: if |n| is sufficiently small it may be one or more * words too short and we'll copy less data. */ memset(out_scalar, 0, 32); #ifdef IS_LITTLE_ENDIAN memcpy(out_scalar, MP_DIGITS(n), MP_USED(n) * sizeof(mp_digit)); #else { mp_size i; mp_digit swapped[MP_DIGITS_IN_256_BITS]; for (i = 0; i < MP_USED(n); i++) { swapped[i] = BYTESWAP_MP_DIGIT_TO_LE(MP_DIGIT(n, i)); } memcpy(out_scalar, swapped, MP_USED(n) * sizeof(mp_digit)); } #endif } /* ec_GFp_nistp256_base_point_mul sets {out_x,out_y} = nG, where n is < the * order of the group. */ static mp_err ec_GFp_nistp256_base_point_mul(const mp_int *n, mp_int *out_x, mp_int *out_y, const ECGroup *group) { u8 scalar[32]; felem x, y, z, x_affine, y_affine; mp_err res; /* FIXME(agl): test that n < order. */ scalar_from_mp_int(scalar, n); scalar_base_mult(x, y, z, scalar); point_to_affine(x_affine, y_affine, x, y, z); MP_CHECKOK(from_montgomery(out_x, x_affine, group)); MP_CHECKOK(from_montgomery(out_y, y_affine, group)); CLEANUP: return res; } /* ec_GFp_nistp256_point_mul sets {out_x,out_y} = n*{in_x,in_y}, where n is < * the order of the group. */ static mp_err ec_GFp_nistp256_point_mul(const mp_int *n, const mp_int *in_x, const mp_int *in_y, mp_int *out_x, mp_int *out_y, const ECGroup *group) { u8 scalar[32]; felem x, y, z, x_affine, y_affine, px, py; mp_err res; scalar_from_mp_int(scalar, n); MP_CHECKOK(to_montgomery(px, in_x, group)); MP_CHECKOK(to_montgomery(py, in_y, group)); scalar_mult(x, y, z, px, py, scalar); point_to_affine(x_affine, y_affine, x, y, z); MP_CHECKOK(from_montgomery(out_x, x_affine, group)); MP_CHECKOK(from_montgomery(out_y, y_affine, group)); CLEANUP: return res; } /* ec_GFp_nistp256_point_mul_vartime sets {out_x,out_y} = n1*G + * n2*{in_x,in_y}, where n1 and n2 are < the order of the group. * * As indicated by the name, this function operates in variable time. This * is safe because it's used for signature validation which doesn't deal * with secrets. */ static mp_err ec_GFp_nistp256_points_mul_vartime( const mp_int *n1, const mp_int *n2, const mp_int *in_x, const mp_int *in_y, mp_int *out_x, mp_int *out_y, const ECGroup *group) { u8 scalar1[32], scalar2[32]; felem x1, y1, z1, x2, y2, z2, x_affine, y_affine, px, py; mp_err res = MP_OKAY; /* If n2 == NULL, this is just a base-point multiplication. */ if (n2 == NULL) { return ec_GFp_nistp256_base_point_mul(n1, out_x, out_y, group); } /* If n1 == nULL, this is just an arbitary-point multiplication. */ if (n1 == NULL) { return ec_GFp_nistp256_point_mul(n2, in_x, in_y, out_x, out_y, group); } /* If both scalars are zero, then the result is the point at infinity. */ if (mp_cmp_z(n1) == 0 && mp_cmp_z(n2) == 0) { mp_zero(out_x); mp_zero(out_y); return res; } scalar_from_mp_int(scalar1, n1); scalar_from_mp_int(scalar2, n2); MP_CHECKOK(to_montgomery(px, in_x, group)); MP_CHECKOK(to_montgomery(py, in_y, group)); scalar_base_mult(x1, y1, z1, scalar1); scalar_mult(x2, y2, z2, px, py, scalar2); if (mp_cmp_z(n2) == 0) { /* If n2 == 0, then {x2,y2,z2} is zero and the result is just * {x1,y1,z1}. */ } else if (mp_cmp_z(n1) == 0) { /* If n1 == 0, then {x1,y1,z1} is zero and the result is just * {x2,y2,z2}. */ memcpy(x1, x2, sizeof(x2)); memcpy(y1, y2, sizeof(y2)); memcpy(z1, z2, sizeof(z2)); } else { /* This function handles the case where {x1,y1,z1} == {x2,y2,z2}. */ point_add_or_double_vartime(x1, y1, z1, x1, y1, z1, x2, y2, z2); } point_to_affine(x_affine, y_affine, x1, y1, z1); MP_CHECKOK(from_montgomery(out_x, x_affine, group)); MP_CHECKOK(from_montgomery(out_y, y_affine, group)); CLEANUP: return res; } /* Wire in fast point multiplication for named curves. */ mp_err ec_group_set_gfp256_32(ECGroup *group, ECCurveName name) { if (name == ECCurve_NIST_P256) { group->base_point_mul = &ec_GFp_nistp256_base_point_mul; group->point_mul = &ec_GFp_nistp256_point_mul; group->points_mul = &ec_GFp_nistp256_points_mul_vartime; } return MP_OKAY; }
thespooler/nss
lib/freebl/ecl/ecp_256_32.c
C
mpl-2.0
50,400
namespace Infrastructure.DataAccess.Migrations { using System; using System.Data.Entity.Migrations; public partial class usersupervisioninfoaddedtosysusage : DbMigration { public override void Up() { AddColumn("dbo.ItSystemUsage", "UserSupervisionDate", c => c.DateTime(nullable: false, precision: 7, storeType: "datetime2")); AddColumn("dbo.ItSystemUsage", "UserSupervision", c => c.Int(nullable: false)); } public override void Down() { DropColumn("dbo.ItSystemUsage", "UserSupervision"); DropColumn("dbo.ItSystemUsage", "UserSupervisionDate"); } } }
miracle-as/kitos
Infrastructure.DataAccess/Migrations/201802161536558_user supervision info added to sysusage.cs
C#
mpl-2.0
683
/* * Copyright © 2013-2020, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.i18n.rest.internal.infrastructure.csv; import com.google.common.collect.Sets; import org.seedstack.i18n.rest.internal.locale.LocaleFinder; import org.seedstack.i18n.rest.internal.locale.LocaleRepresentation; import org.seedstack.io.spi.Template; import org.seedstack.io.spi.TemplateLoader; import org.seedstack.io.supercsv.Column; import org.seedstack.io.supercsv.SuperCsvTemplate; import org.seedstack.jpa.JpaUnit; import org.seedstack.seed.transaction.Transactional; import org.supercsv.cellprocessor.Optional; import javax.inject.Inject; import java.util.List; import java.util.Set; /** * @author pierre.thirouin@ext.mpsa.com */ public class I18nCSVTemplateLoader implements TemplateLoader { public static final String I18N_CSV_TEMPLATE = "i18nTranslations"; public static final String KEY = "key"; @Inject private LocaleFinder localeFinder; @JpaUnit("seed-i18n-domain") @Transactional @Override public Template load(String name) { List<LocaleRepresentation> availableLocales = localeFinder.findAvailableLocales(); SuperCsvTemplate superCsvTemplate = new SuperCsvTemplate(name); superCsvTemplate.addColumn(new Column(KEY, KEY, new Optional(), new Optional())); for (LocaleRepresentation availableLocale : availableLocales) { superCsvTemplate.addColumn(new Column(availableLocale.getCode(), availableLocale.getCode(), new Optional(), new Optional())); } return superCsvTemplate; } @Override public Set<String> names() { return Sets.newHashSet(I18N_CSV_TEMPLATE); } @Override public boolean contains(String name) { return names().contains(name); } @Override public String templateRenderer() { return I18nCSVRenderer.I18N_RENDERER; } @Override public String templateParser() { return CSVParser.I18N_PARSER; } }
seedstack/i18n-function
rest/src/main/java/org/seedstack/i18n/rest/internal/infrastructure/csv/I18nCSVTemplateLoader.java
Java
mpl-2.0
2,205
<?php declare(strict_types=1); /* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ namespace ParkManager\Application\Command\User; use Rollerworks\Component\SplitToken\SplitToken; final class ConfirmPasswordReset { /** * @param string $password The password in hashed format */ public function __construct(public SplitToken $token, public string $password) { } }
park-manager/park-manager
src/Application/Command/User/ConfirmPasswordReset.php
PHP
mpl-2.0
551
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MovingPlatform : MonoBehaviour { public float moveSpeed; private float moveForce; public float limit; public bool vertical; public bool movingPlus; public Vector3 startPos; Rigidbody2D rb; // Use this for initialization void Start () { rb = GetComponent<Rigidbody2D> (); startPos = transform.position; } // Update is called once per frame void Update () { if (vertical == false) { rb.velocity = new Vector2 (moveForce, rb.velocity.y); } else { rb.velocity = new Vector2 (rb.velocity.x, moveForce); } if (vertical == false) { if (transform.localPosition.x >= startPos.x + limit) { movingPlus = false; } if (transform.localPosition.x <= startPos.x - limit) { movingPlus = true; } } else { if (transform.localPosition.y >= startPos.y + limit) { movingPlus = false; } if (transform.localPosition.y <= startPos.y - limit) { movingPlus = true; } } if (movingPlus == true) { moveForce = moveSpeed; } if (movingPlus == false) { moveForce = moveSpeed * -1; } } }
apetersell/RPSX
RPSXUnity/Assets/Scripts/Level Stuff/MovingPlatform.cs
C#
mpl-2.0
1,165
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(alloc)] #![feature(box_syntax)] #![feature(collections)] #![feature(core)] #![feature(env)] #![feature(hash)] #![feature(int_uint)] #![feature(io)] #![feature(optin_builtin_traits)] #![feature(path)] #![feature(plugin)] #![feature(rustc_private)] #![feature(std_misc)] #![feature(unicode)] #![feature(unsafe_destructor)] #![allow(missing_copy_implementations)] #[macro_use] extern crate log; extern crate alloc; #[macro_use] extern crate bitflags; extern crate collections; extern crate cssparser; extern crate geom; extern crate getopts; extern crate layers; extern crate libc; #[no_link] #[macro_use] extern crate cssparser; extern crate rand; #[cfg(target_os="linux")] extern crate regex; extern crate "rustc-serialize" as rustc_serialize; #[cfg(target_os="macos")] extern crate task_info; extern crate "time" as std_time; extern crate text_writer; extern crate selectors; extern crate string_cache; extern crate unicode; extern crate url; #[no_link] #[macro_use] #[plugin] extern crate string_cache_macros; extern crate lazy_static; pub use selectors::smallvec; use std::sync::Arc; pub mod cache; pub mod cursor; pub mod debug_utils; pub mod deque; pub mod dlist; pub mod fnv; pub mod geometry; pub mod logical_geometry; pub mod memory; pub mod namespace; pub mod opts; pub mod persistent_list; pub mod range; pub mod resource_files; pub mod str; pub mod task; pub mod tid; pub mod time; pub mod taskpool; pub mod task_state; pub mod vec; pub mod workqueue; pub fn breakpoint() { unsafe { ::std::intrinsics::breakpoint() }; } // Workaround for lack of `ptr_eq` on Arcs... #[inline] pub fn arc_ptr_eq<T: 'static + Send + Sync>(a: &Arc<T>, b: &Arc<T>) -> bool { let a: &T = &**a; let b: &T = &**b; (a as *const T) == (b as *const T) }
luniv/servo
components/util/lib.rs
Rust
mpl-2.0
1,979
import pytest from umodbus.server.serial import AbstractSerialServer @pytest.fixture def abstract_serial_server(): return AbstractSerialServer() def test_abstract_serial_server_get_meta_data(abstract_serial_server): """ Test if meta data is correctly extracted from request. """ assert abstract_serial_server.get_meta_data(b'\x01x\02\x03') ==\ {'unit_id': 1} def test_abract_serial_server_shutdown(abstract_serial_server): assert abstract_serial_server._shutdown_request is False abstract_serial_server.shutdown() assert abstract_serial_server._shutdown_request is True
AdvancedClimateSystems/python-modbus
tests/unit/server/serial/test_init.py
Python
mpl-2.0
611
-- new sessions stored procedure CREATE PROCEDURE `sessions_1` ( IN `uidArg` BINARY(16) ) BEGIN SELECT tokenId, uid, createdAt, uaBrowser, uaBrowserVersion, uaOS, uaOSVersion, uaDeviceType, lastAccessTime FROM sessionTokens WHERE uid = uidArg; END; -- Schema patch-level increment. UPDATE dbMetadata SET value = '17' WHERE name = 'schema-patch-level';
mozilla/fxa-auth-db-mysql
lib/db/schema/patch-016-017.sql
SQL
mpl-2.0
442
// ======================================================================== // // Copyright 2009-2015 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "bvh4_factory.h" #include "../bvh/bvh.h" #include "../geometry/bezier1v.h" #include "../geometry/bezier1i.h" #include "../geometry/linei.h" #include "../geometry/triangle.h" #include "../geometry/trianglev.h" #include "../geometry/trianglev_mb.h" #include "../geometry/trianglei.h" #include "../geometry/quadv.h" #include "../geometry/quadi.h" #include "../geometry/quadi_mb.h" #include "../geometry/subdivpatch1cached.h" #include "../geometry/object.h" #include "../../common/accelinstance.h" namespace embree { DECLARE_SYMBOL2(Accel::Intersector1,BVH4Line4iIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Line4iMBIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Bezier1vIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Bezier1iIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Bezier1vIntersector1_OBB); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Bezier1iIntersector1_OBB); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Bezier1iMBIntersector1_OBB); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Triangle4Intersector1Moeller); DECLARE_SYMBOL2(Accel::Intersector1,BVH4XfmTriangle4Intersector1Moeller); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Triangle8Intersector1Moeller); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Triangle4vIntersector1Pluecker); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Triangle4iIntersector1Pluecker); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Triangle4vMBIntersector1Moeller); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Subdivpatch1CachedIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4GridAOSIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4VirtualIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4VirtualMBIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Quad4vIntersector1Moeller); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Quad4iIntersector1Pluecker); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Quad4iMBIntersector1Pluecker); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Line4iIntersector4); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Line4iMBIntersector4); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Bezier1vIntersector4Single); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Bezier1iIntersector4Single); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Bezier1vIntersector4Single_OBB); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Bezier1iIntersector4Single_OBB); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Bezier1iMBIntersector4Single_OBB); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle4Intersector4HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle4Intersector4HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle8Intersector4HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle8Intersector4HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle4vIntersector4HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle4iIntersector4HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle4vMBIntersector4HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Quad4vIntersector4HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Quad4vIntersector4HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Quad4iIntersector4HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Quad4iMBIntersector4HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Subdivpatch1CachedIntersector4); DECLARE_SYMBOL2(Accel::Intersector4,BVH4GridAOSIntersector4); DECLARE_SYMBOL2(Accel::Intersector4,BVH4VirtualIntersector4Chunk); DECLARE_SYMBOL2(Accel::Intersector4,BVH4VirtualMBIntersector4Chunk); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Line4iIntersector8); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Line4iMBIntersector8); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Bezier1vIntersector8Single); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Bezier1iIntersector8Single); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Bezier1vIntersector8Single_OBB); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Bezier1iIntersector8Single_OBB); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Bezier1iMBIntersector8Single_OBB); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle4Intersector8HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle4Intersector8HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle8Intersector8HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle8Intersector8HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle4vIntersector8HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle4iIntersector8HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle4vMBIntersector8HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Quad4vIntersector8HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Quad4vIntersector8HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Quad4iIntersector8HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Quad4iMBIntersector8HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Subdivpatch1CachedIntersector8); DECLARE_SYMBOL2(Accel::Intersector8,BVH4GridAOSIntersector8); DECLARE_SYMBOL2(Accel::Intersector8,BVH4VirtualIntersector8Chunk); DECLARE_SYMBOL2(Accel::Intersector8,BVH4VirtualMBIntersector8Chunk); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Line4iIntersector16); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Line4iMBIntersector16); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Bezier1vIntersector16Single); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Bezier1iIntersector16Single); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Bezier1vIntersector16Single_OBB); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Bezier1iIntersector16Single_OBB); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Bezier1iMBIntersector16Single_OBB); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle4Intersector16HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle4Intersector16HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle8Intersector16HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle8Intersector16HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle4vIntersector16HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle4iIntersector16HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle4vMBIntersector16HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Quad4vIntersector16HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Quad4vIntersector16HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Quad4iIntersector16HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Quad4iMBIntersector16HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Subdivpatch1CachedIntersector16); DECLARE_SYMBOL2(Accel::Intersector16,BVH4GridAOSIntersector16); DECLARE_SYMBOL2(Accel::Intersector16,BVH4VirtualIntersector16Chunk); DECLARE_SYMBOL2(Accel::Intersector16,BVH4VirtualMBIntersector16Chunk); DECLARE_BUILDER2(void,Scene,const createLineSegmentsAccelTy,BVH4BuilderTwoLevelLineSegmentsSAH); DECLARE_BUILDER2(void,Scene,const createTriangleMeshAccelTy,BVH4BuilderTwoLevelTriangleMeshSAH); DECLARE_BUILDER2(void,Scene,const createTriangleMeshAccelTy,BVH4BuilderInstancingTriangleMeshSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Bezier1vBuilder_OBB_New); DECLARE_BUILDER2(void,Scene,size_t,BVH4Bezier1iBuilder_OBB_New); DECLARE_BUILDER2(void,Scene,size_t,BVH4Bezier1iMBBuilder_OBB_New); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4SceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle8SceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4vSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4iSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4vMBSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Quad4vSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Quad4iSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Quad4iMBSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4SceneBuilderSpatialSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle8SceneBuilderSpatialSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4vSceneBuilderSpatialSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4iSceneBuilderSpatialSAH); DECLARE_BUILDER2(void,LineSegments,size_t,BVH4Line4iMeshBuilderSAH); DECLARE_BUILDER2(void,LineSegments,size_t,BVH4Line4iMBMeshBuilderSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4MeshBuilderSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle8MeshBuilderSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4vMeshBuilderSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4iMeshBuilderSAH); DECLARE_BUILDER2(void,QuadMesh,size_t,BVH4Quad4vMeshBuilderSAH); DECLARE_BUILDER2(void,QuadMesh,size_t,BVH4Quad4iMeshBuilderSAH); DECLARE_BUILDER2(void,QuadMesh,size_t,BVH4Quad4iMBMeshBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Bezier1vSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Bezier1iSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Line4iSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Line4iMBSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4VirtualSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4VirtualMBSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4SubdivPatch1CachedBuilderBinnedSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4SubdivGridEagerBuilderBinnedSAH); DECLARE_BUILDER2(void,LineSegments,size_t,BVH4Line4iMeshRefitSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4MeshRefitSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle8MeshRefitSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4vMeshRefitSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4iMeshRefitSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4MeshBuilderMortonGeneral); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle8MeshBuilderMortonGeneral); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4vMeshBuilderMortonGeneral); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4iMeshBuilderMortonGeneral); BVH4Factory::BVH4Factory (int features) { /* select builders */ SELECT_SYMBOL_DEFAULT_AVX(features,BVH4BuilderTwoLevelLineSegmentsSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4BuilderTwoLevelTriangleMeshSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4BuilderInstancingTriangleMeshSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1vBuilder_OBB_New); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1iBuilder_OBB_New); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1iMBBuilder_OBB_New); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4SceneBuilderSAH); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle8SceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vMBSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX_AVX512KNL(features,BVH4Quad4vSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX_AVX512KNL(features,BVH4Quad4iSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Quad4iMBSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4SceneBuilderSpatialSAH); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle8SceneBuilderSpatialSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vSceneBuilderSpatialSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iSceneBuilderSpatialSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Line4iMeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4MeshBuilderSAH); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle8MeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vMeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iMeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Quad4vMeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Quad4iMeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Quad4iMBMeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Line4iSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Line4iMBSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1vSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1iSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4VirtualSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4VirtualMBSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX_AVX512KNL(features,BVH4SubdivPatch1CachedBuilderBinnedSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4SubdivGridEagerBuilderBinnedSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Line4iMeshRefitSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4MeshRefitSAH); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle8MeshRefitSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vMeshRefitSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iMeshRefitSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4MeshBuilderMortonGeneral); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle8MeshBuilderMortonGeneral); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vMeshBuilderMortonGeneral); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iMeshBuilderMortonGeneral); /* select intersectors1 */ SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Line4iIntersector1); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Line4iMBIntersector1); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1vIntersector1); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1iIntersector1); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1vIntersector1_OBB); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1iIntersector1_OBB); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1iMBIntersector1_OBB); SELECT_SYMBOL_DEFAULT_AVX_AVX2_AVX512KNL(features,BVH4Triangle4Intersector1Moeller); SELECT_SYMBOL_DEFAULT_AVX_AVX2_AVX512KNL(features,BVH4XfmTriangle4Intersector1Moeller); SELECT_SYMBOL_INIT_AVX_AVX2 (features,BVH4Triangle8Intersector1Moeller); SELECT_SYMBOL_DEFAULT_SSE42_AVX (features,BVH4Triangle4vIntersector1Pluecker); SELECT_SYMBOL_DEFAULT_SSE42_AVX (features,BVH4Triangle4iIntersector1Pluecker); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Triangle4vMBIntersector1Moeller); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Subdivpatch1CachedIntersector1); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4GridAOSIntersector1); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4VirtualIntersector1); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4VirtualMBIntersector1); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Quad4vIntersector1Moeller); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Quad4iIntersector1Pluecker); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Quad4iMBIntersector1Pluecker); #if defined (RTCORE_RAY_PACKETS) /* select intersectors4 */ SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Line4iIntersector4); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Line4iMBIntersector4); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Bezier1vIntersector4Single); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Bezier1iIntersector4Single); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Bezier1vIntersector4Single_OBB); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Bezier1iIntersector4Single_OBB); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Bezier1iMBIntersector4Single_OBB); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Triangle4Intersector4HybridMoeller); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Triangle4Intersector4HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle8Intersector4HybridMoeller); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle8Intersector4HybridMoellerNoFilter); SELECT_SYMBOL_DEFAULT_SSE42_AVX(features,BVH4Triangle4vIntersector4HybridPluecker); SELECT_SYMBOL_DEFAULT_SSE42_AVX(features,BVH4Triangle4iIntersector4HybridPluecker); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Triangle4vMBIntersector4HybridMoeller); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Quad4vIntersector4HybridMoeller); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Quad4vIntersector4HybridMoellerNoFilter); SELECT_SYMBOL_DEFAULT_AVX (features,BVH4Quad4iIntersector4HybridPluecker); SELECT_SYMBOL_DEFAULT_AVX (features,BVH4Quad4iMBIntersector4HybridPluecker); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Subdivpatch1CachedIntersector4); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4GridAOSIntersector4); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4VirtualIntersector4Chunk); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4VirtualMBIntersector4Chunk); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Quad4vIntersector4HybridMoeller); /* select intersectors8 */ SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Line4iIntersector8); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Line4iMBIntersector8); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Bezier1vIntersector8Single); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Bezier1iIntersector8Single); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Bezier1vIntersector8Single_OBB); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Bezier1iIntersector8Single_OBB); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Bezier1iMBIntersector8Single_OBB); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle4Intersector8HybridMoeller); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle4Intersector8HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle8Intersector8HybridMoeller); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle8Intersector8HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle4vIntersector8HybridPluecker); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle4iIntersector8HybridPluecker); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle4vMBIntersector8HybridMoeller); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Quad4vIntersector8HybridMoeller); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Quad4vIntersector8HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX (features,BVH4Quad4iIntersector8HybridPluecker); SELECT_SYMBOL_INIT_AVX (features,BVH4Quad4iMBIntersector8HybridPluecker); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Subdivpatch1CachedIntersector8); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4GridAOSIntersector8); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4VirtualIntersector8Chunk); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4VirtualMBIntersector8Chunk); /* select intersectors16 */ SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Line4iIntersector16); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Line4iMBIntersector16); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Bezier1vIntersector16Single); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Bezier1iIntersector16Single); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Bezier1vIntersector16Single_OBB); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Bezier1iIntersector16Single_OBB); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Bezier1iMBIntersector16Single_OBB); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle4Intersector16HybridMoeller); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle4Intersector16HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle8Intersector16HybridMoeller); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle8Intersector16HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle4vIntersector16HybridPluecker); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle4iIntersector16HybridPluecker); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle4vMBIntersector16HybridMoeller); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Quad4vIntersector16HybridMoeller); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Quad4vIntersector16HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Quad4iIntersector16HybridPluecker); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Quad4iMBIntersector16HybridPluecker); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Subdivpatch1CachedIntersector16); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4GridAOSIntersector16); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4VirtualIntersector16Chunk); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4VirtualMBIntersector16Chunk); #endif } Accel::Intersectors BVH4Factory::BVH4Bezier1vIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Bezier1vIntersector1; intersectors.intersector4 = BVH4Bezier1vIntersector4Single; intersectors.intersector8 = BVH4Bezier1vIntersector8Single; intersectors.intersector16 = BVH4Bezier1vIntersector16Single; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Bezier1iIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Bezier1iIntersector1; intersectors.intersector4 = BVH4Bezier1iIntersector4Single; intersectors.intersector8 = BVH4Bezier1iIntersector8Single; intersectors.intersector16 = BVH4Bezier1iIntersector16Single; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Line4iIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Line4iIntersector1; intersectors.intersector4 = BVH4Line4iIntersector4; intersectors.intersector8 = BVH4Line4iIntersector8; intersectors.intersector16 = BVH4Line4iIntersector16; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Line4iMBIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Line4iMBIntersector1; intersectors.intersector4 = BVH4Line4iMBIntersector4; intersectors.intersector8 = BVH4Line4iMBIntersector8; intersectors.intersector16 = BVH4Line4iMBIntersector16; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Bezier1vIntersectors_OBB(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Bezier1vIntersector1_OBB; intersectors.intersector4 = BVH4Bezier1vIntersector4Single_OBB; intersectors.intersector8 = BVH4Bezier1vIntersector8Single_OBB; intersectors.intersector16 = BVH4Bezier1vIntersector16Single_OBB; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Bezier1iIntersectors_OBB(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Bezier1iIntersector1_OBB; intersectors.intersector4 = BVH4Bezier1iIntersector4Single_OBB; intersectors.intersector8 = BVH4Bezier1iIntersector8Single_OBB; intersectors.intersector16 = BVH4Bezier1iIntersector16Single_OBB; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Bezier1iMBIntersectors_OBB(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Bezier1iMBIntersector1_OBB; intersectors.intersector4 = BVH4Bezier1iMBIntersector4Single_OBB; intersectors.intersector8 = BVH4Bezier1iMBIntersector8Single_OBB; intersectors.intersector16 = BVH4Bezier1iMBIntersector16Single_OBB; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Triangle4IntersectorsHybrid(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Triangle4Intersector1Moeller; intersectors.intersector4_filter = BVH4Triangle4Intersector4HybridMoeller; intersectors.intersector4_nofilter = BVH4Triangle4Intersector4HybridMoellerNoFilter; intersectors.intersector8_filter = BVH4Triangle4Intersector8HybridMoeller; intersectors.intersector8_nofilter = BVH4Triangle4Intersector8HybridMoellerNoFilter; intersectors.intersector16_filter = BVH4Triangle4Intersector16HybridMoeller; intersectors.intersector16_nofilter = BVH4Triangle4Intersector16HybridMoellerNoFilter; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Triangle4IntersectorsInstancing(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4XfmTriangle4Intersector1Moeller; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Triangle8IntersectorsHybrid(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Triangle8Intersector1Moeller; intersectors.intersector4_filter = BVH4Triangle8Intersector4HybridMoeller; intersectors.intersector4_nofilter = BVH4Triangle8Intersector4HybridMoellerNoFilter; intersectors.intersector8_filter = BVH4Triangle8Intersector8HybridMoeller; intersectors.intersector8_nofilter = BVH4Triangle8Intersector8HybridMoellerNoFilter; intersectors.intersector16_filter = BVH4Triangle8Intersector16HybridMoeller; intersectors.intersector16_nofilter = BVH4Triangle8Intersector16HybridMoellerNoFilter; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Triangle4vIntersectorsHybrid(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Triangle4vIntersector1Pluecker; intersectors.intersector4 = BVH4Triangle4vIntersector4HybridPluecker; intersectors.intersector8 = BVH4Triangle4vIntersector8HybridPluecker; intersectors.intersector16 = BVH4Triangle4vIntersector16HybridPluecker; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Triangle4iIntersectorsHybrid(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Triangle4iIntersector1Pluecker; intersectors.intersector4 = BVH4Triangle4iIntersector4HybridPluecker; intersectors.intersector8 = BVH4Triangle4iIntersector8HybridPluecker; intersectors.intersector16 = BVH4Triangle4iIntersector16HybridPluecker; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Triangle4vMBIntersectorsHybrid(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Triangle4vMBIntersector1Moeller; intersectors.intersector4 = BVH4Triangle4vMBIntersector4HybridMoeller; intersectors.intersector8 = BVH4Triangle4vMBIntersector8HybridMoeller; intersectors.intersector16 = BVH4Triangle4vMBIntersector16HybridMoeller; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Quad4vIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Quad4vIntersector1Moeller; intersectors.intersector4_filter = BVH4Quad4vIntersector4HybridMoeller; intersectors.intersector4_nofilter = BVH4Quad4vIntersector4HybridMoellerNoFilter; intersectors.intersector8_filter = BVH4Quad4vIntersector8HybridMoeller; intersectors.intersector8_nofilter = BVH4Quad4vIntersector8HybridMoellerNoFilter; intersectors.intersector16_filter = BVH4Quad4vIntersector16HybridMoeller; intersectors.intersector16_nofilter = BVH4Quad4vIntersector16HybridMoellerNoFilter; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Quad4iIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Quad4iIntersector1Pluecker; intersectors.intersector4 = BVH4Quad4iIntersector4HybridPluecker; intersectors.intersector8 = BVH4Quad4iIntersector8HybridPluecker; intersectors.intersector16= BVH4Quad4iIntersector16HybridPluecker; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Quad4iMBIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Quad4iMBIntersector1Pluecker; intersectors.intersector4 = BVH4Quad4iMBIntersector4HybridPluecker; intersectors.intersector8 = BVH4Quad4iMBIntersector8HybridPluecker; intersectors.intersector16= BVH4Quad4iMBIntersector16HybridPluecker; return intersectors; } void BVH4Factory::createLineSegmentsLine4i(LineSegments* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Line4i::type,mesh->parent); switch (mesh->flags) { case RTC_GEOMETRY_STATIC: builder = factory->BVH4Line4iMeshBuilderSAH(accel,mesh,0); break; case RTC_GEOMETRY_DEFORMABLE: builder = factory->BVH4Line4iMeshRefitSAH(accel,mesh,0); break; case RTC_GEOMETRY_DYNAMIC: builder = factory->BVH4Line4iMeshBuilderSAH(accel,mesh,0); break; default: throw_RTCError(RTC_UNKNOWN_ERROR,"invalid geometry flag"); } } void BVH4Factory::createTriangleMeshTriangle4Morton(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle4::type,mesh->parent); builder = mesh->parent->device->bvh4_factory->BVH4Triangle4MeshBuilderMortonGeneral(accel,mesh,0); } #if defined (__TARGET_AVX__) void BVH4Factory::createTriangleMeshTriangle8Morton(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { accel = new BVH4(Triangle8::type,mesh->parent); builder = mesh->parent->device->bvh4_factory->BVH4Triangle8MeshBuilderMortonGeneral(accel,mesh,0); } #endif void BVH4Factory::createTriangleMeshTriangle4vMorton(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle4v::type,mesh->parent); builder = mesh->parent->device->bvh4_factory->BVH4Triangle4vMeshBuilderMortonGeneral(accel,mesh,0); } void BVH4Factory::createTriangleMeshTriangle4iMorton(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle4i::type,mesh->parent); builder = mesh->parent->device->bvh4_factory->BVH4Triangle4iMeshBuilderMortonGeneral(accel,mesh,0); } void BVH4Factory::createTriangleMeshTriangle4(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle4::type,mesh->parent); switch (mesh->flags) { case RTC_GEOMETRY_STATIC: builder = factory->BVH4Triangle4MeshBuilderSAH(accel,mesh,0); break; case RTC_GEOMETRY_DEFORMABLE: builder = factory->BVH4Triangle4MeshRefitSAH(accel,mesh,0); break; case RTC_GEOMETRY_DYNAMIC: builder = factory->BVH4Triangle4MeshBuilderMortonGeneral(accel,mesh,0); break; default: throw_RTCError(RTC_UNKNOWN_ERROR,"invalid geometry flag"); } } #if defined (__TARGET_AVX__) void BVH4Factory::createTriangleMeshTriangle8(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle8::type,mesh->parent); switch (mesh->flags) { case RTC_GEOMETRY_STATIC: builder = factory->BVH4Triangle8MeshBuilderSAH(accel,mesh,0); break; case RTC_GEOMETRY_DEFORMABLE: builder = factory->BVH4Triangle8MeshRefitSAH(accel,mesh,0); break; case RTC_GEOMETRY_DYNAMIC: builder = factory->BVH4Triangle8MeshBuilderMortonGeneral(accel,mesh,0); break; default: throw_RTCError(RTC_UNKNOWN_ERROR,"invalid geometry flag"); } } #endif void BVH4Factory::createTriangleMeshTriangle4v(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle4v::type,mesh->parent); switch (mesh->flags) { case RTC_GEOMETRY_STATIC: builder = factory->BVH4Triangle4vMeshBuilderSAH(accel,mesh,0); break; case RTC_GEOMETRY_DEFORMABLE: builder = factory->BVH4Triangle4vMeshRefitSAH(accel,mesh,0); break; case RTC_GEOMETRY_DYNAMIC: builder = factory->BVH4Triangle4vMeshBuilderMortonGeneral(accel,mesh,0); break; default: throw_RTCError(RTC_UNKNOWN_ERROR,"invalid geometry flag"); } } void BVH4Factory::createTriangleMeshTriangle4i(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle4i::type,mesh->parent); switch (mesh->flags) { case RTC_GEOMETRY_STATIC: builder = factory->BVH4Triangle4iMeshBuilderSAH(accel,mesh,0); break; case RTC_GEOMETRY_DEFORMABLE: builder = factory->BVH4Triangle4iMeshRefitSAH(accel,mesh,0); break; case RTC_GEOMETRY_DYNAMIC: builder = factory->BVH4Triangle4iMeshBuilderMortonGeneral(accel,mesh,0); break; default: throw_RTCError(RTC_UNKNOWN_ERROR,"invalid geometry flag"); } } Accel* BVH4Factory::BVH4Bezier1v(Scene* scene) { BVH4* accel = new BVH4(Bezier1v::type,scene); Accel::Intersectors intersectors = BVH4Bezier1vIntersectors(accel); Builder* builder = BVH4Bezier1vSceneBuilderSAH(accel,scene,0); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Bezier1i(Scene* scene) { BVH4* accel = new BVH4(Bezier1i::type,scene); Accel::Intersectors intersectors = BVH4Bezier1iIntersectors(accel); Builder* builder = BVH4Bezier1iSceneBuilderSAH(accel,scene,0); scene->needBezierVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Line4i(Scene* scene) { BVH4* accel = new BVH4(Line4i::type,scene); Accel::Intersectors intersectors = BVH4Line4iIntersectors(accel); Builder* builder = nullptr; if (scene->device->line_builder == "default" ) builder = BVH4Line4iSceneBuilderSAH(accel,scene,0); else if (scene->device->line_builder == "sah" ) builder = BVH4Line4iSceneBuilderSAH(accel,scene,0); else if (scene->device->line_builder == "dynamic" ) builder = BVH4BuilderTwoLevelLineSegmentsSAH(accel,scene,&createLineSegmentsLine4i); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->line_builder+" for BVH4<Line4i>"); scene->needLineVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Line4iMB(Scene* scene) { BVH4* accel = new BVH4(Line4i::type,scene); Accel::Intersectors intersectors = BVH4Line4iMBIntersectors(accel); Builder* builder = BVH4Line4iMBSceneBuilderSAH(accel,scene,0); scene->needLineVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Line4iTwolevel(Scene* scene) { BVH4* accel = new BVH4(Line4i::type,scene); Accel::Intersectors intersectors = BVH4Line4iIntersectors(accel); Builder* builder = BVH4BuilderTwoLevelLineSegmentsSAH(accel,scene,&createLineSegmentsLine4i); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4OBBBezier1v(Scene* scene, bool highQuality) { BVH4* accel = new BVH4(Bezier1v::type,scene); Accel::Intersectors intersectors = BVH4Bezier1vIntersectors_OBB(accel); Builder* builder = BVH4Bezier1vBuilder_OBB_New(accel,scene,0); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4OBBBezier1i(Scene* scene, bool highQuality) { BVH4* accel = new BVH4(Bezier1i::type,scene); Accel::Intersectors intersectors = BVH4Bezier1iIntersectors_OBB(accel); Builder* builder = BVH4Bezier1iBuilder_OBB_New(accel,scene,0); scene->needBezierVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4OBBBezier1iMB(Scene* scene, bool highQuality) { BVH4* accel = new BVH4(Bezier1i::type,scene); Accel::Intersectors intersectors = BVH4Bezier1iMBIntersectors_OBB(accel); Builder* builder = BVH4Bezier1iMBBuilder_OBB_New(accel,scene,0); scene->needBezierVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4(Scene* scene) { BVH4* accel = new BVH4(Triangle4::type,scene); Accel::Intersectors intersectors; if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle4IntersectorsHybrid(accel); else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle4IntersectorsHybrid(accel); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle4>"); Builder* builder = nullptr; if (scene->device->tri_builder == "default" ) builder = BVH4Triangle4SceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah" ) builder = BVH4Triangle4SceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_spatial" ) builder = BVH4Triangle4SceneBuilderSpatialSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_presplit") builder = BVH4Triangle4SceneBuilderSAH(accel,scene,MODE_HIGH_QUALITY); else if (scene->device->tri_builder == "dynamic" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4); else if (scene->device->tri_builder == "morton" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4Morton); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->tri_builder+" for BVH4<Triangle4>"); return new AccelInstance(accel,builder,intersectors); } #if defined (__TARGET_AVX__) Accel* BVH4Factory::BVH4Triangle8(Scene* scene) { BVH4* accel = new BVH4(Triangle8::type,scene); Accel::Intersectors intersectors; if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle8IntersectorsHybrid(accel); else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle8IntersectorsHybrid(accel); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle8>"); Builder* builder = nullptr; if (scene->device->tri_builder == "default" ) builder = BVH4Triangle8SceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah" ) builder = BVH4Triangle8SceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_spatial" ) builder = BVH4Triangle8SceneBuilderSpatialSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_presplit") builder = BVH4Triangle8SceneBuilderSAH(accel,scene,MODE_HIGH_QUALITY); else if (scene->device->tri_builder == "dynamic" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle8); else if (scene->device->tri_builder == "morton" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle8Morton); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->tri_builder+" for BVH4<Triangle8>"); return new AccelInstance(accel,builder,intersectors); } #endif Accel* BVH4Factory::BVH4Triangle4v(Scene* scene) { BVH4* accel = new BVH4(Triangle4v::type,scene); Accel::Intersectors intersectors; if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle4vIntersectorsHybrid(accel); else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle4vIntersectorsHybrid(accel); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle4>"); Builder* builder = nullptr; if (scene->device->tri_builder == "default" ) builder = BVH4Triangle4vSceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah" ) builder = BVH4Triangle4vSceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_spatial" ) builder = BVH4Triangle4vSceneBuilderSpatialSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_presplit") builder = BVH4Triangle4vSceneBuilderSAH(accel,scene,MODE_HIGH_QUALITY); else if (scene->device->tri_builder == "dynamic" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4v); else if (scene->device->tri_builder == "morton" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4vMorton); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->tri_builder+" for BVH4<Triangle4v>"); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4i(Scene* scene) { BVH4* accel = new BVH4(Triangle4i::type,scene); Accel::Intersectors intersectors; if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle4iIntersectorsHybrid(accel); else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle4iIntersectorsHybrid(accel); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle4i>"); Builder* builder = nullptr; if (scene->device->tri_builder == "default" ) builder = BVH4Triangle4iSceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah" ) builder = BVH4Triangle4iSceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_spatial" ) builder = BVH4Triangle4iSceneBuilderSpatialSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_presplit") builder = BVH4Triangle4iSceneBuilderSAH(accel,scene,MODE_HIGH_QUALITY); else if (scene->device->tri_builder == "dynamic" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4i); else if (scene->device->tri_builder == "morton" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4iMorton); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->tri_builder+" for BVH4<Triangle4i>"); scene->needTriangleVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4vMB(Scene* scene) { BVH4* accel = new BVH4(Triangle4vMB::type,scene); Accel::Intersectors intersectors; if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle4vMBIntersectorsHybrid(accel); else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle4vMBIntersectorsHybrid(accel); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle4vMB>"); Builder* builder = nullptr; if (scene->device->tri_builder_mb == "default" ) builder = BVH4Triangle4vMBSceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder_mb == "sah") builder = BVH4Triangle4vMBSceneBuilderSAH(accel,scene,0); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->tri_builder_mb+" for BVH4<Triangle4vMB>"); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4InstancedBVH4Triangle4ObjectSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle4::type,scene); Accel::Intersectors intersectors = BVH4Triangle4IntersectorsInstancing(accel); Builder* builder = BVH4BuilderInstancingTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4Twolevel(Scene* scene) { BVH4* accel = new BVH4(Triangle4::type,scene); Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel); Builder* builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4); return new AccelInstance(accel,builder,intersectors); } #if defined (__TARGET_AVX__) Accel* BVH4Factory::BVH4Triangle8Twolevel(Scene* scene) { BVH4* accel = new BVH4(Triangle8::type,scene); Accel::Intersectors intersectors = BVH4Triangle8IntersectorsHybrid(accel); Builder* builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle8); return new AccelInstance(accel,builder,intersectors); } #endif Accel* BVH4Factory::BVH4Triangle4vTwolevel(Scene* scene) { BVH4* accel = new BVH4(Triangle4v::type,scene); Accel::Intersectors intersectors = BVH4Triangle4vIntersectorsHybrid(accel); Builder* builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4v); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4iTwolevel(Scene* scene) { BVH4* accel = new BVH4(Triangle4i::type,scene); Accel::Intersectors intersectors = BVH4Triangle4iIntersectorsHybrid(accel); Builder* builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4i); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4SpatialSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle4::type,scene); Builder* builder = BVH4Triangle4SceneBuilderSpatialSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } #if defined (__TARGET_AVX__) Accel* BVH4Factory::BVH4Triangle8SpatialSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle8::type,scene); Builder* builder = BVH4Triangle8SceneBuilderSpatialSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Triangle8IntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } #endif Accel* BVH4Factory::BVH4Triangle4ObjectSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle4::type,scene); Builder* builder = BVH4Triangle4SceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } #if defined (__TARGET_AVX__) Accel* BVH4Factory::BVH4Triangle8ObjectSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle8::type,scene); Builder* builder = BVH4Triangle8SceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Triangle8IntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } #endif Accel* BVH4Factory::BVH4Triangle4vObjectSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle4v::type,scene); Builder* builder = BVH4Triangle4vSceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Triangle4vIntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4iObjectSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle4i::type,scene); Builder* builder = BVH4Triangle4iSceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Triangle4iIntersectorsHybrid(accel); scene->needTriangleVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4SubdivPatch1Cached(Scene* scene) { BVH4* accel = new BVH4(SubdivPatch1Cached::type,scene); Accel::Intersectors intersectors; intersectors.ptr = accel; intersectors.intersector1 = BVH4Subdivpatch1CachedIntersector1; intersectors.intersector4 = BVH4Subdivpatch1CachedIntersector4; intersectors.intersector8 = BVH4Subdivpatch1CachedIntersector8; intersectors.intersector16 = BVH4Subdivpatch1CachedIntersector16; Builder* builder = BVH4SubdivPatch1CachedBuilderBinnedSAH(accel,scene,0); scene->needSubdivIndices = false; scene->needSubdivVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4SubdivGridEager(Scene* scene) { BVH4* accel = new BVH4(SubdivPatch1Eager::type,scene); Accel::Intersectors intersectors; intersectors.ptr = accel; intersectors.intersector1 = BVH4GridAOSIntersector1; intersectors.intersector4 = BVH4GridAOSIntersector4; intersectors.intersector8 = BVH4GridAOSIntersector8; intersectors.intersector16 = BVH4GridAOSIntersector16; Builder* builder = BVH4SubdivGridEagerBuilderBinnedSAH(accel,scene,0); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4UserGeometry(Scene* scene) { BVH4* accel = new BVH4(Object::type,scene); Accel::Intersectors intersectors; intersectors.ptr = accel; intersectors.intersector1 = BVH4VirtualIntersector1; intersectors.intersector4 = BVH4VirtualIntersector4Chunk; intersectors.intersector8 = BVH4VirtualIntersector8Chunk; intersectors.intersector16 = BVH4VirtualIntersector16Chunk; Builder* builder = BVH4VirtualSceneBuilderSAH(accel,scene,0); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4UserGeometryMB(Scene* scene) { BVH4* accel = new BVH4(Object::type,scene); Accel::Intersectors intersectors; intersectors.ptr = accel; intersectors.intersector1 = BVH4VirtualMBIntersector1; intersectors.intersector4 = BVH4VirtualMBIntersector4Chunk; intersectors.intersector8 = BVH4VirtualMBIntersector8Chunk; intersectors.intersector16 = BVH4VirtualMBIntersector16Chunk; Builder* builder = BVH4VirtualMBSceneBuilderSAH(accel,scene,0); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4ObjectSplit(TriangleMesh* mesh) { BVH4* accel = new BVH4(Triangle4::type,mesh->parent); Builder* builder = BVH4Triangle4MeshBuilderSAH(accel,mesh,0); Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4vObjectSplit(TriangleMesh* mesh) { BVH4* accel = new BVH4(Triangle4v::type,mesh->parent); Builder* builder = BVH4Triangle4vMeshBuilderSAH(accel,mesh,0); Accel::Intersectors intersectors = BVH4Triangle4vIntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4Refit(TriangleMesh* mesh) { BVH4* accel = new BVH4(Triangle4::type,mesh->parent); Builder* builder = BVH4Triangle4MeshRefitSAH(accel,mesh,0); Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Quad4v(Scene* scene) { BVH4* accel = new BVH4(Quad4v::type,scene); Builder* builder = BVH4Quad4vSceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Quad4vIntersectors(accel); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Quad4i(Scene* scene) { BVH4* accel = new BVH4(Quad4i::type,scene); Builder* builder = BVH4Quad4iSceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Quad4iIntersectors(accel); scene->needQuadVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Quad4iMB(Scene* scene) { BVH4* accel = new BVH4(Quad4iMB::type,scene); Builder* builder = BVH4Quad4iMBSceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Quad4iMBIntersectors(accel); scene->needQuadVertices = true; return new AccelInstance(accel,builder,intersectors); } }
KIKI007/ReusedPrinter
external/embree/kernels/xeon/bvh/bvh4_factory.cpp
C++
mpl-2.0
52,759
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */ .frames ul .frames-group .group, .frames ul .frames-group .group .location { font-weight: 500; cursor: default; } .frames ul .frames-group.expanded .group, .frames ul .frames-group.expanded .group .location { color: var(--theme-highlight-blue); } .frames ul .frames-group.expanded .react path { fill: var(--theme-highlight-blue); } .frames ul .frames-group .frames-list li { padding-left: 30px; } .frames ul .frames-group .frames-list { border-top: 1px solid var(--theme-splitter-color); border-bottom: 1px solid var(--theme-splitter-color); } .frames ul .frames-group.expanded .badge { color: var(--theme-highlight-blue); }
jbhoosreddy/debugger.html
src/components/SecondaryPanes/Frames/Group.css
CSS
mpl-2.0
854
/** * Nooku Platform - http://www.nooku.org/platform * * @copyright Copyright (C) 2011 - 2014 Johan Janssens and Timble CVBA. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link https://github.com/nooku/nooku-platform for the canonical source repository */ if(!Attachments) var Attachments = {}; Attachments.List = new Class({ element : null, initialize: function(options) { this.element = document.id(options.container); this.url = options.action; this.token = options.token; this.coordinates = ''; this.trueSize = ''; if(!this.element) { return; } this.addCrop(); var that = this; this.element.getElements('a[data-action]').each(function(a) { if(a.get('data-action')) { a.addEvent('click', function(e) { e.stop(); that.execute(this.get('data-action'), this.get('data-id'), this.get('data-row')); }); } }); }, addCrop: function() { var target = jQuery('#target'); var img = new Image(), self = this; img.onload = function() { self.trueSize = [this.width, this.height]; if (target.length) { target.Jcrop({ boxWidth: 600, boxHeight: 600, trueSize: self.trueSize, aspectRatio: 4 / 3, minSize: [200, 150], setSelect: [0, 0, 200, 150], onSelect: self.setCoordinates.bind(self), onChange: self.setCoordinates.bind(self) }); } }; var source = target.attr("src"); if (source) { img.src = source; } }, setCoordinates: function(c) { this.coordinates = c; }, execute: function(action, id, row) { var method = '_action' + action.capitalize(); if($type(this[method]) == 'function') { this.action = action; var uri = new URI(this.url); uri.setData('id', id); this[method].call(this, uri); } }, _actionDelete: function(uri) { var form = new Kodekit.Form({ method: 'post', url: uri.toString(), params: { _action: 'delete', csrf_token: this.token } }); form.submit(); }, _actionCrop: function(uri) { jQuery.ajax({ url: uri.toString(), dataType: 'json', method: 'post', data: { _action: 'edit', csrf_token: this.token, x1: this.coordinates.x, y1: this.coordinates.y, x2: this.coordinates.x2, y2: this.coordinates.y2 } }).then(function(data, textStatus, xhr) { if (xhr.status === 204) { jQuery.ajax({ url: uri.toString(), dataType: 'json', method: 'get' }).then(function(data, textStatus, xhr) { if (xhr.status === 200 && typeof data.item === 'object') { var thumbnail = data.item.thumbnail, element = window.parent.jQuery('.thumbnail[data-id="'+data.item.id+'"] img'), source = element.attr('src'); thumbnail = source.substring(0, source.lastIndexOf('/'))+'/'+thumbnail; element.attr('src', thumbnail); if (window.parent.SqueezeBox) { window.parent.SqueezeBox.close(); } } }); } else { alert('Unable to crop thumbnail'); } }); } });
nooku/nooku-platform
component/attachments/resources/assets/js/attachments.list.js
JavaScript
mpl-2.0
4,062
/*! JointJS v3.4.1 (2021-08-18) - JavaScript diagramming library This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ this.joint = this.joint || {}; this.joint.shapes = this.joint.shapes || {}; (function (exports, basic_mjs, Element_mjs, Link_mjs) { 'use strict'; var State = basic_mjs.Circle.define('fsa.State', { attrs: { circle: { 'stroke-width': 3 }, text: { 'font-weight': '800' } } }); var StartState = Element_mjs.Element.define('fsa.StartState', { size: { width: 20, height: 20 }, attrs: { circle: { transform: 'translate(10, 10)', r: 10, fill: '#000000' } } }, { markup: '<g class="rotatable"><g class="scalable"><circle/></g></g>', }); var EndState = Element_mjs.Element.define('fsa.EndState', { size: { width: 20, height: 20 }, attrs: { '.outer': { transform: 'translate(10, 10)', r: 10, fill: '#ffffff', stroke: '#000000' }, '.inner': { transform: 'translate(10, 10)', r: 6, fill: '#000000' } } }, { markup: '<g class="rotatable"><g class="scalable"><circle class="outer"/><circle class="inner"/></g></g>', }); var Arrow = Link_mjs.Link.define('fsa.Arrow', { attrs: { '.marker-target': { d: 'M 10 0 L 0 5 L 10 10 z' }}, smooth: true }); exports.Arrow = Arrow; exports.EndState = EndState; exports.StartState = StartState; exports.State = State; }(this.joint.shapes.fsa = this.joint.shapes.fsa || {}, joint.shapes.basic, joint.dia, joint.dia));
DavidDurman/joint
dist/joint.shapes.fsa.js
JavaScript
mpl-2.0
1,920
<!doctype html> <script> var searchParams = new URL(location).searchParams; var test = searchParams.get("test"); window.onportalactivate = function(e) { if (test == "adopt-once") { var portal = e.adoptPredecessor(); document.body.appendChild(portal); if (portal instanceof HTMLPortalElement) { portal.postMessage("adopted", "*"); } } if (test == "adopt-twice") { var portal = e.adoptPredecessor(); document.body.appendChild(portal); try { e.adoptPredecessor(); } catch(e) { if (e.name == "InvalidStateError") { portal.postMessage("passed", "*"); } } } if (test == "adopt-after-event") { setTimeout(function() { try { e.adoptPredecessor(); } catch(e) { if (e.name == "InvalidStateError") { var bc_test = new BroadcastChannel(`test-${test}`); bc_test.postMessage("passed"); bc_test.close(); } } }); } } </script>
pyfisch/servo
tests/wpt/web-platform-tests/portals/resources/portals-adopt-predecessor-portal.html
HTML
mpl-2.0
1,044
<!DOCTYPE html> <html lang="en"> <head> <title>HYPERNOM</title> <!-- Nom all the cells of each 4d platonic solid, by mapping your head rotations to S^3. By Henry Segerman, Vi Hart, and Andrea Hawksley, using Marc ten Bosch's 4D graphics shader, Mozilla's webVR stuff, and threejs. http://www.segerman.org/ http://vihart.com https://github.com/hawksley http://www.marctenbosch.com https://github.com/MozVR/vr-web-examples/tree/master/threejs-vr-boilerplate http://threejs.org --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> <style> body { background-color: #000; color: #fff; margin: 0px; padding: 0; overflow: hidden; } </style> </head> <body style="cursor:pointer"> <audio id='music' src="media/monkeygif.mp3"/> <audio id='nom1' src="media/nom1.ogg" > <audio id='nom2' src="media/nom2.ogg" > <audio id='nom3' src="media/nom3.ogg" > <audio id='nom4' src="media/nom4.ogg" > <audio id='nom5' src="media/nom5.ogg" > <audio id='win' src="media/win.ogg" > </body> <!-- three.js 3d library --> <script src="js/lib/three.min.js"></script> <script src="js/lib/threex.dynamictexture.js"></script> <!-- library for fast quaternion rotation --> <script src="js/lib/gl-matrix.js"></script> <script src="js/sphMath.js"></script> <!-- VRControls.js acquires positional information from connected VR devices and applies the transformations to a three.js camera object. --> <script src="js/vr/PhoneVR.js"></script> <script src="js/vr/VRControlsHyperNom.js"></script> <!-- VREffect.js handles stereo camera setup and rendering. --> <script src="js/vr/VREffect.js"></script> <!-- Quaternions for the centers of the cells --> <script src="js/centers_600_cell.js"></script> <script src="js/centers_5_cell.js"></script> <script src="js/centers_8_cell.js"></script> <script src="js/centers_16_cell.js"></script> <script src="js/centers_24_cell.js"></script> <script src="js/centers_120_cell.js"></script> <script src="js/loaders/OBJLoader.js"></script> <!--font from http://mrdoob.github.com/three.js/examples/fonts/helvetiker_regular.typeface.js --> <script src="lib/helvetiker.js"></script> <script type="x-shader/x-vertex" id="vertexShader"> // This shader moves vertices around // Quaternion Multiplication vec4 quatMult( in vec4 p, in vec4 q ) { vec4 r; r.w = + p.w*q.w - p.x*q.x - p.y*q.y - p.z*q.z; r.x = + p.w*q.x + p.x*q.w + p.y*q.z - p.z*q.y; r.y = + p.w*q.y - p.x*q.z + p.y*q.w + p.z*q.x; r.z = + p.w*q.z + p.x*q.y - p.y*q.x + p.z*q.w; return r; } vec4 quatInv( in vec4 p ) { vec4 r; r.x = -p.x; r.y = -p.y; r.z = -p.z; r.w = p.w; return r; } // Project the vector p to the 3-space perpendicular to q vec4 projVecPerp( in vec4 p, in vec4 q ) { vec4 r; float pDotq = dot(p,q); float qDotq = dot(q,q); float foo = pDotq / qDotq; r = p - foo*q; return r; } // point on geod in S3 from p in direction of q going distance dist vec4 pointOnS3Geod( in vec4 p, in vec4 q, in float dist) { vec4 Q = normalize( q - dot(p,q) * p ); return cos(dist)*p + sin(dist)*Q; } // input uniform float time; // global time in seconds uniform vec4 quatPerCell; // quaternion that moves this monkey into 4-space, set once per monkey // uniform int fogType; // which type of fog to use uniform vec2 mousePos; uniform vec4 travelDir; //quaternion for which way we are rotating uniform vec4 colourDir; //quaternion for which way we are colouring uniform mat4 HopfColorMatrix; //rotates colourDir to lie along (0,0,z,w) uniform vec4 moveQuat; //quaternion for head uniform mat3 rotMatrix; //rotate tetrahedral cells into correct orientation uniform float modelScale; //scale model by this // Hopf fibration coloring // returns a color based on the 4D normal vec3 HopfColor( in vec4 nBase ) /// head foot are all same colour { /////////first rotate the 4D normal to a space aligned with the polychoron vec4 n = HopfColorMatrix * nBase; // compute the color float x = n.x; float y = n.y; float u = n.z; float v = n.w; float r = 2. * (u*x + v*y); float g = 2. * (u*y - v*x); float b = x*x + y*y - u*u - v*v; /// first two coords are 2*z*conj(w), where z = x+iy, w = u+iv /// rotate [0,0,-1] to [-1,-1,-1]/sqrt(3) mat3 RotDownToDiag = mat3( vec3(0.707107, -0.707107, 0.), ///// input columns not rows?!?!?! vec3(0.408248, 0.408248, -0.816497), //Because line n+3 is RotDownToDiag*newCol, not newCol*RotDownToDiag. vec3(0.57735, 0.57735, 0.57735) ); //This basically lets the shader do matrix multiplication via dot products, which is relatively efficient. vec3 newCol = vec3(r,g,b); newCol = RotDownToDiag * newCol; return vec3(newCol.x*0.5 + 0.5,newCol.y*0.5 + 0.5,newCol.z*0.5 + 0.5); } // output varying vec3 vColor; // this shader computes the color of each vertex // this gets called once per vertex of the monkey mesh (and numCells times since there are numCells monkeys) void main() { // base position // turn a 3D position of a model into a 4D position by adding a 1 as the w component then normalizing to get onto the unit 3-sphere // vec4 p3sphere = normalize( vec4(position.zyx, 1.0) ); vec3 posn = position.zyx; posn = rotMatrix * posn; vec4 p3sphere = normalize( vec4(modelScale * posn, 1.0) ); // then rotate using this cell's quaternion to place in 4D vec4 pt0 = quatMult( quatPerCell, p3sphere ); //position at time = 0 // this is the normal to the point // same concept as for the position, but we add a 0 as the w component vec4 n3sphere = vec4( normal.zyx, 0.0); // above is normal on a cubical cell of the hypercube, below we get the corresponding // normal on the 3-sphere n3sphere = projVecPerp( n3sphere, p3sphere ); // rotate the normal using this monkey's quaternion vec4 nt0 = quatMult(quatPerCell, n3sphere ); // // also rotate everything over time // vec4 quatOverTime = pointOnS3Geod( vec4(0,0,0,1), travelDir, 0.5*time ); // vec4 quatOverTime = vec4(0,0,0,1); vec4 quatOverTime = moveQuat; vec4 p = quatMult( quatOverTime, pt0 ); vec4 n = quatMult( quatOverTime, nt0 ); // stereographic projection from 4D to 3D vec3 pos3 = vec3( p.x / (1.0-p.w), p.y / (1.0-p.w), p.z / (1.0-p.w) ); // compute the color from the normal //// using HopfColor again... vec3 nColor = HopfColor(nt0); //// or the transported back to 1 normal // vec4 nTransported = quatMult(quatInv(pt0), nt0); // vec3 nColor = vec3(0.5,0.5,0.5) + 0.5*normalize( vec3( nTransported.x, nTransported.y, nTransported.z) ); vec3 pColor = HopfColor(pt0); vColor = -0.5*(nColor-vec3(0.5,0.5,0.5)) + 1.0*(pColor-vec3(0.5,0.5,0.5)) + vec3(0.5,0.5,0.5); // vColor = pColor; // vColor = nColor; // take the final 3D position and project it onto the screen // gl_Position = projectionMatrix * modelViewMatrix * vec4( pos3 + vec3(0.0,-0.6,-1.5), 1.0 ); // gl_Position = projectionMatrix * modelViewMatrix * vec4( pos3 + vec3(0.0,-0.7,-2.3), 1.0 ); gl_Position = modelViewMatrix * vec4( pos3 , 1.0 ); //truncate before the projectionMatrix transform (continued on line 253) //Okay, now a slightly tricky thing: //The camera's going to cull any vertices that are closer than 0.2, or further away than 25, from the camera. //(in practice, this seems to be slightly different. I'm not sure why.) //When this happens, it creates the black triangle of death, which pulls the viewer out of the virtual reality. //To get around this, we're going to flatten out each vertex just before it reaches 0.2 or 25, moving it to where it would be. //So, essentially, this is like replacing actual stars with a correctly painted planetarium. //In case there's some weird z-layering going on, we're going to map -0.3,0 to -0.3, -0.2, preserving order. float oldz=gl_Position.z; if(oldz>-0.3 && oldz<0.0){ //map [-0.3, 0.0] to [-0.3,-0.2] float newz=(oldz*0.3333333 - 0.2); gl_Position.x=gl_Position.x*newz/(oldz); gl_Position.y=gl_Position.y*newz/(oldz); gl_Position.z=newz; gl_Position.w=1.0; } gl_Position=projectionMatrix * gl_Position; // do fog // if ( fogType == 1 ) // { // ramp fog // compute distance to camera from 0 to 1 float zz = gl_Position.z / gl_Position.w; // go from 1 to 0 instead (0 is furthest and 1 is where the camera is ) // ( note that the computed distance is not linear ) float fogScale = 1. - zz; // anything closer than 0.1 gets regular color if ( fogScale > 0.1 ) fogScale = 1.0; // everything else ramps from 0 to 1 else fogScale = fogScale / 0.1; // mutliply color by this value to make it go to black vColor *= fogScale; //2015-02-17: fog re-enabled // } // else if ( fogType == 2 ) // { // // near fog // float zz = gl_Position.z / gl_Position.w; // // go from 1 to 0, and make the curve less straight // float fogScale = pow( 1. - zz, 0.7 ); // // everything closer than 0.2 gets regular color // // but everything else stays the same, creating a discontinuity // if ( fogScale > 0.2 ) fogScale = 1.0; // // mutliply color by this value to make it go to black // vColor *= fogScale; // } else if (fogType == 3 ){ // vColor.r *= mousePos.x/1000.; // vColor.g *= mousePos.y/1000.; // vColor.b *= abs(1. - (mousePos.x + mousePos.y)/1000.); // } } </script> <script type="x-shader/x-vertex" id="fragmentShader"> // this gets called once per pixel varying vec3 vColor; void main() { // just use the color we computed and assign it to this pixel gl_FragColor = vec4( vColor, 1. ); } </script> <script type="text/javascript" id="mainCode" src="js/hypernom.js"></script> </html>
DarkPrince304/webVR-playing-with
hypernom.html
HTML
mpl-2.0
10,152
.pinboard-open-btn { margin-top: -1px; background-color: #e6eef5 !important; color: #252c33 !important; } #pinboard-panel { background-color: #e6eef5; color: #252c33; flex: auto; -webkit-flex: auto; display: flex; display: -webkit-flex; flex-flow: row; -webkit-flex-flow: row; } #pinboard-panel .header { padding-left: 2px; height: 18px; } /* * Pinned jobs container */ #pinned-job-list { position: relative; flex: auto; -webkit-flex: auto; margin: 7px 7px 10px; } #pinned-job-list .content { position: absolute; width: 100%; height: 100%; padding: 2px; overflow: auto; background-color: #FFFFFF; } .pinned-job { margin-bottom: 2px; padding: 1px 2px; width: 3.5em; } .pinned-job-close-btn { padding: 1px 2px 1px 2px; border-color: #fafafa #fafafa #fafafa transparent; } .pinboard-preload-txt { color: #bfbfbf; } /* * Related bugs container */ #pinboard-related-bugs { position: relative; width: 200px; flex: none; -webkit-flex: none; margin: 7px 7px 10px; } #pinboard-related-bugs .content { position: absolute; height: 100%; width: 200px; padding: 2px; overflow-x: hidden; color: black; background-color: #FFFFFF; } .add-related-bugs-icon { margin-right: 2px; font-size: 17px; color: #98c3da; } .add-related-bugs-form { position: relative; top: -18px; left: 20px; } .add-related-bugs-input { width: 12em; } .pinboard-related-bug-preload-txt { vertical-align: top; } .pinboard-related-bugs-btn { margin-bottom: -1px; } .pinboard-related-bugs-btn:hover > .related-bugs-link { color: #2a6496; text-decoration: underline; } /* Spin button suppression on chrome (bug 1045611) */ #pinboard-related-bugs form input[type=number]::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } /* Spin button suppression on firefox (bug 1045611) */ #pinboard-related-bugs form input[type=number] { -moz-appearance: textfield; } /* * Classification container */ #pinboard-classification { flex: none; -webkit-flex: none; width: 185px; padding: 5px; } .pinboard-label { color: #777; } #pinboard-classification-content { color: black; } #pinboard-classification select { width: 177px; } .add-classification-input { width: 177px; height: 20px; padding: 0 0 0 3px; border-radius: 0; font-size: 12px; } /* * Save container and dropdown menu controls */ #pinboard-controls { flex: none; -webkit-flex: none; height: 43px; margin: 20px; } #pinboard-controls .dropdown-menu { z-index: 2000; } #pinboard-controls .save-btn-dropdown { margin-left: -1px; padding-top: 1px; display: inline; width: 24px; float: right; } #pinboard-controls .save-btn { float: left; display: inline; width: 70px; } .save-btn { width: 81px; } .save-btn-dropdown { width: 18px; } .btn-group + .btn + .save-btn-dropdown { margin-left: -5px; }
glenn124f/treeherder
ui/css/treeherder-pinboard.css
CSS
mpl-2.0
2,910
<form class="form-horizontal well" ng-submit="create(procedure)" > <fieldset> <legend>Create Procedure</legend> <div class="form-group"> <label for="inputMessage" class="col-lg-2 control-label">Message</label> <div class="col-lg-10"> <input type="text" class="form-control" id="inputMessage" placeholder="message" ng-model="procedure.message" > </div> </div> <div class="form-group"> <label for="inputSource" class="col-lg-2 control-label">Source</label> <div class="col-lg-10"> <input type="text" class="form-control" id="inputSource" placeholder="source" ng-model="procedure.source" > </div> </div> <div class="form-group"> <label for="inputType" class="col-lg-2 control-label">Type</label> <div class="col-lg-10"> <select id="inputType" class="form-control" placeholder="type" ng-model="procedure.type"> <option>Crown Procedure</option> <option>Surface Procedure</option> <option>Ground Procedure</option> </select> </div> </div> <div class="form-group"> <label for="inputEnvironment" class="col-lg-2 control-label">Environment</label> <div class="col-lg-10"> <select id="inputEnvironment" class="form-control" placeholder="environment" ng-model="procedure.environment"> <option>Production</option> <option>Staging</option> <option>Development</option> </select> </div> </div> <div class="form-group"> <label for="inputNetwork" class="col-lg-2 control-label">Network</label> <div class="col-lg-10"> <input type="text" class="form-control" id="inputNetwork" placeholder="network" ng-model="procedure.network" > </div> </div> <div class="form-group"> <label for="inputDevice" class="col-lg-2 control-label">Device</label> <div class="col-lg-10"> <input type="text" class="form-control" id="inputDevice" placeholder="device" ng-model="procedure.device" > </div> </div> <div class="form-group"> <label for="inputApplication" class="col-lg-2 control-label">Application</label> <div class="col-lg-10"> <input type="text" class="form-control" id="inputApplication" placeholder="application" ng-model="procedure.application" > </div> </div> <div class="form-group"> <label for="inputStatus" class="col-lg-2 control-label">Status</label> <div class="col-lg-10"> <select id="inputStatus" class="form-control" placeholder="status" ng-model="procedure.status"> <option>Draft</option> <option>Active</option> <option>Inactive</option> </select> </div> </div> <div class="form-group"> <label for="inputDescription" class="col-lg-2 control-label">Description</label> <div class="col-lg-10"> <div text-angular ng-model="procedure.description" ></div> </div> </div> <div class="form-group"> <label for="inputSteps" class="col-lg-2 control-label">Detailed Steps</label> <div class="col-lg-10"> <div text-angular ng-model="procedure.steps" ></div> </div> </div> <div class="form-group"> <div class="col-lg-10 col-lg-offset-2"> <a href="#/procedures" type="reset" class="btn btn-sm btn-default">Cancel</a> <button type="submit" class="btn btn-sm btn-primary">Save</button> </div> </div> </fieldset> </form>
justmiles/smokejumper
app/procedures/create.html
HTML
mpl-2.0
3,489
#!/usr/bin/env python # -*- coding: utf-8 -*- panel_file = open('panels.txt','r') name_file = open('testName.txt','r') sample_type_file = open("sampleType.txt") test_panel_results = open("output/testPanelResults.txt", 'w') panel = [] type = [] test_names = [] def get_split_names( name ): split_name_list = name.split("/") for i in range(0, len(split_name_list)): split_name_list[i] = split_name_list[i].strip() return split_name_list def esc_char(name): if "'" in name: return "$$" + name + "$$" else: return "'" + name + "'" for line in panel_file: panel.append(line.strip()) panel_file.close() for line in sample_type_file: type.append(line.strip()) sample_type_file.close() for line in name_file: test_names.append(line.strip()) name_file.close() test_panel_results.write("Below should be pasted to TestPanel.csv\n\n") for row in range(0, len(test_names)): if len(panel[row]) > 1: test_description = esc_char(test_names[row] + "(" + type[row] + ")") test_panel_results.write("nextval( 'panel_item_seq' ) , (select id from panel where name = '" + panel[row] + "')") test_panel_results.write(" , (select id from test where description = " + test_description + ") , null , now() \n") test_panel_results.close() print "Done look for results in testPanelResults.txt"
mark47/OESandbox
liquibase/OE2.8/testCatalogCI_LNSP/scripts/testPanel.py
Python
mpl-2.0
1,391
/* This file is part of SUPPL - the supplemental library for DOS Copyright (C) 1996-2000 Steffen Kaiser This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* $RCSfile: eestrcon.c,v $ $Locker: $ $Name: $ $State: Exp $ char *EStrConcat(int argcnt, ...) Concats up to argcnt strings together and malloc() a buffer that will receive the result. If one of the string == NULL, this string is ignored. On failure, the program is terminated with the "out of memory" error. Return: the malloc'ed buffer ob(ject): EStrConcat su(bsystem): error ty(pe): H sh(ort description): Concat several strings together lo(ng description): Concats several strings together, by using the \tok{StrConcat()} function, and terminates the program on failure with the error message: "Out of memory" pr(erequistes): re(lated to): StrConcat se(condary subsystems): dynstr in(itialized by): wa(rning): bu(gs): va(lue): constructed dynamic string fi(le): eestrcon.c */ #include "initsupl.loc" #ifndef _MICROC_ #include <string.h> #include <stdarg.h> #include <stdlib.h> #endif #include "dynstr.h" #include "msgs.h" #include "suppldbg.h" #ifdef RCS_Version static char const rcsid[] = "$Id: eestrcon.c,v 1.1 2006/06/17 03:25:02 blairdude Exp $"; #endif #ifdef _MICROC_ register char *EStrConcat(int argcnt) { unsigned cnt, *poi; unsigned Xcnt, *Xpoi; unsigned length; char *h, *p; DBG_ENTER1 cnt = nargs(); DBG_ENTER2("EStrConcat", "error") DBG_ARGUMENTS( ("argcnt=%u cnt=%u", argcnt, cnt) ) Xpoi = poi = cnt * 2 - 2 + &argcnt; Xcnt = cnt = min(cnt, *poi); for(length = 1; cnt--;) if(*--poi) length += strlen(*poi); chkHeap if((h = p = malloc(length)) == 0) Esuppl_noMem(); chkHeap while(Xcnt--) if(*--Xpoi) p = stpcpy(p, *Xpoi); chkHeap DBG_RETURN_S( h) } #else /* !_MICROC_ */ char *EStrConcat(int argcnt, ...) { va_list strings; char *p, *s; size_t length, l; DBG_ENTER("EStrConcat", Suppl_error) DBG_ARGUMENTS( ("argcnt=%u cnt=%u", argcnt, argcnt) ) va_start(strings, argcnt); chkHeap p = Estrdup(""); chkHeap length = 1; while(argcnt--) { s = va_arg(strings, char *); if(s && *s) { l = length - 1; Eresize(p, length += strlen(s)); strcpy(p + l, s); } } va_end(strings); chkHeap DBG_RETURN_S( p) } #endif /* _MICROC_ */
joyent/sdcboot
freedos/source/command/suppl/src/eestrcon.c
C
mpl-2.0
2,977
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import { createStore, applyMiddleware } from 'redux'; import threadDispatcher from '../../common/thread-middleware'; import handleMessages from '../../common/message-handler'; import messages from './messages-worker'; import reducers from './reducers'; import thunk from 'redux-thunk'; const store = createStore( // Reducers: reducers, // Initial State: {}, // Enhancers: applyMiddleware( ...[ thunk, threadDispatcher(self, 'toContent'), ].filter(fn => fn) ) ); handleMessages(self, store, messages);
squarewave/bhr.html
src/workers/summary/index.js
JavaScript
mpl-2.0
743
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //----------------------------------------------------------------------------- var BUGNUMBER = 474935; var summary = 'Do not assert: !ti->typeMap.matches(ti_other->typeMap)'; var actual = ''; var expect = ''; //----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function test() { enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); var a = ["", 0, 0, 0, 0, 0, "", "", 0, "", 0, ""]; var i = 0; var g = 0; for each (let e in a) { "" + [e]; if (i == 3 || i == 7) { for each (g in [1]) { } } ++i; } reportCompare(expect, actual, summary); exitFunc ('test'); }
cstipkovic/spidermonkey-research
js/src/tests/js1_8/regress/regress-474935.js
JavaScript
mpl-2.0
1,026
package command import ( "strings" "testing" "time" "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/nomad/structs" "github.com/mitchellh/cli" ) func TestMonitor_Update_Eval(t *testing.T) { t.Parallel() ui := new(cli.MockUi) mon := newMonitor(ui, nil, fullId) // Evals triggered by jobs log state := &evalState{ status: structs.EvalStatusPending, job: "job1", } mon.update(state) out := ui.OutputWriter.String() if !strings.Contains(out, "job1") { t.Fatalf("missing job\n\n%s", out) } ui.OutputWriter.Reset() // Evals trigerred by nodes log state = &evalState{ status: structs.EvalStatusPending, node: "12345678-abcd-efab-cdef-123456789abc", } mon.update(state) out = ui.OutputWriter.String() if !strings.Contains(out, "12345678-abcd-efab-cdef-123456789abc") { t.Fatalf("missing node\n\n%s", out) } // Transition to pending should not be logged if strings.Contains(out, structs.EvalStatusPending) { t.Fatalf("should skip status\n\n%s", out) } ui.OutputWriter.Reset() // No logs sent if no update mon.update(state) if out := ui.OutputWriter.String(); out != "" { t.Fatalf("expected no output\n\n%s", out) } // Status change sends more logs state = &evalState{ status: structs.EvalStatusComplete, node: "12345678-abcd-efab-cdef-123456789abc", } mon.update(state) out = ui.OutputWriter.String() if !strings.Contains(out, structs.EvalStatusComplete) { t.Fatalf("missing status\n\n%s", out) } } func TestMonitor_Update_Allocs(t *testing.T) { t.Parallel() ui := new(cli.MockUi) mon := newMonitor(ui, nil, fullId) // New allocations write new logs state := &evalState{ allocs: map[string]*allocState{ "alloc1": &allocState{ id: "87654321-abcd-efab-cdef-123456789abc", group: "group1", node: "12345678-abcd-efab-cdef-123456789abc", desired: structs.AllocDesiredStatusRun, client: structs.AllocClientStatusPending, index: 1, }, }, } mon.update(state) // Logs were output out := ui.OutputWriter.String() if !strings.Contains(out, "87654321-abcd-efab-cdef-123456789abc") { t.Fatalf("missing alloc\n\n%s", out) } if !strings.Contains(out, "group1") { t.Fatalf("missing group\n\n%s", out) } if !strings.Contains(out, "12345678-abcd-efab-cdef-123456789abc") { t.Fatalf("missing node\n\n%s", out) } if !strings.Contains(out, "created") { t.Fatalf("missing created\n\n%s", out) } ui.OutputWriter.Reset() // No change yields no logs mon.update(state) if out := ui.OutputWriter.String(); out != "" { t.Fatalf("expected no output\n\n%s", out) } ui.OutputWriter.Reset() // Alloc updates cause more log lines state = &evalState{ allocs: map[string]*allocState{ "alloc1": &allocState{ id: "87654321-abcd-efab-cdef-123456789abc", group: "group1", node: "12345678-abcd-efab-cdef-123456789abc", desired: structs.AllocDesiredStatusRun, client: structs.AllocClientStatusRunning, index: 2, }, }, } mon.update(state) // Updates were logged out = ui.OutputWriter.String() if !strings.Contains(out, "87654321-abcd-efab-cdef-123456789abc") { t.Fatalf("missing alloc\n\n%s", out) } if !strings.Contains(out, "pending") { t.Fatalf("missing old status\n\n%s", out) } if !strings.Contains(out, "running") { t.Fatalf("missing new status\n\n%s", out) } } func TestMonitor_Update_AllocModification(t *testing.T) { t.Parallel() ui := new(cli.MockUi) mon := newMonitor(ui, nil, fullId) // New allocs with a create index lower than the // eval create index are logged as modifications state := &evalState{ index: 2, allocs: map[string]*allocState{ "alloc3": &allocState{ id: "87654321-abcd-bafe-cdef-123456789abc", node: "12345678-abcd-efab-cdef-123456789abc", group: "group2", index: 1, }, }, } mon.update(state) // Modification was logged out := ui.OutputWriter.String() if !strings.Contains(out, "87654321-abcd-bafe-cdef-123456789abc") { t.Fatalf("missing alloc\n\n%s", out) } if !strings.Contains(out, "group2") { t.Fatalf("missing group\n\n%s", out) } if !strings.Contains(out, "12345678-abcd-efab-cdef-123456789abc") { t.Fatalf("missing node\n\n%s", out) } if !strings.Contains(out, "modified") { t.Fatalf("missing modification\n\n%s", out) } } func TestMonitor_Monitor(t *testing.T) { t.Parallel() srv, client, _ := testServer(t, false, nil) defer srv.Shutdown() // Create the monitor ui := new(cli.MockUi) mon := newMonitor(ui, client, fullId) // Submit a job - this creates a new evaluation we can monitor job := testJob("job1") resp, _, err := client.Jobs().Register(job, nil) if err != nil { t.Fatalf("err: %s", err) } // Start monitoring the eval var code int doneCh := make(chan struct{}) go func() { defer close(doneCh) code = mon.monitor(resp.EvalID, false) }() // Wait for completion select { case <-doneCh: case <-time.After(5 * time.Second): t.Fatalf("eval monitor took too long") } // Check the return code. We should get exit code 2 as there // would be a scheduling problem on the test server (no clients). if code != 2 { t.Fatalf("expect exit 2, got: %d", code) } // Check the output out := ui.OutputWriter.String() if !strings.Contains(out, resp.EvalID) { t.Fatalf("missing eval\n\n%s", out) } if !strings.Contains(out, "finished with status") { t.Fatalf("missing final status\n\n%s", out) } } func TestMonitor_MonitorWithPrefix(t *testing.T) { t.Parallel() srv, client, _ := testServer(t, false, nil) defer srv.Shutdown() // Create the monitor ui := new(cli.MockUi) mon := newMonitor(ui, client, shortId) // Submit a job - this creates a new evaluation we can monitor job := testJob("job1") resp, _, err := client.Jobs().Register(job, nil) if err != nil { t.Fatalf("err: %s", err) } // Start monitoring the eval var code int doneCh := make(chan struct{}) go func() { defer close(doneCh) code = mon.monitor(resp.EvalID[:8], true) }() // Wait for completion select { case <-doneCh: case <-time.After(5 * time.Second): t.Fatalf("eval monitor took too long") } // Check the return code. We should get exit code 2 as there // would be a scheduling problem on the test server (no clients). if code != 2 { t.Fatalf("expect exit 2, got: %d", code) } // Check the output out := ui.OutputWriter.String() if !strings.Contains(out, resp.EvalID[:8]) { t.Fatalf("missing eval\n\n%s", out) } if strings.Contains(out, resp.EvalID) { t.Fatalf("expected truncated eval id, got: %s", out) } if !strings.Contains(out, "finished with status") { t.Fatalf("missing final status\n\n%s", out) } // Fail on identifier with too few characters code = mon.monitor(resp.EvalID[:1], true) if code != 1 { t.Fatalf("expect exit 1, got: %d", code) } if out := ui.ErrorWriter.String(); !strings.Contains(out, "must contain at least two characters.") { t.Fatalf("expected too few characters error, got: %s", out) } ui.ErrorWriter.Reset() code = mon.monitor(resp.EvalID[:3], true) if code != 2 { t.Fatalf("expect exit 2, got: %d", code) } if out := ui.OutputWriter.String(); !strings.Contains(out, "Monitoring evaluation") { t.Fatalf("expected evaluation monitoring output, got: %s", out) } } func TestMonitor_DumpAllocStatus(t *testing.T) { t.Parallel() ui := new(cli.MockUi) // Create an allocation and dump its status to the UI alloc := &api.Allocation{ ID: "87654321-abcd-efab-cdef-123456789abc", TaskGroup: "group1", ClientStatus: structs.AllocClientStatusRunning, Metrics: &api.AllocationMetric{ NodesEvaluated: 10, NodesFiltered: 5, NodesExhausted: 1, DimensionExhausted: map[string]int{ "cpu": 1, }, ConstraintFiltered: map[string]int{ "$attr.kernel.name = linux": 1, }, ClassExhausted: map[string]int{ "web-large": 1, }, }, } dumpAllocStatus(ui, alloc, fullId) // Check the output out := ui.OutputWriter.String() if !strings.Contains(out, "87654321-abcd-efab-cdef-123456789abc") { t.Fatalf("missing alloc\n\n%s", out) } if !strings.Contains(out, structs.AllocClientStatusRunning) { t.Fatalf("missing status\n\n%s", out) } if !strings.Contains(out, "5/10") { t.Fatalf("missing filter stats\n\n%s", out) } if !strings.Contains( out, `Constraint "$attr.kernel.name = linux" filtered 1 nodes`) { t.Fatalf("missing constraint\n\n%s", out) } if !strings.Contains(out, "Resources exhausted on 1 nodes") { t.Fatalf("missing resource exhaustion\n\n%s", out) } if !strings.Contains(out, `Class "web-large" exhausted on 1 nodes`) { t.Fatalf("missing class exhaustion\n\n%s", out) } if !strings.Contains(out, `Dimension "cpu" exhausted on 1 nodes`) { t.Fatalf("missing dimension exhaustion\n\n%s", out) } ui.OutputWriter.Reset() // Dumping alloc status with no eligible nodes adds a warning alloc.Metrics.NodesEvaluated = 0 dumpAllocStatus(ui, alloc, shortId) // Check the output out = ui.OutputWriter.String() if !strings.Contains(out, "No nodes were eligible") { t.Fatalf("missing eligibility warning\n\n%s", out) } if strings.Contains(out, "87654321-abcd-efab-cdef-123456789abc") { t.Fatalf("expected truncated id, got %s", out) } if !strings.Contains(out, "87654321") { t.Fatalf("expected alloc id, got %s", out) } }
frundh/nomad
command/monitor_test.go
GO
mpl-2.0
9,320
#!/bin/bash # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at https://mozilla.org/MPL/2.0/. set -ex # required env vars: CLUSTER_NAME, CONFIG_BRANCH, CONFIG_REPO, NAMESPACE, # DEPLOYMENT_YAML, DEPLOYMENT_LOG_BASE_URL, DEPLOYMENT_NAME, DEPLOYMENT_VERSION . ${BASH_SOURCE%/*}/../docker/bin/set_git_env_vars.sh # sets DEPLOYMENT_DOCKER_IMAGE pushd $(mktemp -d) git clone --depth=1 -b ${CONFIG_BRANCH:=master} ${CONFIG_REPO} config_checkout cd config_checkout set -u for CLUSTER in ${CLUSTERS:=iowa-a}; do for DEPLOYMENT in {clock-,canary-,}deploy.yaml daemonset.yaml; do DEPLOYMENT_FILE=${CLUSTER}/${NAMESPACE:=bedrock-dev}/${DEPLOYMENT} if [[ -f ${DEPLOYMENT_FILE} ]]; then sed -i -e "s|image: .*|image: ${DEPLOYMENT_DOCKER_IMAGE}|" ${DEPLOYMENT_FILE} git add ${DEPLOYMENT_FILE} fi done done TEST_IMAGE=mozmeao/bedrock_test:${GIT_COMMIT} sed -i -e "s|TEST_IMAGE: .*|TEST_IMAGE: ${TEST_IMAGE}|;s|image: mozmeao/bedrock_test.*|image: ${TEST_IMAGE}|" .gitlab-ci.yml git add .gitlab-ci.yml git commit -m "${NAMESPACE}: set image to ${DEPLOYMENT_DOCKER_IMAGE} in ${CLUSTERS}" || echo "nothing new to commit" git push
flodolo/bedrock
bin/update_config.sh
Shell
mpl-2.0
1,291
package org.hl7.v3; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ResponseMode. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="ResponseMode"> * &lt;restriction base="{urn:hl7-org:v3}cs"> * &lt;enumeration value="D"/> * &lt;enumeration value="I"/> * &lt;enumeration value="Q"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "ResponseMode") @XmlEnum public enum ResponseMode { D, I, Q; public String value() { return name(); } public static ResponseMode fromValue(String v) { return valueOf(v); } }
jembi/openhim-encounter-orchestrator
src/main/java/org/hl7/v3/ResponseMode.java
Java
mpl-2.0
754
#if BUILD_UNIT_TESTS #include "augs/misc/enum/enum_map.h" #include <Catch/single_include/catch2/catch.hpp> TEST_CASE("EnumMap") { enum class tenum { _0, _1, _2, _3, _4, COUNT }; augs::enum_map<tenum, int> mm; mm[tenum::_0] = 0; mm[tenum::_1] = 1; mm[tenum::_2] = 2; int cnt = 0; for (const auto&& m : mm) { REQUIRE(m.first == tenum(m.second)); REQUIRE(m.second == cnt++); } REQUIRE(3 == cnt); for (const auto&& m : reverse(mm)) { REQUIRE(m.first == tenum(m.second)); REQUIRE(m.second == --cnt); } REQUIRE(0 == cnt); { augs::enum_map<tenum, int> emp; for (const auto&& abc : emp) { REQUIRE(false); (void)abc; } for (const auto&& abc : reverse(emp)) { REQUIRE(false); (void)abc; } REQUIRE(emp.size() == 0); emp[tenum::_0] = 48; REQUIRE(emp.size() == 1); for (const auto&& m : reverse(emp)) { REQUIRE(48 == m.second); } emp.clear(); REQUIRE(emp.size() == 0); emp[tenum::_1] = 84; REQUIRE(emp.size() == 1); for (const auto&& m : reverse(emp)) { REQUIRE(84 == m.second); } emp[tenum::_0] = 0; emp[tenum::_1] = 1; emp[tenum::_2] = 2; REQUIRE(emp.size() == 3); for (const auto&& m : emp) { REQUIRE(m.first == tenum(m.second)); REQUIRE(m.second == cnt++); } REQUIRE(3 == cnt); for (const auto&& m : reverse(emp)) { REQUIRE(m.first == tenum(m.second)); REQUIRE(m.second == --cnt); } emp.clear(); REQUIRE(emp.size() == 0); emp[tenum::_4] = 4; emp[tenum::_3] = 3; emp[tenum::_1] = 1; emp[tenum::_0] = 0; auto it = emp.rbegin(); REQUIRE((*it).second == 4); REQUIRE((*++it).second == 3); REQUIRE((*++it).second == 1); REQUIRE((*++it).second == 0); REQUIRE(++it == emp.rend()); } } #endif
TeamHypersomnia/Augmentations
src/augs/misc/enum/enum_map.cpp
C++
agpl-3.0
1,737
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated: 12/10/2015, 13:28 * */ package ims.core.clinical.domain.objects; /** * * @author John MacEnri * Generated. */ public class NonUniqueTaxonomyMap extends ims.domain.DomainObject implements ims.domain.SystemInformationRetainer, java.io.Serializable { public static final int CLASSID = 1003100071; private static final long serialVersionUID = 1003100071L; public static final String CLASSVERSION = "${ClassVersion}"; @Override public boolean shouldCapQuery() { return true; } private ims.domain.lookups.LookupInstance taxonomyName; private String taxonomyCode; private java.util.Date effectiveFrom; private java.util.Date effectiveTo; /** SystemInformation */ private ims.domain.SystemInformation systemInformation = new ims.domain.SystemInformation(); public NonUniqueTaxonomyMap (Integer id, int ver) { super(id, ver); isComponentClass=true; } public NonUniqueTaxonomyMap () { super(); isComponentClass=true; } public NonUniqueTaxonomyMap (Integer id, int ver, Boolean includeRecord) { super(id, ver, includeRecord); isComponentClass=true; } public Class getRealDomainClass() { return ims.core.clinical.domain.objects.NonUniqueTaxonomyMap.class; } public ims.domain.lookups.LookupInstance getTaxonomyName() { return taxonomyName; } public void setTaxonomyName(ims.domain.lookups.LookupInstance taxonomyName) { this.taxonomyName = taxonomyName; } public String getTaxonomyCode() { return taxonomyCode; } public void setTaxonomyCode(String taxonomyCode) { if ( null != taxonomyCode && taxonomyCode.length() > 30 ) { throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for taxonomyCode. Tried to set value: "+ taxonomyCode); } this.taxonomyCode = taxonomyCode; } public java.util.Date getEffectiveFrom() { return effectiveFrom; } public void setEffectiveFrom(java.util.Date effectiveFrom) { this.effectiveFrom = effectiveFrom; } public java.util.Date getEffectiveTo() { return effectiveTo; } public void setEffectiveTo(java.util.Date effectiveTo) { this.effectiveTo = effectiveTo; } public ims.domain.SystemInformation getSystemInformation() { if (systemInformation == null) systemInformation = new ims.domain.SystemInformation(); return systemInformation; } /** * isConfigurationObject * Taken from the Usage property of the business object, this method will return * a boolean indicating whether this is a configuration object or not * Configuration = true, Instantiation = false */ public static boolean isConfigurationObject() { if ( "Instantiation".equals("Configuration") ) return true; else return false; } public int getClassId() { return CLASSID; } public String getClassVersion() { return CLASSVERSION; } public String toAuditString() { StringBuffer auditStr = new StringBuffer(); auditStr.append("\r\n*taxonomyName* :"); if (taxonomyName != null) auditStr.append(taxonomyName.getText()); auditStr.append("; "); auditStr.append("\r\n*taxonomyCode* :"); auditStr.append(taxonomyCode); auditStr.append("; "); auditStr.append("\r\n*effectiveFrom* :"); auditStr.append(effectiveFrom); auditStr.append("; "); auditStr.append("\r\n*effectiveTo* :"); auditStr.append(effectiveTo); auditStr.append("; "); return auditStr.toString(); } public String toXMLString() { return toXMLString(new java.util.HashMap()); } public String toXMLString(java.util.HashMap domMap) { StringBuffer sb = new StringBuffer(); sb.append("<class type=\"" + this.getClass().getName() + "\" "); sb.append(" source=\"" + ims.configuration.EnvironmentConfig.getImportExportSourceName() + "\" "); sb.append(" classVersion=\"" + this.getClassVersion() + "\" "); sb.append(" component=\"" + this.getIsComponentClass() + "\" >"); if (domMap.get(this) == null) { domMap.put(this, this); sb.append(this.fieldsToXMLString(domMap)); } sb.append("</class>"); return sb.toString(); } public String fieldsToXMLString(java.util.HashMap domMap) { StringBuffer sb = new StringBuffer(); if (this.getTaxonomyName() != null) { sb.append("<taxonomyName>"); sb.append(this.getTaxonomyName().toXMLString()); sb.append("</taxonomyName>"); } if (this.getTaxonomyCode() != null) { sb.append("<taxonomyCode>"); sb.append(ims.framework.utils.StringUtils.encodeXML(this.getTaxonomyCode().toString())); sb.append("</taxonomyCode>"); } if (this.getEffectiveFrom() != null) { sb.append("<effectiveFrom>"); sb.append(new ims.framework.utils.DateTime(this.getEffectiveFrom()).toString(ims.framework.utils.DateTimeFormat.MILLI)); sb.append("</effectiveFrom>"); } if (this.getEffectiveTo() != null) { sb.append("<effectiveTo>"); sb.append(new ims.framework.utils.DateTime(this.getEffectiveTo()).toString(ims.framework.utils.DateTimeFormat.MILLI)); sb.append("</effectiveTo>"); } return sb.toString(); } public static java.util.List fromListXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.List list, java.util.HashMap domMap) throws Exception { if (list == null) list = new java.util.ArrayList(); fillListFromXMLString(list, el, factory, domMap); return list; } public static java.util.Set fromSetXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.Set set, java.util.HashMap domMap) throws Exception { if (set == null) set = new java.util.HashSet(); fillSetFromXMLString(set, el, factory, domMap); return set; } private static void fillSetFromXMLString(java.util.Set set, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return; java.util.List cl = el.elements("class"); int size = cl.size(); java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i); NonUniqueTaxonomyMap domainObject = getNonUniqueTaxonomyMapfromXML(itemEl, factory, domMap); if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!set.contains(domainObject)) set.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = set.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { set.remove(iter.next()); } } private static void fillListFromXMLString(java.util.List list, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return; java.util.List cl = el.elements("class"); int size = cl.size(); for(int i=0; i<size; i++) { org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i); NonUniqueTaxonomyMap domainObject = getNonUniqueTaxonomyMapfromXML(itemEl, factory, domMap); if (domainObject == null) { continue; } int domIdx = list.indexOf(domainObject); if (domIdx == -1) { list.add(i, domainObject); } else if (i != domIdx && i < list.size()) { Object tmp = list.get(i); list.set(i, list.get(domIdx)); list.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=list.size(); while (i1 > size) { list.remove(i1-1); i1=list.size(); } } public static NonUniqueTaxonomyMap getNonUniqueTaxonomyMapfromXML(String xml, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { org.dom4j.Document doc = new org.dom4j.io.SAXReader().read(new org.xml.sax.InputSource(xml)); return getNonUniqueTaxonomyMapfromXML(doc.getRootElement(), factory, domMap); } public static NonUniqueTaxonomyMap getNonUniqueTaxonomyMapfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return null; String className = el.attributeValue("type"); if (!NonUniqueTaxonomyMap.class.getName().equals(className)) { Class clz = Class.forName(className); if (!NonUniqueTaxonomyMap.class.isAssignableFrom(clz)) throw new Exception("Element of type = " + className + " cannot be imported using the NonUniqueTaxonomyMap class"); String shortClassName = className.substring(className.lastIndexOf(".")+1); String methodName = "get" + shortClassName + "fromXML"; java.lang.reflect.Method m = clz.getMethod(methodName, new Class[]{org.dom4j.Element.class, ims.domain.DomainFactory.class, java.util.HashMap.class}); return (NonUniqueTaxonomyMap)m.invoke(null, new Object[]{el, factory, domMap}); } String impVersion = el.attributeValue("classVersion"); if(!impVersion.equals(NonUniqueTaxonomyMap.CLASSVERSION)) { throw new Exception("Incompatible class structure found. Cannot import instance."); } NonUniqueTaxonomyMap ret = null; if (ret == null) { ret = new NonUniqueTaxonomyMap(); } fillFieldsfromXML(el, factory, ret, domMap); return ret; } public static void fillFieldsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, NonUniqueTaxonomyMap obj, java.util.HashMap domMap) throws Exception { org.dom4j.Element fldEl; fldEl = el.element("taxonomyName"); if(fldEl != null) { fldEl = fldEl.element("lki"); obj.setTaxonomyName(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory)); } fldEl = el.element("taxonomyCode"); if(fldEl != null) { obj.setTaxonomyCode(new String(fldEl.getTextTrim())); } fldEl = el.element("effectiveFrom"); if(fldEl != null) { obj.setEffectiveFrom(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim())); } fldEl = el.element("effectiveTo"); if(fldEl != null) { obj.setEffectiveTo(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim())); } } public static String[] getCollectionFields() { return new String[]{ }; } /** equals */ public boolean equals(Object obj) { if (null == obj) { return false; } if(!(obj instanceof NonUniqueTaxonomyMap)) { return false; } NonUniqueTaxonomyMap compareObj=(NonUniqueTaxonomyMap)obj; if((taxonomyCode==null ? compareObj.taxonomyCode == null : taxonomyCode.equals(compareObj.taxonomyCode))&& (taxonomyName==null ? compareObj.taxonomyName==null : taxonomyName.equals(compareObj.taxonomyName))&& (effectiveFrom==null? compareObj.effectiveFrom==null : effectiveFrom.equals(compareObj.effectiveFrom))&& (effectiveTo==null? compareObj.effectiveTo==null : effectiveTo.equals(compareObj.effectiveTo))) return true; return super.equals(obj); } /** toString */ public String toString() { StringBuffer objStr = new StringBuffer(); if (taxonomyName != null) objStr.append(taxonomyName.getText() + "-"); objStr.append(taxonomyCode); return objStr.toString(); } /** hashcode */ public int hashCode() { int hash = 0; if (taxonomyName!= null) hash += taxonomyName.hashCode()* 10011; if (taxonomyCode!= null) hash += taxonomyCode.hashCode(); if (effectiveFrom!= null) hash += effectiveFrom.hashCode(); if (effectiveTo!= null) hash += effectiveTo.hashCode(); return hash; } public static class FieldNames { public static final String ID = "id"; public static final String TaxonomyName = "taxonomyName"; public static final String TaxonomyCode = "taxonomyCode"; public static final String EffectiveFrom = "effectiveFrom"; public static final String EffectiveTo = "effectiveTo"; } }
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/DomainObjects/src/ims/core/clinical/domain/objects/NonUniqueTaxonomyMap.java
Java
agpl-3.0
14,623
/* * RapidMiner * * Copyright (C) 2001-2014 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.plotter.mathplot; import org.math.plot.Plot3DPanel; import org.math.plot.PlotPanel; import com.rapidminer.datatable.DataTable; import com.rapidminer.gui.plotter.PlotterConfigurationModel; /** The abstract super class for all 3D plotters using the JMathPlot library. * * @author Ingo Mierswa */ public abstract class JMathPlotter3D extends JMathPlotter { private static final long serialVersionUID = -8695197842788069313L; public JMathPlotter3D(PlotterConfigurationModel settings) { super(settings); } public JMathPlotter3D(PlotterConfigurationModel settings, DataTable dataTable) { super(settings, dataTable); } @Override public PlotPanel createPlotPanel() { return new Plot3DPanel(); } @Override public int getNumberOfOptionIcons() { return 5; } }
rapidminer/rapidminer-5
src/com/rapidminer/gui/plotter/mathplot/JMathPlotter3D.java
Java
agpl-3.0
1,676
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.analysis; import com.google.common.collect.ImmutableMap; import org.apache.lucene.analysis.Analyzer; import org.elasticsearch.ElasticSearchIllegalArgumentException; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.component.CloseableComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.AbstractIndexComponent; import org.elasticsearch.index.Index; import org.elasticsearch.index.settings.IndexSettings; import org.elasticsearch.indices.analysis.IndicesAnalysisService; import java.util.Map; import static com.google.common.collect.Maps.newHashMap; /** * */ public class AnalysisService extends AbstractIndexComponent implements CloseableComponent { private final ImmutableMap<String, NamedAnalyzer> analyzers; private final ImmutableMap<String, TokenizerFactory> tokenizers; private final ImmutableMap<String, CharFilterFactory> charFilters; private final ImmutableMap<String, TokenFilterFactory> tokenFilters; private final NamedAnalyzer defaultAnalyzer; private final NamedAnalyzer defaultIndexAnalyzer; private final NamedAnalyzer defaultSearchAnalyzer; private final NamedAnalyzer defaultSearchQuoteAnalyzer; public AnalysisService(Index index) { this(index, ImmutableSettings.Builder.EMPTY_SETTINGS, null, null, null, null, null); } @Inject public AnalysisService(Index index, @IndexSettings Settings indexSettings, @Nullable IndicesAnalysisService indicesAnalysisService, @Nullable Map<String, AnalyzerProviderFactory> analyzerFactoryFactories, @Nullable Map<String, TokenizerFactoryFactory> tokenizerFactoryFactories, @Nullable Map<String, CharFilterFactoryFactory> charFilterFactoryFactories, @Nullable Map<String, TokenFilterFactoryFactory> tokenFilterFactoryFactories) { super(index, indexSettings); Map<String, TokenizerFactory> tokenizers = newHashMap(); if (tokenizerFactoryFactories != null) { Map<String, Settings> tokenizersSettings = indexSettings.getGroups("index.analysis.tokenizer"); for (Map.Entry<String, TokenizerFactoryFactory> entry : tokenizerFactoryFactories.entrySet()) { String tokenizerName = entry.getKey(); TokenizerFactoryFactory tokenizerFactoryFactory = entry.getValue(); Settings tokenizerSettings = tokenizersSettings.get(tokenizerName); if (tokenizerSettings == null) { tokenizerSettings = ImmutableSettings.Builder.EMPTY_SETTINGS; } TokenizerFactory tokenizerFactory = tokenizerFactoryFactory.create(tokenizerName, tokenizerSettings); tokenizers.put(tokenizerName, tokenizerFactory); tokenizers.put(Strings.toCamelCase(tokenizerName), tokenizerFactory); } } if (indicesAnalysisService != null) { for (Map.Entry<String, PreBuiltTokenizerFactoryFactory> entry : indicesAnalysisService.tokenizerFactories().entrySet()) { String name = entry.getKey(); if (!tokenizers.containsKey(name)) { tokenizers.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS)); } name = Strings.toCamelCase(entry.getKey()); if (!name.equals(entry.getKey())) { if (!tokenizers.containsKey(name)) { tokenizers.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS)); } } } } this.tokenizers = ImmutableMap.copyOf(tokenizers); Map<String, CharFilterFactory> charFilters = newHashMap(); if (charFilterFactoryFactories != null) { Map<String, Settings> charFiltersSettings = indexSettings.getGroups("index.analysis.char_filter"); for (Map.Entry<String, CharFilterFactoryFactory> entry : charFilterFactoryFactories.entrySet()) { String charFilterName = entry.getKey(); CharFilterFactoryFactory charFilterFactoryFactory = entry.getValue(); Settings charFilterSettings = charFiltersSettings.get(charFilterName); if (charFilterSettings == null) { charFilterSettings = ImmutableSettings.Builder.EMPTY_SETTINGS; } CharFilterFactory tokenFilterFactory = charFilterFactoryFactory.create(charFilterName, charFilterSettings); charFilters.put(charFilterName, tokenFilterFactory); charFilters.put(Strings.toCamelCase(charFilterName), tokenFilterFactory); } } if (indicesAnalysisService != null) { for (Map.Entry<String, PreBuiltCharFilterFactoryFactory> entry : indicesAnalysisService.charFilterFactories().entrySet()) { String name = entry.getKey(); if (!charFilters.containsKey(name)) { charFilters.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS)); } name = Strings.toCamelCase(entry.getKey()); if (!name.equals(entry.getKey())) { if (!charFilters.containsKey(name)) { charFilters.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS)); } } } } this.charFilters = ImmutableMap.copyOf(charFilters); Map<String, TokenFilterFactory> tokenFilters = newHashMap(); if (tokenFilterFactoryFactories != null) { Map<String, Settings> tokenFiltersSettings = indexSettings.getGroups("index.analysis.filter"); for (Map.Entry<String, TokenFilterFactoryFactory> entry : tokenFilterFactoryFactories.entrySet()) { String tokenFilterName = entry.getKey(); TokenFilterFactoryFactory tokenFilterFactoryFactory = entry.getValue(); Settings tokenFilterSettings = tokenFiltersSettings.get(tokenFilterName); if (tokenFilterSettings == null) { tokenFilterSettings = ImmutableSettings.Builder.EMPTY_SETTINGS; } TokenFilterFactory tokenFilterFactory = tokenFilterFactoryFactory.create(tokenFilterName, tokenFilterSettings); tokenFilters.put(tokenFilterName, tokenFilterFactory); tokenFilters.put(Strings.toCamelCase(tokenFilterName), tokenFilterFactory); } } // pre initialize the globally registered ones into the map if (indicesAnalysisService != null) { for (Map.Entry<String, PreBuiltTokenFilterFactoryFactory> entry : indicesAnalysisService.tokenFilterFactories().entrySet()) { String name = entry.getKey(); if (!tokenFilters.containsKey(name)) { tokenFilters.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS)); } name = Strings.toCamelCase(entry.getKey()); if (!name.equals(entry.getKey())) { if (!tokenFilters.containsKey(name)) { tokenFilters.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS)); } } } } this.tokenFilters = ImmutableMap.copyOf(tokenFilters); Map<String, AnalyzerProvider> analyzerProviders = newHashMap(); if (analyzerFactoryFactories != null) { Map<String, Settings> analyzersSettings = indexSettings.getGroups("index.analysis.analyzer"); for (Map.Entry<String, AnalyzerProviderFactory> entry : analyzerFactoryFactories.entrySet()) { String analyzerName = entry.getKey(); AnalyzerProviderFactory analyzerFactoryFactory = entry.getValue(); Settings analyzerSettings = analyzersSettings.get(analyzerName); if (analyzerSettings == null) { analyzerSettings = ImmutableSettings.Builder.EMPTY_SETTINGS; } AnalyzerProvider analyzerFactory = analyzerFactoryFactory.create(analyzerName, analyzerSettings); analyzerProviders.put(analyzerName, analyzerFactory); } } if (indicesAnalysisService != null) { for (Map.Entry<String, PreBuiltAnalyzerProviderFactory> entry : indicesAnalysisService.analyzerProviderFactories().entrySet()) { String name = entry.getKey(); if (!analyzerProviders.containsKey(name)) { analyzerProviders.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS)); } name = Strings.toCamelCase(entry.getKey()); if (!name.equals(entry.getKey())) { if (!analyzerProviders.containsKey(name)) { analyzerProviders.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS)); } } } } if (!analyzerProviders.containsKey("default")) { analyzerProviders.put("default", new StandardAnalyzerProvider(index, indexSettings, null, "default", ImmutableSettings.Builder.EMPTY_SETTINGS)); } if (!analyzerProviders.containsKey("default_index")) { analyzerProviders.put("default_index", analyzerProviders.get("default")); } if (!analyzerProviders.containsKey("default_search")) { analyzerProviders.put("default_search", analyzerProviders.get("default")); } if (!analyzerProviders.containsKey("default_search_quoted")) { analyzerProviders.put("default_search_quoted", analyzerProviders.get("default_search")); } Map<String, NamedAnalyzer> analyzers = newHashMap(); for (AnalyzerProvider analyzerFactory : analyzerProviders.values()) { if (analyzerFactory instanceof CustomAnalyzerProvider) { ((CustomAnalyzerProvider) analyzerFactory).build(this); } Analyzer analyzerF = analyzerFactory.get(); if (analyzerF == null) { throw new ElasticSearchIllegalArgumentException("analyzer [" + analyzerFactory.name() + "] created null analyzer"); } NamedAnalyzer analyzer; // if we got a named analyzer back, use it... if (analyzerF instanceof NamedAnalyzer) { analyzer = (NamedAnalyzer) analyzerF; } else { analyzer = new NamedAnalyzer(analyzerFactory.name(), analyzerFactory.scope(), analyzerF); } analyzers.put(analyzerFactory.name(), analyzer); analyzers.put(Strings.toCamelCase(analyzerFactory.name()), analyzer); String strAliases = indexSettings.get("index.analysis.analyzer." + analyzerFactory.name() + ".alias"); if (strAliases != null) { for (String alias : Strings.commaDelimitedListToStringArray(strAliases)) { analyzers.put(alias, analyzer); } } String[] aliases = indexSettings.getAsArray("index.analysis.analyzer." + analyzerFactory.name() + ".alias"); for (String alias : aliases) { analyzers.put(alias, analyzer); } } defaultAnalyzer = analyzers.get("default"); if (defaultAnalyzer == null) { throw new ElasticSearchIllegalArgumentException("no default analyzer configured"); } defaultIndexAnalyzer = analyzers.containsKey("default_index") ? analyzers.get("default_index") : analyzers.get("default"); defaultSearchAnalyzer = analyzers.containsKey("default_search") ? analyzers.get("default_search") : analyzers.get("default"); defaultSearchQuoteAnalyzer = analyzers.containsKey("default_search_quote") ? analyzers.get("default_search_quote") : defaultSearchAnalyzer; this.analyzers = ImmutableMap.copyOf(analyzers); } public void close() { for (NamedAnalyzer analyzer : analyzers.values()) { if (analyzer.scope() == AnalyzerScope.INDEX) { try { analyzer.close(); } catch (NullPointerException e) { // because analyzers are aliased, they might be closed several times // an NPE is thrown in this case, so ignore.... } catch (Exception e) { logger.debug("failed to close analyzer " + analyzer); } } } } public NamedAnalyzer analyzer(String name) { return analyzers.get(name); } public NamedAnalyzer defaultAnalyzer() { return defaultAnalyzer; } public NamedAnalyzer defaultIndexAnalyzer() { return defaultIndexAnalyzer; } public NamedAnalyzer defaultSearchAnalyzer() { return defaultSearchAnalyzer; } public NamedAnalyzer defaultSearchQuoteAnalyzer() { return defaultSearchQuoteAnalyzer; } public TokenizerFactory tokenizer(String name) { return tokenizers.get(name); } public CharFilterFactory charFilter(String name) { return charFilters.get(name); } public TokenFilterFactory tokenFilter(String name) { return tokenFilters.get(name); } }
exercitussolus/yolo
src/main/java/org/elasticsearch/index/analysis/AnalysisService.java
Java
agpl-3.0
14,624
<?php /** * Smarty Internal Plugin Compile Make_Nocache * Compiles the {make_nocache} tag * * @package Smarty * @subpackage Compiler * @author Uwe Tews */ /** * Smarty Internal Plugin Compile Make_Nocache Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Make_Nocache extends Smarty_Internal_CompileBase { /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $option_flags = []; /** * Array of names of required attribute required by tag * * @var array */ public $required_attributes = ['var']; /** * Shorttag attribute order defined by its names * * @var array */ public $shorttag_order = ['var']; /** * Compiles code for the {make_nocache} tag * * @param array $args array with attributes from parser * @param \Smarty_Internal_TemplateCompilerBase $compiler compiler object * @param array $parameter array with compilation parameter * * @return string compiled code * @throws \SmartyCompilerException */ public function compile($args, Smarty_Internal_TemplateCompilerBase $compiler, $parameter) { // check and get attributes $_attr = $this->getAttributes($compiler, $args); if ($compiler->template->caching) { $output = "<?php \$_smarty_tpl->smarty->ext->_make_nocache->save(\$_smarty_tpl, {$_attr[ 'var' ]});\n?>\n"; $compiler->has_code = true; $compiler->suppressNocacheProcessing = true; return $output; } else { return true; } } }
WWXD/WorldWeb-XD
lib/smarty/sysplugins/smarty_internal_compile_make_nocache.php
PHP
agpl-3.0
1,773
<?php /* * Copyright 2007-2017 Charles du Jeu - Abstrium SAS <team (at) pyd.io> * This file is part of Pydio. * * Pydio is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pydio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Pydio. If not, see <http://www.gnu.org/licenses/>. * * The latest code can be found at <https://pydio.com>. */ // spanish translation: Salva Gómez <salva.gomez at gmail.com>, 2015 $mess=array( "Generic Conf Features" => "Configuraciones genéricas", "Let user create repositories" => "Permitir al usuario crear repositorios", "Remember guest preferences" => "Recordar preferencias de invitado", "If the 'guest' user is enabled, remember her preferences accross sessions." => "Si el usuario 'Invitado' está habilitado, recordar sus preferencias a través de sesiones.", "Configurations Management" => "Gestión de configuraciones", "Sets how the application core data (users,roles,etc) is stored." => "Establece cómo se almacenan los datos básicos de aplicación (usuarios, roles, etc.)", "Default start repository" => "Repositorio de inicio por defecto", "Default repository" => "Repositorio por defecto", "Maximum number of shared users per user" => "Número máximo de usuarios compartidos por usuario", "Shared users limit" => "Límite de usuarios compartidos", "Core SQL Connexion" => "Conexión SQL Principal", "SQL Connexion" => "Conexión SQL", "Simple SQL Connexion definition that can be used by other sql-based plugins" => "Definición de conexión SQL simple que puede ser utilizada por otros plugins basados en SQL", "Preferences Saving" => "Preferencias de guardado", "Skip user history" => "Omitir preferencias de interfaz", "Use this option to avoid automatic reloading of the interface state (last folder, opened tabs, etc)" => "Utilice esta opción para evitar la carga automática del estado de la interfaz (última carpeta, pestañas abiertas, etc)", "Internal / External Users" => "Usuarios internos / externos", "Maximum number of users displayed in the users autocompleter" => "Número máximo de usuarios mostrados en la lista autocompletada de usuarios", "Users completer limit" => "Límite del completador de usuarios", "Minimum number of characters to trigger the auto completion feature" => "Número mínimo de caracteres para activar la función de autocompletado", "Users completer min chars" => "Número mínimo de caracteres del completador de usuarios", "Do not display real login in parenthesis" => "No mostrar el nombre de inicio de sesión real entre paréntesis", "Hide real login" => "Ocultar nombre de inicio de sesión real", "See existing users" => "Ver usuarios existentes", "Allow the users to pick an existing user when sharing a folder" => "Permitir a los usuarios elegir un usuario existente al compartir una carpeta", "Create external users" => "Crear usuarios externos", "Allow the users to create a new user when sharing a folder" => "Permitir a los usuarios crear un nuevo usuario al compartir una carpeta", "External users parameters" => "Parámetros de usuarios externos", "List of parameters to be edited when creating a new shared user." => "Lista de parámetros a editar al crear un nuevo usuario compartido.", "Configuration Store Instance" => "Instancia de almacenamiento de la configuración", "Instance" => "Instancia", "Choose the configuration plugin" => "Seleccionar el plugin de configuración", "Name" => "Nombre", "Full name displayed to others" => "Mostrar el nombre completo a los demás", "Avatar" => "Avatar", "Image displayed next to the user name" => "Imágen mostrada junto al nombre de usuario", "Email" => "Correo electrónico", "Address used for notifications" => "Dirección utilizada para las notificaciones", "Country" => "País", "Language" => "Idioma", "User Language" => "Idioma del usuario", "Role Label" => "Etiqueta de rol", "Users Lock Action" => "Acción de bloqueo de usuarios", "If set, this action will be triggered automatically at users login. Can be logout (to lock out the users), pass_change (to force password change), or anything else" => "Si se establece, esta acción se activará automáticamente en el inicio de sesión de los usuarios. Puede ser cerrar la sesión (para bloquear a los usuarios), cambiar contraseña (para forzar el cambio de contraseña), o cualquier otra cosa", "Worskpace creation delegation" => "Delegación de la creación de repositorios", "Let user create repositories from templates" => "Permitir al usuario crear repositorios usando plantillas", "Whether users can create their own repositories, based on predefined templates." => "Si los usuarios pueden crear sus propios repositorios, hacerlo basándose en plantillas predefinidas.", "Users Directory Listing" => "Listado del directorio de usuarios", "Share with existing users from all groups" => "Compartir con los usuarios existentes de todos los grupos", "Allow to search users from other groups through auto completer (can be handy if previous option is set to false) and share workspaces with them" => "Permitir de buscar usuarios de otros grupos a través de autocompletar (puede ser útil si la opción anterior se establece en False) y compartir repositorios con ellos", "List existing from all groups" => "Listar existentes de todos los grupos", "If previous option is set to True, directly display a full list of users from all groups" => "Si la opción anterior se establece en True, mostrar directamente una lista completa de los usuarios de todos los grupos", "Roles / Groups Directory Listing" => "Listado de roles / directorio de grupos", "Display roles and/or groups" => "Mostrar roles y/o grupos", "Users only (do not list groups nor roles)" => "Sólo usuarios (no listar grupos ni roles)", "Allow Group Listing" => "Permitir el listado de grupos", "Allow Role Listing" => "Permitir el listado de roles", "Role/Group Listing" => "Listado de roles/grupos", "List Roles By" => "Listar roles por", "All roles" => "Todos los roles", "User roles only" => "Sólo roles de usuario", "role prefix" => "Prefijo del rol", "Excluded Roles" => "Roles excluidos", "Included Roles" => "Roles incluidos", "Some roles should be disappered in the list. list separated by ',' or start with 'preg:' for regex." => "Roles ocultos en la lista. Lista separada por ',' o empezar con 'preg: ' para expresiones regulares regex.", "Some roles should be shown in the list. list separated by ',' or start with 'preg:' for regex." => "Roles que deben mostrarse en la lista. Lista separada por ',' o empezar con 'preg: ' para expresiones regulares regex.", "External Users Creation" => "Creación de usuarios externos", "Always override other roles, included group roles." => "Ignorar siempre otros roles, incluido los roles de grupo.", "Always Override" => "Ignorar Siempre", "Do not load groups and users list if no regexp is entered. Avoid sending large search on LDAP." => "No cargar la lista de grupos y usuarios si no se introduce una regexp. Evita enviar búsquedas largas a LDAP.", "Make regexp mandatory" => "Regexp obligatorio", );
pydio/pydio-core
core/src/plugins/core.conf/i18n/conf/es.php
PHP
agpl-3.0
7,509
<!-- title: crm --> <div class="dev-header"> <a class="btn btn-default btn-sm" disabled style="margin-bottom: 10px;"> Version 6.7.7</a> <a class="btn btn-default btn-sm" href="https://github.com/frappe/erpnext/tree/develop/crm" target="_blank" style="margin-left: 10px; margin-bottom: 10px;"><i class="octicon octicon-mark-github"></i> Source</a> </div> <h3>Package Contents</h3> {index} <!-- autodoc -->
susuchina/ERPNEXT
erpnext/docs/current/api/crm/index.html
HTML
agpl-3.0
417
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\Profiler; use Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface; /** * Profile. * * @author Fabien Potencier <fabien@symfony.com> */ class Profile { private $token; /** * @var DataCollectorInterface[] */ private $collectors = array(); private $ip; private $method; private $url; private $time; /** * @var Profile */ private $parent; /** * @var Profile[] */ private $children = array(); /** * Constructor. * * @param string $token The token */ public function __construct($token) { $this->token = $token; } /** * Returns the parent profile. * * @return Profile The parent profile */ public function getParent() { return $this->parent; } /** * Sets the parent token * * @param Profile $parent The parent Profile */ public function setParent( Profile $parent ) { $this->parent = $parent; } /** * Returns the parent token. * * @return null|string The parent token */ public function getParentToken() { return $this->parent ? $this->parent->getToken() : null; } /** * Gets the token. * * @return string The token */ public function getToken() { return $this->token; } /** * Sets the token. * * @param string $token The token */ public function setToken( $token ) { $this->token = $token; } /** * Returns the IP. * * @return string The IP */ public function getIp() { return $this->ip; } /** * Sets the IP. * * @param string $ip */ public function setIp($ip) { $this->ip = $ip; } /** * Returns the request method. * * @return string The request method */ public function getMethod() { return $this->method; } public function setMethod($method) { $this->method = $method; } /** * Returns the URL. * * @return string The URL */ public function getUrl() { return $this->url; } public function setUrl($url) { $this->url = $url; } /** * Returns the time. * * @return string The time */ public function getTime() { if (null === $this->time) { return 0; } return $this->time; } public function setTime($time) { $this->time = $time; } /** * Finds children profilers. * * @return Profile[] An array of Profile */ public function getChildren() { return $this->children; } /** * Sets children profiler. * * @param Profile[] $children An array of Profile */ public function setChildren(array $children) { $this->children = array(); foreach ($children as $child) { $this->addChild($child); } } /** * Adds the child token * * @param Profile $child The child Profile */ public function addChild(Profile $child) { $this->children[] = $child; $child->setParent($this); } /** * Gets a Collector by name. * * @param string $name A collector name * * @return DataCollectorInterface A DataCollectorInterface instance * * @throws \InvalidArgumentException if the collector does not exist */ public function getCollector($name) { if (!isset($this->collectors[$name])) { throw new \InvalidArgumentException(sprintf('Collector "%s" does not exist.', $name)); } return $this->collectors[$name]; } /** * Gets the Collectors associated with this profile. * * @return DataCollectorInterface[] */ public function getCollectors() { return $this->collectors; } /** * Sets the Collectors associated with this profile. * * @param DataCollectorInterface[] $collectors */ public function setCollectors(array $collectors) { $this->collectors = array(); foreach ($collectors as $collector) { $this->addCollector($collector); } } /** * Adds a Collector. * * @param DataCollectorInterface $collector A DataCollectorInterface instance */ public function addCollector(DataCollectorInterface $collector) { $this->collectors[$collector->getName()] = $collector; } /** * Returns true if a Collector for the given name exists. * * @param string $name A collector name * * @return bool */ public function hasCollector($name) { return isset($this->collectors[$name]); } public function __sleep() { return array('token', 'parent', 'children', 'collectors', 'ip', 'method', 'url', 'time'); } }
KWZwickau/KREDA-Sphere
Library/MOC-V/Component/Router/Vendor/Symfony/Component/HttpKernel/Profiler/Profile.php
PHP
agpl-3.0
5,311
# session module tests # # Copyright (C) 2012-2013 Mohammed Morsi <mo@morsi.org> # Licensed under the AGPLv3 http://www.gnu.org/licenses/agpl.txt require 'spec_helper' require 'timecop' require 'users/session' module Users describe Session do after(:all) do Timecop.return end describe "#initialize" do it "sets attributes" do id = Motel.gen_uuid u = User.new :id => 'user1' s = Session.new :id => id, :user => u, :endpoint_id => 'node1' s.id.should == id s.user.id.should == 'user1' s.refreshed_time.should_not be_nil s.endpoint_id.should == 'node1' end end describe "#timed_out" do before(:each) do Timecop.freeze @u = User.new :id => 'user1' @s = Session.new :id => 'id', :user => @u end after(:each) do Timecop.travel end context "timeout has passed" do it "returns true" do Timecop.freeze Session::SESSION_EXPIRATION + 1 @s.timed_out?.should be_true end end context "timeout has not passed" do it "returns false" do @s.timed_out?.should be_false @s.instance_variable_get(:@refreshed_time).should == Time.now end end context "user is permenant" do it "always returns false" do @u.permenant = true Timecop.freeze Session::SESSION_EXPIRATION + 1 @s.timed_out?.should be_false end end end describe "#to_json" do it "returns json representation of session" do u = User.new :id => 'user1' s = Session.new :id => '1234', :user => u, :endpoint_id => 'node1' j = s.to_json j.should include('"json_class":"Users::Session"') j.should include('"id":"1234"') j.should include('"json_class":"Users::User"') j.should include('"id":"user1"') j.should include('"refreshed_time":') j.should include('"endpoint_id":"node1"') end end describe "#json_create" do it "returns session from json format" do j = '{"json_class":"Users::Session","data":{"user":{"json_class":"Users::User","data":{"id":"user1","email":null,"roles":null,"permenant":false,"npc":false,"attributes":null,"password":null,"registration_code":null}},"id":"1234","refreshed_time":"2013-05-30 00:43:54 -0400"}}' s = ::RJR::JSONParser.parse(j) s.class.should == Users::Session s.id.should == "1234" s.user.id.should == 'user1' s.refreshed_time.should_not be_nil end end end # describe Session end # module Users
movitto/omega
spec/users/session_spec.rb
Ruby
agpl-3.0
2,513
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import IconButton from './icon_button'; import DropdownMenu from './dropdown_menu'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; const messages = defineMessages({ delete: { id: 'status.delete', defaultMessage: 'Delete' }, mention: { id: 'status.mention', defaultMessage: 'Mention @{name}' }, mute: { id: 'account.mute', defaultMessage: 'Mute @{name}' }, block: { id: 'account.block', defaultMessage: 'Block @{name}' }, reply: { id: 'status.reply', defaultMessage: 'Reply' }, replyAll: { id: 'status.replyAll', defaultMessage: 'Reply to thread' }, reblog: { id: 'status.reblog', defaultMessage: 'Boost' }, cannot_reblog: { id: 'status.cannot_reblog', defaultMessage: 'This post cannot be boosted' }, favourite: { id: 'status.favourite', defaultMessage: 'Favourite' }, open: { id: 'status.open', defaultMessage: 'Expand this status' }, report: { id: 'status.report', defaultMessage: 'Report @{name}' }, muteConversation: { id: 'status.mute_conversation', defaultMessage: 'Mute conversation' }, unmuteConversation: { id: 'status.unmute_conversation', defaultMessage: 'Unmute conversation' }, }); @injectIntl export default class StatusActionBar extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map.isRequired, onReply: PropTypes.func, onFavourite: PropTypes.func, onReblog: PropTypes.func, onDelete: PropTypes.func, onMention: PropTypes.func, onMute: PropTypes.func, onBlock: PropTypes.func, onReport: PropTypes.func, onMuteConversation: PropTypes.func, me: PropTypes.number.isRequired, withDismiss: PropTypes.bool, intl: PropTypes.object.isRequired, }; // Avoid checking props that are functions (and whose equality will always // evaluate to false. See react-immutable-pure-component for usage. updateOnProps = [ 'status', 'me', 'withDismiss', ] handleReplyClick = () => { this.props.onReply(this.props.status, this.context.router.history); } handleFavouriteClick = () => { this.props.onFavourite(this.props.status); } handleReblogClick = (e) => { this.props.onReblog(this.props.status, e); } handleDeleteClick = () => { this.props.onDelete(this.props.status); } handleMentionClick = () => { this.props.onMention(this.props.status.get('account'), this.context.router.history); } handleMuteClick = () => { this.props.onMute(this.props.status.get('account')); } handleBlockClick = () => { this.props.onBlock(this.props.status.get('account')); } handleOpen = () => { this.context.router.history.push(`/statuses/${this.props.status.get('id')}`); } handleReport = () => { this.props.onReport(this.props.status); } handleConversationMuteClick = () => { this.props.onMuteConversation(this.props.status); } render () { const { status, me, intl, withDismiss } = this.props; const reblogDisabled = status.get('visibility') === 'private' || status.get('visibility') === 'direct'; const mutingConversation = status.get('muted'); let menu = []; let reblogIcon = 'retweet'; let replyIcon; let replyTitle; menu.push({ text: intl.formatMessage(messages.open), action: this.handleOpen }); menu.push(null); if (withDismiss) { menu.push({ text: intl.formatMessage(mutingConversation ? messages.unmuteConversation : messages.muteConversation), action: this.handleConversationMuteClick }); menu.push(null); } if (status.getIn(['account', 'id']) === me) { menu.push({ text: intl.formatMessage(messages.delete), action: this.handleDeleteClick }); } else { menu.push({ text: intl.formatMessage(messages.mention, { name: status.getIn(['account', 'username']) }), action: this.handleMentionClick }); menu.push(null); menu.push({ text: intl.formatMessage(messages.mute, { name: status.getIn(['account', 'username']) }), action: this.handleMuteClick }); menu.push({ text: intl.formatMessage(messages.block, { name: status.getIn(['account', 'username']) }), action: this.handleBlockClick }); menu.push({ text: intl.formatMessage(messages.report, { name: status.getIn(['account', 'username']) }), action: this.handleReport }); } if (status.get('visibility') === 'direct') { reblogIcon = 'envelope'; } else if (status.get('visibility') === 'private') { reblogIcon = 'lock'; } if (status.get('in_reply_to_id', null) === null) { replyIcon = 'reply'; replyTitle = intl.formatMessage(messages.reply); } else { replyIcon = 'reply-all'; replyTitle = intl.formatMessage(messages.replyAll); } return ( <div className='status__action-bar'> <IconButton className='status__action-bar-button' title={replyTitle} icon={replyIcon} onClick={this.handleReplyClick} /> <IconButton className='status__action-bar-button' disabled={reblogDisabled} active={status.get('reblogged')} title={reblogDisabled ? intl.formatMessage(messages.cannot_reblog) : intl.formatMessage(messages.reblog)} icon={reblogIcon} onClick={this.handleReblogClick} /> <IconButton className='status__action-bar-button star-icon' animate active={status.get('favourited')} title={intl.formatMessage(messages.favourite)} icon='star' onClick={this.handleFavouriteClick} /> <div className='status__action-bar-dropdown'> <DropdownMenu items={menu} icon='ellipsis-h' size={18} direction='right' ariaLabel='More' /> </div> </div> ); } }
Toootim/mastodon
app/javascript/mastodon/components/status_action_bar.js
JavaScript
agpl-3.0
5,791
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save()
jorge-marques/shoop
shoop/discount_pricing/admin_form_part.py
Python
agpl-3.0
2,820
/******************************************************************************* * HELIUM V, Open Source ERP software for sustained success * at small and medium-sized enterprises. * Copyright (C) 2004 - 2015 HELIUM V IT-Solutions GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of theLicense, or * (at your option) any later version. * * According to sec. 7 of the GNU Affero General Public License, version 3, * the terms of the AGPL are supplemented with the following terms: * * "HELIUM V" and "HELIUM 5" are registered trademarks of * HELIUM V IT-Solutions GmbH. The licensing of the program under the * AGPL does not imply a trademark license. Therefore any rights, title and * interest in our trademarks remain entirely with us. If you want to propagate * modified versions of the Program under the name "HELIUM V" or "HELIUM 5", * you may only do so if you have a written permission by HELIUM V IT-Solutions * GmbH (to acquire a permission please contact HELIUM V IT-Solutions * at trademark@heliumv.com). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact: developers@heliumv.com ******************************************************************************/ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.12.03 at 10:12:07 AM MEZ // package com.lp.server.schema.opentrans.cc.orderresponse; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for _XML_XML_COST_CATEGORY_ID complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="_XML_XML_COST_CATEGORY_ID"> * &lt;simpleContent> * &lt;extension base="&lt;http://www.opentrans.org/XMLSchema/1.0>typeCOST_CATEGORY_ID"> * &lt;attGroup ref="{http://www.opentrans.org/XMLSchema/1.0}ComIbmMrmNamespaceInfo154"/> * &lt;attribute name="type"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN"> * &lt;minLength value="1"/> * &lt;maxLength value="32"/> * &lt;enumeration value="cost_center"/> * &lt;enumeration value="project"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/extension> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "_XML_XML_COST_CATEGORY_ID", propOrder = { "value" }) public class XMLXMLCOSTCATEGORYID { @XmlValue protected String value; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String type; @XmlAttribute(name = "xsi_schemaLocation") protected String xsiSchemaLocation; @XmlAttribute(name = "xmlns_xsd") protected String xmlnsXsd; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } /** * Gets the value of the xsiSchemaLocation property. * * @return * possible object is * {@link String } * */ public String getXsiSchemaLocation() { if (xsiSchemaLocation == null) { return "openbase_1_0.mxsd"; } else { return xsiSchemaLocation; } } /** * Sets the value of the xsiSchemaLocation property. * * @param value * allowed object is * {@link String } * */ public void setXsiSchemaLocation(String value) { this.xsiSchemaLocation = value; } /** * Gets the value of the xmlnsXsd property. * * @return * possible object is * {@link String } * */ public String getXmlnsXsd() { if (xmlnsXsd == null) { return "http://www.w3.org/2001/XMLSchema"; } else { return xmlnsXsd; } } /** * Sets the value of the xmlnsXsd property. * * @param value * allowed object is * {@link String } * */ public void setXmlnsXsd(String value) { this.xmlnsXsd = value; } }
erdincay/ejb
src/com/lp/server/schema/opentrans/cc/orderresponse/XMLXMLCOSTCATEGORYID.java
Java
agpl-3.0
5,991
-- uncomment for testing /* DECLARE @id int = 1 */ SELECT * FROM Products WHERE Id = @id
SyncToday/synctoday2015
sync.today.ent.products/GetProduct.sql
SQL
agpl-3.0
94
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>api Package &mdash; ally-py 1.0b1 documentation</title> <link rel="stylesheet" href="_static/default.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '', VERSION: '1.0b1', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <link rel="top" title="ally-py 1.0b1 documentation" href="index.html" /> <link rel="up" title="person Package" href="superdesk.person.html" /> <link rel="next" title="impl Package" href="superdesk.person.impl.html" /> <link rel="prev" title="person Package" href="superdesk.person.html" /> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="superdesk.person.impl.html" title="impl Package" accesskey="N">next</a> |</li> <li class="right" > <a href="superdesk.person.html" title="person Package" accesskey="P">previous</a> |</li> <li><a href="index.html">ally-py 1.0b1 documentation</a> &raquo;</li> <li><a href="superdesk.html" >superdesk Package</a> &raquo;</li> <li><a href="superdesk.person.html" accesskey="U">person Package</a> &raquo;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <div class="section" id="api-package"> <h1>api Package<a class="headerlink" href="#api-package" title="Permalink to this headline">¶</a></h1> <div class="section" id="person-module"> <h2><tt class="xref py py-mod docutils literal"><span class="pre">person</span></tt> Module<a class="headerlink" href="#person-module" title="Permalink to this headline">¶</a></h2> </div> </div> </div> </div> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> <h3><a href="index.html">Table Of Contents</a></h3> <ul> <li><a class="reference internal" href="#">api Package</a><ul> <li><a class="reference internal" href="#person-module"><tt class="docutils literal"><span class="pre">person</span></tt> Module</a></li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="superdesk.person.html" title="previous chapter">person Package</a></p> <h4>Next topic</h4> <p class="topless"><a href="superdesk.person.impl.html" title="next chapter">impl Package</a></p> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="_sources/superdesk.person.api.txt" rel="nofollow">Show Source</a></li> </ul> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="search" action="search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="superdesk.person.impl.html" title="impl Package" >next</a> |</li> <li class="right" > <a href="superdesk.person.html" title="person Package" >previous</a> |</li> <li><a href="index.html">ally-py 1.0b1 documentation</a> &raquo;</li> <li><a href="superdesk.html" >superdesk Package</a> &raquo;</li> <li><a href="superdesk.person.html" >person Package</a> &raquo;</li> </ul> </div> <div class="footer"> &copy; Copyright 2012, Gabriel Nistor. Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3. </div> </body> </html>
superdesk/Live-Blog
doc/html/superdesk.person.api.html
HTML
agpl-3.0
5,145
/* ************************************************************************ ******************* CANADIAN ASTRONOMY DATA CENTRE ******************* ************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES ************** * * (c) 2019. (c) 2019. * Government of Canada Gouvernement du Canada * National Research Council Conseil national de recherches * Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6 * All rights reserved Tous droits réservés * * NRC disclaims any warranties, Le CNRC dénie toute garantie * expressed, implied, or énoncée, implicite ou légale, * statutory, of any kind with de quelque nature que ce * respect to the software, soit, concernant le logiciel, * including without limitation y compris sans restriction * any warranty of merchantability toute garantie de valeur * or fitness for a particular marchande ou de pertinence * purpose. NRC shall not be pour un usage particulier. * liable in any event for any Le CNRC ne pourra en aucun cas * damages, whether direct or être tenu responsable de tout * indirect, special or general, dommage, direct ou indirect, * consequential or incidental, particulier ou général, * arising from the use of the accessoire ou fortuit, résultant * software. Neither the name de l'utilisation du logiciel. Ni * of the National Research le nom du Conseil National de * Council of Canada nor the Recherches du Canada ni les noms * names of its contributors may de ses participants ne peuvent * be used to endorse or promote être utilisés pour approuver ou * products derived from this promouvoir les produits dérivés * software without specific prior de ce logiciel sans autorisation * written permission. préalable et particulière * par écrit. * * This file is part of the Ce fichier fait partie du projet * OpenCADC project. OpenCADC. * * OpenCADC is free software: OpenCADC est un logiciel libre ; * you can redistribute it and/or vous pouvez le redistribuer ou le * modify it under the terms of modifier suivant les termes de * the GNU Affero General Public la “GNU Affero General Public * License as published by the License” telle que publiée * Free Software Foundation, par la Free Software Foundation * either version 3 of the : soit la version 3 de cette * License, or (at your option) licence, soit (à votre gré) * any later version. toute version ultérieure. * * OpenCADC is distributed in the OpenCADC est distribué * hope that it will be useful, dans l’espoir qu’il vous * but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE * without even the implied GARANTIE : sans même la garantie * warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ * or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF * PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence * General Public License for Générale Publique GNU Affero * more details. pour plus de détails. * * You should have received Vous devriez avoir reçu une * a copy of the GNU Affero copie de la Licence Générale * General Public License along Publique GNU Affero avec * with OpenCADC. If not, see OpenCADC ; si ce n’est * <http://www.gnu.org/licenses/>. pas le cas, consultez : * <http://www.gnu.org/licenses/>. * * ************************************************************************ */ package org.opencadc.proxy; import ca.nrc.cadc.auth.AuthMethod; import ca.nrc.cadc.reg.client.RegistryClient; import java.net.URI; import java.net.URL; import org.junit.Test; import org.junit.Assert; import static org.mockito.Mockito.*; public class ProxyServletTest { @Test public void lookupServiceURL() throws Exception { final RegistryClient mockRegistryClient = mock(RegistryClient.class); final ProxyServlet testSubject = new ProxyServlet() { /** * Useful for overriding in tests. * * @return RegistryClient instance. Never null. */ @Override RegistryClient getRegistryClient() { return mockRegistryClient; } }; final URL lookedUpServiceURL = new URL("https://www.services.com/myservice"); final ServiceParameterMap serviceParameterMap = new ServiceParameterMap(); serviceParameterMap.put(ServiceParameterName.RESOURCE_ID, "ivo://cadc.nrc.ca/resource"); serviceParameterMap.put(ServiceParameterName.STANDARD_ID, "ivo://cadc.nrc.ca/mystandard"); serviceParameterMap.put(ServiceParameterName.INTERFACE_TYPE_ID, "ivo://cadc.nrc.ca/interface#https"); serviceParameterMap.put(ServiceParameterName.AUTH_TYPE, "cookie"); when(mockRegistryClient.getServiceURL(URI.create("ivo://cadc.nrc.ca/resource"), URI.create("ivo://cadc.nrc.ca/mystandard"), AuthMethod.COOKIE, URI.create("ivo://cadc.nrc.ca/interface#https"))).thenReturn( lookedUpServiceURL); final URL result = testSubject.lookupServiceURL(serviceParameterMap); Assert.assertEquals("URLs do not match.", lookedUpServiceURL, result); } @Test public void lookupServiceURLWithPath() throws Exception { final RegistryClient mockRegistryClient = mock(RegistryClient.class); final ProxyServlet testSubject = new ProxyServlet() { /** * Useful for overriding in tests. * * @return RegistryClient instance. Never null. */ @Override RegistryClient getRegistryClient() { return mockRegistryClient; } }; final URL lookedUpServiceURL = new URL("https://www.services.com/myservice"); final ServiceParameterMap serviceParameterMap = new ServiceParameterMap(); serviceParameterMap.put(ServiceParameterName.RESOURCE_ID, "ivo://cadc.nrc.ca/resource"); serviceParameterMap.put(ServiceParameterName.STANDARD_ID, "ivo://cadc.nrc.ca/mystandard"); serviceParameterMap.put(ServiceParameterName.INTERFACE_TYPE_ID, "ivo://cadc.nrc.ca/interface#https"); serviceParameterMap.put(ServiceParameterName.AUTH_TYPE, "anon"); serviceParameterMap.put(ServiceParameterName.EXTRA_PATH, "alt-site"); when(mockRegistryClient.getServiceURL(URI.create("ivo://cadc.nrc.ca/resource"), URI.create("ivo://cadc.nrc.ca/mystandard"), AuthMethod.ANON, URI.create("ivo://cadc.nrc.ca/interface#https"))).thenReturn( lookedUpServiceURL); final URL result = testSubject.lookupServiceURL(serviceParameterMap); final URL expected = new URL("https://www.services.com/myservice/alt-site"); Assert.assertEquals("URLs do not match.", expected, result); } @Test public void lookupServiceURLWithPathQuery() throws Exception { final RegistryClient mockRegistryClient = mock(RegistryClient.class); final ProxyServlet testSubject = new ProxyServlet() { /** * Useful for overriding in tests. * * @return RegistryClient instance. Never null. */ @Override RegistryClient getRegistryClient() { return mockRegistryClient; } }; final URL lookedUpServiceURL = new URL("https://www.services.com/myservice"); final ServiceParameterMap serviceParameterMap = new ServiceParameterMap(); serviceParameterMap.put(ServiceParameterName.RESOURCE_ID, "ivo://cadc.nrc.ca/resource"); serviceParameterMap.put(ServiceParameterName.STANDARD_ID, "ivo://cadc.nrc.ca/mystandard"); serviceParameterMap.put(ServiceParameterName.INTERFACE_TYPE_ID, "ivo://cadc.nrc.ca/interface#https"); serviceParameterMap.put(ServiceParameterName.AUTH_TYPE, "anon"); serviceParameterMap.put(ServiceParameterName.EXTRA_PATH, "alt-site"); serviceParameterMap.put(ServiceParameterName.EXTRA_QUERY, "myquery=a&g=j"); when(mockRegistryClient.getServiceURL(URI.create("ivo://cadc.nrc.ca/resource"), URI.create("ivo://cadc.nrc.ca/mystandard"), AuthMethod.ANON, URI.create("ivo://cadc.nrc.ca/interface#https"))).thenReturn( lookedUpServiceURL); final URL result = testSubject.lookupServiceURL(serviceParameterMap); final URL expected = new URL("https://www.services.com/myservice/alt-site?myquery=a&g=j"); Assert.assertEquals("URLs do not match.", expected, result); } }
at88mph/web
cadc-web-util/src/test/java/org/opencadc/proxy/ProxyServletTest.java
Java
agpl-3.0
9,512
import ITEM_QUALITIES from '../ITEM_QUALITIES'; export default { // Shared legendaries SOUL_OF_THE_SHADOWBLADE: { id: 150936, name: 'Soul of the Shadowblade', icon: 'inv_jewelry_ring_56', quality: ITEM_QUALITIES.LEGENDARY, }, MANTLE_OF_THE_MASTER_ASSASSIN: { id: 144236, name: 'Mantle of the Master Assassin', icon: 'inv_shoulder_leather_raidrogue_k_01', quality: ITEM_QUALITIES.LEGENDARY, }, INSIGNIA_OF_RAVENHOLDT: { id: 137049, name: 'Insignia of Ravenholdt', icon: 'inv_misc_epicring_a2', quality: ITEM_QUALITIES.LEGENDARY, }, WILL_OF_VALEERA: { id: 137069, name: 'Will of Valeera', icon: 'inv_pants_cloth_02', quality: ITEM_QUALITIES.LEGENDARY, }, THE_DREADLORDS_DECEIT: { id: 137021, name: 'The Dreadlord\'s Deceit', icon: 'inv_cape_pandaria_d_03', quality: ITEM_QUALITIES.LEGENDARY, }, // Assassination legendaries DUSKWALKERS_FOOTPADS: { id: 137030, name: 'Duskwalker\'s Footpads', icon: 'inv_boots_leather_8', quality: ITEM_QUALITIES.LEGENDARY, }, ZOLDYCK_FAMILY_TRAINING_SHACKLES: { id: 137098, name: 'Zoldyck Family Training Shackles', icon: 'inv_bracer_leather_raiddruid_i_01', quality: ITEM_QUALITIES.LEGENDARY, }, THE_EMPTY_CROWN: { id: 151815, name: 'The Empty Crown', icon: 'inv_crown_02', quality: ITEM_QUALITIES.LEGENDARY, }, // Outlaw legendaries THRAXIS_TRICKSY_TREADS: { id: 137031, name: 'Thraxi\'s Tricksy Treads', icon: 'inv_boots_leather_03a', quality: ITEM_QUALITIES.LEGENDARY, }, GREENSKINS_WATERLOGGED_WRISTCUFFS: { id: 137099, name: 'Greenskin\'s Waterlogged Wristcuffs', icon: 'inv_bracer_leather_raidrogue_k_01', quality: ITEM_QUALITIES.LEGENDARY, }, SHIVARRAN_SYMMETRY: { id: 141321, name: 'Shivarran Symmetry', icon: 'inv_gauntlets_83', quality: ITEM_QUALITIES.LEGENDARY, }, THE_CURSE_OF_RESTLESSNESS: { id: 151817, name: 'The Curse of Restlessness', icon: 'inv_qiraj_draperegal', quality: ITEM_QUALITIES.LEGENDARY, }, // Subtlety legendaries SHADOW_SATYRS_WALK: { id: 137032, name: 'Shadow Satyr\'s Walk', icon: 'inv_boots_mail_dungeonmail_c_04', quality: ITEM_QUALITIES.LEGENDARY, }, DENIAL_OF_THE_HALF_GIANTS: { id: 137100, name: 'Denial of the Half-Giants', icon: 'inv_bracer_leather_panda_b_02_crimson', quality: ITEM_QUALITIES.LEGENDARY, }, THE_FIRST_OF_THE_DEAD: { id: 151818, name: 'The First of the Dead', icon: 'inv_glove_cloth_raidwarlockmythic_q_01', quality: ITEM_QUALITIES.LEGENDARY, }, };
enragednuke/WoWAnalyzer
src/common/ITEMS/ROGUE.js
JavaScript
agpl-3.0
2,649
module Merb::Maintainer::BillingHelper def get_stats(metric, dom) today = Date.today date_this_month = Date.new(today.year, today.month, dom) data = [] data_length = 30 data << get_stat(metric, date_this_month) if dom < today.mday (1..(data_length-data.length)).each do |i| date = date_this_month << i data << get_stat(metric, date) end data end # to add a new metric to the billing section, add a case below def get_stat(metric, date) case metric when "active_loans" count = repository.adapter.query(%Q{ SELECT COUNT(date) FROM loan_history lh, (SELECT max(date) AS mdt, loan_id FROM loan_history lh2 WHERE date <= '#{date.strftime}' GROUP BY loan_id) AS md WHERE lh.date = md.mdt AND lh.loan_id = md.loan_id AND lh.status IN (2,4,5,6); }).first when "total_loans" count = Loan.count(:applied_on.lte => date) when "total_clients" count = Client.count(:date_joined.lte => date) end { :date => date.strftime(DATE_FORMAT_READABLE), :count => count } end end
Mostfit/mostfit
slices/maintainer/app/helpers/billing_helper.rb
Ruby
agpl-3.0
1,102
/*************************************************************************** constraintteachersmaxgapsperdayform.cpp - description ------------------- begin : Jan 21, 2008 copyright : (C) 2008 by Lalescu Liviu email : Please see http://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address) ***************************************************************************/ /*************************************************************************** * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * * ***************************************************************************/ #include <QMessageBox> #include "longtextmessagebox.h" #include "constraintteachersmaxgapsperdayform.h" #include "addconstraintteachersmaxgapsperdayform.h" #include "modifyconstraintteachersmaxgapsperdayform.h" #include <QListWidget> #include <QScrollBar> #include <QAbstractItemView> ConstraintTeachersMaxGapsPerDayForm::ConstraintTeachersMaxGapsPerDayForm(QWidget* parent): QDialog(parent) { setupUi(this); currentConstraintTextEdit->setReadOnly(true); modifyConstraintPushButton->setDefault(true); constraintsListWidget->setSelectionMode(QAbstractItemView::SingleSelection); connect(constraintsListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(constraintChanged(int))); connect(addConstraintPushButton, SIGNAL(clicked()), this, SLOT(addConstraint())); connect(closePushButton, SIGNAL(clicked()), this, SLOT(close())); connect(removeConstraintPushButton, SIGNAL(clicked()), this, SLOT(removeConstraint())); connect(modifyConstraintPushButton, SIGNAL(clicked()), this, SLOT(modifyConstraint())); connect(constraintsListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(modifyConstraint())); centerWidgetOnScreen(this); restoreFETDialogGeometry(this); this->filterChanged(); } ConstraintTeachersMaxGapsPerDayForm::~ConstraintTeachersMaxGapsPerDayForm() { saveFETDialogGeometry(this); } bool ConstraintTeachersMaxGapsPerDayForm::filterOk(TimeConstraint* ctr) { if(ctr->type==CONSTRAINT_TEACHERS_MAX_GAPS_PER_DAY) return true; else return false; } void ConstraintTeachersMaxGapsPerDayForm::filterChanged() { this->visibleConstraintsList.clear(); constraintsListWidget->clear(); for(int i=0; i<gt.rules.timeConstraintsList.size(); i++){ TimeConstraint* ctr=gt.rules.timeConstraintsList[i]; if(filterOk(ctr)){ visibleConstraintsList.append(ctr); constraintsListWidget->addItem(ctr->getDescription(gt.rules)); } } if(constraintsListWidget->count()>0) constraintsListWidget->setCurrentRow(0); else constraintChanged(-1); } void ConstraintTeachersMaxGapsPerDayForm::constraintChanged(int index) { if(index<0){ currentConstraintTextEdit->setPlainText(""); return; } assert(index<this->visibleConstraintsList.size()); TimeConstraint* ctr=this->visibleConstraintsList.at(index); assert(ctr!=NULL); currentConstraintTextEdit->setPlainText(ctr->getDetailedDescription(gt.rules)); } void ConstraintTeachersMaxGapsPerDayForm::addConstraint() { AddConstraintTeachersMaxGapsPerDayForm form(this); setParentAndOtherThings(&form, this); form.exec(); filterChanged(); constraintsListWidget->setCurrentRow(constraintsListWidget->count()-1); } void ConstraintTeachersMaxGapsPerDayForm::modifyConstraint() { int valv=constraintsListWidget->verticalScrollBar()->value(); int valh=constraintsListWidget->horizontalScrollBar()->value(); int i=constraintsListWidget->currentRow(); if(i<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected constraint")); return; } TimeConstraint* ctr=this->visibleConstraintsList.at(i); ModifyConstraintTeachersMaxGapsPerDayForm form(this, (ConstraintTeachersMaxGapsPerDay*)ctr); setParentAndOtherThings(&form, this); form.exec(); filterChanged(); constraintsListWidget->verticalScrollBar()->setValue(valv); constraintsListWidget->horizontalScrollBar()->setValue(valh); if(i>=constraintsListWidget->count()) i=constraintsListWidget->count()-1; if(i>=0) constraintsListWidget->setCurrentRow(i); else this->constraintChanged(-1); } void ConstraintTeachersMaxGapsPerDayForm::removeConstraint() { int i=constraintsListWidget->currentRow(); if(i<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected constraint")); return; } TimeConstraint* ctr=this->visibleConstraintsList.at(i); QString s; s=tr("Remove constraint?"); s+="\n\n"; s+=ctr->getDetailedDescription(gt.rules); QListWidgetItem* item; switch( LongTextMessageBox::confirmation( this, tr("FET confirmation"), s, tr("Yes"), tr("No"), 0, 0, 1 ) ){ case 0: // The user clicked the OK button or pressed Enter gt.rules.removeTimeConstraint(ctr); visibleConstraintsList.removeAt(i); constraintsListWidget->setCurrentRow(-1); item=constraintsListWidget->takeItem(i); delete item; break; case 1: // The user clicked the Cancel button or pressed Escape break; } if(i>=constraintsListWidget->count()) i=constraintsListWidget->count()-1; if(i>=0) constraintsListWidget->setCurrentRow(i); else this->constraintChanged(-1); }
fet-project/fet
src/interface/constraintteachersmaxgapsperdayform.cpp
C++
agpl-3.0
5,667
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 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 base64 import netsvc from osv import osv from osv import fields from tools.translate import _ import tools def _reopen(self, wizard_id, res_model, res_id): return {'type': 'ir.actions.act_window', 'view_mode': 'form', 'view_type': 'form', 'res_id': wizard_id, 'res_model': self._name, 'target': 'new', # save original model in context, otherwise # it will be lost on the action's context switch 'context': {'mail.compose.target.model': res_model, 'mail.compose.target.id': res_id,} } class mail_compose_message(osv.osv_memory): _inherit = 'mail.compose.message' def _get_templates(self, cr, uid, context=None): """ Return Email Template of particular Model. """ if context is None: context = {} record_ids = [] email_template= self.pool.get('email.template') model = False if context.get('message_id'): mail_message = self.pool.get('mail.message') message_data = mail_message.browse(cr, uid, int(context.get('message_id')), context) model = message_data.model elif context.get('mail.compose.target.model') or context.get('active_model'): model = context.get('mail.compose.target.model', context.get('active_model')) if model: record_ids = email_template.search(cr, uid, [('model', '=', model)]) return email_template.name_get(cr, uid, record_ids, context) + [(False,'')] return [] _columns = { 'use_template': fields.boolean('Use Template'), 'template_id': fields.selection(_get_templates, 'Template', size=-1 # means we want an int db column ), } _defaults = { 'template_id' : lambda self, cr, uid, context={} : context.get('mail.compose.template_id', False) } def on_change_template(self, cr, uid, ids, use_template, template_id, email_from=None, email_to=None, context=None): if context is None: context = {} values = {} if template_id: res_id = context.get('mail.compose.target.id') or context.get('active_id') or False if context.get('mail.compose.message.mode') == 'mass_mail': # use the original template values - to be rendered when actually sent # by super.send_mail() values = self.pool.get('email.template').read(cr, uid, template_id, self.fields_get_keys(cr, uid), context) report_xml_pool = self.pool.get('ir.actions.report.xml') template = self.pool.get('email.template').get_email_template(cr, uid, template_id, res_id, context) values['attachments'] = False attachments = {} if template.report_template: report_name = self.render_template(cr, uid, template.report_name, template.model, res_id, context=context) report_service = 'report.' + report_xml_pool.browse(cr, uid, template.report_template.id, context).report_name # Ensure report is rendered using template's language ctx = context.copy() if template.lang: ctx['lang'] = self.render_template(cr, uid, template.lang, template.model, res_id, context) service = netsvc.LocalService(report_service) (result, format) = service.create(cr, uid, [res_id], {'model': template.model}, ctx) result = base64.b64encode(result) if not report_name: report_name = report_service ext = "." + format if not report_name.endswith(ext): report_name += ext attachments[report_name] = result # Add document attachments for attach in template.attachment_ids: # keep the bytes as fetched from the db, base64 encoded attachments[attach.datas_fname] = attach.datas values['attachments'] = attachments if values['attachments']: attachment = values.pop('attachments') attachment_obj = self.pool.get('ir.attachment') att_ids = [] for fname, fcontent in attachment.iteritems(): data_attach = { 'name': fname, 'datas': fcontent, 'datas_fname': fname, 'description': fname, 'res_model' : self._name, 'res_id' : ids[0] if ids else False } att_ids.append(attachment_obj.create(cr, uid, data_attach)) values['attachment_ids'] = att_ids else: # render the mail as one-shot values = self.pool.get('email.template').generate_email(cr, uid, template_id, res_id, context=context) # retrofit generated attachments in the expected field format if values['attachments']: attachment = values.pop('attachments') attachment_obj = self.pool.get('ir.attachment') att_ids = [] for fname, fcontent in attachment.iteritems(): data_attach = { 'name': fname, 'datas': fcontent, 'datas_fname': fname, 'description': fname, 'res_model' : self._name, 'res_id' : ids[0] if ids else False } att_ids.append(attachment_obj.create(cr, uid, data_attach)) values['attachment_ids'] = att_ids else: # restore defaults values = self.default_get(cr, uid, self.fields_get_keys(cr, uid), context) values.update(use_template=use_template, template_id=template_id) return {'value': values} def template_toggle(self, cr, uid, ids, context=None): for record in self.browse(cr, uid, ids, context=context): had_template = record.use_template record.write({'use_template': not(had_template)}) if had_template: # equivalent to choosing an empty template onchange_defaults = self.on_change_template(cr, uid, record.id, not(had_template), False, email_from=record.email_from, email_to=record.email_to, context=context) record.write(onchange_defaults['value']) return _reopen(self, record.id, record.model, record.res_id) def save_as_template(self, cr, uid, ids, context=None): if context is None: context = {} email_template = self.pool.get('email.template') model_pool = self.pool.get('ir.model') for record in self.browse(cr, uid, ids, context=context): model = record.model or context.get('active_model') model_ids = model_pool.search(cr, uid, [('model', '=', model)]) model_id = model_ids and model_ids[0] or False model_name = '' if model_id: model_name = model_pool.browse(cr, uid, model_id, context=context).name template_name = "%s: %s" % (model_name, tools.ustr(record.subject)) values = { 'name': template_name, 'email_from': record.email_from or False, 'subject': record.subject or False, 'body_text': record.body_text or False, 'email_to': record.email_to or False, 'email_cc': record.email_cc or False, 'email_bcc': record.email_bcc or False, 'reply_to': record.reply_to or False, 'model_id': model_id or False, 'attachment_ids': [(6, 0, [att.id for att in record.attachment_ids])] } template_id = email_template.create(cr, uid, values, context=context) record.write({'template_id': template_id, 'use_template': True}) # _reopen same wizard screen with new template preselected return _reopen(self, record.id, model, record.res_id) # override the basic implementation def render_template(self, cr, uid, template, model, res_id, context=None): return self.pool.get('email.template').render_template(cr, uid, template, model, res_id, context=context) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
ksrajkumar/openerp-6.1
openerp/addons/email_template/wizard/mail_compose_message.py
Python
agpl-3.0
10,036
package org.osforce.connect.service.system; import org.osforce.connect.entity.system.ProjectFeature; /** * * @author gavin * @since 1.0.0 * @create Feb 12, 2011 - 9:23:35 PM * <a href="http://www.opensourceforce.org">开源力量</a> */ public interface ProjectFeatureService { ProjectFeature getProjectFeature(Long featureId); ProjectFeature getProjectFeature(String code, Long projectId); void createProjectFeature(ProjectFeature feature); void updateProjectFeature(ProjectFeature feature); void deleteProjectFeature(Long featureId); }
shook2012/focus-sns
connect-service/src/main/java/org/osforce/connect/service/system/ProjectFeatureService.java
Java
agpl-3.0
562
// This file may be edited manually or auto-generated using IfcKit at www.buildingsmart-tech.org. // IFC content is copyright (C) 1996-2018 BuildingSMART International Ltd. using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Xml.Serialization; namespace BuildingSmart.IFC.IfcGeometricModelResource { public enum IfcBooleanOperator { [Description("The operation of constructing the regularized set theoretic union of the volumes " + "defined by two solids.")] UNION = 1, [Description("The operation of constructing the regularised set theoretic intersection of the v" + "olumes defined by two solids.")] INTERSECTION = 2, [Description("The regularised set theoretic difference between the volumes defined by two solid" + "s.")] DIFFERENCE = 3, } }
pipauwel/IfcDoc
IfcKit/schemas/IfcGeometricModelResource/IfcBooleanOperator.cs
C#
agpl-3.0
995
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include "rocksdb/sst_file_writer.h" #include <vector> #include "db/dbformat.h" #include "rocksdb/table.h" #include "table/block_based_table_builder.h" #include "table/sst_file_writer_collectors.h" #include "util/file_reader_writer.h" #include "util/sync_point.h" namespace rocksdb { const std::string ExternalSstFilePropertyNames::kVersion = "rocksdb.external_sst_file.version"; const std::string ExternalSstFilePropertyNames::kGlobalSeqno = "rocksdb.external_sst_file.global_seqno"; #ifndef ROCKSDB_LITE const size_t kFadviseTrigger = 1024 * 1024; // 1MB struct SstFileWriter::Rep { Rep(const EnvOptions& _env_options, const Options& options, const Comparator* _user_comparator, ColumnFamilyHandle* _cfh, bool _invalidate_page_cache) : env_options(_env_options), ioptions(options), mutable_cf_options(options), internal_comparator(_user_comparator), cfh(_cfh), invalidate_page_cache(_invalidate_page_cache), last_fadvise_size(0) {} std::unique_ptr<WritableFileWriter> file_writer; std::unique_ptr<TableBuilder> builder; EnvOptions env_options; ImmutableCFOptions ioptions; MutableCFOptions mutable_cf_options; InternalKeyComparator internal_comparator; ExternalSstFileInfo file_info; InternalKey ikey; std::string column_family_name; ColumnFamilyHandle* cfh; // If true, We will give the OS a hint that this file pages is not needed // everytime we write 1MB to the file bool invalidate_page_cache; // the size of the file during the last time we called Fadvise to remove // cached pages from page cache. uint64_t last_fadvise_size; }; SstFileWriter::SstFileWriter(const EnvOptions& env_options, const Options& options, const Comparator* user_comparator, ColumnFamilyHandle* column_family, bool invalidate_page_cache) : rep_(new Rep(env_options, options, user_comparator, column_family, invalidate_page_cache)) { rep_->file_info.file_size = 0; } SstFileWriter::~SstFileWriter() { if (rep_->builder) { // User did not call Finish() or Finish() failed, we need to // abandon the builder. rep_->builder->Abandon(); } delete rep_; } Status SstFileWriter::Open(const std::string& file_path) { Rep* r = rep_; Status s; std::unique_ptr<WritableFile> sst_file; s = r->ioptions.env->NewWritableFile(file_path, &sst_file, r->env_options); if (!s.ok()) { return s; } CompressionType compression_type; if (r->ioptions.bottommost_compression != kDisableCompressionOption) { compression_type = r->ioptions.bottommost_compression; } else if (!r->ioptions.compression_per_level.empty()) { // Use the compression of the last level if we have per level compression compression_type = *(r->ioptions.compression_per_level.rbegin()); } else { compression_type = r->mutable_cf_options.compression; } std::vector<std::unique_ptr<IntTblPropCollectorFactory>> int_tbl_prop_collector_factories; // SstFileWriter properties collector to add SstFileWriter version. int_tbl_prop_collector_factories.emplace_back( new SstFileWriterPropertiesCollectorFactory(2 /* version */, 0 /* global_seqno*/)); // User collector factories auto user_collector_factories = r->ioptions.table_properties_collector_factories; for (size_t i = 0; i < user_collector_factories.size(); i++) { int_tbl_prop_collector_factories.emplace_back( new UserKeyTablePropertiesCollectorFactory( user_collector_factories[i])); } int unknown_level = -1; uint32_t cf_id; if (r->cfh != nullptr) { // user explicitly specified that this file will be ingested into cfh, // we can persist this information in the file. cf_id = r->cfh->GetID(); r->column_family_name = r->cfh->GetName(); } else { r->column_family_name = ""; cf_id = TablePropertiesCollectorFactory::Context::kUnknownColumnFamily; } TableBuilderOptions table_builder_options( r->ioptions, r->internal_comparator, &int_tbl_prop_collector_factories, compression_type, r->ioptions.compression_opts, nullptr /* compression_dict */, false /* skip_filters */, r->column_family_name, unknown_level); r->file_writer.reset( new WritableFileWriter(std::move(sst_file), r->env_options)); // TODO(tec) : If table_factory is using compressed block cache, we will // be adding the external sst file blocks into it, which is wasteful. r->builder.reset(r->ioptions.table_factory->NewTableBuilder( table_builder_options, cf_id, r->file_writer.get())); r->file_info.file_path = file_path; r->file_info.file_size = 0; r->file_info.num_entries = 0; r->file_info.sequence_number = 0; r->file_info.version = 2; return s; } Status SstFileWriter::Add(const Slice& user_key, const Slice& value) { Rep* r = rep_; if (!r->builder) { return Status::InvalidArgument("File is not opened"); } if (r->file_info.num_entries == 0) { r->file_info.smallest_key.assign(user_key.data(), user_key.size()); } else { if (r->internal_comparator.user_comparator()->Compare( user_key, r->file_info.largest_key) <= 0) { // Make sure that keys are added in order return Status::InvalidArgument("Keys must be added in order"); } } // TODO(tec) : For external SST files we could omit the seqno and type. r->ikey.Set(user_key, 0 /* Sequence Number */, ValueType::kTypeValue /* Put */); r->builder->Add(r->ikey.Encode(), value); // update file info r->file_info.num_entries++; r->file_info.largest_key.assign(user_key.data(), user_key.size()); r->file_info.file_size = r->builder->FileSize(); InvalidatePageCache(false /* closing */); return Status::OK(); } Status SstFileWriter::Finish(ExternalSstFileInfo* file_info) { Rep* r = rep_; if (!r->builder) { return Status::InvalidArgument("File is not opened"); } if (r->file_info.num_entries == 0) { return Status::InvalidArgument("Cannot create sst file with no entries"); } Status s = r->builder->Finish(); r->file_info.file_size = r->builder->FileSize(); if (s.ok()) { s = r->file_writer->Sync(r->ioptions.use_fsync); InvalidatePageCache(true /* closing */); if (s.ok()) { s = r->file_writer->Close(); } } if (!s.ok()) { r->ioptions.env->DeleteFile(r->file_info.file_path); } if (file_info != nullptr) { *file_info = r->file_info; } r->builder.reset(); return s; } void SstFileWriter::InvalidatePageCache(bool closing) { Rep* r = rep_; if (r->invalidate_page_cache == false) { // Fadvise disabled return; } uint64_t bytes_since_last_fadvise = r->builder->FileSize() - r->last_fadvise_size; if (bytes_since_last_fadvise > kFadviseTrigger || closing) { TEST_SYNC_POINT_CALLBACK("SstFileWriter::InvalidatePageCache", &(bytes_since_last_fadvise)); // Tell the OS that we dont need this file in page cache r->file_writer->InvalidateCache(0, 0); r->last_fadvise_size = r->builder->FileSize(); } } uint64_t SstFileWriter::FileSize() { return rep_->file_info.file_size; } #endif // !ROCKSDB_LITE } // namespace rocksdb
chain/chain
vendor/github.com/facebook/rocksdb/table/sst_file_writer.cc
C++
agpl-3.0
7,678
const LdapStrategy = require('./LdapStrategy'); const MoodleStrategy = require('./MoodleStrategy'); const IservStrategy = require('./IservStrategy'); const TSPStrategy = require('./TSPStrategy'); const ApiKeyStrategy = require('./ApiKeyStrategy'); module.exports = { LdapStrategy, MoodleStrategy, IservStrategy, TSPStrategy, ApiKeyStrategy, };
schul-cloud/schulcloud-server
src/services/authentication/strategies/index.js
JavaScript
agpl-3.0
350
/* Copyright (C) 2014-2016 Leosac This file is part of Leosac. Leosac is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leosac is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "AccessOverview.hpp" #include "core/auth/Door.hpp" #include "core/auth/Door_odb.h" #include "core/auth/User_odb.h" #include "tools/JSONUtils.hpp" #include "tools/db/DBService.hpp" using namespace Leosac; using namespace Leosac::Module; using namespace Leosac::Module::WebSockAPI; AccessOverview::AccessOverview(RequestContext ctx) : MethodHandler(ctx) { } MethodHandlerUPtr AccessOverview::create(RequestContext ctx) { return std::make_unique<AccessOverview>(ctx); } json AccessOverview::process_impl(const json &) { json rep; DBPtr db = ctx_.dbsrv->db(); odb::transaction t(db->begin()); // todo: This probably doesn't scale very well... auto doors = db->query<Auth::Door>(); // Since we'll be looping over users multiple time, we cannot use // an odb::result object. auto users_odb = db->query<Auth::User>(); // So we'll have to convert this to a vector of User, instead of // odb::result::iterator. std::vector<Auth::UserPtr> users; for (auto itr_odb(users_odb.begin()); itr_odb != users_odb.end(); ++itr_odb) users.push_back(itr_odb.load()); for (const auto &door : doors) { std::set<Auth::UserId> unique_user_ids; json door_info = {{"door_id", door.id()}, {"user_ids", json::array()}}; for (const auto &lazy_mapping : door.lazy_mapping()) { auto mapping = lazy_mapping.load(); for (const auto &user_ptr : users) { // Check the std::set in case the user is already authorized to // access the door. if (unique_user_ids.count(user_ptr->id())) { continue; } if (mapping->has_user_indirect(user_ptr)) { unique_user_ids.insert(user_ptr->id()); } } } for (const auto &id : unique_user_ids) door_info["user_ids"].push_back(id); rep.push_back(door_info); } return rep; } std::vector<ActionActionParam> AccessOverview::required_permission(const json &) const { std::vector<ActionActionParam> perm_; SecurityContext::ActionParam ap; perm_.push_back({SecurityContext::Action::ACCESS_OVERVIEW, ap}); return perm_; }
islog/leosac
src/modules/websock-api/api/AccessOverview.cpp
C++
agpl-3.0
3,045
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('schedules', '0005_auto_20171010_1722'), ] operations = [ migrations.CreateModel( name='ScheduleExperience', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('experience_type', models.PositiveSmallIntegerField(default=0, choices=[(0, b'Recurring Nudge and Upgrade Reminder'), (1, b'Course Updates')])), ('schedule', models.OneToOneField(related_name='experience', to='schedules.Schedule', on_delete=models.CASCADE)), ], ), ]
ESOedX/edx-platform
openedx/core/djangoapps/schedules/migrations/0006_scheduleexperience.py
Python
agpl-3.0
793
# -*- coding: utf-8 -*- # Copyright 2017 KMEE # Hendrix Costa <hendrix.costa@kmee.com.br> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openerp.addons.financial.tests.financial_test_classes import \ FinancialTestCase class ManualFinancialProcess(FinancialTestCase): def setUp(self): self.financial_model = self.env['financial.move'] super(ManualFinancialProcess, self).setUp() def test_01_check_return_views(self): """Check if view is correctly called for python code""" # test for len(financial.move) == 1 financial_move_id = self.financial_model.search([], limit=1) action = financial_move_id.action_view_financial('2receive') self.assertEqual( action.get('display_name'), 'financial.move.debt.2receive.form (in financial)') self.assertEqual( action.get('res_id'), financial_move_id.id) action = financial_move_id.action_view_financial('2pay') self.assertEqual( action.get('display_name'), 'financial.move.debt.2pay.form (in financial)') self.assertEqual( action.get('res_id'), financial_move_id.id) # test for len(financial.move) > 1 financial_move_id = self.financial_model.search([], limit=2) action = financial_move_id.action_view_financial('2pay') self.assertEqual(action.get('domain')[0][2], financial_move_id.ids) # test for len(financial.move) < 1 action = self.financial_model.action_view_financial('2pay') self.assertEqual(action.get('type'), 'ir.actions.act_window_close')
thinkopensolutions/l10n-brazil
financial/tests/test_financial_move.py
Python
agpl-3.0
1,651
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django import forms from django.utils.translation import ugettext_lazy as _ from shuup.core.models import Category from shuup.xtheme import TemplatedPlugin from shuup.xtheme.plugins.forms import GenericPluginForm, TranslatableField class CategoryLinksConfigForm(GenericPluginForm): """ A configuration form for the CategoryLinksPlugin """ def populate(self): """ A custom populate method to display category choices """ for field in self.plugin.fields: if isinstance(field, tuple): name, value = field value.initial = self.plugin.config.get(name, value.initial) self.fields[name] = value self.fields["categories"] = forms.ModelMultipleChoiceField( queryset=Category.objects.all_visible(customer=None), required=False, initial=self.plugin.config.get("categories", None), ) def clean(self): """ A custom clean method to save category configuration information in a serializable form """ cleaned_data = super(CategoryLinksConfigForm, self).clean() categories = cleaned_data.get("categories", []) cleaned_data["categories"] = [category.pk for category in categories if hasattr(category, "pk")] return cleaned_data class CategoryLinksPlugin(TemplatedPlugin): """ A plugin for displaying links to visible categories on the shop front """ identifier = "category_links" name = _("Category Links") template_name = "shuup/xtheme/plugins/category_links.jinja" editor_form_class = CategoryLinksConfigForm fields = [ ("title", TranslatableField(label=_("Title"), required=False, initial="")), ("show_all_categories", forms.BooleanField( label=_("Show all categories"), required=False, initial=True, help_text=_("All categories are shown, even if not selected"), )), "categories", ] def get_context_data(self, context): """ A custom get_context_data method to return only visible categories for request customer. """ selected_categories = self.config.get("categories", []) show_all_categories = self.config.get("show_all_categories", True) request = context.get("request") categories = Category.objects.all_visible( customer=getattr(request, "customer"), shop=getattr(request, "shop") ) if not show_all_categories: categories = categories.filter(id__in=selected_categories) return { "title": self.get_translated_value("title"), "categories": categories, }
shawnadelic/shuup
shuup/xtheme/plugins/category_links.py
Python
agpl-3.0
2,994