code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php namespace Oro\Bundle\AttachmentBundle\Command; use Doctrine\Common\Persistence\ManagerRegistry; use Oro\Bundle\AttachmentBundle\Entity\File; use Oro\Bundle\AttachmentBundle\Migration\FilteredAttachmentMigrationServiceInterface; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * Migrate filtered images folder structure to new one */ class MigrateImagesCommand extends Command { /** * @var string */ protected static $defaultName = 'oro:attachment:migrate-directory-structure'; /** * @var ManagerRegistry */ private $registry; /** * @var FilteredAttachmentMigrationServiceInterface */ private $migrationService; /** * @var string */ private $prefix; /** * @param ManagerRegistry $registry * @param FilteredAttachmentMigrationServiceInterface $migrationService * @param string $prefix */ public function __construct( ManagerRegistry $registry, FilteredAttachmentMigrationServiceInterface $migrationService, string $prefix ) { $this->registry = $registry; $this->migrationService = $migrationService; $this->prefix = $prefix; parent::__construct(); } /** * {@inheritdoc} */ protected function configure() { $this ->setDescription('Migrate filtered attachments to new directory structure'); } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('Starting attachments migration'); $manager = $this->registry->getManagerForClass(File::class); $this->migrationService->setManager($manager); $this->migrationService->migrate($this->prefix, $this->prefix); $output->writeln('Attachments migration finished'); } }
orocrm/platform
src/Oro/Bundle/AttachmentBundle/Command/MigrateImagesCommand.php
PHP
mit
1,972
IF (OBJECT_ID('FK_kunsthåndværk_users', 'F') IS NOT NULL) BEGIN ALTER TABLE [kunsthåndværk] DROP CONSTRAINT [FK_kunsthåndværk_users] END GO IF (OBJECT_ID('FK_barcodes_products', 'F') IS NOT NULL) BEGIN ALTER TABLE [barcodes] DROP CONSTRAINT [FK_barcodes_products] END GO IF (OBJECT_ID('FK_posts_users', 'F') IS NOT NULL) BEGIN ALTER TABLE [posts] DROP CONSTRAINT [FK_posts_users] END GO IF (OBJECT_ID('FK_posts_categories', 'F') IS NOT NULL) BEGIN ALTER TABLE [posts] DROP CONSTRAINT [FK_posts_categories] END GO IF (OBJECT_ID('FK_post_tags_tags', 'F') IS NOT NULL) BEGIN ALTER TABLE [post_tags] DROP CONSTRAINT [FK_post_tags_tags] END GO IF (OBJECT_ID('FK_post_tags_posts', 'F') IS NOT NULL) BEGIN ALTER TABLE [post_tags] DROP CONSTRAINT [FK_post_tags_posts] END GO IF (OBJECT_ID('FK_comments_posts', 'F') IS NOT NULL) BEGIN ALTER TABLE [comments] DROP CONSTRAINT [FK_comments_posts] END GO IF (OBJECT_ID('barcodes2', 'U') IS NOT NULL) BEGIN DROP TABLE [barcodes2] END GO IF (OBJECT_ID('barcodes', 'U') IS NOT NULL) BEGIN DROP TABLE [barcodes] END GO IF (OBJECT_ID('products', 'U') IS NOT NULL) BEGIN DROP TABLE [products] END GO IF (OBJECT_ID('events', 'U') IS NOT NULL) BEGIN DROP TABLE [events] END GO IF (OBJECT_ID('countries', 'U') IS NOT NULL) BEGIN DROP TABLE [countries] END GO IF (OBJECT_ID('users', 'U') IS NOT NULL) BEGIN DROP TABLE [users] END GO IF (OBJECT_ID('tags', 'U') IS NOT NULL) BEGIN DROP TABLE [tags] END GO IF (OBJECT_ID('posts', 'U') IS NOT NULL) BEGIN DROP TABLE [posts] END GO IF (OBJECT_ID('post_tags', 'U') IS NOT NULL) BEGIN DROP TABLE [post_tags] END GO IF (OBJECT_ID('comments', 'U') IS NOT NULL) BEGIN DROP TABLE [comments] END GO IF (OBJECT_ID('categories', 'U') IS NOT NULL) BEGIN DROP TABLE [categories] END GO IF (OBJECT_ID('tag_usage', 'V') IS NOT NULL) BEGIN DROP VIEW [tag_usage] END GO IF (OBJECT_ID('kunsthåndværk', 'U') IS NOT NULL) BEGIN DROP TABLE [kunsthåndværk] END GO IF (OBJECT_ID('invisibles', 'U') IS NOT NULL) BEGIN DROP TABLE [invisibles] END GO IF (OBJECT_ID('nopk', 'U') IS NOT NULL) BEGIN DROP TABLE [nopk] END GO CREATE TABLE [categories]( [id] [int] IDENTITY, [name] [nvarchar](255) NOT NULL, [icon] [image], PRIMARY KEY CLUSTERED([id] ASC) ) GO CREATE TABLE [comments]( [id] [bigint] IDENTITY, [post_id] [int] NOT NULL, [message] [nvarchar](255) NOT NULL, PRIMARY KEY CLUSTERED([id] ASC) ) GO CREATE TABLE [post_tags]( [id] [int] IDENTITY, [post_id] [int] NOT NULL, [tag_id] [int] NOT NULL, PRIMARY KEY CLUSTERED([id] ASC) ) GO CREATE TABLE [posts]( [id] [int] IDENTITY, [user_id] [int] NOT NULL, [category_id] [int] NOT NULL, [content] [nvarchar](255) NOT NULL, PRIMARY KEY CLUSTERED([id] ASC) ) GO CREATE TABLE [tags]( [id] [int] IDENTITY, [name] [nvarchar](255) NOT NULL, [is_important] [bit] NOT NULL, PRIMARY KEY CLUSTERED([id] ASC) ) GO CREATE TABLE [users]( [id] [int] IDENTITY, [username] [nvarchar](255) NOT NULL, [password] [nvarchar](255) NOT NULL, [location] [geometry], CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED([id] ASC) ) GO CREATE TABLE [countries]( [id] [int] IDENTITY, [name] [nvarchar](255) NOT NULL, [shape] [geometry] NOT NULL, CONSTRAINT [PK_countries] PRIMARY KEY CLUSTERED([id] ASC) ) GO CREATE TABLE [events]( [id] [int] IDENTITY, [name] [nvarchar](255) NOT NULL, [datetime] [datetime2](0), [visitors] [bigint], CONSTRAINT [PK_events] PRIMARY KEY CLUSTERED([id] ASC) ) GO CREATE VIEW [tag_usage] AS SELECT top 100 PERCENT name, COUNT_BIG(name) AS [count] FROM tags, post_tags WHERE tags.id = post_tags.tag_id GROUP BY name ORDER BY [count] DESC, name GO CREATE TABLE [products]( [id] [int] IDENTITY, [name] [nvarchar](255) NOT NULL, [price] [decimal](10,2) NOT NULL, [properties] [xml] NOT NULL, [created_at] [datetime2](0) NOT NULL, [deleted_at] [datetime2](0), CONSTRAINT [PK_products] PRIMARY KEY CLUSTERED([id] ASC) ) GO CREATE TABLE [barcodes]( [id] [int] IDENTITY, [product_id] [int] NOT NULL, [hex] [nvarchar](255) NOT NULL, [bin] [varbinary](max) NOT NULL, CONSTRAINT [PK_barcodes] PRIMARY KEY CLUSTERED([id] ASC) ) GO CREATE TABLE [kunsthåndværk]( [id] [nvarchar](36) NOT NULL, [Umlauts ä_ö_ü-COUNT] [int] NOT NULL, [user_id] [int] NOT NULL, [invisible] [nvarchar](36), CONSTRAINT [PK_kunsthåndværk] PRIMARY KEY CLUSTERED([id] ASC) ) GO CREATE TABLE [invisibles]( [id] [nvarchar](36) NOT NULL, CONSTRAINT [PK_invisibles] PRIMARY KEY CLUSTERED([id] ASC) ) GO CREATE TABLE [nopk]( [id] [nvarchar](36) NOT NULL ) GO INSERT [categories] ([name], [icon]) VALUES (N'announcement', NULL) GO INSERT [categories] ([name], [icon]) VALUES (N'article', NULL) GO INSERT [comments] ([post_id], [message]) VALUES (1, N'great') GO INSERT [comments] ([post_id], [message]) VALUES (1, N'fantastic') GO INSERT [comments] ([post_id], [message]) VALUES (2, N'thank you') GO INSERT [comments] ([post_id], [message]) VALUES (2, N'awesome') GO INSERT [post_tags] ([post_id], [tag_id]) VALUES (1, 1) GO INSERT [post_tags] ([post_id], [tag_id]) VALUES (1, 2) GO INSERT [post_tags] ([post_id], [tag_id]) VALUES (2, 1) GO INSERT [post_tags] ([post_id], [tag_id]) VALUES (2, 2) GO INSERT [posts] ([user_id], [category_id], [content]) VALUES (1, 1, N'blog started') GO INSERT [posts] ([user_id], [category_id], [content]) VALUES (1, 2, N'It works!') GO INSERT [tags] ([name], [is_important]) VALUES (N'funny', 0) GO INSERT [tags] ([name], [is_important]) VALUES (N'important', 1) GO INSERT [users] ([username], [password], [location]) VALUES (N'user1', N'pass1', NULL) GO INSERT [users] ([username], [password], [location]) VALUES (N'user2', N'pass2', NULL) GO INSERT [countries] ([name], [shape]) VALUES (N'Left', N'POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))') GO INSERT [countries] ([name], [shape]) VALUES (N'Right', N'POLYGON ((70 10, 80 40, 60 40, 50 20, 70 10))') GO INSERT [events] ([name], [datetime], [visitors]) VALUES (N'Launch', N'2016-01-01 13:01:01', 0) GO INSERT [products] ([name], [price], [properties], [created_at]) VALUES (N'Calculator', N'23.01', N'<root type="object"><depth type="boolean">false</depth><model type="string">TRX-120</model><width type="number">100</width><height type="null" /></root>', '1970-01-01 01:01:01') GO INSERT [barcodes] ([product_id], [hex], [bin]) VALUES (1, N'00ff01', 0x00ff01) GO INSERT [kunsthåndværk] ([id], [Umlauts ä_ö_ü-COUNT], [user_id], [invisible]) VALUES ('e42c77c6-06a4-4502-816c-d112c7142e6d', 1, 1, NULL) GO INSERT [kunsthåndværk] ([id], [Umlauts ä_ö_ü-COUNT], [user_id], [invisible]) VALUES ('e31ecfe6-591f-4660-9fbd-1a232083037f', 2, 2, NULL) GO INSERT [invisibles] ([id]) VALUES ('e42c77c6-06a4-4502-816c-d112c7142e6d') GO INSERT [nopk] ([id]) VALUES ('e42c77c6-06a4-4502-816c-d112c7142e6d') GO ALTER TABLE [comments] WITH CHECK ADD CONSTRAINT [FK_comments_posts] FOREIGN KEY([post_id]) REFERENCES [posts] ([id]) GO ALTER TABLE [comments] CHECK CONSTRAINT [FK_comments_posts] GO ALTER TABLE [post_tags] WITH CHECK ADD CONSTRAINT [FK_post_tags_posts] FOREIGN KEY([post_id]) REFERENCES [posts] ([id]) GO ALTER TABLE [post_tags] CHECK CONSTRAINT [FK_post_tags_posts] GO ALTER TABLE [post_tags] WITH CHECK ADD CONSTRAINT [FK_post_tags_tags] FOREIGN KEY([tag_id]) REFERENCES [tags] ([id]) GO ALTER TABLE [post_tags] CHECK CONSTRAINT [FK_post_tags_tags] GO ALTER TABLE [posts] WITH CHECK ADD CONSTRAINT [FK_posts_categories] FOREIGN KEY([category_id]) REFERENCES [categories] ([id]) GO ALTER TABLE [posts] CHECK CONSTRAINT [FK_posts_categories] GO ALTER TABLE [posts] WITH CHECK ADD CONSTRAINT [FK_posts_users] FOREIGN KEY([user_id]) REFERENCES [users] ([id]) GO ALTER TABLE [posts] CHECK CONSTRAINT [FK_posts_users] GO ALTER TABLE [barcodes] WITH CHECK ADD CONSTRAINT [FK_barcodes_products] FOREIGN KEY([product_id]) REFERENCES [products] ([id]) GO ALTER TABLE [barcodes] CHECK CONSTRAINT [FK_barcodes_products] GO ALTER TABLE [kunsthåndværk] WITH CHECK ADD CONSTRAINT [UC_kunsthåndværk_Umlauts ä_ö_ü-COUNT] UNIQUE([Umlauts ä_ö_ü-COUNT]) GO ALTER TABLE [kunsthåndværk] WITH CHECK ADD CONSTRAINT [FK_kunsthåndværk_users] FOREIGN KEY([user_id]) REFERENCES [users] ([id]) GO ALTER TABLE [kunsthåndværk] CHECK CONSTRAINT [FK_kunsthåndværk_users] GO
mvdriel/php-crud-api
tests/fixtures/blog_sqlsrv.sql
SQL
mit
8,255
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Borders</title> <link rel="stylesheet" href="Styles2.css"> </head> <body> <p class="red"> <span>Red</span> Border</p> <p class="green"> <span>Green</span> Border</p> <p class="blue"> <span>Blue</span> Border</p> </body> </html>
D0NTLIKE/homeWorks
html & css 101/colorsAndBorders.html
HTML
mit
333
var element = require( './../lib' ); // Methods to create elements: var createHTMLElement = element.html, createSVGElement = element.svg, createCustomElement = element.custom, createTextNode = element.text; // Define some variables: var width = 600, height = 400, numData = 100, radius = 5, xPos, yPos; // Define our elements: var widget, figure, canvas, data, caption, text; // Create a custom figure widget: widget = createCustomElement( 'widget-figure' ); widget .attr( 'property', 'widget' ) .attr( 'class', 'widget' ); // Create a new figure element: figure = createHTMLElement( 'figure' ); // Configure the figure: figure .attr( 'property', 'figure' ) .attr( 'class', 'figure' ); // Create a new SVG canvas element and configure: canvas = createSVGElement( 'svg' ); canvas .attr( 'xmlns', 'http://www.w3.org/2000/svg' ) .attr( 'xmlns:xlink', 'http://www.w3.org/1999/xlink' ) .attr( 'xmlns:ev', 'http://www.w3.org/2001/xml-events' ) .attr( 'property', 'canvas' ) .attr( 'class', 'canvas' ) .attr( 'width', width ) .attr( 'height', height ) .attr( 'viewBox', '0 0 ' + width + ' ' + height ) .attr( 'preserveAspectRatio', 'xMidYMid' ) .attr( 'data-aspect', width/height ); // Append the figure to the widget: widget.append( figure ); // Append the canvas to the figure: figure.append( canvas ); // Create data elements and append to the canvas... data = new Array( numData ); for ( var i = 0; i < numData; i++ ) { xPos = Math.round( Math.random()*width ); yPos = Math.round( Math.random()*height ); data[ i ] = createSVGElement( 'circle' ); data[ i ] .attr( 'cx', xPos ) .attr( 'cy', yPos ) .attr( 'r', radius ); canvas.append( data[ i ] ); } // Create a caption element: caption = createHTMLElement( 'figcaption' ); caption .attr( 'property', 'caption' ) .attr( 'class', 'caption' ); // Create a text node to insert text into the caption element: text = createTextNode(); text.content( 'Random particles on a canvas.' ); // Append the text to the caption element: caption.append( text ); // Append the caption to the figure: figure.append( caption ); // Serialize the figure: console.log( widget.toString() );
element-io/minimal-element
examples/index.js
JavaScript
mit
2,176
/* Summary panel */ .summary { } .summary-label { color: #7F7F7F; } .summary-detail { color: #0B0C0C; font-size: 24px; font-weight: 700; margin-top: 10px; } .summary-group { margin-top: 5px; display:inline-block; margin-right: 90px; margin-bottom: 10px; } /*Table*/ .dropdown-container { border-top: 1px solid #ccc; /* border-bottom: 1px solid #ccc;*/ padding: 17px 0px 9px 17px; } .dropdown-container { position: relative; } .form-group.continue-validation { margin-bottom: 0 !important; padding-bottom: 0 !important; } .subsection_content { } .list-summary-item { padding: 14px 0px 10px 0; } .list-summary-item:first-child { border-top: 0px; } .list-summary-item:last-child { border-bottom: 0px; } .list-summary-item span:first-child { width: 40%; margin-left: 27px; margin-right: 25px; } .sub-cost { position: absolute; text-align: right; } .section { color:#231F20; width:100%; } .section-not-active { margin-top:0px; margin-left:23px; } .section-name { width:40%; margin-right: 25px; display:inline-block; } .section-status-complete { position: absolute; color:#28A197; text-transform: uppercase; } .section-status-not-started { position: absolute; color: #6F777B; text-transform: uppercase; font-size: 700 ; } .section-link-container { right: 0px; position:absolute; z-index: 9999; } .section-link { font-size: 700 ; text-align: right; } .section-question { display:inline-block; } .section-answer { font-weight:700; } .hide-border { border-style:none; } .inactive-row { padding: 0px 0px 5px 25px; }
dudelmeister/rave
app/assets/stylesheets/registration-overview.css
CSS
mit
1,692
<?php declare(strict_types=1); namespace Lookyman\NetteOAuth2Server\Tests\User; use Lookyman\NetteOAuth2Server\RedirectConfig; use Lookyman\NetteOAuth2Server\UI\OAuth2Presenter; use Lookyman\NetteOAuth2Server\User\LoginSubscriber; use Nette\Application\Application; use Nette\Application\UI\Presenter; use Nette\Security\User; use PHPUnit\Framework\TestCase; class LoginSubscriberTest extends TestCase { public function testGetSubscribedEvents(): void { $subscriber = new LoginSubscriber( $this->createMock(RedirectConfig::class), 10 ); self::assertEquals([ Application::class . '::onPresenter', User::class . '::onLoggedIn' => [ ['onLoggedIn', 10], ], ], $subscriber->getSubscribedEvents()); } public function testOnLoggedIn(): void { $redirectConfig = $this->createMock(RedirectConfig::class); $redirectConfig->expects(self::once())->method('getApproveDestination')->willReturn(['destination']); $presenter = $this->createMock(Presenter::class); $presenter->expects(self::once())->method('getSession')->with(OAuth2Presenter::SESSION_NAMESPACE)->willReturn((object) ['authorizationRequest' => true]); $presenter->expects(self::once())->method('redirect')->with('destination'); $user = $this->createMock(User::class); $subscriber = new LoginSubscriber($redirectConfig); $subscriber->onPresenter($this->createMock(Application::class), $presenter); $subscriber->onLoggedIn($user); } /** * @expectedException \Nette\InvalidStateException */ public function testOnLoggedInNoPresenter(): void { $redirectConfig = $this->createMock(RedirectConfig::class); $user = $this->createMock(User::class); $subscriber = new LoginSubscriber($redirectConfig); $subscriber->onLoggedIn($user); } }
lookyman/nette-oauth2-server
tests/User/LoginSubscriberTest.php
PHP
mit
1,757
package com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly; import com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.ErrorInfo.CustomMessageGeneratorErrorDescription; import com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.ErrorInfo.PlainTextErrorDescription; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; /** * Autogenerated by XGen4J on January 1, 0001. */ public class Information { private static List<ErrorInfo> errorInfoList; private static Map<String, ErrorInfo> idToErrorInfoMap; private static final AtomicBoolean loaded = new AtomicBoolean(); private static void load() { if (loaded.compareAndSet(false, true)) { errorInfoList = new ArrayList<>(); idToErrorInfoMap = new HashMap<>(); errorInfoList.add(new ErrorInfo( com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.RootError.class, new ExceptionInfo(com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.RootException.class), com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.RootError.CODE, false )); errorInfoList.add(new ErrorInfo( com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_c1.C1Error.class, new ExceptionInfo(com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_c1.C1Exception.class), com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_c1.C1Error.CODE, true )); errorInfoList.add(new ErrorInfo( com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_c1.code_name_root.C2Error.class, new ExceptionInfo(com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_c1.code_name_root.C2Exception.class), com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_c1.code_name_root.C2Error.CODE, true )); errorInfoList.add(new ErrorInfo( com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_c1.code_name_root.code_name_root.C3Error.class, new ExceptionInfo(com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_c1.code_name_root.code_name_root.C3Exception.class), com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_c1.code_name_root.code_name_root.C3Error.CODE, true )); errorInfoList.add(new ErrorInfo( com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_e1.E1Error.class, new ExceptionInfo(com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_e1.E1Exception.TYPE, com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_e1.E1Exception.class), com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_e1.E1Error.CODE, false )); errorInfoList.add(new ErrorInfo( com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_e1.code_name_root.E2Error.class, new ExceptionInfo(com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_e1.code_name_root.E2Exception.TYPE, com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_e1.code_name_root.E2Exception.class), com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_e1.code_name_root.E2Error.CODE, false )); errorInfoList.add(new ErrorInfo( com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_e1.code_name_root.code_name_root.E3Error.class, new ExceptionInfo(com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_e1.code_name_root.code_name_root.E3Exception.TYPE, com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_e1.code_name_root.code_name_root.E3Exception.class), com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_e1.code_name_root.code_name_root.E3Error.CODE, false )); errorInfoList.add(new ErrorInfo( com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_eb1.EB1Error.class, new ExceptionInfo(com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_eb1.EB1Exception.TYPE, com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_eb1.EB1Exception.class), com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_eb1.EB1Error.CODE, false )); errorInfoList.add(new ErrorInfo( com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_eb1.code_name_root.EB2Error.class, new ExceptionInfo(com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_eb1.code_name_root.EB2Exception.TYPE, com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_eb1.code_name_root.EB2Exception.class), com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_eb1.code_name_root.EB2Error.CODE, false )); errorInfoList.add(new ErrorInfo( com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_eb1.code_name_root.code_name_root.EB3Error.class, new ExceptionInfo(com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_eb1.code_name_root.code_name_root.EB3Exception.TYPE, com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_eb1.code_name_root.code_name_root.EB3Exception.class), com.rodrigodev.xgen4j.test.code.codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly.code_name_eb1.code_name_root.code_name_root.EB3Error.CODE, false )); errorInfoList = Collections.unmodifiableList(errorInfoList); for (ErrorInfo errorInfo : errorInfoList) { idToErrorInfoMap.put(errorInfo.code().id(), errorInfo); } loaded.set(true); } } public static List<ErrorInfo> list() { load(); return errorInfoList; } public static ErrorInfo forId(String id) { if (id == null) throw new IllegalArgumentException("id"); load(); return idToErrorInfoMap.get(id); } }
RodrigoQuesadaDev/XGen4J
xgen4j/src/test-gen/java/com/rodrigodev/xgen4j/test/code/codeNameCanBeEqualToRootCodeNameForErrorsThatAreNotChildrenOfRootError_nameOnly/Information.java
Java
mit
8,732
/** @toc 2. load grunt plugins 3. init 4. setup variables 5. grunt.initConfig 6. register grunt tasks */ 'use strict'; module.exports = function(grunt) { /** Load grunt plugins @toc 2. */ grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-karma'); /** Function that wraps everything to allow dynamically setting/changing grunt options and config later by grunt task. This init function is called once immediately (for using the default grunt options, config, and setup) and then may be called again AFTER updating grunt (command line) options. @toc 3. @method init */ function init(params) { /** Project configuration. @toc 5. */ grunt.initConfig({ jshint: { options: { //force: true, globalstrict: true, //sub: true, node: true, loopfunc: true, browser: true, devel: true, globals: { angular: false, $: false, moment: false, Pikaday: false, module: false, forge: false } }, beforeconcat: { options: { force: false, ignores: ['**.min.js'] }, files: { src: [] } }, //quick version - will not fail entire grunt process if there are lint errors beforeconcatQ: { options: { force: true, ignores: ['**.min.js'] }, files: { src: ['**.js'] } } }, uglify: { build: { files: {}, src: 'src/focus-on.js', dest: 'dist/focus-on.min.js' } }/*, karma: { unit: { configFile: publicPathRelativeRoot+'config/karma.conf.js', singleRun: true, browsers: ['PhantomJS'] } }*/ }); /** register/define grunt tasks @toc 6. */ // Default task(s). // grunt.registerTask('default', ['jshint:beforeconcat', 'concat:devJs']); grunt.registerTask('default', ['jshint:beforeconcatQ', 'uglify:build']); } init({}); //initialize here for defaults (init may be called again later within a task) };
kfuchs/angular-focus-on
Gruntfile.js
JavaScript
mit
2,234
// Copyright (C) 2011-2019 Roki. Distributed under the MIT License #ifndef INCLUDED_SROOK_TMPL_VT_SWAP_AT_HPP #define INCLUDED_SROOK_TMPL_VT_SWAP_AT_HPP #include <srook/tmpl/vt/detail/config.hpp> SROOK_NESTED_NAMESPACE(srook, tmpl, vt) { SROOK_INLINE_NAMESPACE(v1) template <class, class, std::size_t> struct swap_at_left; template <class, class, std::size_t> struct swap_at_right; template <class... L, class... R, std::size_t target> struct swap_at_left<packer<L...>, packer<R...>, target> : public type_constant<SROOK_DEDUCED_TYPENAME detail::SwapAt_L_type<pack<L...>, pack<R...>, target>::type::rebind_packer> {}; template <class... L, class... R, std::size_t target> struct swap_at_right<packer<L...>, packer<R...>, target> : public type_constant<SROOK_DEDUCED_TYPENAME detail::SwapAt_R_type<pack<L...>, pack<R...>, target>::type::rebind_packer> {}; #if SROOK_CPP_ALIAS_TEMPLATES template <class L, class R, std::size_t target> using swap_at_left_t = SROOK_DEDUCED_TYPENAME swap_at_left<L, R, target>::type; template <class L, class R, std::size_t target> using swap_at_right_t = SROOK_DEDUCED_TYPENAME swap_at_right<L, R, target>::type; #endif SROOK_INLINE_NAMESPACE_END } SROOK_NESTED_NAMESPACE_END(vt, tmpl, srook) #endif
falgon/SrookCppLibraries
srook/tmpl/vt/swap_at.hpp
C++
mit
1,249
import {ElementRef, Input, OnDestroy, OnInit, Component} from '@angular/core'; import {AbstractControl, FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms'; import {Subject} from 'rxjs'; import {takeUntil} from 'rxjs/operators'; import {NgbAccordion, NgbActiveModal, NgbTooltipConfig} from '@ng-bootstrap/ng-bootstrap'; import {TranslateService} from '@ngx-translate/core'; import {SystemNameService} from './services/system-name.service'; import {DataService} from './services/data-service.abstract'; import {FileModel} from './models/file.model'; import {FormFieldInterface, FormFieldOptionsInterface} from './models/form-field.interface'; /** * @deprecated since version 4.1.1. Use AppModalContentAbstractComponent instead. */ @Component({ template: '' }) export abstract class ModalContentAbstractComponent<M> implements OnInit, OnDestroy { @Input() modalTitle: string; @Input() itemId: number | null; @Input() modalId = ''; @Input() isItemCopy: boolean; @Input() isEditMode: boolean; submitted = false; loading = false; errorMessage: string; form: FormGroup; formErrors: {[key: string]: string} = {}; validationMessages: {[key: string]: { [key: string]: string }} = {}; formFields: FormFieldInterface = {}; model: any; files: {[key: string]: File} = {}; isSaveButtonDisabled = false; localeList: string[]; localeDefault = ''; localeCurrent = ''; localeFieldsAllowed: string[] = []; localePreviousValues: {[fieldName: string]: string} = {}; closeReason = 'canceled'; uniqueId = ''; destroyed$ = new Subject<void>(); constructor( public fb: FormBuilder, public dataService: DataService<any>, public systemNameService: SystemNameService, public activeModal: NgbActiveModal, public tooltipConfig: NgbTooltipConfig, public translateService: TranslateService, public elRef: ElementRef ) { tooltipConfig.placement = 'bottom'; tooltipConfig.container = 'body'; tooltipConfig.triggers = 'hover click'; } ngOnInit(): void { this.uniqueId = this.createUniqueId(); if (this.elRef) { this.getRootElement().setAttribute('id', this.modalId); } this.onBeforeInit(); this.buildForm(); if (this.isEditMode || this.isItemCopy) { this.getModelData().then(() => { this.onAfterGetData(); }); } else { this.onAfterGetData(); } this.onAfterInit(); } onBeforeInit(): void {} onAfterInit(): void {} onAfterGetData(): void {} getSystemFieldName(): string { return 'name'; } getLangString(value: string): string { const translations = this.translateService.store.translations[this.translateService.currentLang]; return translations[value] || value; } getModelData(): Promise<M> { this.loading = true; return new Promise((resolve, reject) => { this.dataService.getItem(this.itemId) .pipe(takeUntil(this.destroyed$)) .subscribe({ next: (data) => { if (this.isItemCopy) { data.id = null; data[this.getSystemFieldName()] = ''; } this.model = data as M; this.loading = false; resolve(data as M); }, error: (err) => { this.errorMessage = err.error || this.getLangString('ERROR'); this.loading = false; reject(err); } }); }); } /** Build form groups */ buildForm(): void { const controls = this.buildControls(this.formFields); this.form = this.fb.group(controls); this.form.valueChanges .pipe(takeUntil(this.destroyed$)) .subscribe({ next: (value: any) => this.onValueChanged('form', '', value) }); } /** Build controls */ buildControls(options: {}, modelName = 'model', keyPrefix = ''): { [s: string]: FormControl; } { const controls = {}; for (const key in options) { if (!options.hasOwnProperty(key)) { continue; } const opts = options[key] as FormFieldOptionsInterface; const object = opts['dataKey'] ? this[modelName][opts['dataKey']] : this[modelName]; if (!object[key]) { object[key] = opts.value; } controls[key] = new FormControl({ value: object[key] || '', disabled: opts.disabled || false }, opts.validators); this.formErrors[keyPrefix + key] = ''; this.translateValidationMessages(keyPrefix, key, opts); } return controls; } translateValidationMessages(keyPrefix: string, fieldKey: string, fieldOptions: FormFieldOptionsInterface): void { const messages: {[key: string]: string } = {}; if (!fieldOptions.fieldLabel) { return; } Object.keys(fieldOptions.messages).forEach((messageKey) => { if (messageKey === 'required') { return; } this.translateService.get(String(fieldOptions.messages[messageKey])) .subscribe((res: string) => { messages[messageKey] = res; }); }); if (fieldOptions.validators.indexOf(Validators.required) > -1) { this.translateService.get(fieldOptions.fieldLabel) .subscribe((fieldLabel: string) => { this.translateService.get('FIELD_REQUIRED', {name: fieldLabel}) .subscribe((res: string) => { messages.required = res; }); }); } this.validationMessages[keyPrefix + fieldKey] = messages; } getControl(name: string): AbstractControl { return this.form.controls['name']; } /** Callback on form value changed */ onValueChanged(formName?: string, keyPrefix: string = '', value?: any): void { if (!this[formName]) { return; } const data = this[formName].value; for (const fieldName in data) { if (!data.hasOwnProperty(fieldName)) { continue; } this.formErrors[keyPrefix + fieldName] = ''; const control = this[formName].get(fieldName); if (control && (control.dirty || this[keyPrefix + 'submitted']) && !control.valid) { for (const key in control.errors) { if (this.validationMessages[keyPrefix + fieldName][key]) { this.formErrors[keyPrefix + fieldName] += this.validationMessages[keyPrefix + fieldName][key] + ' '; } else { this.formErrors[keyPrefix + fieldName] += this.getLangString('ERROR') + ' '; } } } } } /** Element display toggle */ displayToggle(element: HTMLElement, display?: boolean): void { display = display || element.style.display === 'none'; element.style.display = display ? 'block' : 'none'; } toggleAccordion(accordion: NgbAccordion, panelId: string, display?: boolean): void { const isOpened = accordion.activeIds.indexOf(panelId) > -1; if (isOpened && display) { return; } accordion.toggle(panelId); } generateName(model): void { const title = model.title || ''; model.name = this.systemNameService.generateName(title); } /** Close modal */ closeModal(event?: MouseEvent) { if (event) { event.preventDefault(); } const reason = this.itemId ? 'edit' : 'create'; this.activeModal.close({reason: reason, data: this.model}); } close(event?: MouseEvent) { if (event) { event.preventDefault(); } this.activeModal.dismiss(this.closeReason); } minimize(event?: MouseEvent): void { if (event) { event.preventDefault(); } window.document.body.classList.remove('modal-open'); const modalEl = this.getRootElement(); const backdropEl = modalEl.previousElementSibling; modalEl.classList.remove('d-block'); modalEl.classList.add('modal-minimized'); backdropEl.classList.add('d-none'); } maximize(event?: MouseEvent): void { if (event) { event.preventDefault(); } window.document.body.classList.add('modal-open'); const modalEl = this.getRootElement(); const backdropEl = modalEl.previousElementSibling; modalEl.classList.add('d-block'); modalEl.classList.remove('modal-minimized'); backdropEl.classList.remove('d-none'); } getFormData(): any { const data = {}; Object.keys(this.model).forEach((key) => { if (this.files[key]) { data[key] = Array.isArray(this.model[key]) ? [ FileModel.getFileData(this.files[key]) ] : FileModel.getFileData(this.files[key]); } else { data[key] = this.model[key]; } }); return data; } fileChange(event, fieldName: string, isArray = false) { const fileList: FileList = event.target.files; if (fileList.length > 0) { this.model[fieldName] = isArray ? [ FileModel.getFileData(fileList[0]) ] : FileModel.getFileData(fileList[0]); this.files[fieldName] = fileList[0]; this.form.controls[fieldName].setValue(this.files[fieldName].name); } } fileClear(fieldName: string, inputElement: HTMLInputElement) { this.model[fieldName] = null; this.form.controls[fieldName].reset(null); inputElement.files = null; inputElement.value = ''; delete this.files[fieldName]; } onLocaleSwitch(): void { if (this.localeCurrent === this.localeDefault) { this.localeFieldsAllowed.forEach((fieldName) => { this.model[fieldName] = this.localePreviousValues[fieldName]; }); this.isSaveButtonDisabled = false; return; } if (!this.model.translations) { this.model.translations = {}; } this.isSaveButtonDisabled = true; this.localeFieldsAllowed.forEach((fieldName) => { this.localePreviousValues[fieldName] = this.model[fieldName] || ''; if (this.model.translations[fieldName]) { this.model[fieldName] = this.model.translations[fieldName][this.localeCurrent] || ''; } else { this.model[fieldName] = ''; } }); } saveTranslations(event?: MouseEvent): void { if (event) { event.preventDefault(); } this.localeFieldsAllowed.forEach((fieldName) => { if (this.model[fieldName]) { if (!this.model.translations[fieldName]) { this.model.translations[fieldName] = {}; } this.model.translations[fieldName][this.localeCurrent] = this.model[fieldName]; } else { if (this.model.translations[fieldName]) { if (this.model.translations[fieldName][this.localeCurrent]) { delete this.model.translations[fieldName][this.localeCurrent]; } if (Object.keys(this.model.translations[fieldName]).length === 0) { delete this.model.translations[fieldName]; } } } }); this.localeCurrent = this.localeDefault; this.onLocaleSwitch(); } saveRequest() { if (this.isEditMode) { return this.dataService.update(this.getFormData()); } else { return this.dataService.create(this.getFormData()); } } /** Submit form */ onSubmit() { this.submitted = true; this.closeModal(); } appendFormData(formData: FormData): void { } saveFiles(itemId: number) { if (Object.keys(this.files).length === 0) { this.closeModal(); return; } const formData: FormData = new FormData(); for (const key in this.files) { if (this.files.hasOwnProperty(key) && this.files[key] instanceof File) { formData.append(key, this.files[key], this.files[key].name); } } formData.append('itemId', String(itemId)); this.appendFormData(formData); this.dataService.postFormData(formData) .pipe(takeUntil(this.destroyed$)) .subscribe({ next: () => { this.closeModal(); }, error: (err) => { this.errorMessage = err.error || this.getLangString('ERROR'); this.submitted = false; this.loading = false } }); } save(autoClose = false, event?: MouseEvent): void { if (event) { event.preventDefault(); } this.submitted = true; this.errorMessage = ''; if (!this.form.valid) { this.onValueChanged('form'); this.submitted = false; return; } this.loading = true; this.saveRequest() .pipe(takeUntil(this.destroyed$)) .subscribe({ next: (res) => { if (Object.keys(this.files).length > 0) { this.saveFiles(res._id || res.id); } else { if (autoClose) { this.closeModal(); } else if (res && res['id']) { this.model = res as M; this.onAfterGetData(); this.isEditMode = true; } this.closeReason = 'updated'; this.loading = false; this.submitted = false; } }, error: (err) => { this.errorMessage = err.error || this.getLangString('ERROR'); this.loading = false; this.submitted = false; } }); } emailValidator(control: FormControl): { [s: string]: boolean } { const EMAIL_REGEXP = /\S+@\S+\.\S+/; if (!control.value) { return {required: true}; } else if (!EMAIL_REGEXP.test(control.value)) { return {email: true}; } } getRootElement(): HTMLElement { return this.elRef.nativeElement.parentNode.parentNode.parentNode; } createUniqueId(): string { return Math.random().toString(36).substr(2, 9); } ngOnDestroy(): void { this.destroyed$.next(); this.destroyed$.complete(); } }
andchir/shopkeeper4
frontend/src/app/modal.abstract.ts
TypeScript
mit
15,571
<?php namespace app\framework\Component\Image\Bridge\Filter\Basic; use app\framework\Component\Image\Bridge\Filter\FilterInterface; use app\framework\Component\Image\Bridge\Image\BoxInterface; use app\framework\Component\Image\Bridge\Image\ImageInterface; class CropBalanced implements FilterInterface { /** * @var BoxInterface */ private $size; /** * Constructs a CropBalanced filter * * @param BoxInterface $size */ public function __construct(BoxInterface $size) { $this->size = $size; } /** * {@inheritdoc} */ public function apply(ImageInterface $image) { return $image->resizeAndCropBalanced($this->size); } }
MrFibunacci/Framy
app/framework/Component/Image/Bridge/Imagine/Filter/Basic/CropBalanced.php
PHP
mit
719
import { allUnits } from './constants' import * as utils from './utils' import slug from '../../utils/slug' export default { allUnits () { return allUnits }, unitsByType () { let byType = {} allUnits.forEach(unit => { if (!byType[unit.type]) byType[unit.type] = [] byType[unit.type].push(unit) }) let types = [ { key: 'spectrum', label: 'Spectrum' }, { key: 'quantity', label: 'Quantity' } ] return types.map(type => { return { label: type.label, items: byType[type.key] } }) }, isSelectionAnchor (state): boolean { return state.currentSelection && state.currentSelection.length >= 10 }, currentAnchor (state, getters) { if (getters.isSelectionAnchor) { return slug(state.currentSelection).value } else if (state.currentVideoTime) { let minutes = Math.floor(this.currentVideoTime / 60) let seconds = Math.floor(this.currentVideoTime - minutes * 60) return `${('00' + minutes).slice(-2)}:${('00' + seconds).slice(-2)}` } return null }, currentPageDefinition (state): NodeDefinition { return { title: state.currentPage, anchor: null, unit: 'Unreliable-Reliable', comments: [] } }, currentNode (state): NodeWithData { let stateNode = state.nodes.find(n => utils.compareDefinition(n.definition, state.definition, ['comments'])) let data = null if (stateNode && stateNode.data) { let mapReferences = (references) => { return references.map(({ definition, referenceResults}) => { let stateNode = state.nodes.find(n => utils.compareDefinition(n.definition, definition)) if (!stateNode) return null return { ...stateNode, referenceResults, } }).filter(x => x) } data = { results: stateNode.data.results, references: mapReferences(stateNode.data.references), inverseReferences: mapReferences(stateNode.data.inverseReferences), comments: stateNode.data.comments } } return { definition: { ...state.definition, isSpectrum: state.definition.unit.indexOf('-') >= 0, }, data: data } }, activeNode (state): NodeWithData { if (!state.activeDefinition) return null let stateNode = state.nodes.find(n => utils.compareDefinition(n.definition, state.activeDefinition)) return { definition: state.activeDefinition, data: stateNode ? stateNode.data : null } }, availableHistory (state): object { return { back: state.historyIndex > 0, forward: state.historyIndex < state.history.length - 1, } }, recentDefinitions (state) { let uniqueDefinitions = [] for (let i = state.history.length - 1; i >= 0; i--) { let definition = state.history[i] if (!(state.definition && utils.compareDefinition(state.definition, definition)) && !uniqueDefinitions.find(d => utils.compareDefinition(d, definition))) { uniqueDefinitions.push(definition) } } return uniqueDefinitions }, }
zan-kusterle/Liquio
assets/src/store/annotate/getters.ts
TypeScript
mit
2,929
package com.birdcopy.BirdCopyApp.IM.photo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.support.v4.util.LruCache; import android.util.DisplayMetrics; import android.util.Log; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import java.lang.reflect.Field; import java.util.LinkedList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; public class ImageLoader { /** * 图片缓存的核心类 */ private LruCache<String, Bitmap> mLruCache; /** * 线程池 */ private ExecutorService mThreadPool; /** * 线程池的线程数量,默认为1 */ private int mThreadCount = 1; /** * 队列的调度方式 */ private Type mType = Type.LIFO; /** * 任务队列 */ private LinkedList<Runnable> mTasks; /** * 轮询的线程 */ private Thread mPoolThread; private Handler mPoolThreadHander; /** * 运行在UI线程的handler,用于给ImageView设置图片 */ private Handler mHandler; /** * 引入一个值为1的信号量,防止mPoolThreadHander未初始化完成 */ private volatile Semaphore mSemaphore = new Semaphore(0); /** * 引入一个值为1的信号量,由于线程池内部也有一个阻塞线程,防止加入任务的速度过快,使LIFO效果不明显 */ private volatile Semaphore mPoolSemaphore; private static ImageLoader mInstance; /** * 队列的调度方式 * * @author zhy * */ public enum Type { FIFO, LIFO } /** * 单例获得该实例对象 * * @return */ public static ImageLoader getInstance() { if (mInstance == null) { synchronized (ImageLoader.class) { if (mInstance == null) { mInstance = new ImageLoader(10, Type.LIFO); } } } return mInstance; } private ImageLoader(int threadCount, Type type) { init(threadCount, type); } private void init(int threadCount, Type type) { // loop thread mPoolThread = new Thread() { @Override public void run() { Looper.prepare(); mPoolThreadHander = new Handler() { @Override public void handleMessage(Message msg) { mThreadPool.execute(getTask()); try { mPoolSemaphore.acquire(); } catch (InterruptedException e) { } } }; // 释放一个信号量 mSemaphore.release(); Looper.loop(); } }; mPoolThread.start(); // 获取应用程序最大可用内存 int maxMemory = (int) Runtime.getRuntime().maxMemory(); // LogUtil.d("maxMemory ==== " + maxMemory); // 内存缓存池为最大内存的1/30 int cacheSize = maxMemory / 30; mLruCache = new LruCache<String, Bitmap>(cacheSize) { /*获取每个 value 的大小*/ @Override protected int sizeOf(String key, Bitmap value) { return value.getRowBytes() * value.getHeight() / 1024; }; /*当缓存大于我们设定的最大值时,会调用这个方法,我们可以用来做内存释放操作*/ @Override protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) { super.entryRemoved(evicted, key, oldValue, newValue); if (evicted && oldValue != null){ oldValue.recycle(); } } }; mThreadPool = Executors.newFixedThreadPool(threadCount); mPoolSemaphore = new Semaphore(threadCount); mTasks = new LinkedList<Runnable>(); mType = type == null ? Type.LIFO : type; } /** * 加载图片 * * @param path * @param imageView */ public void loadImage(final String path, final ImageView imageView) { // set tag imageView.setTag(path); // UI线程 if (mHandler == null) { mHandler = new Handler() { @Override public void handleMessage(Message msg) { ImgBeanHolder holder = (ImgBeanHolder) msg.obj; ImageView imageView = holder.imageView; Bitmap bm = holder.bitmap; String path = holder.path; if (imageView.getTag().toString().equals(path)) { imageView.setImageBitmap(bm); } } }; } Bitmap bm = getBitmapFromLruCache(path); if (bm != null) { ImgBeanHolder holder = new ImgBeanHolder(); holder.bitmap = bm; holder.imageView = imageView; holder.path = path; Message message = Message.obtain(); message.obj = holder; mHandler.sendMessage(message); } else { addTask(new Runnable() { @Override public void run() { ImageSize imageSize = getImageViewWidth(imageView); int reqWidth = imageSize.width; int reqHeight = imageSize.height; Bitmap bm = decodeSampledBitmapFromResource(path, reqWidth, reqHeight); if (bm==null) { mPoolSemaphore.release(); return; } addBitmapToLruCache(path, bm); ImgBeanHolder holder = new ImgBeanHolder(); holder.bitmap = getBitmapFromLruCache(path); holder.imageView = imageView; holder.path = path; Message message = Message.obtain(); message.obj = holder; Log.e("TAG", "mHandler.sendMessage(message);"); mHandler.sendMessage(message); mPoolSemaphore.release(); } }); } } /** * 添加一个任务 * * @param runnable */ private synchronized void addTask(Runnable runnable) { try { // 请求信号量,防止mPoolThreadHander为null if (mPoolThreadHander == null) mSemaphore.acquire(); } catch (InterruptedException e) { } mTasks.add(runnable); mPoolThreadHander.sendEmptyMessage(0x110); } /** * 取出一个任务 * * @return */ private synchronized Runnable getTask() { if (mType == Type.FIFO) { return mTasks.removeFirst(); } else if (mType == Type.LIFO) { return mTasks.removeLast(); } return null; } /** * 单例获得该实例对象 * * @return */ public static ImageLoader getInstance(int threadCount, Type type) { if (mInstance == null) { synchronized (ImageLoader.class) { if (mInstance == null) { mInstance = new ImageLoader(threadCount, type); } } } return mInstance; } /** * 根据ImageView获得适当的压缩的宽和高 * * @param imageView * @return */ private ImageSize getImageViewWidth(ImageView imageView) { ImageSize imageSize = new ImageSize(); final DisplayMetrics displayMetrics = imageView.getContext() .getResources().getDisplayMetrics(); final LayoutParams params = imageView.getLayoutParams(); int width = params.width == LayoutParams.WRAP_CONTENT ? 0 : imageView .getWidth(); // Get actual image width if (width <= 0) width = params.width; // Get layout width parameter if (width <= 0) width = getImageViewFieldValue(imageView, "mMaxWidth"); // Check // maxWidth // parameter if (width <= 0) width = displayMetrics.widthPixels; int height = params.height == LayoutParams.WRAP_CONTENT ? 0 : imageView .getHeight(); // Get actual image height if (height <= 0) height = params.height; // Get layout height parameter if (height <= 0) height = getImageViewFieldValue(imageView, "mMaxHeight"); // Check // maxHeight // parameter if (height <= 0) height = displayMetrics.heightPixels; imageSize.width = width; imageSize.height = height; return imageSize; } /** * 从LruCache中获取一张图片,如果不存在就返回null。 */ private Bitmap getBitmapFromLruCache(String key) { return mLruCache.get(key); } /** * 往LruCache中添加一张图片 * * @param key * @param bitmap */ private void addBitmapToLruCache(String key, Bitmap bitmap) { if (getBitmapFromLruCache(key) == null) { if (bitmap != null) mLruCache.put(key, bitmap); } } /** * 计算inSampleSize,用于压缩图片 * * @param options * @param reqWidth * @param reqHeight * @return */ private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // 源图片的宽度 int width = options.outWidth; int height = options.outHeight; int inSampleSize = 1; if (width > reqWidth && height > reqHeight) { // 计算出实际宽度和目标宽度的比率 int widthRatio = Math.round((float) width / (float) reqWidth); int heightRatio = Math.round((float) width / (float) reqWidth); inSampleSize = Math.max(widthRatio, heightRatio); } return inSampleSize; } /** * 根据计算的inSampleSize,得到压缩后图片 * * @param pathName * @param reqWidth * @param reqHeight * @return */ private Bitmap decodeSampledBitmapFromResource(String pathName, int reqWidth, int reqHeight) { // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小 final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(pathName, options); // 调用上面定义的方法计算inSampleSize值 options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // 使用获取到的inSampleSize值再次解析图片 options.inJustDecodeBounds = false; Bitmap bitmap = BitmapFactory.decodeFile(pathName, options); return bitmap; // return BitmapUtils.loadBitmap(0, pathName); } private class ImgBeanHolder { Bitmap bitmap; ImageView imageView; String path; } private class ImageSize { int width; int height; } /** * 反射获得ImageView设置的最大宽度和高度 * * @param object * @param fieldName * @return */ private static int getImageViewFieldValue(Object object, String fieldName) { int value = 0; try { Field field = ImageView.class.getDeclaredField(fieldName); field.setAccessible(true); int fieldValue = (Integer) field.get(object); if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE) { value = fieldValue; Log.e("TAG", value + ""); } } catch (Exception e) { } return value; } }
birdcopy/Android-Birdcopy-Application
app/src/main/java/com/birdcopy/BirdCopyApp/IM/photo/ImageLoader.java
Java
mit
10,594
define(["knockout", "lodash", "jquery", "toast"], function(ko, _, $, toast) { var BaseRuleset = function() { var self = this; }; _.extend(BaseRuleset.prototype, { initialize: function(char_hook, loading_callback) { var self = this; loading_callback(true); console.log('[base ruleset] about to load character data from', char_hook.filename()); $.getJSON(char_hook.filename(), function(data) { console.log("[base ruleset] loading complete"); loading_callback(false); self.load(data); $.toast({ text: 'Character ' + char_hook.name() + ' loaded.', heading: 'Loading successful', icon: 'success', hideAfter: 3000, position: 'bottom-center' }); }).fail(function(xhr, status, error) { console.log("[base ruleset] loading failed"); $.toast({ text: 'Message: ' + error, heading: 'Loading failed', icon: 'error', hideAfter: 3000, position: 'bottom-center' }); }); }, op_list: function() { var self = this; var _op_list = { 'INC': function(a, b) { return a+b; }, 'TAL': function(talent_name) { var tal = self.get_talent(talent_name); return tal.value(); }, 'RNK': function(artes_name) { var artes = self.get_artes(artes_name); return artes.rank(); }, 'MUL': function(a, b) { return Math.floor(a * b); }, 'IF': function(cond, if_val, then_val) { return cond ? if_val : then_val; }, 'MIN': function(value, min) { return (value > min); }, 'VAL': function(name) { return self[name](); }, 'TXT': function(text) { console.log(text); return text; } }; return _op_list; } }); return BaseRuleset; });
dzerrenner/orc
client/scripts/app/ruleset_base.js
JavaScript
mit
2,469
--- --- # Creating multiple plots on a single figure Through this brief introductory course, we have been plotting single plots. Multiple plots within the same figure are possible - have a look [here](http://matplotlib.org/users/pyplot_tutorial.html#working-with-multiple-figures-and-axes) for a detailed work through as how to get started on this - there is also some more information on how the mechanics of matplotlib actually work. To give an overview and try and iron out any confusion, let's run a quick example. As when making the [3D plots](../matplotlib_3d), first import ```matplotlib.pyplot``` using an alias of ```plt``` and create a figure object: ```python import matplotlib.pyplot as plt fig = plt.figure() ``` We are going to create 2 scatter plots on the same figure. To do this we want to make 2 axes subplot objects which we will call ```ax1``` and ```ax2```. To do this type: ```python ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) ``` This adds a subplot to the figure object and assigns it to a variable (```ax1``` or ```ax2```). The numbers - for example 121 - are a way of locating your subplot in the overall space of the figure object. The code 121 can be though of as *1 row, 2 columns, 1st position*. 122 would therefore be *1 row, 2 columns, 2nd position*. By defining separate axis objects, we can modify the diofferent plots specifically. We are going to plot two basic scatter plots - create some data using numpy (import it using an alias of np): ```python import numpy as np data_1=np.array(np.random.random((10,2)))*10 data_2=np.array(np.random.random((10,2))) ``` We now need to define out scatter plots specifically to the axis objects of ```ax1``` and ```ax2```, passing in the data from ```data_1``` and ```data_2``` - you can do this using: ```python ax1.scatter(data_1[:,0],data_1[:,1]) ax2.scatter(data_2[:,0],data_2[:,1]) ``` Note that we are calling the data using numpy's indexing (look at the [numpy](http://www.numpy.org/) indexing course notes [here](../../PythonPackages_numpy/numpy_indexing)). To modify the axis objects by adding labels, you can use the methods inherent of the axis objects e.g.: ```python ax1.set_title('data 1') ax1.set_xlabel('x') ax1.set_ylabel('y') ax2.set_title('data 2') ax2.set_xlabel('x') ax2.set_ylabel('y') ``` To view this, you can now just call: ```python plt.show() ``` and you should end up with this: !["A basic multiplot figure"]({{ site.baseurl }}../basic_multiplot.png) Have a play in the interactive plot window that opens up where you can move your data around - this also provides some options for savimng your figure. You can also save the figure (but this must be done before calling ```plt.plot()```) using the plt.savefig() function. # [Previous](../matplotlib_3d) [Home](../README_matplotlib) [Next](../matplotlib_what_next)
Chris35Wills/Chris35Wills.github.io
courses/PythonPackages_matplotlib/matplotlib_multiple_figs.md
Markdown
mit
2,851
// <copyright file="ConcurrentListTests.CountSane.g.cs" company="Microsoft">Copyright © Microsoft 2011</copyright> // <auto-generated> // This file contains automatically generated unit tests. // Do NOT modify this file manually. // // When Pex is invoked again, // it might remove or update any previously generated unit tests. // // If the contents of this file becomes outdated, e.g. if it does not // compile anymore, you may delete this file and invoke Pex again. // </auto-generated> using System; using NUnit.Framework; using Microsoft.Pex.Framework.Generated; namespace ConcurrentList.UnitTests { public partial class ConcurrentListHandWrittenTests { } }
damageboy/ConcurrentList
ConcurrentList.UnitTests/ConcurrentListTests.CountSane.g.cs
C#
mit
693
from utils.handle_transcript import TranscriptionParser, OmekaXML from models import * from database import init_db import sys, os DEFAULT = 'omeka.xml' if __name__ == "__main__": if len(sys.argv) > 1: filename = sys.argv[1] else: filename = DEFAULT if not os.path.exists(filename): print("Cannot find file '{0}'...?".format(filename)) sys.exit(2) print("Loading new jokes from '{0}'".format(filename)) dbsession = init_db() # get Admin user 'ben' u = User.query.filter(User.name == "ben").first() def create_or_get_bib_record(row): bib = Biblio.query.filter(Biblio.title == row['periodical_title']) \ .filter(Biblio.date == row['date']).first() if bib != None: return bib else: print("Found no matching Biblio record") try: year = int(row['year']) except ValueError as e: year = None b = Biblio(title=row['periodical_title'], date = row['date'], year = year, \ gale = row['gale'], periodical_freq = row['periodical_freq'], itemtype = 'periodical', \ citation = row['citation'], record_creator = u) dbsession.add(b) dbsession.commit() return b def create_or_get_Transcription(row): b = create_or_get_bib_record(row) transc = Transcription.query.filter(Transcription.biblio == b) \ .filter(Transcription.article_title == row['article_title']).first() if transc != None: print("Found existing Transcription record id {0} - reusing".format(transc.id)) return transc else: t = Transcription(by_user = u, parsed = 1, biblio = b, article_title = row['article_title'], \ pagestart = row['page'], raw = row['raw']) dbsession.add(t) dbsession.commit() return t with open(filename, "r") as inp: o = OmekaXML(inp.read()) o.parse() # get/create bib records for idx, item in o.metadata.iteritems(): t = create_or_get_Transcription(item) dbsession.close()
BL-Labs/jokedbapp
jokedbapp/load_omeka.py
Python
mit
2,082
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ (function (process,global,Buffer,__argument0,__argument1,__argument2,__argument3,__filename,__dirname){ var GpxFile = require('./lib/gpxfile'), GpxRoute = require('./lib/gpxroute'), GpxPoint = require('./lib/gpxpoint'), GpxTrack = require('./lib/gpxtrack'), GpxTrackSegment = require('./lib/gpxtracksegment'), GpxFileBuilder = require('./lib/gpxfilebuilder'); module.exports = { GpxFile : GpxFile, GpxRoute : GpxRoute, GpxPoint : GpxPoint, GpxTrack : GpxTrack, GpxTrackSegment : GpxTrackSegment, GpxFileBuilder : GpxFileBuilder }; }).call(this,require("IrXUsu"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/fake_5374100a.js","/") },{"./lib/gpxfile":2,"./lib/gpxfilebuilder":3,"./lib/gpxpoint":5,"./lib/gpxroute":6,"./lib/gpxtrack":7,"./lib/gpxtracksegment":8,"IrXUsu":13,"buffer":10}],2:[function(require,module,exports){ (function (process,global,Buffer,__argument0,__argument1,__argument2,__argument3,__filename,__dirname){ var helpers = require('./helpers'), GpxObject = require('./gpxobject'); var GpxFile = (function () { "use strict"; var GpxFile = function (properties) { GpxFile.super.call(this, properties); }; helpers.extends(GpxFile, GpxObject); GpxFile.prototype.creator = null; GpxFile.prototype.name = null; GpxFile.prototype.description = null; GpxFile.prototype.time = null; GpxFile.prototype.keywords = null; GpxFile.prototype.setProperties = function (properties) { if (properties.hasOwnProperty('creator')) { this.setCreator(properties.creator); } if (properties.hasOwnProperty('name')) { this.setName(properties.name); } if (properties.hasOwnProperty('description')) { this.setDescription(properties.description); } if (properties.hasOwnProperty('time')) { this.setTime(properties.time); } if (properties.hasOwnProperty('keywords')) { this.setKeywords(properties.keywords); } }; GpxFile.prototype.setCreator = function (creator) { this.creator = creator; }; GpxFile.prototype.setName = function (name) { this.name = name; }; GpxFile.prototype.setDescription = function (description) { this.description = description; }; GpxFile.prototype.setTime = function (time) { if (typeof time === 'string') { this.time = time; } else if (typeof time.toISOString === 'function') { this.time = time.toISOString(); } else { throw new Error('arguments must be a string or an object with a toISOString method'); } }; GpxFile.prototype.setKeywords = function (keywords) { this.keywords = [].concat(keywords).join(', '); }; GpxFile.prototype.getMimeType = function () { return 'application/gpx+xml'; }; GpxFile.prototype.getXml = function () { var xml = [], enc = helpers.encodeXml, i; xml.push('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'); xml.push('<gpx version="1.1" creator="' + enc(this.creator) + '"'); xml.push(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'); xml.push(' xmlns="http://www.topografix.com/GPX/1/1"'); xml.push(' xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">'); xml.push('<metadata>'); if (this.name !== null) { xml.push(this.getXmlElement('name', this.name)); } if (this.description !== null) { xml.push(this.getXmlElement('desc', this.description)); } if (this.time !== null) { xml.push(this.getXmlElement('time', this.time)); } if (this.keywords !== null) { xml.push(this.getXmlElement('keywords', this.keywords)); } xml.push('</metadata>'); for (i = 0; i < this.contents.length; i++) { xml.push(this.contents[i].getXml()); } xml.push('</gpx>'); return xml.join('\n'); }; return GpxFile; }()); module.exports = GpxFile; }).call(this,require("IrXUsu"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/lib/gpxfile.js","/lib") },{"./gpxobject":4,"./helpers":9,"IrXUsu":13,"buffer":10}],3:[function(require,module,exports){ (function (process,global,Buffer,__argument0,__argument1,__argument2,__argument3,__filename,__dirname){ var GpxFile = require('./gpxfile'), GpxRoute = require('./gpxroute'), GpxPoint = require('./gpxpoint'), GpxTrack = require('./gpxtrack'), GpxTrackSegment = require('./gpxtracksegment'), helpers = require('./helpers'); var GpxFileBuilder = (function () { "use strict"; var GpxFileBuilder = function (metadata) { this.file = new GpxFile(metadata); }; GpxFileBuilder.prototype.setFileInfo = function (metadata) { if (metadata) { this.file.setProperties(metadata); } return this; }; GpxFileBuilder.prototype.addTrack = function (info, segments) { var track = this.file.add(GpxTrack, info), i, k; if (segments) { segments = helpers.force2d(segments); for (i = 0; i < segments.length; i++) { var segment = track.add(GpxTrackSegment), points = segments[i]; for (k = 0; k < points.length; k++) { segment.add(GpxPoint, points[k]); } } } return this; }; GpxFileBuilder.prototype.addRoute = function (info, points) { var route = this.file.add(GpxRoute, info), i; if (points) { points = [].concat(points); for (i = 0; i < points.length; i++) { route.add(GpxPoint, points[i]); } } return this; }; GpxFileBuilder.prototype.addWayPoints = function (points) { var i; points = [].concat(points); for (i = 0; i < points.length; i++) { this.file.add(GpxPoint, points[i]); } return this; }; GpxFileBuilder.prototype.xml = function () { return this.file.getXml(); }; return GpxFileBuilder; }()); module.exports = GpxFileBuilder; }).call(this,require("IrXUsu"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/lib/gpxfilebuilder.js","/lib") },{"./gpxfile":2,"./gpxpoint":5,"./gpxroute":6,"./gpxtrack":7,"./gpxtracksegment":8,"./helpers":9,"IrXUsu":13,"buffer":10}],4:[function(require,module,exports){ (function (process,global,Buffer,__argument0,__argument1,__argument2,__argument3,__filename,__dirname){ var helpers = require('./helpers'); var GpxObject = (function () { "use strict"; var enc = helpers.encodeXml; var GpxObject = function (properties) { if (properties) { this.setProperties(properties); } this.contents = []; }; GpxObject.prototype.contents = null; GpxObject.prototype.add = function (content, properties) { if (typeof content === 'function') { content = new content(properties); } if (typeof content.getXml !== 'function') { throw new Error('arguments must be an object with a getXml method'); } this.contents.push(content); return content; }; GpxObject.prototype.setProperty = function (property, value) {}; GpxObject.prototype.setProperties = function (properties) {}; GpxObject.prototype.getXml = function (tagname) {}; GpxObject.prototype.getXmlElement = function (tagname, value) { return '<' + tagname + '>' + enc(value) + '</' + tagname + '>'; }; return GpxObject; }()); module.exports = GpxObject; }).call(this,require("IrXUsu"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/lib/gpxobject.js","/lib") },{"./helpers":9,"IrXUsu":13,"buffer":10}],5:[function(require,module,exports){ (function (process,global,Buffer,__argument0,__argument1,__argument2,__argument3,__filename,__dirname){ var GpxObject = require('./gpxobject'), helpers = require('./helpers'); var GpxPoint = (function () { "use strict"; var GpxPoint = function (properties) { if (properties) { this.setProperties(properties); } }; helpers.extends(GpxPoint, GpxObject); GpxPoint.prototype.name = null; GpxPoint.prototype.elevation = null; GpxPoint.prototype.latitude = null; GpxPoint.prototype.longitude = null; GpxPoint.prototype.setProperties = function (properties) { if (properties.hasOwnProperty('name')) { this.setName(properties.name); } if (properties.hasOwnProperty('elevation')) { this.setElevation(properties.elevation); } if (properties.hasOwnProperty('latitude')) { this.setLatitude(properties.latitude); } if (properties.hasOwnProperty('longitude')) { this.setLongitude(properties.longitude); } }; GpxPoint.prototype.setName = function (name) { this.name = name; }; GpxPoint.prototype.setElevation = function (elevation) { this.elevation = helpers.toFloat(elevation, false); }; GpxPoint.prototype.setLatitude = function (latitude) { this.latitude = helpers.toFloat(latitude, false); }; GpxPoint.prototype.setLongitude = function (longitude) { this.longitude = helpers.toFloat(longitude, true); }; GpxPoint.prototype.getXml = function (tagname) { var xml = [], enc = helpers.encodeXml; tagname = tagname || 'wpt'; xml.push('<' + tagname + ' lon="' + enc(this.longitude) + '" lat="' + enc(this.latitude) + '">'); if (this.elevation !== null) { xml.push(this.getXmlElement('ele', this.elevation)); } if (this.name !== null) { xml.push(this.getXmlElement('name', this.name)); } xml.push('</' + tagname + '>'); return xml.join('\n'); }; return GpxPoint; }()); module.exports = GpxPoint; }).call(this,require("IrXUsu"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/lib/gpxpoint.js","/lib") },{"./gpxobject":4,"./helpers":9,"IrXUsu":13,"buffer":10}],6:[function(require,module,exports){ (function (process,global,Buffer,__argument0,__argument1,__argument2,__argument3,__filename,__dirname){ var GpxObject = require('./gpxobject'), helpers = require('./helpers'); var GpxRoute = (function () { "use strict"; var GpxRoute = function (properties) { GpxRoute.super.call(this, properties); }; helpers.extends(GpxRoute, GpxObject); GpxRoute.prototype.name = null; GpxRoute.prototype.setProperties = function (properties) { if (properties.hasOwnProperty('name')) { this.setName(properties.name); } }; GpxRoute.prototype.setName = function (name) { this.name = name; }; GpxRoute.prototype.getXml = function () { var xml = [], i; xml.push('<rte>'); if (this.name !== null) { xml.push(this.getXmlElement('name', this.name)); } for (i = 0; i < this.contents.length; i++) { xml.push(this.contents[i].getXml('rtept')); } xml.push('</rte>'); return xml.join('\n'); }; return GpxRoute; }()); module.exports = GpxRoute; }).call(this,require("IrXUsu"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/lib/gpxroute.js","/lib") },{"./gpxobject":4,"./helpers":9,"IrXUsu":13,"buffer":10}],7:[function(require,module,exports){ (function (process,global,Buffer,__argument0,__argument1,__argument2,__argument3,__filename,__dirname){ var GpxObject = require('./gpxobject'), helpers = require('./helpers'); var GpxTrack = (function () { "use strict"; var GpxTrack = function (properties) { GpxTrack.super.call(this, properties); }; helpers.extends(GpxTrack, GpxObject); GpxTrack.prototype.name = null; GpxTrack.prototype.setProperties = function (properties) { if (properties.hasOwnProperty('name')) { this.setName(properties.name); } }; GpxTrack.prototype.setName = function (name) { this.name = name; }; GpxTrack.prototype.getXml = function () { var xml = [], i; xml.push('<trk>'); if (this.name !== null) { xml.push(this.getXmlElement('name', this.name)); } for (i = 0; i < this.contents.length; i++) { xml.push(this.contents[i].getXml()); } xml.push('</trk>'); return xml.join('\n'); }; return GpxTrack; }()); module.exports = GpxTrack; }).call(this,require("IrXUsu"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/lib/gpxtrack.js","/lib") },{"./gpxobject":4,"./helpers":9,"IrXUsu":13,"buffer":10}],8:[function(require,module,exports){ (function (process,global,Buffer,__argument0,__argument1,__argument2,__argument3,__filename,__dirname){ var GpxObject = require('./gpxobject'), helpers = require('./helpers'); var GpxTrackSegment = (function () { "use strict"; var GpxTrackSegment = function (properties) { GpxTrackSegment.super.call(this, properties); }; helpers.extends(GpxTrackSegment, GpxObject); GpxTrackSegment.prototype.getXml = function () { var xml = [], i; xml.push('<trkseg>'); for (i = 0; i < this.contents.length; i++) { xml.push(this.contents[i].getXml('trkpt')); } xml.push('</trkseg>'); return xml.join('\n'); }; return GpxTrackSegment; }()); module.exports = GpxTrackSegment; }).call(this,require("IrXUsu"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/lib/gpxtracksegment.js","/lib") },{"./gpxobject":4,"./helpers":9,"IrXUsu":13,"buffer":10}],9:[function(require,module,exports){ (function (process,global,Buffer,__argument0,__argument1,__argument2,__argument3,__filename,__dirname){ var helpers = (function () { "use strict"; var helpers = {}; helpers.isArray = Array.isArray || function (value) { return Object.prototype.toString.call(value) === '[object Array]'; }; helpers.force2d = function (array) { var processedArray = [], segment = null, i; for (i = 0; i < array.length; i++) { if (helpers.isArray(array[i])) { processedArray.push(array[i]); segment = null; } else { if (segment === null) { segment = []; processedArray.push(segment); } segment.push(array[i]); } } return processedArray; }; helpers.extends = function (ctor, proto) { ctor.super = proto; ctor.prototype = Object.create(proto.prototype); ctor.prototype.constructor = ctor; }; helpers.encodeXml = function (string) { if (string === null || typeof string === 'undefined') { string = ''; } return String(string) .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&apos;'); }; helpers.toInteger = function (value, acceptNull) { if (acceptNull && value === null) { return value; } value = parseInt(value, 10); return isNaN(value) ? 0 : value; }; helpers.toFloat = function (value, acceptNull) { if (acceptNull && value === null) { return value; } value = parseFloat(value); return isNaN(value) ? 0 : value; }; return helpers; }()); module.exports = helpers; }).call(this,require("IrXUsu"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/lib/helpers.js","/lib") },{"IrXUsu":13,"buffer":10}],10:[function(require,module,exports){ (function (process,global,Buffer,__argument0,__argument1,__argument2,__argument3,__filename,__dirname){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <[email protected]> <http://feross.org> * @license MIT */ var base64 = require('base64-js') var ieee754 = require('ieee754') exports.Buffer = Buffer exports.SlowBuffer = Buffer exports.INSPECT_MAX_BYTES = 50 Buffer.poolSize = 8192 /** * If `Buffer._useTypedArrays`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (compatible down to IE6) */ Buffer._useTypedArrays = (function () { // Detect if browser supports Typed Arrays. Supported browsers are IE 10+, Firefox 4+, // Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+. If the browser does not support adding // properties to `Uint8Array` instances, then that's the same as no `Uint8Array` support // because we need to be able to add all the node Buffer API methods. This is an issue // in Firefox 4-29. Now fixed: https://bugzilla.mozilla.org/show_bug.cgi?id=695438 try { var buf = new ArrayBuffer(0) var arr = new Uint8Array(buf) arr.foo = function () { return 42 } return 42 === arr.foo() && typeof arr.subarray === 'function' // Chrome 9-10 lack `subarray` } catch (e) { return false } })() /** * Class: Buffer * ============= * * The Buffer constructor returns instances of `Uint8Array` that are augmented * with function properties for all the node `Buffer` API functions. We use * `Uint8Array` so that square bracket notation works as expected -- it returns * a single octet. * * By augmenting the instances, we can avoid modifying the `Uint8Array` * prototype. */ function Buffer (subject, encoding, noZero) { if (!(this instanceof Buffer)) return new Buffer(subject, encoding, noZero) var type = typeof subject // Workaround: node's base64 implementation allows for non-padded strings // while base64-js does not. if (encoding === 'base64' && type === 'string') { subject = stringtrim(subject) while (subject.length % 4 !== 0) { subject = subject + '=' } } // Find the length var length if (type === 'number') length = coerce(subject) else if (type === 'string') length = Buffer.byteLength(subject, encoding) else if (type === 'object') length = coerce(subject.length) // assume that object is array-like else throw new Error('First argument needs to be a number, array or string.') var buf if (Buffer._useTypedArrays) { // Preferred: Return an augmented `Uint8Array` instance for best performance buf = Buffer._augment(new Uint8Array(length)) } else { // Fallback: Return THIS instance of Buffer (created by `new`) buf = this buf.length = length buf._isBuffer = true } var i if (Buffer._useTypedArrays && typeof subject.byteLength === 'number') { // Speed optimization -- use set if we're copying from a typed array buf._set(subject) } else if (isArrayish(subject)) { // Treat array-ish objects as a byte array for (i = 0; i < length; i++) { if (Buffer.isBuffer(subject)) buf[i] = subject.readUInt8(i) else buf[i] = subject[i] } } else if (type === 'string') { buf.write(subject, 0, encoding) } else if (type === 'number' && !Buffer._useTypedArrays && !noZero) { for (i = 0; i < length; i++) { buf[i] = 0 } } return buf } // STATIC METHODS // ============== Buffer.isEncoding = function (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'raw': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.isBuffer = function (b) { return !!(b !== null && b !== undefined && b._isBuffer) } Buffer.byteLength = function (str, encoding) { var ret str = str + '' switch (encoding || 'utf8') { case 'hex': ret = str.length / 2 break case 'utf8': case 'utf-8': ret = utf8ToBytes(str).length break case 'ascii': case 'binary': case 'raw': ret = str.length break case 'base64': ret = base64ToBytes(str).length break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = str.length * 2 break default: throw new Error('Unknown encoding') } return ret } Buffer.concat = function (list, totalLength) { assert(isArray(list), 'Usage: Buffer.concat(list, [totalLength])\n' + 'list should be an Array.') if (list.length === 0) { return new Buffer(0) } else if (list.length === 1) { return list[0] } var i if (typeof totalLength !== 'number') { totalLength = 0 for (i = 0; i < list.length; i++) { totalLength += list[i].length } } var buf = new Buffer(totalLength) var pos = 0 for (i = 0; i < list.length; i++) { var item = list[i] item.copy(buf, pos) pos += item.length } return buf } // BUFFER INSTANCE METHODS // ======================= function _hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length assert(strLen % 2 === 0, 'Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; i++) { var byte = parseInt(string.substr(i * 2, 2), 16) assert(!isNaN(byte), 'Invalid hex string') buf[offset + i] = byte } Buffer._charsWritten = i * 2 return i } function _utf8Write (buf, string, offset, length) { var charsWritten = Buffer._charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length) return charsWritten } function _asciiWrite (buf, string, offset, length) { var charsWritten = Buffer._charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length) return charsWritten } function _binaryWrite (buf, string, offset, length) { return _asciiWrite(buf, string, offset, length) } function _base64Write (buf, string, offset, length) { var charsWritten = Buffer._charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length) return charsWritten } function _utf16leWrite (buf, string, offset, length) { var charsWritten = Buffer._charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length) return charsWritten } Buffer.prototype.write = function (string, offset, length, encoding) { // Support both (string, offset, length, encoding) // and the legacy (string, encoding, offset, length) if (isFinite(offset)) { if (!isFinite(length)) { encoding = length length = undefined } } else { // legacy var swap = encoding encoding = offset offset = length length = swap } offset = Number(offset) || 0 var remaining = this.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } encoding = String(encoding || 'utf8').toLowerCase() var ret switch (encoding) { case 'hex': ret = _hexWrite(this, string, offset, length) break case 'utf8': case 'utf-8': ret = _utf8Write(this, string, offset, length) break case 'ascii': ret = _asciiWrite(this, string, offset, length) break case 'binary': ret = _binaryWrite(this, string, offset, length) break case 'base64': ret = _base64Write(this, string, offset, length) break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = _utf16leWrite(this, string, offset, length) break default: throw new Error('Unknown encoding') } return ret } Buffer.prototype.toString = function (encoding, start, end) { var self = this encoding = String(encoding || 'utf8').toLowerCase() start = Number(start) || 0 end = (end !== undefined) ? Number(end) : end = self.length // Fastpath empty strings if (end === start) return '' var ret switch (encoding) { case 'hex': ret = _hexSlice(self, start, end) break case 'utf8': case 'utf-8': ret = _utf8Slice(self, start, end) break case 'ascii': ret = _asciiSlice(self, start, end) break case 'binary': ret = _binarySlice(self, start, end) break case 'base64': ret = _base64Slice(self, start, end) break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = _utf16leSlice(self, start, end) break default: throw new Error('Unknown encoding') } return ret } Buffer.prototype.toJSON = function () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function (target, target_start, start, end) { var source = this if (!start) start = 0 if (!end && end !== 0) end = this.length if (!target_start) target_start = 0 // Copy 0 bytes; we're done if (end === start) return if (target.length === 0 || source.length === 0) return // Fatal error conditions assert(end >= start, 'sourceEnd < sourceStart') assert(target_start >= 0 && target_start < target.length, 'targetStart out of bounds') assert(start >= 0 && start < source.length, 'sourceStart out of bounds') assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - target_start < end - start) end = target.length - target_start + start var len = end - start if (len < 100 || !Buffer._useTypedArrays) { for (var i = 0; i < len; i++) target[i + target_start] = this[i + start] } else { target._set(this.subarray(start, start + len), target_start) } } function _base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function _utf8Slice (buf, start, end) { var res = '' var tmp = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { if (buf[i] <= 0x7F) { res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) tmp = '' } else { tmp += '%' + buf[i].toString(16) } } return res + decodeUtf8Char(tmp) } function _asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) ret += String.fromCharCode(buf[i]) return ret } function _binarySlice (buf, start, end) { return _asciiSlice(buf, start, end) } function _hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; i++) { out += toHex(buf[i]) } return out } function _utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i+1] * 256) } return res } Buffer.prototype.slice = function (start, end) { var len = this.length start = clamp(start, len, 0) end = clamp(end, len, len) if (Buffer._useTypedArrays) { return Buffer._augment(this.subarray(start, end)) } else { var sliceLen = end - start var newBuf = new Buffer(sliceLen, undefined, true) for (var i = 0; i < sliceLen; i++) { newBuf[i] = this[i + start] } return newBuf } } // `get` will be removed in Node 0.13+ Buffer.prototype.get = function (offset) { console.log('.get() is deprecated. Access using array indexes instead.') return this.readUInt8(offset) } // `set` will be removed in Node 0.13+ Buffer.prototype.set = function (v, offset) { console.log('.set() is deprecated. Access using array indexes instead.') return this.writeUInt8(v, offset) } Buffer.prototype.readUInt8 = function (offset, noAssert) { if (!noAssert) { assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < this.length, 'Trying to read beyond buffer length') } if (offset >= this.length) return return this[offset] } function _readUInt16 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) return var val if (littleEndian) { val = buf[offset] if (offset + 1 < len) val |= buf[offset + 1] << 8 } else { val = buf[offset] << 8 if (offset + 1 < len) val |= buf[offset + 1] } return val } Buffer.prototype.readUInt16LE = function (offset, noAssert) { return _readUInt16(this, offset, true, noAssert) } Buffer.prototype.readUInt16BE = function (offset, noAssert) { return _readUInt16(this, offset, false, noAssert) } function _readUInt32 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) return var val if (littleEndian) { if (offset + 2 < len) val = buf[offset + 2] << 16 if (offset + 1 < len) val |= buf[offset + 1] << 8 val |= buf[offset] if (offset + 3 < len) val = val + (buf[offset + 3] << 24 >>> 0) } else { if (offset + 1 < len) val = buf[offset + 1] << 16 if (offset + 2 < len) val |= buf[offset + 2] << 8 if (offset + 3 < len) val |= buf[offset + 3] val = val + (buf[offset] << 24 >>> 0) } return val } Buffer.prototype.readUInt32LE = function (offset, noAssert) { return _readUInt32(this, offset, true, noAssert) } Buffer.prototype.readUInt32BE = function (offset, noAssert) { return _readUInt32(this, offset, false, noAssert) } Buffer.prototype.readInt8 = function (offset, noAssert) { if (!noAssert) { assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < this.length, 'Trying to read beyond buffer length') } if (offset >= this.length) return var neg = this[offset] & 0x80 if (neg) return (0xff - this[offset] + 1) * -1 else return this[offset] } function _readInt16 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) return var val = _readUInt16(buf, offset, littleEndian, true) var neg = val & 0x8000 if (neg) return (0xffff - val + 1) * -1 else return val } Buffer.prototype.readInt16LE = function (offset, noAssert) { return _readInt16(this, offset, true, noAssert) } Buffer.prototype.readInt16BE = function (offset, noAssert) { return _readInt16(this, offset, false, noAssert) } function _readInt32 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) return var val = _readUInt32(buf, offset, littleEndian, true) var neg = val & 0x80000000 if (neg) return (0xffffffff - val + 1) * -1 else return val } Buffer.prototype.readInt32LE = function (offset, noAssert) { return _readInt32(this, offset, true, noAssert) } Buffer.prototype.readInt32BE = function (offset, noAssert) { return _readInt32(this, offset, false, noAssert) } function _readFloat (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') } return ieee754.read(buf, offset, littleEndian, 23, 4) } Buffer.prototype.readFloatLE = function (offset, noAssert) { return _readFloat(this, offset, true, noAssert) } Buffer.prototype.readFloatBE = function (offset, noAssert) { return _readFloat(this, offset, false, noAssert) } function _readDouble (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset + 7 < buf.length, 'Trying to read beyond buffer length') } return ieee754.read(buf, offset, littleEndian, 52, 8) } Buffer.prototype.readDoubleLE = function (offset, noAssert) { return _readDouble(this, offset, true, noAssert) } Buffer.prototype.readDoubleBE = function (offset, noAssert) { return _readDouble(this, offset, false, noAssert) } Buffer.prototype.writeUInt8 = function (value, offset, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < this.length, 'trying to write beyond buffer length') verifuint(value, 0xff) } if (offset >= this.length) return this[offset] = value } function _writeUInt16 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'trying to write beyond buffer length') verifuint(value, 0xffff) } var len = buf.length if (offset >= len) return for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } } Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) { _writeUInt16(this, value, offset, true, noAssert) } Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) { _writeUInt16(this, value, offset, false, noAssert) } function _writeUInt32 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'trying to write beyond buffer length') verifuint(value, 0xffffffff) } var len = buf.length if (offset >= len) return for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } } Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) { _writeUInt32(this, value, offset, true, noAssert) } Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) { _writeUInt32(this, value, offset, false, noAssert) } Buffer.prototype.writeInt8 = function (value, offset, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < this.length, 'Trying to write beyond buffer length') verifsint(value, 0x7f, -0x80) } if (offset >= this.length) return if (value >= 0) this.writeUInt8(value, offset, noAssert) else this.writeUInt8(0xff + value + 1, offset, noAssert) } function _writeInt16 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'Trying to write beyond buffer length') verifsint(value, 0x7fff, -0x8000) } var len = buf.length if (offset >= len) return if (value >= 0) _writeUInt16(buf, value, offset, littleEndian, noAssert) else _writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert) } Buffer.prototype.writeInt16LE = function (value, offset, noAssert) { _writeInt16(this, value, offset, true, noAssert) } Buffer.prototype.writeInt16BE = function (value, offset, noAssert) { _writeInt16(this, value, offset, false, noAssert) } function _writeInt32 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to write beyond buffer length') verifsint(value, 0x7fffffff, -0x80000000) } var len = buf.length if (offset >= len) return if (value >= 0) _writeUInt32(buf, value, offset, littleEndian, noAssert) else _writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert) } Buffer.prototype.writeInt32LE = function (value, offset, noAssert) { _writeInt32(this, value, offset, true, noAssert) } Buffer.prototype.writeInt32BE = function (value, offset, noAssert) { _writeInt32(this, value, offset, false, noAssert) } function _writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to write beyond buffer length') verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38) } var len = buf.length if (offset >= len) return ieee754.write(buf, value, offset, littleEndian, 23, 4) } Buffer.prototype.writeFloatLE = function (value, offset, noAssert) { _writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function (value, offset, noAssert) { _writeFloat(this, value, offset, false, noAssert) } function _writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 7 < buf.length, 'Trying to write beyond buffer length') verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308) } var len = buf.length if (offset >= len) return ieee754.write(buf, value, offset, littleEndian, 52, 8) } Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) { _writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) { _writeDouble(this, value, offset, false, noAssert) } // fill(value, start=0, end=buffer.length) Buffer.prototype.fill = function (value, start, end) { if (!value) value = 0 if (!start) start = 0 if (!end) end = this.length if (typeof value === 'string') { value = value.charCodeAt(0) } assert(typeof value === 'number' && !isNaN(value), 'value is not a number') assert(end >= start, 'end < start') // Fill 0 bytes; we're done if (end === start) return if (this.length === 0) return assert(start >= 0 && start < this.length, 'start out of bounds') assert(end >= 0 && end <= this.length, 'end out of bounds') for (var i = start; i < end; i++) { this[i] = value } } Buffer.prototype.inspect = function () { var out = [] var len = this.length for (var i = 0; i < len; i++) { out[i] = toHex(this[i]) if (i === exports.INSPECT_MAX_BYTES) { out[i + 1] = '...' break } } return '<Buffer ' + out.join(' ') + '>' } /** * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. * Added in Node 0.12. Only available in browsers that support ArrayBuffer. */ Buffer.prototype.toArrayBuffer = function () { if (typeof Uint8Array !== 'undefined') { if (Buffer._useTypedArrays) { return (new Buffer(this)).buffer } else { var buf = new Uint8Array(this.length) for (var i = 0, len = buf.length; i < len; i += 1) buf[i] = this[i] return buf.buffer } } else { throw new Error('Buffer.toArrayBuffer not supported in this browser') } } // HELPER FUNCTIONS // ================ function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } var BP = Buffer.prototype /** * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods */ Buffer._augment = function (arr) { arr._isBuffer = true // save reference to original Uint8Array get/set methods before overwriting arr._get = arr.get arr._set = arr.set // deprecated, will be removed in node 0.13+ arr.get = BP.get arr.set = BP.set arr.write = BP.write arr.toString = BP.toString arr.toLocaleString = BP.toString arr.toJSON = BP.toJSON arr.copy = BP.copy arr.slice = BP.slice arr.readUInt8 = BP.readUInt8 arr.readUInt16LE = BP.readUInt16LE arr.readUInt16BE = BP.readUInt16BE arr.readUInt32LE = BP.readUInt32LE arr.readUInt32BE = BP.readUInt32BE arr.readInt8 = BP.readInt8 arr.readInt16LE = BP.readInt16LE arr.readInt16BE = BP.readInt16BE arr.readInt32LE = BP.readInt32LE arr.readInt32BE = BP.readInt32BE arr.readFloatLE = BP.readFloatLE arr.readFloatBE = BP.readFloatBE arr.readDoubleLE = BP.readDoubleLE arr.readDoubleBE = BP.readDoubleBE arr.writeUInt8 = BP.writeUInt8 arr.writeUInt16LE = BP.writeUInt16LE arr.writeUInt16BE = BP.writeUInt16BE arr.writeUInt32LE = BP.writeUInt32LE arr.writeUInt32BE = BP.writeUInt32BE arr.writeInt8 = BP.writeInt8 arr.writeInt16LE = BP.writeInt16LE arr.writeInt16BE = BP.writeInt16BE arr.writeInt32LE = BP.writeInt32LE arr.writeInt32BE = BP.writeInt32BE arr.writeFloatLE = BP.writeFloatLE arr.writeFloatBE = BP.writeFloatBE arr.writeDoubleLE = BP.writeDoubleLE arr.writeDoubleBE = BP.writeDoubleBE arr.fill = BP.fill arr.inspect = BP.inspect arr.toArrayBuffer = BP.toArrayBuffer return arr } // slice(start, end) function clamp (index, len, defaultValue) { if (typeof index !== 'number') return defaultValue index = ~~index; // Coerce to integer. if (index >= len) return len if (index >= 0) return index index += len if (index >= 0) return index return 0 } function coerce (length) { // Coerce length to a number (possibly NaN), round up // in case it's fractional (e.g. 123.456) then do a // double negate to coerce a NaN to 0. Easy, right? length = ~~Math.ceil(+length) return length < 0 ? 0 : length } function isArray (subject) { return (Array.isArray || function (subject) { return Object.prototype.toString.call(subject) === '[object Array]' })(subject) } function isArrayish (subject) { return isArray(subject) || Buffer.isBuffer(subject) || subject && typeof subject === 'object' && typeof subject.length === 'number' } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { var b = str.charCodeAt(i) if (b <= 0x7F) byteArray.push(str.charCodeAt(i)) else { var start = i if (b >= 0xD800 && b <= 0xDFFF) i++ var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%') for (var j = 0; j < h.length; j++) byteArray.push(parseInt(h[j], 16)) } } return byteArray } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; i++) { c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(str) } function blitBuffer (src, dst, offset, length) { var pos for (var i = 0; i < length; i++) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function decodeUtf8Char (str) { try { return decodeURIComponent(str) } catch (err) { return String.fromCharCode(0xFFFD) // UTF 8 invalid char } } /* * We have to make sure that the value is a valid integer. This means that it * is non-negative. It has no fractional component and that it does not * exceed the maximum allowed value. */ function verifuint (value, max) { assert(typeof value === 'number', 'cannot write a non-number as a number') assert(value >= 0, 'specified a negative value for writing an unsigned value') assert(value <= max, 'value is larger than maximum value for type') assert(Math.floor(value) === value, 'value has a fractional component') } function verifsint (value, max, min) { assert(typeof value === 'number', 'cannot write a non-number as a number') assert(value <= max, 'value larger than maximum allowed value') assert(value >= min, 'value smaller than minimum allowed value') assert(Math.floor(value) === value, 'value has a fractional component') } function verifIEEE754 (value, max, min) { assert(typeof value === 'number', 'cannot write a non-number as a number') assert(value <= max, 'value larger than maximum allowed value') assert(value >= min, 'value smaller than minimum allowed value') } function assert (test, message) { if (!test) throw new Error(message || 'Failed assertion') } }).call(this,require("IrXUsu"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/browserify/node_modules/buffer") },{"IrXUsu":13,"base64-js":11,"buffer":10,"ieee754":12}],11:[function(require,module,exports){ (function (process,global,Buffer,__argument0,__argument1,__argument2,__argument3,__filename,__dirname){ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; ;(function (exports) { 'use strict'; var Arr = (typeof Uint8Array !== 'undefined') ? Uint8Array : Array var PLUS = '+'.charCodeAt(0) var SLASH = '/'.charCodeAt(0) var NUMBER = '0'.charCodeAt(0) var LOWER = 'a'.charCodeAt(0) var UPPER = 'A'.charCodeAt(0) var PLUS_URL_SAFE = '-'.charCodeAt(0) var SLASH_URL_SAFE = '_'.charCodeAt(0) function decode (elt) { var code = elt.charCodeAt(0) if (code === PLUS || code === PLUS_URL_SAFE) return 62 // '+' if (code === SLASH || code === SLASH_URL_SAFE) return 63 // '/' if (code < NUMBER) return -1 //no match if (code < NUMBER + 10) return code - NUMBER + 26 + 26 if (code < UPPER + 26) return code - UPPER if (code < LOWER + 26) return code - LOWER + 26 } function b64ToByteArray (b64) { var i, j, l, tmp, placeHolders, arr if (b64.length % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice var len = b64.length placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 // base64 is 4/3 + up to two characters of the original data arr = new Arr(b64.length * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? b64.length - 4 : b64.length var L = 0 function push (v) { arr[L++] = v } for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) push((tmp & 0xFF0000) >> 16) push((tmp & 0xFF00) >> 8) push(tmp & 0xFF) } if (placeHolders === 2) { tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) push(tmp & 0xFF) } else if (placeHolders === 1) { tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) push((tmp >> 8) & 0xFF) push(tmp & 0xFF) } return arr } function uint8ToBase64 (uint8) { var i, extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes output = "", temp, length function encode (num) { return lookup.charAt(num) } function tripletToBase64 (num) { return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) } // go through the array every three bytes, we'll deal with trailing stuff later for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output += tripletToBase64(temp) } // pad the end with zeros, but make sure to not forget the extra bytes switch (extraBytes) { case 1: temp = uint8[uint8.length - 1] output += encode(temp >> 2) output += encode((temp << 4) & 0x3F) output += '==' break case 2: temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) output += encode(temp >> 10) output += encode((temp >> 4) & 0x3F) output += encode((temp << 2) & 0x3F) output += '=' break } return output } exports.toByteArray = b64ToByteArray exports.fromByteArray = uint8ToBase64 }(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) }).call(this,require("IrXUsu"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/browserify/node_modules/buffer/node_modules/base64-js/lib/b64.js","/node_modules/gulp-browserify/node_modules/browserify/node_modules/buffer/node_modules/base64-js/lib") },{"IrXUsu":13,"buffer":10}],12:[function(require,module,exports){ (function (process,global,Buffer,__argument0,__argument1,__argument2,__argument3,__filename,__dirname){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } }).call(this,require("IrXUsu"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/browserify/node_modules/buffer/node_modules/ieee754/index.js","/node_modules/gulp-browserify/node_modules/browserify/node_modules/buffer/node_modules/ieee754") },{"IrXUsu":13,"buffer":10}],13:[function(require,module,exports){ (function (process,global,Buffer,__argument0,__argument1,__argument2,__argument3,__filename,__dirname){ // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } if (canPost) { var queue = []; window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); } // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; }).call(this,require("IrXUsu"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/browserify/node_modules/process/browser.js","/node_modules/gulp-browserify/node_modules/browserify/node_modules/process") },{"IrXUsu":13,"buffer":10}]},{},[1])
Wilkins/gpx
browserify/index.js
JavaScript
mit
57,263
finite-difference-method-bvp ============================ That application uses finite difference method to solve boundary value problem You may read about algorithm and solution [here](http://pers.narod.ru/algorithms/pas_odu_kraevaya.html) (in Russian).
kubsau-aif-students-labs/finite-difference-method-bvp
README.md
Markdown
mit
257
<?php use Symfony\Component\Routing\Exception\MethodNotAllowedException; use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\Routing\RequestContext; /** * This class has been auto-generated * by the Symfony Routing Component. */ class ProjectUrlMatcher extends Symfony\Component\Routing\Matcher\UrlMatcher { public function __construct(RequestContext $context) { $this->context = $context; } public function match($rawPathinfo) { $allow = array(); $pathinfo = rawurldecode($rawPathinfo); $trimmedPathinfo = rtrim($pathinfo, '/'); $context = $this->context; $request = $this->request ?: $this->createRequest($pathinfo); $requestMethod = $canonicalMethod = $context->getMethod(); if ('HEAD' === $requestMethod) { $canonicalMethod = 'GET'; } if (0 === strpos($pathinfo, '/rootprefix')) { // static if ('/rootprefix/test' === $pathinfo) { return array('_route' => 'static'); } // dynamic if (preg_match('#^/rootprefix/(?P<var>[^/]++)$#sD', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'dynamic')), array ()); } } // with-condition if ('/with-condition' === $pathinfo && ($context->getMethod() == "GET")) { return array('_route' => 'with-condition'); } if ('/' === $pathinfo) { throw new Symfony\Component\Routing\Exception\NoConfigurationException(); } throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException(); } }
rana0105/rental
vendor/symfony/routing/Tests/Fixtures/dumper/url_matcher3.php
PHP
mit
1,765
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("04.CountsubstringsInText")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("04.CountsubstringsInText")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e3e828aa-34cd-46a0-8de0-38dd7fbb8eb5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
bstaykov/Telerik-CSharp-Part-2
Strings-and-Text-Processing/04.CountsubstringsInText/Properties/AssemblyInfo.cs
C#
mit
1,460
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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.apache.naming.resources; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import java.util.Vector; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttribute; /** * Attributes implementation. * * @author <a href="mailto:[email protected]">Remy Maucherat</a> * */ public class ResourceAttributes implements Attributes { // -------------------------------------------------------------- Constants // Default attribute names /** * Creation date. */ public static final String CREATION_DATE = "creationdate"; /** * Creation date. */ public static final String ALTERNATE_CREATION_DATE = "creation-date"; /** * Last modification date. */ public static final String LAST_MODIFIED = "getlastmodified"; /** * Last modification date. */ public static final String ALTERNATE_LAST_MODIFIED = "last-modified"; /** * Name. */ public static final String NAME = "displayname"; /** * Type. */ public static final String TYPE = "resourcetype"; /** * Type. */ public static final String ALTERNATE_TYPE = "content-type"; /** * Source. */ public static final String SOURCE = "source"; /** * MIME type of the content. */ public static final String CONTENT_TYPE = "getcontenttype"; /** * Content language. */ public static final String CONTENT_LANGUAGE = "getcontentlanguage"; /** * Content length. */ public static final String CONTENT_LENGTH = "getcontentlength"; /** * Content length. */ public static final String ALTERNATE_CONTENT_LENGTH = "content-length"; /** * ETag. */ public static final String ETAG = "getetag"; /** * ETag. */ public static final String ALTERNATE_ETAG = "etag"; /** * Collection type. */ public static final String COLLECTION_TYPE = "<collection/>"; /** * HTTP date format. */ protected static final SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); /** * Date formats using for Date parsing. */ protected static final SimpleDateFormat formats[] = { new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US), new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US), new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US) }; protected final static TimeZone gmtZone = TimeZone.getTimeZone("GMT"); /** * GMT timezone - all HTTP dates are on GMT */ static { format.setTimeZone(gmtZone); formats[0].setTimeZone(gmtZone); formats[1].setTimeZone(gmtZone); formats[2].setTimeZone(gmtZone); } // ----------------------------------------------------------- Constructors /** * Default constructor. */ public ResourceAttributes() { } /** * Merges with another attribute set. */ public ResourceAttributes(Attributes attributes) { this.attributes = attributes; } // ----------------------------------------------------- Instance Variables /** * Collection flag. */ protected boolean collection = false; /** * Content length. */ protected long contentLength = -1; /** * Creation time. */ protected long creation = -1; /** * Creation date. */ protected Date creationDate = null; /** * Last modified time. */ protected long lastModified = -1; /** * Last modified date. */ protected Date lastModifiedDate = null; /** * Last modified date in HTTP format. */ protected String lastModifiedHttp = null; /** * MIME type. */ protected String mimeType = null; /** * Name. */ protected String name = null; /** * Weak ETag. */ protected String weakETag = null; /** * Strong ETag. */ protected String strongETag = null; /** * External attributes. */ protected Attributes attributes = null; // ------------------------------------------------------------- Properties /** * Is collection. */ public boolean isCollection() { if (attributes != null) { return (COLLECTION_TYPE.equals(getResourceType())); } else { return (collection); } } /** * Set collection flag. * * @param collection New flag value */ public void setCollection(boolean collection) { this.collection = collection; if (attributes != null) { String value = ""; if (collection) value = COLLECTION_TYPE; attributes.put(TYPE, value); } } /** * Get content length. * * @return content length value */ public long getContentLength() { if (contentLength != -1L) return contentLength; if (attributes != null) { Attribute attribute = attributes.get(CONTENT_LENGTH); if (attribute != null) { try { Object value = attribute.get(); if (value instanceof Long) { contentLength = ((Long) value).longValue(); } else { try { contentLength = Long.parseLong(value.toString()); } catch (NumberFormatException e) { ; // Ignore } } } catch (NamingException e) { ; // No value for the attribute } } } return contentLength; } /** * Set content length. * * @param contentLength New content length value */ public void setContentLength(long contentLength) { this.contentLength = contentLength; if (attributes != null) attributes.put(CONTENT_LENGTH, new Long(contentLength)); } /** * Get creation time. * * @return creation time value */ public long getCreation() { if (creation != -1L) return creation; if (creationDate != null) return creationDate.getTime(); if (attributes != null) { Attribute attribute = attributes.get(CREATION_DATE); if (attribute != null) { try { Object value = attribute.get(); if (value instanceof Long) { creation = ((Long) value).longValue(); } else if (value instanceof Date) { creation = ((Date) value).getTime(); creationDate = (Date) value; } else { String creationDateValue = value.toString(); Date result = null; // Parsing the HTTP Date for (int i = 0; (result == null) && (i < formats.length); i++) { try { result = formats[i].parse(creationDateValue); } catch (ParseException e) { ; } } if (result != null) { creation = result.getTime(); creationDate = result; } } } catch (NamingException e) { ; // No value for the attribute } } } return creation; } /** * Set creation. * * @param creation New creation value */ public void setCreation(long creation) { this.creation = creation; this.creationDate = null; if (attributes != null) attributes.put(CREATION_DATE, new Date(creation)); } /** * Get creation date. * * @return Creation date value */ public Date getCreationDate() { if (creationDate != null) return creationDate; if (creation != -1L) { creationDate = new Date(creation); return creationDate; } if (attributes != null) { Attribute attribute = attributes.get(CREATION_DATE); if (attribute != null) { try { Object value = attribute.get(); if (value instanceof Long) { creation = ((Long) value).longValue(); creationDate = new Date(creation); } else if (value instanceof Date) { creation = ((Date) value).getTime(); creationDate = (Date) value; } else { String creationDateValue = value.toString(); Date result = null; // Parsing the HTTP Date for (int i = 0; (result == null) && (i < formats.length); i++) { try { result = formats[i].parse(creationDateValue); } catch (ParseException e) { ; } } if (result != null) { creation = result.getTime(); creationDate = result; } } } catch (NamingException e) { ; // No value for the attribute } } } return creationDate; } /** * Creation date mutator. * * @param creationDate New creation date */ public void setCreationDate(Date creationDate) { this.creation = creationDate.getTime(); this.creationDate = creationDate; if (attributes != null) attributes.put(CREATION_DATE, creationDate); } /** * Get last modified time. * * @return lastModified time value */ public long getLastModified() { if (lastModified != -1L) return lastModified; if (lastModifiedDate != null) return lastModifiedDate.getTime(); if (attributes != null) { Attribute attribute = attributes.get(LAST_MODIFIED); if (attribute != null) { try { Object value = attribute.get(); if (value instanceof Long) { lastModified = ((Long) value).longValue(); } else if (value instanceof Date) { lastModified = ((Date) value).getTime(); lastModifiedDate = (Date) value; } else { String lastModifiedDateValue = value.toString(); Date result = null; // Parsing the HTTP Date for (int i = 0; (result == null) && (i < formats.length); i++) { try { result = formats[i].parse(lastModifiedDateValue); } catch (ParseException e) { ; } } if (result != null) { lastModified = result.getTime(); lastModifiedDate = result; } } } catch (NamingException e) { ; // No value for the attribute } } } return lastModified; } /** * Set last modified. * * @param lastModified New last modified value */ public void setLastModified(long lastModified) { this.lastModified = lastModified; this.lastModifiedDate = null; if (attributes != null) attributes.put(LAST_MODIFIED, new Date(lastModified)); } /** * Set last modified date. * * @param lastModified New last modified date value * @deprecated */ public void setLastModified(Date lastModified) { setLastModifiedDate(lastModified); } /** * Get lastModified date. * * @return LastModified date value */ public Date getLastModifiedDate() { if (lastModifiedDate != null) return lastModifiedDate; if (lastModified != -1L) { lastModifiedDate = new Date(lastModified); return lastModifiedDate; } if (attributes != null) { Attribute attribute = attributes.get(LAST_MODIFIED); if (attribute != null) { try { Object value = attribute.get(); if (value instanceof Long) { lastModified = ((Long) value).longValue(); lastModifiedDate = new Date(lastModified); } else if (value instanceof Date) { lastModified = ((Date) value).getTime(); lastModifiedDate = (Date) value; } else { String lastModifiedDateValue = value.toString(); Date result = null; // Parsing the HTTP Date for (int i = 0; (result == null) && (i < formats.length); i++) { try { result = formats[i].parse(lastModifiedDateValue); } catch (ParseException e) { ; } } if (result != null) { lastModified = result.getTime(); lastModifiedDate = result; } } } catch (NamingException e) { ; // No value for the attribute } } } return lastModifiedDate; } /** * Last modified date mutator. * * @param lastModifiedDate New last modified date */ public void setLastModifiedDate(Date lastModifiedDate) { this.lastModified = lastModifiedDate.getTime(); this.lastModifiedDate = lastModifiedDate; if (attributes != null) attributes.put(LAST_MODIFIED, lastModifiedDate); } /** * @return Returns the lastModifiedHttp. */ public String getLastModifiedHttp() { if (lastModifiedHttp != null) return lastModifiedHttp; Date modifiedDate = getLastModifiedDate(); if (modifiedDate == null) { modifiedDate = getCreationDate(); } if (modifiedDate == null) { modifiedDate = new Date(); } synchronized (format) { lastModifiedHttp = format.format(modifiedDate); } return lastModifiedHttp; } /** * @param lastModifiedHttp The lastModifiedHttp to set. */ public void setLastModifiedHttp(String lastModifiedHttp) { this.lastModifiedHttp = lastModifiedHttp; } /** * @return Returns the mimeType. */ public String getMimeType() { return mimeType; } /** * @param mimeType The mimeType to set. */ public void setMimeType(String mimeType) { this.mimeType = mimeType; } /** * Get name. * * @return Name value */ public String getName() { if (name != null) return name; if (attributes != null) { Attribute attribute = attributes.get(NAME); if (attribute != null) { try { name = attribute.get().toString(); } catch (NamingException e) { ; // No value for the attribute } } } return name; } /** * Set name. * * @param name New name value */ public void setName(String name) { this.name = name; if (attributes != null) attributes.put(NAME, name); } /** * Get resource type. * * @return String resource type */ public String getResourceType() { String result = null; if (attributes != null) { Attribute attribute = attributes.get(TYPE); if (attribute != null) { try { result = attribute.get().toString(); } catch (NamingException e) { ; // No value for the attribute } } } if (result == null) { if (collection) result = COLLECTION_TYPE; else result = null; } return result; } /** * Type mutator. * * @param resourceType New resource type */ public void setResourceType(String resourceType) { collection = resourceType.equals(COLLECTION_TYPE); if (attributes != null) attributes.put(TYPE, resourceType); } /** * Get ETag. * * @return strong ETag if available, else weak ETag. */ public String getETag() { String result = null; if (attributes != null) { Attribute attribute = attributes.get(ETAG); if (attribute != null) { try { result = attribute.get().toString(); } catch (NamingException e) { ; // No value for the attribute } } } if (result == null) { if (strongETag != null) { // The strong ETag must always be calculated by the resources result = strongETag; } else { // The weakETag is contentLength + lastModified if (weakETag == null) { long contentLength = getContentLength(); long lastModified = getLastModified(); if ((contentLength >= 0) || (lastModified >= 0)) { weakETag = "W/\"" + contentLength + "-" + lastModified + "\""; } } result = weakETag; } } return result; } /** * Get ETag. * * @param strong Ignored * @return strong ETag if available, else weak ETag. * @deprecated */ public String getETag(boolean strong) { return getETag(); } /** * Set strong ETag. */ public void setETag(String eTag) { this.strongETag = eTag; if (attributes != null) attributes.put(ETAG, eTag); } /** * Return the canonical path of the resource, to possibly be used for * direct file serving. Implementations which support this should override * it to return the file path. * * @return The canonical path of the resource */ public String getCanonicalPath() { return null; } // ----------------------------------------------------- Attributes Methods /** * Get attribute. */ public Attribute get(String attrID) { if (attributes == null) { if (attrID.equals(CREATION_DATE)) { Date creationDate = getCreationDate(); if (creationDate == null) return null; return new BasicAttribute(CREATION_DATE, creationDate); } else if (attrID.equals(ALTERNATE_CREATION_DATE)) { Date creationDate = getCreationDate(); if (creationDate == null) return null; return new BasicAttribute(ALTERNATE_CREATION_DATE, creationDate); } else if (attrID.equals(LAST_MODIFIED)) { Date lastModifiedDate = getLastModifiedDate(); if (lastModifiedDate == null) return null; return new BasicAttribute(LAST_MODIFIED, lastModifiedDate); } else if (attrID.equals(ALTERNATE_LAST_MODIFIED)) { Date lastModifiedDate = getLastModifiedDate(); if (lastModifiedDate == null) return null; return new BasicAttribute(ALTERNATE_LAST_MODIFIED, lastModifiedDate); } else if (attrID.equals(NAME)) { String name = getName(); if (name == null) return null; return new BasicAttribute(NAME, name); } else if (attrID.equals(TYPE)) { String resourceType = getResourceType(); if (resourceType == null) return null; return new BasicAttribute(TYPE, resourceType); } else if (attrID.equals(ALTERNATE_TYPE)) { String resourceType = getResourceType(); if (resourceType == null) return null; return new BasicAttribute(ALTERNATE_TYPE, resourceType); } else if (attrID.equals(CONTENT_LENGTH)) { long contentLength = getContentLength(); if (contentLength < 0) return null; return new BasicAttribute(CONTENT_LENGTH, new Long(contentLength)); } else if (attrID.equals(ALTERNATE_CONTENT_LENGTH)) { long contentLength = getContentLength(); if (contentLength < 0) return null; return new BasicAttribute(ALTERNATE_CONTENT_LENGTH, new Long(contentLength)); } else if (attrID.equals(ETAG)) { String etag = getETag(); if (etag == null) return null; return new BasicAttribute(ETAG, etag); } else if (attrID.equals(ALTERNATE_ETAG)) { String etag = getETag(); if (etag == null) return null; return new BasicAttribute(ALTERNATE_ETAG, etag); } } else { return attributes.get(attrID); } return null; } /** * Put attribute. */ public Attribute put(Attribute attribute) { if (attributes == null) { try { return put(attribute.getID(), attribute.get()); } catch (NamingException e) { return null; } } else { return attributes.put(attribute); } } /** * Put attribute. */ public Attribute put(String attrID, Object val) { if (attributes == null) { return null; // No reason to implement this } else { return attributes.put(attrID, val); } } /** * Remove attribute. */ public Attribute remove(String attrID) { if (attributes == null) { return null; // No reason to implement this } else { return attributes.remove(attrID); } } /** * Get all attributes. */ public NamingEnumeration getAll() { if (attributes == null) { Vector attributes = new Vector(); Date creationDate = getCreationDate(); if (creationDate != null) { attributes.addElement(new BasicAttribute (CREATION_DATE, creationDate)); attributes.addElement(new BasicAttribute (ALTERNATE_CREATION_DATE, creationDate)); } Date lastModifiedDate = getLastModifiedDate(); if (lastModifiedDate != null) { attributes.addElement(new BasicAttribute (LAST_MODIFIED, lastModifiedDate)); attributes.addElement(new BasicAttribute (ALTERNATE_LAST_MODIFIED, lastModifiedDate)); } String name = getName(); if (name != null) { attributes.addElement(new BasicAttribute(NAME, name)); } String resourceType = getResourceType(); if (resourceType != null) { attributes.addElement(new BasicAttribute(TYPE, resourceType)); attributes.addElement(new BasicAttribute(ALTERNATE_TYPE, resourceType)); } long contentLength = getContentLength(); if (contentLength >= 0) { Long contentLengthLong = new Long(contentLength); attributes.addElement(new BasicAttribute(CONTENT_LENGTH, contentLengthLong)); attributes.addElement(new BasicAttribute(ALTERNATE_CONTENT_LENGTH, contentLengthLong)); } String etag = getETag(); if (etag != null) { attributes.addElement(new BasicAttribute(ETAG, etag)); attributes.addElement(new BasicAttribute(ALTERNATE_ETAG, etag)); } return new RecyclableNamingEnumeration(attributes); } else { return attributes.getAll(); } } /** * Get all attribute IDs. */ public NamingEnumeration getIDs() { if (attributes == null) { Vector attributeIDs = new Vector(); Date creationDate = getCreationDate(); if (creationDate != null) { attributeIDs.addElement(CREATION_DATE); attributeIDs.addElement(ALTERNATE_CREATION_DATE); } Date lastModifiedDate = getLastModifiedDate(); if (lastModifiedDate != null) { attributeIDs.addElement(LAST_MODIFIED); attributeIDs.addElement(ALTERNATE_LAST_MODIFIED); } if (getName() != null) { attributeIDs.addElement(NAME); } String resourceType = getResourceType(); if (resourceType != null) { attributeIDs.addElement(TYPE); attributeIDs.addElement(ALTERNATE_TYPE); } long contentLength = getContentLength(); if (contentLength >= 0) { attributeIDs.addElement(CONTENT_LENGTH); attributeIDs.addElement(ALTERNATE_CONTENT_LENGTH); } String etag = getETag(); if (etag != null) { attributeIDs.addElement(ETAG); attributeIDs.addElement(ALTERNATE_ETAG); } return new RecyclableNamingEnumeration(attributeIDs); } else { return attributes.getIDs(); } } /** * Retrieves the number of attributes in the attribute set. */ public int size() { if (attributes == null) { int size = 0; if (getCreationDate() != null) size += 2; if (getLastModifiedDate() != null) size += 2; if (getName() != null) size++; if (getResourceType() != null) size += 2; if (getContentLength() >= 0) size += 2; if (getETag() != null) size += 2; return size; } else { return attributes.size(); } } /** * Clone the attributes object (WARNING: fake cloning). */ public Object clone() { return this; } /** * Case sensitivity. */ public boolean isCaseIgnored() { return false; } }
plumer/codana
tomcat_files/6.0.43/ResourceAttributes.java
Java
mit
29,406
/* * Generated by class-dump 3.3.4 (64 bit). * * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard. */ #import "SBLockScreenPluginTransition.h" @interface SBLockScreenAnimatedPluginTransition : SBLockScreenPluginTransition { } - (void)_finalizeAndClearPluginAnimationContext; - (void)beginTransition; @end
matthewsot/CocoaSharp
Headers/SpringBoard/SBLockScreenAnimatedPluginTransition.h
C
mit
349
'use strict'; module.exports = { singleQuote: true, printWidth: 120, };
kaliber5/ember-bootstrap
.prettierrc.js
JavaScript
mit
77
<?php /* @name Metabox Class @package GPanel WordPress Framework @since 3.0.0 @author Pavel RICHTER <[email protected]> @copyright Copyright (c) 2013, Grand Pixels */ // Prevent loading this file directly defined('ABSPATH') || exit; /* ==================================================================================================== Metabox Class ==================================================================================================== */ if (!class_exists('gp_Metabox')) { class gp_Metabox { var $meta_box; var $fields; var $types; var $validation; // Metabox Construct function __construct($meta_box) { if (!is_admin()) { return; } $this->meta_box = self::normalize( $meta_box ); $this->fields = &$this->meta_box['fields']; $this->validation = &$this->meta_box['validation']; add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts')); foreach ($this->fields as $field) { $class = self::get_class_name($field); if (method_exists($class, 'add_actions')) { call_user_func(array($class, 'add_actions')); } } foreach ($this->meta_box['pages'] as $page) { add_action("add_meta_boxes_{$page}", array($this, 'add_meta_boxes')); } add_action('save_post', array($this, 'save_post')); } // _construct end function admin_enqueue_scripts() { $screen = get_current_screen(); if ('post' != $screen->base || !in_array($screen->post_type, $this->meta_box['pages'])) { return; } $has_clone = false; foreach ($this->fields as $field) { if ($field['clone']) { $has_clone = true; } $class = self::get_class_name($field); if (method_exists($class, 'admin_enqueue_scripts')) { call_user_func(array($class, 'admin_enqueue_scripts')); } } if ($has_clone) { wp_enqueue_script('gp-clone', trailingslashit(get_template_directory_uri()) . 'backend/javascripts/jquery.clone.js', array('jquery'), GP_VERSION, true); } if ($this->validation) { wp_enqueue_script('gp-validate-jquery', trailingslashit(get_template_directory_uri()) . 'backend/javascripts/jquery.validate.min.js', array('jquery'), GP_VERSION, true); wp_enqueue_script('gp-validate', trailingslashit(get_template_directory_uri()) . 'backend/javascripts/jquery.validate.js', array('gp-validate-jquery'), GP_VERSION, true); } } // Metabox Add function add_meta_boxes() { foreach ($this->meta_box['pages'] as $page) { $show = true; $show = apply_filters('gp_show', $show, $this->meta_box); $show = apply_filters("gp_show_{$this->meta_box['id']}", $show, $this->meta_box); if (!$show) { continue; } add_meta_box( $this->meta_box['id'], $this->meta_box['title'], array($this, 'show'), $page, $this->meta_box['context'], $this->meta_box['priority'] ); } } // Metabox Render public function show() { global $post; $saved = self::has_been_saved($post->ID, $this->fields); wp_nonce_field("gp-save-{$this->meta_box['id']}", "nonce_{$this->meta_box['id']}"); do_action('gp_before'); do_action("gp_before_{$this->meta_box['id']}"); foreach ($this->fields as $field) { $group = ''; $type = $field['type']; $id = $field['id']; $meta = self::apply_field_class_filters($field, 'meta', '', $post->ID, $saved); $meta = apply_filters("gp_{$type}_meta", $meta); $meta = apply_filters("gp_{$id}_meta", $meta); $begin = self::apply_field_class_filters($field, 'begin_html', '', $meta); $begin = apply_filters('gp_begin_html', $begin, $field, $meta); $begin = apply_filters("gp_{$type}_begin_html", $begin, $field, $meta); $begin = apply_filters("gp_{$id}_begin_html", $begin, $field, $meta); if ($field['clone']) { if (isset( $field['clone-group'])) { $group = " clone-group='{$field['clone-group']}'"; } $meta = (array) $meta; $field_html = ''; foreach ($meta as $index => $meta_data) { $sub_field = $field; $sub_field['field_name'] = $field['field_name'] . "[{$index}]"; if ($field['multiple']) { $sub_field['field_name'] .= '[]'; } add_filter("gp_{$id}_html", array($this, 'add_clone_buttons'), 10, 3); $input_html = '<div class="gp-clone clearfix">'; $input_html .= self::apply_field_class_filters($sub_field, 'html', '', $meta_data); $input_html = apply_filters("gp_{$type}_html", $input_html, $field, $meta_data); $input_html = apply_filters("gp_{$id}_html", $input_html, $field, $meta_data); $input_html .= '</div>'; $field_html .= $input_html; } } else { $field_html = self::apply_field_class_filters($field, 'html', '', $meta); $field_html = apply_filters("gp_{$type}_html", $field_html, $field, $meta); $field_html = apply_filters("gp_{$id}_html", $field_html, $field, $meta); } $end = self::apply_field_class_filters($field, 'end_html', '', $meta); $end = apply_filters('gp_end_html', $end, $field, $meta); $end = apply_filters("gp_{$type}_end_html", $end, $field, $meta); $end = apply_filters("gp_{$id}_end_html", $end, $field, $meta); $html = apply_filters("gp_{$type}_wrapper_html", "{$begin}{$field_html}{$end}", $field, $meta); $html = apply_filters("gp_{$id}_wrapper_html", $html, $field, $meta); $classes = array('gp-block', "gp-{$field['type']}-wrapper", 'clearfix'); if ('hidden' === $field['type']) { $classes[] = 'hidden'; } if (!empty( $field['required'])) { $classes[] = 'required'; } if (!empty( $field['class'])) { $classes[] = $field['class']; } printf( '<div class="%s"%s>%s</div>', implode(' ', $classes), $group, $html ); } if (isset($this->validation) && $this->validation) { echo ' <script type="text/javascript"> if (typeof gp == "undefined") { var gp = { validationOptions : jQuery.parseJSON(\'' . json_encode($this->validation) . '\'), summaryMessage : "' . __('Please correct the errors highlighted below and try again.', 'gp') . '" }; } else { var tempOptions = jQuery.parseJSON(\'' . json_encode($this->validation) . '\'); jQuery.extend(true, gp.validationOptions, tempOptions); }; </script> '; } do_action('gp_after'); do_action("gp_after_{$this->meta_box['id']}"); } static function begin_html($html, $meta, $field) { if (empty($field['name'])) { return '<div class="gp-input">'; } return sprintf( '<div class="gp-label"> <label for="%s">%s</label> </div> <div class="gp-field">', $field['id'], $field['name'] ); } static function end_html($html, $meta, $field) { $id = $field['id']; $button = ''; if ($field['clone']) { $button = '<a href="#" class="gp-button-primary add-clone">' . __('+', 'gp') . '</a>'; } $desc = !empty($field['desc']) ? "<p id='{$id}_description' class='description'>{$field['desc']}</p>" : ''; $html = "{$button}{$desc}</div>"; return $html; } static function add_clone_buttons($html, $field, $meta_data) { $button = '<a href="#" class="gp-button-secondary remove-clone">' . __('&#8211;', 'gp') . '</a>'; return "{$html}{$button}"; } static function meta($meta, $post_id, $saved, $field) { $meta = get_post_meta( $post_id, $field['id'], !$field['multiple']); $meta = (!$saved && '' === $meta || array() === $meta) ? $field['std'] : $meta; if ('wysiwyg' !== $field['type']) { $meta = is_array($meta) ? array_map('esc_attr', $meta) : esc_attr($meta); } return $meta; } function save_post($post_id) { $post_type = null; $post = get_post($post_id); if ($post) { $post_type = $post->post_type; } else if (isset($_POST['post_type']) && post_type_exists($_POST['post_type'])) { $post_type = $_POST['post_type']; } $post_type_object = get_post_type_object($post_type); if ((defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) || ( !isset($_POST['post_ID']) || $post_id != $_POST['post_ID']) || (!in_array($post_type, $this->meta_box['pages'])) || ( !current_user_can($post_type_object->cap->edit_post, $post_id))) { return $post_id; } // Verify check_admin_referer("gp-save-{$this->meta_box['id']}", "nonce_{$this->meta_box['id']}"); foreach ($this->fields as $field) { $name = $field['id']; $old = get_post_meta($post_id, $name, !$field['multiple']); $new = isset($_POST[$name]) ? $_POST[$name] : ($field['multiple'] ? array() : ''); $new = self::apply_field_class_filters($field, 'value', $new, $old, $post_id); $new = apply_filters("gp_{$field['type']}_value", $new, $field, $old); $new = apply_filters("gp_{$name}_value", $new, $field, $old); self::do_field_class_actions($field, 'save', $new, $old, $post_id); } } static function save($new, $old, $post_id, $field) { $name = $field['id']; if ('' === $new || array() === $new) { delete_post_meta($post_id, $name); return; } if ($field['multiple']) { foreach ($new as $new_value) { if (!in_array($new_value, $old)) { add_post_meta($post_id, $name, $new_value, false); } } foreach ($old as $old_value) { if (!in_array( $old_value, $new)) { delete_post_meta($post_id, $name, $old_value); } } } else { update_post_meta($post_id, $name, $new); } } static function normalize($meta_box) { $meta_box = wp_parse_args( $meta_box, array( 'id' => sanitize_title($meta_box['title']), 'context' => 'normal', 'priority' => 'high', 'pages' => array('post') ) ); foreach ($meta_box['fields'] as &$field) { $field = wp_parse_args($field, array( 'multiple' => false, 'clone' => false, 'std' => '', 'desc' => '', 'format' => '', )); $field = self::apply_field_class_filters($field, 'normalize_field', $field); if (!isset($field['field_name'])) { $field['field_name'] = $field['id']; } } return $meta_box; } static function get_class_name($field) { $type = ucwords($field['type']); $class = "gp_Metabox_{$type}"; if (class_exists($class)) { return $class; } return false; } static function apply_field_class_filters($field, $method_name, $value) { $args = array_slice(func_get_args(), 2); $args[] = $field; $class = self::get_class_name($field); if (method_exists($class, $method_name)) { $value = call_user_func_array(array($class, $method_name), $args); } else if ( method_exists(__CLASS__, $method_name)) { $value = call_user_func_array(array(__CLASS__, $method_name), $args); } return $value; } static function do_field_class_actions($field, $method_name) { $args = array_slice(func_get_args(), 2); $args[] = $field; $class = self::get_class_name($field); if (method_exists($class, $method_name)) { call_user_func_array(array($class, $method_name), $args); } else if (method_exists(__CLASS__, $method_name)) { call_user_func_array(array(__CLASS__, $method_name), $args); } } static function ajax_response($message, $status) { $response = array('what' => 'meta-box'); $response['data'] = 'error' === $status ? new WP_Error('error', $message) : $message; $x = new WP_Ajax_Response($response); $x->send(); } static function has_been_saved($post_id, $fields) { $saved = false; foreach ($fields as $field) { if (get_post_meta($post_id, $field['id'], !$field['multiple'])) { $saved = true; break; } } return $saved; } } }
tiffanytse/breadbyus-wordpress
linguini/backend/classes/class-metabox.php
PHP
mit
12,438
import Editor from 'tinymce/core/api/Editor'; import { EditorOptions } from 'tinymce/core/api/OptionTypes'; const option: { <K extends keyof EditorOptions>(name: K): (editor: Editor) => EditorOptions[K] | undefined; <T>(name: string): (editor: Editor) => T | undefined; } = (name: string) => (editor: Editor) => editor.options.get(name); const register = (editor: Editor): void => { const registerOption = editor.options.register; registerOption('allow_html_in_named_anchor', { processor: 'boolean', default: false }); }; const allowHtmlInNamedAnchor = option<boolean>('allow_html_in_named_anchor'); export { register, allowHtmlInNamedAnchor };
tinymce/tinymce
modules/tinymce/src/plugins/anchor/main/ts/api/Options.ts
TypeScript
mit
674
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('library', '0004_auto_20160825_1001'), ] operations = [ migrations.AlterModelOptions( name='car', options={'ordering': ['name'], 'verbose_name': 'Car Setup'}, ), migrations.AddField( model_name='car', name='fixed_setup', field=models.TextField(help_text=b'Store a fixed setup here if you wish; the contents can be copied from "Documents\\Assetto Corsa\\setups\\<car>\\<track>\\<setup-name>.ini", and pasted here. If you check the "fixed setup" option in your Preset\'s Entries - this fixed setup is applied', null=True, blank=True), ), ]
PeteTheAutomator/ACServerManager
library/migrations/0005_auto_20160828_1046.py
Python
mit
822
using System; using System.Collections.Generic; using System.Web.Mvc; using BtsPortal.Entities.Bts; using PagedList; namespace BtsPortal.Web.ViewModels.Bts { public class BtsSearchRequestResponse { public BtsSearchRequestResponse() { Responses = new List<BtsInstance>(); } public BtsSearchRequest Request { get; set; } public List<BtsInstance> Responses { get; set; } public int? PageSize { get; set; } public int? Page { get; set; } public int? TotalRows { get; set; } public string Error { get; set; } public IPagedList<BtsInstance> PagedResponses { get { return new StaticPagedList<BtsInstance>(Responses, Page.GetValueOrDefault(1), PageSize.GetValueOrDefault(1), TotalRows.GetValueOrDefault(0)); } } } public class BtsSearchRequest { public BtsSearchRequest() { ArtifactIds = new List<SelectListItem>(); Applications = new List<SelectListItem>(); } public bool Init { get; set; } public BtsArtifactType? ArtifactType { get; set; } public Guid? ArtifactId { get; set; } public List<SelectListItem> ArtifactIds { get; set; } public BtsInstanceStatus Status { get; set; } public int Application { get; set; } public List<SelectListItem> Applications { get; set; } public DateTime? DateCreatedFrom { get; set; } public DateTime? DateCreatedTo { get; set; } } }
nishantnepal/BtsPortal
BtsPortal.Web/ViewModels/Bts/BtsSearch.cs
C#
mit
1,575
package strings import ( "reflect" "testing" ) func TestInt32(t *testing.T) { i := []int32{1, 2, 3} s := JoinInt32s(i, ",") ii, _ := SplitInt32s(s, ",") if !reflect.DeepEqual(i, ii) { t.FailNow() } } func TestInt64(t *testing.T) { i := []int64{1, 2, 3} s := JoinInt64s(i, ",") ii, _ := SplitInt64s(s, ",") if !reflect.DeepEqual(i, ii) { t.FailNow() } }
Terry-Mao/goim
pkg/strings/ints_test.go
GO
mit
372
<?php declare(strict_types = 1); namespace Domain\Specification\Reference; use Domain\Entity\Reference as Entity; use Innmind\Specification\Specification as ParentSpec; interface Specification extends ParentSpec { public function isSatisfiedBy(Entity $reference): bool; }
Innmind/API
src/Domain/Specification/Reference/Specification.php
PHP
mit
279
--- layout: page permalink: /lagda/Cubical.Data.Int.html inline_latex: true agda: true --- <body> {% raw %} <pre class="Agda"> <a id="1" class="Symbol">{-#</a> <a id="5" class="Keyword">OPTIONS</a> <a id="13" class="Pragma">--cubical</a> <a id="23" class="Pragma">--no-import-sorts</a> <a id="41" class="Pragma">--safe</a> <a id="48" class="Symbol">#-}</a> <a id="52" class="Keyword">module</a> <a id="59" href="Cubical.Data.Int.html" class="Module">Cubical.Data.Int</a> <a id="76" class="Keyword">where</a> <a id="83" class="Keyword">open</a> <a id="88" class="Keyword">import</a> <a id="95" href="Cubical.Data.Int.Base.html" class="Module">Cubical.Data.Int.Base</a> <a id="117" class="Keyword">public</a> <a id="125" class="Keyword">open</a> <a id="130" class="Keyword">import</a> <a id="137" href="Cubical.Data.Int.Properties.html" class="Module">Cubical.Data.Int.Properties</a> <a id="165" class="Keyword">public</a> </pre> {% endraw %} </body>
ice1000/ice1000.github.io
assets/lagda/Cubical.Data.Int.md
Markdown
mit
951
<?php require_once '_header.mandatory.php' ?> <?php $config->about = $database->select("tb_about", "*"); $config->about = $config->about[0]; // Meddo put lots of \ in the HTML. Let's remove them. $config->about['site_welcome'] = str_replace(array('\\'),'',$config->about['site_welcome']); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="<?= $config->about['site_meta_description'] ?>" /> <meta name="keywords" content="<?= $config->about['site_meta_keywords'] ?>" /> <title><?= $config->about['site_longname'] ?></title> <link rel="stylesheet" type="text/css" href="jquery-ui/jquery-ui.css"> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css"> <link rel="stylesheet" type="text/css" href="css/custom.css"> <script src="jquery-ui/external/jquery/jquery.js"></script> <script src="jquery-ui/jquery-ui.js"></script> </head> <body> <nav class="navbar navbar-default navbar-static-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="aboutShow.php"><span class="glyphicon glyphicon-book"> <?= $config->about['site_shortname'] ?></span></a> </div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav"> <?= strpos($_SERVER["REQUEST_URI"], 'bookSearch.php') ? "<li class='active'>" : "<li>" ?> <a href="bookSearch.php"><?= $t->__('menu.search_book') ?></a> </li> <?php if ($fmw->isLoggedInOperator()) { ?> <?= strpos($_SERVER["REQUEST_URI"], 'personSearch.php') ? "<li class='active'>" : "<li>" ?> <a href="personSearch.php"><?= $t->__('menu.search_people') ?></a> </li> <?= strpos($_SERVER["REQUEST_URI"], 'reportBookLended.php') ? "<li class='active'>" : "<li>" ?> <a href="reportBookLended.php"><?= $t->__('menu.lent_book') ?></a> </li> <?php } ?> <?php if ($fmw->isLoggedInAdmin() || $fmw->isLoggedInOperator()) { $url = $_SERVER["REQUEST_URI"]; $adminActive = false; $adminActive = $adminActive || strpos($url, 'userList.php'); $adminActive = $adminActive || strpos($url, 'bookCategoryList.php'); $adminActive = $adminActive || strpos($url, 'bookTypeList.php'); $adminActive = $adminActive || strpos($url, 'bookLanguageList.php'); $adminActive = $adminActive || strpos($url, 'bookCoverSearch.php'); $adminActive = $adminActive || strpos($url, 'reportStatistics.php'); ?> <li class="dropdown <?= $adminActive ? "active" : "" ?>"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> <?= $t->__('menu.admin') ?> <span class="caret"></span> </a> <ul class="dropdown-menu" role="menu"> <?php if ($fmw->isLoggedInAdmin()) { ?> <?= strpos($_SERVER["REQUEST_URI"], 'about.php') ? "<li class='active'>" : "<li>" ?> <a href="about.php"><?= $t->__('menu.admin.about') ?></a> </li> <?= strpos($_SERVER["REQUEST_URI"], 'userList.php') ? "<li class='active'>" : "<li>" ?> <a href="userList.php"><?= $t->__('menu.admin.userList') ?></a> </li> <?php } ?> <?= strpos($_SERVER["REQUEST_URI"], 'bookCategoryList.php') ? "<li class='active'>" : "<li>" ?> <a href="bookCategoryList.php"><?= $t->__('menu.admin.bookCategory') ?></a> </li> <?= strpos($_SERVER["REQUEST_URI"], 'bookTypeList.php') ? "<li class='active'>" : "<li>" ?> <a href="bookTypeList.php"><?= $t->__('menu.admin.bookType') ?></a> </li> <?= strpos($_SERVER["REQUEST_URI"], 'bookLanguageList.php') ? "<li class='active'>" : "<li>" ?> <a href="bookLanguageList.php"><?= $t->__('menu.admin.bookLanguage') ?></a> </li> <?= strpos($_SERVER["REQUEST_URI"], 'bookCoverSearch.php') ? "<li class='active'>" : "<li>" ?> <a href="bookCoverSearch.php"><?= $t->__('menu.admin.bookCover') ?></a> </li> <?= strpos($_SERVER["REQUEST_URI"], 'auditSearch.php') ? "<li class='active'>" : "<li>" ?> <a href="auditSearch.php"><?= $t->__('menu.admin.audit') ?></a> </li> <?= strpos($_SERVER["REQUEST_URI"], 'reportStatistics.php') ? "<li class='active'>" : "<li>" ?> <a href="reportStatistics.php"><?= $t->__('menu.admin.statistics') ?></a> </li> <?= strpos($_SERVER["REQUEST_URI"], 'backup.php') ? "<li class='active'>" : "<li>" ?> <a href="backup.php"><?= $t->__('menu.admin.backup') ?></a> </li> </ul> </li> <?php } ?> <?php if (!$fmw->isLoggedIn()) { ?> <li> <a href="login.php"><?= $t->__('menu.login') ?></a> </li> <?php } else { ?> <li> <a href="logout.php"><?= $t->__('menu.logout') ?></a> </li> <?php } ?> </ul> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> <span class="glyphicon glyphicon-globe"></span> </a> <ul class="dropdown-menu" role="menu"> <?php // Getting all possible languages $possible_languages = array_diff(scandir('lang'), array('..', '.')); foreach($possible_languages as $language) { $language = substr($language, 0, strpos($language, '.')); echo "<li>", "<a href='' onClick=\"javascript:_changeLanguage('", $language ,"')\">", $language, "</a></li>"; } ?> </ul> </li> </ul> </div> </div> </nav> <?php $message = $_SESSION['message']; if ($message != '') {?> <div class="alert alert-warning"> <a href="#" class="close" data-dismiss="alert">&times;</a> <?= $fmw->escapeHtml($message) ?> </div> <?php } ?> <?php $message = $_SESSION['error_message']; if ($message != '') {?> <div class="alert alert-danger" role="alert"> <a href="#" class="close" data-dismiss="alert">&times;</a> <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> <span class="sr-only">Error:</span> <?= $fmw->escapeHtml($message) ?> </div> <?php } ?>
easybiblio/easybiblio
server/_header.php
PHP
mit
7,358
module SecretEnv VERSION = "0.7.0" end
adorechic/secret_env
lib/secret_env/version.rb
Ruby
mit
41
package forklift.integration; import static org.junit.Assert.assertTrue; import forklift.connectors.ConnectorException; import forklift.connectors.ForkliftConnectorI; import forklift.consumer.Consumer; import forklift.decorators.OnMessage; import forklift.decorators.Producer; import forklift.decorators.Queue; import forklift.exception.StartupException; import forklift.integration.server.TestServiceManager; import forklift.producers.ForkliftProducerI; import forklift.producers.ProducerException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.atomic.AtomicInteger; /** * Created by afrieze on 3/14/17. */ public class ObjectMessageTests { private static final Logger log = LoggerFactory.getLogger(RebalanceTests.class); private static AtomicInteger called = new AtomicInteger(0); private static boolean isInjectNull = true; TestServiceManager serviceManager; @After public void after() { serviceManager.stop(); } @Before public void setup() { serviceManager = new TestServiceManager(); serviceManager.start(); called.set(0); isInjectNull = true; } @Test public void testSendObjectMessage() throws ConnectorException, ProducerException, StartupException { ForkliftConnectorI connector = serviceManager.newManagedForkliftInstance().getConnector(); int msgCount = 10; ForkliftProducerI producer = connector.getQueueProducer("forklift-object-topic"); for (int i = 0; i < msgCount; i++) { final TestMessage m = new TestMessage(new String("x=producer object send test"), i); producer.send(m); } final Consumer c = new Consumer(ForkliftObjectConsumer.class, connector); // Shutdown the consumer after all the messages have been processed. c.setOutOfMessages((listener) -> { listener.shutdown(); assertTrue("called was not == " + msgCount, called.get() == msgCount); }); // Start the consumer. c.listen(); assertTrue(called.get() == msgCount); } @Queue("forklift-object-topic") public static class ForkliftObjectConsumer { @forklift.decorators.Message private TestMessage testMessage; @Producer(queue = "forklift-string-topic") private ForkliftProducerI injectedProducer; @OnMessage public void onMessage() { if (testMessage == null || testMessage.getText() == null) { return; } int i = called.getAndIncrement(); System.out.println(Thread.currentThread().getName() + testMessage.getText()); isInjectNull = injectedProducer != null ? false : true; } } }
dcshock/forklift-kafka
connectors/kafka/src/test/java/forklift/integration/ObjectMessageTests.java
Java
mit
2,903
package es.um.nosql.s13e.nosqlimport.util; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; public class MapReduceSources { private String mapJSCode; private String reduceJSCode; public MapReduceSources(String mapReduceDir) { try { Path _dir = new File(mapReduceDir).toPath(); // Read the map file Path mapFile = _dir.resolve("map.js"); mapJSCode = new String(Files.readAllBytes(mapFile)); // Read the reduce file Path reduceFile = _dir.resolve("reduce.js"); reduceJSCode = new String(Files.readAllBytes(reduceFile)); } catch(Exception e) { throw new IllegalArgumentException("MapReduce could not be found in " + mapReduceDir); } } public String getMapJSCode() { return mapJSCode; } public String getReduceJSCode() { return reduceJSCode; } }
catedrasaes-umu/NoSQLDataEngineering
projects/es.um.nosql.s13e.nosqlimport/src/es/um/nosql/s13e/nosqlimport/util/MapReduceSources.java
Java
mit
875
MIT License Copyright (c) 2017 Shivraj Nesargi, Fiona Sequeira Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
shivarajnesargi/BotOrNot
LICENSE.md
Markdown
mit
1,089
class AddToContainerType < ActiveRecord::Migration def change add_column :container_types, :label, :string end end
dimitras/collos
db/migrate/20131127213130_add_to_container_type.rb
Ruby
mit
119
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>33 Imágenes · The Plain</title> <meta name="twitter:card" content="summary" /> <meta name="twitter:site" content="@" /> <meta name="twitter:title" content="33 Imágenes" /> <meta name="twitter:description" content="Para incrustar imágenes en los documentos lo haremos así:"> <meta name="description" content="Para incrustar imágenes en los documentos lo haremos así:"> <link rel="icon" href="/emacs/assets/favicon.png"> <link rel="apple-touch-icon" href="/emacs/assets/touch-icon.png"> <link rel="stylesheet" href="/emacs/assets/core.css"> <link rel="canonical" href="/emacs/notes/images"> <link rel="alternate" type="application/atom+xml" title="The Plain" href="/emacs/feed.xml" /> <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> </head> <body> <aside class="logo"> <a href="/emacs/"> <!-- <img src="http://www.gravatar.com/avatar/.png?s=80" class="gravatar"> --> <img src="https://www.gnu.org/software/emacs/images/emacs.png"> </a> <span class="logo-prompt">Back to Home</span> </aside> <main> <article> <div class="center"> <h1>33 Imágenes</h1> <time>May 13, 2017</time> </div> <div class="divider"></div> <p>Para incrustar imágenes en los documentos lo haremos así:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>./image/emacs.png </code></pre></div></div> <p>Deberemos crear un directorio llamado <code class="language-plaintext highlighter-rouge">image</code> un nivel por debajo y una imagen llamada <code class="language-plaintext highlighter-rouge">emacs.png</code></p> </article> <div class="page-navigation"> <a class="next" href="/emacs/notes/notas" title="NEXT: 34 Imprimir subárbol">&lt;&lt;</a> <span> &middot; </span> <a class="home" href="/emacs/" title="Back to Homepage">Home</a> <span> &middot; </span> <a class="prev" href="/emacs/notes/bullets" title="PREV: 32 Bullets">&gt;&gt;</a> </div> </main> <div class="footer"> <span class="block">&lt;/&gt; <a href="http://github.com/heiswayi/the-plain" title="a minimalist Jekyll theme for personal blog">The Plain theme</a> by <a href="http://heiswayi.github.io">Heiswayi Nrird</a>.</span> <span class="block">&copy; 2020 Alfons Rovira</span> </div> </body> </html>
inclusa/emacs
_site/notes/images.html
HTML
mit
2,592
// // MBStoryboardLinkModalSegue.h // MBStoryboardLink // // Created by Markus on 29.11.13. // Copyright (c) 2013 Markus. All rights reserved. // #import <Foundation/Foundation.h> #import "MBStoryboardLinkSegue.h" @interface MBStoryboardLinkModalSegue : MBStoryboardLinkSegue @end
MBulli/MBStoryboardLink
MBStoryboardLinkModalSegue.h
C
mit
289
.fc{direction:ltr;text-align:left;} .fc table{border-collapse:collapse;border-spacing:0;} html .fc, .fc table{font-size:1em;} .fc td, .fc th{padding:0;vertical-align:top;} .fc-header td{white-space:nowrap;} .fc-header-left{width:25%;text-align:left;} .fc-header-center{text-align:center;} .fc-header-right{width:25%;text-align:right;} .fc-header-title{display:inline-block;vertical-align:top;} .fc-header-title h2{margin-top:0;white-space:nowrap;} .fc .fc-header-space{padding-left:10px;} .fc-header .fc-button{margin-bottom:1em;vertical-align:top;} .fc-header .fc-button{margin-right:-1px;} .fc-header .fc-corner-right{margin-right:1px;} .fc-header .ui-corner-right{margin-right:0;} .fc-header .fc-state-hover, .fc-header .ui-state-hover{z-index:2;} .fc-header .fc-state-down{z-index:3;} .fc-header .fc-state-active, .fc-header .ui-state-active{z-index:4;} .fc-content{clear:both;} .fc-view{width:100%;overflow:hidden;} .fc-widget-header, .fc-widget-content{border:1px solid #ccc;} .fc-state-highlight{background:#ffc;} .fc-cell-overlay{background:#9cf;opacity:.2;filter:alpha(opacity=20);} .fc-button{position:relative;display:inline-block;cursor:pointer;} .fc-state-default{border-style:solid;border-width:1px 0;} .fc-button-inner{position:relative;float:left;overflow:hidden;} .fc-state-default .fc-button-inner{border-style:solid;border-width:0 1px;} .fc-button-content{position:relative;float:left;height:1.9em;line-height:1.9em;padding:0 .6em;white-space:nowrap;} .fc-button-content .fc-icon-wrap{position:relative;float:left;top:50%;} .fc-button-content .ui-icon{position:relative;float:left;margin-top:-50%;*margin-top:0;*top:-50%;} .fc-state-default .fc-button-effect{position:absolute;top:50%;left:0;} .fc-state-default .fc-button-effect span{position:absolute;top:-100px;left:0;width:500px;height:100px;border-width:100px 0 0 1px;border-style:solid;border-color:#fff;background:#444;opacity:.09;filter:alpha(opacity=9);} .fc-state-default, .fc-state-default .fc-button-inner{border-style:solid;border-color:#ccc #bbb #aaa;background:#F3F3F3;color:#000;} .fc-state-hover, .fc-state-hover .fc-button-inner{border-color:#999;} .fc-state-down, .fc-state-down .fc-button-inner{border-color:#555;background:#777;} .fc-state-active, .fc-state-active .fc-button-inner{border-color:#555;background:#777;color:#fff;} .fc-state-disabled, .fc-state-disabled .fc-button-inner{color:#999;border-color:#ddd;} .fc-state-disabled{cursor:default;} .fc-state-disabled .fc-button-effect{display:none;} .fc-event{border-style:solid;border-width:0;font-size:.85em;cursor:default;} a.fc-event, .fc-event-draggable{cursor:pointer;} a.fc-event{text-decoration:none;} .fc-rtl .fc-event{text-align:right;} .fc-event-skin{border-color:#36c;background-color:#36c;color:#fff;} .fc-event-inner{position:relative;width:100%;height:100%;border-style:solid;border-width:0;overflow:hidden;} .fc-event-time, .fc-event-title{padding:0 1px;} .fc .ui-resizable-handle{display:block;position:absolute;z-index:99999;overflow:hidden;font-size:300%;line-height:50%;} .fc-event-hori{border-width:1px 0;margin-bottom:1px;} .fc-event-hori .ui-resizable-e{top:0 !important;right:-3px !important;width:7px !important;height:100% !important;cursor:e-resize;} .fc-event-hori .ui-resizable-w{top:0 !important;left:-3px !important;width:7px !important;height:100% !important;cursor:w-resize;} .fc-event-hori .ui-resizable-handle{_padding-bottom:14px;} .fc-corner-left{margin-left:1px;} .fc-corner-left .fc-button-inner, .fc-corner-left .fc-event-inner{margin-left:-1px;} .fc-corner-right{margin-right:1px;} .fc-corner-right .fc-button-inner, .fc-corner-right .fc-event-inner{margin-right:-1px;} .fc-corner-top{margin-top:1px;} .fc-corner-top .fc-event-inner{margin-top:-1px;} .fc-corner-bottom{margin-bottom:1px;} .fc-corner-bottom .fc-event-inner{margin-bottom:-1px;} .fc-corner-left .fc-event-inner{border-left-width:1px;} .fc-corner-right .fc-event-inner{border-right-width:1px;} .fc-corner-top .fc-event-inner{border-top-width:1px;} .fc-corner-bottom .fc-event-inner{border-bottom-width:1px;} table.fc-border-separate{border-collapse:separate;} .fc-border-separate th, .fc-border-separate td{border-width:1px 0 0 1px;} .fc-border-separate th.fc-last, .fc-border-separate td.fc-last{border-right-width:1px;} .fc-border-separate tr.fc-last th, .fc-border-separate tr.fc-last td{border-bottom-width:1px;} .fc-border-separate tbody tr.fc-first td, .fc-border-separate tbody tr.fc-first th{border-top-width:0;} .fc-grid th{text-align:center;} .fc-grid .fc-day-number{float:right;padding:0 2px;} .fc-grid .fc-other-month .fc-day-number{opacity:0.3;filter:alpha(opacity=30);} .fc-grid .fc-day-content{clear:both;padding:2px 2px 1px;} .fc-grid .fc-event-time{font-weight:bold;} .fc-rtl .fc-grid .fc-day-number{float:left;} .fc-rtl .fc-grid .fc-event-time{float:right;} .fc-agenda table{border-collapse:separate;} .fc-agenda-days th{text-align:center;} .fc-agenda .fc-agenda-axis{width:50px;padding:0 4px;vertical-align:middle;text-align:right;white-space:nowrap;font-weight:normal;} .fc-agenda .fc-day-content{padding:2px 2px 1px;} .fc-agenda-days .fc-agenda-axis{border-right-width:1px;} .fc-agenda-days .fc-col0{border-left-width:0;} .fc-agenda-allday th{border-width:0 1px;} .fc-agenda-allday .fc-day-content{min-height:34px;_height:34px;} .fc-agenda-divider-inner{height:2px;overflow:hidden;} .fc-widget-header .fc-agenda-divider-inner{background:#eee;} .fc-agenda-slots th{border-width:1px 1px 0;} .fc-agenda-slots td{border-width:1px 0 0;background:none;} .fc-agenda-slots td div{height:20px;} .fc-agenda-slots tr.fc-slot0 th, .fc-agenda-slots tr.fc-slot0 td{border-top-width:0;} .fc-agenda-slots tr.fc-minor th, .fc-agenda-slots tr.fc-minor td{border-top-style:dotted;} .fc-agenda-slots tr.fc-minor th.ui-widget-header{*border-top-style:solid;} .fc-event-vert{border-width:0 1px;} .fc-event-vert .fc-event-head, .fc-event-vert .fc-event-content{position:relative;z-index:2;width:100%;overflow:hidden;} .fc-event-vert .fc-event-time{white-space:nowrap;font-size:10px;} .fc-event-vert .fc-event-bg{position:absolute;z-index:1;top:0;left:0;width:100%;height:100%;background:#fff;opacity:.3;filter:alpha(opacity=30);} .fc .ui-draggable-dragging .fc-event-bg, .fc-select-helper .fc-event-bg{display:none\9;} .fc-event-vert .ui-resizable-s{bottom:0 !important;width:100% !important;height:8px !important;overflow:hidden !important;line-height:8px !important;font-size:11px !important;font-family:monospace;text-align:center;cursor:s-resize;} .fc-agenda .ui-resizable-resizing{_overflow:hidden;}
adamvduke/phillytechcalendar
public/css/fullcalendar.min.css
CSS
mit
6,551
// ******************************************************************************************************** // Product Name: DotSpatial.Compatibility.dll // Description: Supports DotSpatial interfaces organized for a MapWindow 4 plugin context. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 1/20/2009 1:42:49 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System.Drawing; using GeoAPI.Geometries; namespace DotSpatial.Compatibility { /// <summary> /// The <c>SelectedShape</c> interface is used to access information about a shape that is selected in the DotSpatial. /// </summary> public interface ISelectedShape { /// <summary> /// Returns the extents of this selected shape. /// </summary> Envelope Extents { get; } /// <summary> /// Returns the shape index of this selected shape. /// </summary> int ShapeIndex { get; } /// <summary> /// Initializes all information in the <c>SelectedShape</c> object then highlights the shape on the map. /// </summary> /// <param name="shapeIndex">Index of the shape in the shapefile.</param> /// <param name="selectColor">Color to use when highlighting the shape.</param> void Add(int shapeIndex, Color selectColor); } }
JasminMarinelli/DotSpatial
Source/DotSpatial.Compatibility/ISelectedShape.cs
C#
mit
2,174
/////////////////////////////////////////////////////////////// // This is generated code. ////////////////////////////////////////////////////////////// // Code is generated using LLBLGen Pro version: 4.2 // Code is generated on: // Code is generated using templates: SD.TemplateBindings.SharedTemplates // Templates vendor: Solutions Design. // Templates version: ////////////////////////////////////////////////////////////// using System; using System.ComponentModel; using System.Collections.Generic; #if !CF using System.Runtime.Serialization; #endif using System.Xml.Serialization; using AdventureWorks.Dal; using AdventureWorks.Dal.HelperClasses; using AdventureWorks.Dal.FactoryClasses; using AdventureWorks.Dal.RelationClasses; using SD.LLBLGen.Pro.ORMSupportClasses; namespace AdventureWorks.Dal.EntityClasses { // __LLBLGENPRO_USER_CODE_REGION_START AdditionalNamespaces // __LLBLGENPRO_USER_CODE_REGION_END /// <summary>Entity class which represents the entity 'WorkOrder'.<br/><br/></summary> [Serializable] public partial class WorkOrderEntity : CommonEntityBase // __LLBLGENPRO_USER_CODE_REGION_START AdditionalInterfaces // __LLBLGENPRO_USER_CODE_REGION_END { #region Class Member Declarations private EntityCollection<WorkOrderRoutingEntity> _workOrderRoutings; private EntityCollection<LocationEntity> _locationCollectionViaWorkOrderRouting; private ProductEntity _product; private ScrapReasonEntity _scrapReason; // __LLBLGENPRO_USER_CODE_REGION_START PrivateMembers // __LLBLGENPRO_USER_CODE_REGION_END #endregion #region Statics private static Dictionary<string, string> _customProperties; private static Dictionary<string, Dictionary<string, string>> _fieldsCustomProperties; /// <summary>All names of fields mapped onto a relation. Usable for in-memory filtering</summary> public static partial class MemberNames { /// <summary>Member name Product</summary> public static readonly string Product = "Product"; /// <summary>Member name ScrapReason</summary> public static readonly string ScrapReason = "ScrapReason"; /// <summary>Member name WorkOrderRoutings</summary> public static readonly string WorkOrderRoutings = "WorkOrderRoutings"; /// <summary>Member name LocationCollectionViaWorkOrderRouting</summary> public static readonly string LocationCollectionViaWorkOrderRouting = "LocationCollectionViaWorkOrderRouting"; } #endregion /// <summary> Static CTor for setting up custom property hashtables. Is executed before the first instance of this entity class or derived classes is constructed. </summary> static WorkOrderEntity() { SetupCustomPropertyHashtables(); } /// <summary> CTor</summary> public WorkOrderEntity():base("WorkOrderEntity") { InitClassEmpty(null, null); } /// <summary> CTor</summary> /// <remarks>For framework usage.</remarks> /// <param name="fields">Fields object to set as the fields for this entity.</param> public WorkOrderEntity(IEntityFields2 fields):base("WorkOrderEntity") { InitClassEmpty(null, fields); } /// <summary> CTor</summary> /// <param name="validator">The custom validator object for this WorkOrderEntity</param> public WorkOrderEntity(IValidator validator):base("WorkOrderEntity") { InitClassEmpty(validator, null); } /// <summary> CTor</summary> /// <param name="workOrderId">PK value for WorkOrder which data should be fetched into this WorkOrder object</param> /// <remarks>The entity is not fetched by this constructor. Use a DataAccessAdapter for that.</remarks> public WorkOrderEntity(System.Int32 workOrderId):base("WorkOrderEntity") { InitClassEmpty(null, null); this.WorkOrderId = workOrderId; } /// <summary> CTor</summary> /// <param name="workOrderId">PK value for WorkOrder which data should be fetched into this WorkOrder object</param> /// <param name="validator">The custom validator object for this WorkOrderEntity</param> /// <remarks>The entity is not fetched by this constructor. Use a DataAccessAdapter for that.</remarks> public WorkOrderEntity(System.Int32 workOrderId, IValidator validator):base("WorkOrderEntity") { InitClassEmpty(validator, null); this.WorkOrderId = workOrderId; } /// <summary> Protected CTor for deserialization</summary> /// <param name="info"></param> /// <param name="context"></param> [EditorBrowsable(EditorBrowsableState.Never)] protected WorkOrderEntity(SerializationInfo info, StreamingContext context) : base(info, context) { if(SerializationHelper.Optimization != SerializationOptimization.Fast) { _workOrderRoutings = (EntityCollection<WorkOrderRoutingEntity>)info.GetValue("_workOrderRoutings", typeof(EntityCollection<WorkOrderRoutingEntity>)); _locationCollectionViaWorkOrderRouting = (EntityCollection<LocationEntity>)info.GetValue("_locationCollectionViaWorkOrderRouting", typeof(EntityCollection<LocationEntity>)); _product = (ProductEntity)info.GetValue("_product", typeof(ProductEntity)); if(_product!=null) { _product.AfterSave+=new EventHandler(OnEntityAfterSave); } _scrapReason = (ScrapReasonEntity)info.GetValue("_scrapReason", typeof(ScrapReasonEntity)); if(_scrapReason!=null) { _scrapReason.AfterSave+=new EventHandler(OnEntityAfterSave); } this.FixupDeserialization(FieldInfoProviderSingleton.GetInstance()); } // __LLBLGENPRO_USER_CODE_REGION_START DeserializationConstructor // __LLBLGENPRO_USER_CODE_REGION_END } /// <summary>Performs the desync setup when an FK field has been changed. The entity referenced based on the FK field will be dereferenced and sync info will be removed.</summary> /// <param name="fieldIndex">The fieldindex.</param> protected override void PerformDesyncSetupFKFieldChange(int fieldIndex) { switch((WorkOrderFieldIndex)fieldIndex) { case WorkOrderFieldIndex.ProductId: DesetupSyncProduct(true, false); break; case WorkOrderFieldIndex.ScrapReasonId: DesetupSyncScrapReason(true, false); break; default: base.PerformDesyncSetupFKFieldChange(fieldIndex); break; } } /// <summary> Sets the related entity property to the entity specified. If the property is a collection, it will add the entity specified to that collection.</summary> /// <param name="propertyName">Name of the property.</param> /// <param name="entity">Entity to set as an related entity</param> /// <remarks>Used by prefetch path logic.</remarks> protected override void SetRelatedEntityProperty(string propertyName, IEntityCore entity) { switch(propertyName) { case "Product": this.Product = (ProductEntity)entity; break; case "ScrapReason": this.ScrapReason = (ScrapReasonEntity)entity; break; case "WorkOrderRoutings": this.WorkOrderRoutings.Add((WorkOrderRoutingEntity)entity); break; case "LocationCollectionViaWorkOrderRouting": this.LocationCollectionViaWorkOrderRouting.IsReadOnly = false; this.LocationCollectionViaWorkOrderRouting.Add((LocationEntity)entity); this.LocationCollectionViaWorkOrderRouting.IsReadOnly = true; break; default: this.OnSetRelatedEntityProperty(propertyName, entity); break; } } /// <summary>Gets the relation objects which represent the relation the fieldName specified is mapped on. </summary> /// <param name="fieldName">Name of the field mapped onto the relation of which the relation objects have to be obtained.</param> /// <returns>RelationCollection with relation object(s) which represent the relation the field is maped on</returns> protected override RelationCollection GetRelationsForFieldOfType(string fieldName) { return GetRelationsForField(fieldName); } /// <summary>Gets the relation objects which represent the relation the fieldName specified is mapped on. </summary> /// <param name="fieldName">Name of the field mapped onto the relation of which the relation objects have to be obtained.</param> /// <returns>RelationCollection with relation object(s) which represent the relation the field is maped on</returns> internal static RelationCollection GetRelationsForField(string fieldName) { RelationCollection toReturn = new RelationCollection(); switch(fieldName) { case "Product": toReturn.Add(Relations.ProductEntityUsingProductId); break; case "ScrapReason": toReturn.Add(Relations.ScrapReasonEntityUsingScrapReasonId); break; case "WorkOrderRoutings": toReturn.Add(Relations.WorkOrderRoutingEntityUsingWorkOrderId); break; case "LocationCollectionViaWorkOrderRouting": toReturn.Add(Relations.WorkOrderRoutingEntityUsingWorkOrderId, "WorkOrderEntity__", "WorkOrderRouting_", JoinHint.None); toReturn.Add(WorkOrderRoutingEntity.Relations.LocationEntityUsingLocationId, "WorkOrderRouting_", string.Empty, JoinHint.None); break; default: break; } return toReturn; } #if !CF /// <summary>Checks if the relation mapped by the property with the name specified is a one way / single sided relation. If the passed in name is null, it/ will return true if the entity has any single-sided relation</summary> /// <param name="propertyName">Name of the property which is mapped onto the relation to check, or null to check if the entity has any relation/ which is single sided</param> /// <returns>true if the relation is single sided / one way (so the opposite relation isn't present), false otherwise</returns> protected override bool CheckOneWayRelations(string propertyName) { int numberOfOneWayRelations = 0; switch(propertyName) { case null: return ((numberOfOneWayRelations > 0) || base.CheckOneWayRelations(null)); default: return base.CheckOneWayRelations(propertyName); } } #endif /// <summary> Sets the internal parameter related to the fieldname passed to the instance relatedEntity. </summary> /// <param name="relatedEntity">Instance to set as the related entity of type entityType</param> /// <param name="fieldName">Name of field mapped onto the relation which resolves in the instance relatedEntity</param> protected override void SetRelatedEntity(IEntityCore relatedEntity, string fieldName) { switch(fieldName) { case "Product": SetupSyncProduct(relatedEntity); break; case "ScrapReason": SetupSyncScrapReason(relatedEntity); break; case "WorkOrderRoutings": this.WorkOrderRoutings.Add((WorkOrderRoutingEntity)relatedEntity); break; default: break; } } /// <summary> Unsets the internal parameter related to the fieldname passed to the instance relatedEntity. Reverses the actions taken by SetRelatedEntity() </summary> /// <param name="relatedEntity">Instance to unset as the related entity of type entityType</param> /// <param name="fieldName">Name of field mapped onto the relation which resolves in the instance relatedEntity</param> /// <param name="signalRelatedEntityManyToOne">if set to true it will notify the manytoone side, if applicable.</param> protected override void UnsetRelatedEntity(IEntityCore relatedEntity, string fieldName, bool signalRelatedEntityManyToOne) { switch(fieldName) { case "Product": DesetupSyncProduct(false, true); break; case "ScrapReason": DesetupSyncScrapReason(false, true); break; case "WorkOrderRoutings": this.PerformRelatedEntityRemoval(this.WorkOrderRoutings, relatedEntity, signalRelatedEntityManyToOne); break; default: break; } } /// <summary> Gets a collection of related entities referenced by this entity which depend on this entity (this entity is the PK side of their FK fields). These entities will have to be persisted after this entity during a recursive save.</summary> /// <returns>Collection with 0 or more IEntity2 objects, referenced by this entity</returns> protected override List<IEntity2> GetDependingRelatedEntities() { List<IEntity2> toReturn = new List<IEntity2>(); return toReturn; } /// <summary> Gets a collection of related entities referenced by this entity which this entity depends on (this entity is the FK side of their PK fields). These /// entities will have to be persisted before this entity during a recursive save.</summary> /// <returns>Collection with 0 or more IEntity2 objects, referenced by this entity</returns> protected override List<IEntity2> GetDependentRelatedEntities() { List<IEntity2> toReturn = new List<IEntity2>(); if(_product!=null) { toReturn.Add(_product); } if(_scrapReason!=null) { toReturn.Add(_scrapReason); } return toReturn; } /// <summary>Gets a list of all entity collections stored as member variables in this entity. Only 1:n related collections are returned.</summary> /// <returns>Collection with 0 or more IEntityCollection2 objects, referenced by this entity</returns> protected override List<IEntityCollection2> GetMemberEntityCollections() { List<IEntityCollection2> toReturn = new List<IEntityCollection2>(); toReturn.Add(this.WorkOrderRoutings); return toReturn; } /// <summary>ISerializable member. Does custom serialization so event handlers do not get serialized. Serializes members of this entity class and uses the base class' implementation to serialize the rest.</summary> /// <param name="info"></param> /// <param name="context"></param> [EditorBrowsable(EditorBrowsableState.Never)] protected override void GetObjectData(SerializationInfo info, StreamingContext context) { if (SerializationHelper.Optimization != SerializationOptimization.Fast) { info.AddValue("_workOrderRoutings", ((_workOrderRoutings!=null) && (_workOrderRoutings.Count>0) && !this.MarkedForDeletion)?_workOrderRoutings:null); info.AddValue("_locationCollectionViaWorkOrderRouting", ((_locationCollectionViaWorkOrderRouting!=null) && (_locationCollectionViaWorkOrderRouting.Count>0) && !this.MarkedForDeletion)?_locationCollectionViaWorkOrderRouting:null); info.AddValue("_product", (!this.MarkedForDeletion?_product:null)); info.AddValue("_scrapReason", (!this.MarkedForDeletion?_scrapReason:null)); } // __LLBLGENPRO_USER_CODE_REGION_START GetObjectInfo // __LLBLGENPRO_USER_CODE_REGION_END base.GetObjectData(info, context); } /// <summary>Gets a list of all the EntityRelation objects the type of this instance has.</summary> /// <returns>A list of all the EntityRelation objects the type of this instance has. Hierarchy relations are excluded.</returns> protected override List<IEntityRelation> GetAllRelations() { return new WorkOrderRelations().GetAllRelations(); } /// <summary> Creates a new IRelationPredicateBucket object which contains the predicate expression and relation collection to fetch the related entities of type 'WorkOrderRouting' to this entity.</summary> /// <returns></returns> public virtual IRelationPredicateBucket GetRelationInfoWorkOrderRoutings() { IRelationPredicateBucket bucket = new RelationPredicateBucket(); bucket.PredicateExpression.Add(new FieldCompareValuePredicate(WorkOrderRoutingFields.WorkOrderId, null, ComparisonOperator.Equal, this.WorkOrderId)); return bucket; } /// <summary> Creates a new IRelationPredicateBucket object which contains the predicate expression and relation collection to fetch the related entities of type 'Location' to this entity.</summary> /// <returns></returns> public virtual IRelationPredicateBucket GetRelationInfoLocationCollectionViaWorkOrderRouting() { IRelationPredicateBucket bucket = new RelationPredicateBucket(); bucket.Relations.AddRange(GetRelationsForFieldOfType("LocationCollectionViaWorkOrderRouting")); bucket.PredicateExpression.Add(new FieldCompareValuePredicate(WorkOrderFields.WorkOrderId, null, ComparisonOperator.Equal, this.WorkOrderId, "WorkOrderEntity__")); return bucket; } /// <summary> Creates a new IRelationPredicateBucket object which contains the predicate expression and relation collection to fetch the related entity of type 'Product' to this entity.</summary> /// <returns></returns> public virtual IRelationPredicateBucket GetRelationInfoProduct() { IRelationPredicateBucket bucket = new RelationPredicateBucket(); bucket.PredicateExpression.Add(new FieldCompareValuePredicate(ProductFields.ProductId, null, ComparisonOperator.Equal, this.ProductId)); return bucket; } /// <summary> Creates a new IRelationPredicateBucket object which contains the predicate expression and relation collection to fetch the related entity of type 'ScrapReason' to this entity.</summary> /// <returns></returns> public virtual IRelationPredicateBucket GetRelationInfoScrapReason() { IRelationPredicateBucket bucket = new RelationPredicateBucket(); bucket.PredicateExpression.Add(new FieldCompareValuePredicate(ScrapReasonFields.ScrapReasonId, null, ComparisonOperator.Equal, this.ScrapReasonId)); return bucket; } /// <summary>Creates a new instance of the factory related to this entity</summary> protected override IEntityFactory2 CreateEntityFactory() { return EntityFactoryCache2.GetEntityFactory(typeof(WorkOrderEntityFactory)); } #if !CF /// <summary>Adds the member collections to the collections queue (base first)</summary> /// <param name="collectionsQueue">The collections queue.</param> protected override void AddToMemberEntityCollectionsQueue(Queue<IEntityCollection2> collectionsQueue) { base.AddToMemberEntityCollectionsQueue(collectionsQueue); collectionsQueue.Enqueue(this._workOrderRoutings); collectionsQueue.Enqueue(this._locationCollectionViaWorkOrderRouting); } /// <summary>Gets the member collections queue from the queue (base first)</summary> /// <param name="collectionsQueue">The collections queue.</param> protected override void GetFromMemberEntityCollectionsQueue(Queue<IEntityCollection2> collectionsQueue) { base.GetFromMemberEntityCollectionsQueue(collectionsQueue); this._workOrderRoutings = (EntityCollection<WorkOrderRoutingEntity>) collectionsQueue.Dequeue(); this._locationCollectionViaWorkOrderRouting = (EntityCollection<LocationEntity>) collectionsQueue.Dequeue(); } /// <summary>Determines whether the entity has populated member collections</summary> /// <returns>true if the entity has populated member collections.</returns> protected override bool HasPopulatedMemberEntityCollections() { bool toReturn = false; toReturn |=(this._workOrderRoutings != null); toReturn |= (this._locationCollectionViaWorkOrderRouting != null); return toReturn ? true : base.HasPopulatedMemberEntityCollections(); } /// <summary>Creates the member entity collections queue.</summary> /// <param name="collectionsQueue">The collections queue.</param> /// <param name="requiredQueue">The required queue.</param> protected override void CreateMemberEntityCollectionsQueue(Queue<IEntityCollection2> collectionsQueue, Queue<bool> requiredQueue) { base.CreateMemberEntityCollectionsQueue(collectionsQueue, requiredQueue); collectionsQueue.Enqueue(requiredQueue.Dequeue() ? new EntityCollection<WorkOrderRoutingEntity>(EntityFactoryCache2.GetEntityFactory(typeof(WorkOrderRoutingEntityFactory))) : null); collectionsQueue.Enqueue(requiredQueue.Dequeue() ? new EntityCollection<LocationEntity>(EntityFactoryCache2.GetEntityFactory(typeof(LocationEntityFactory))) : null); } #endif /// <summary>Gets all related data objects, stored by name. The name is the field name mapped onto the relation for that particular data element.</summary> /// <returns>Dictionary with per name the related referenced data element, which can be an entity collection or an entity or null</returns> protected override Dictionary<string, object> GetRelatedData() { Dictionary<string, object> toReturn = new Dictionary<string, object>(); toReturn.Add("Product", _product); toReturn.Add("ScrapReason", _scrapReason); toReturn.Add("WorkOrderRoutings", _workOrderRoutings); toReturn.Add("LocationCollectionViaWorkOrderRouting", _locationCollectionViaWorkOrderRouting); return toReturn; } /// <summary> Initializes the class members</summary> private void InitClassMembers() { PerformDependencyInjection(); // __LLBLGENPRO_USER_CODE_REGION_START InitClassMembers // __LLBLGENPRO_USER_CODE_REGION_END OnInitClassMembersComplete(); } #region Custom Property Hashtable Setup /// <summary> Initializes the hashtables for the entity type and entity field custom properties. </summary> private static void SetupCustomPropertyHashtables() { _customProperties = new Dictionary<string, string>(); _fieldsCustomProperties = new Dictionary<string, Dictionary<string, string>>(); Dictionary<string, string> fieldHashtable; fieldHashtable = new Dictionary<string, string>(); _fieldsCustomProperties.Add("DueDate", fieldHashtable); fieldHashtable = new Dictionary<string, string>(); _fieldsCustomProperties.Add("EndDate", fieldHashtable); fieldHashtable = new Dictionary<string, string>(); _fieldsCustomProperties.Add("ModifiedDate", fieldHashtable); fieldHashtable = new Dictionary<string, string>(); _fieldsCustomProperties.Add("OrderQty", fieldHashtable); fieldHashtable = new Dictionary<string, string>(); _fieldsCustomProperties.Add("ProductId", fieldHashtable); fieldHashtable = new Dictionary<string, string>(); _fieldsCustomProperties.Add("ScrappedQty", fieldHashtable); fieldHashtable = new Dictionary<string, string>(); _fieldsCustomProperties.Add("ScrapReasonId", fieldHashtable); fieldHashtable = new Dictionary<string, string>(); _fieldsCustomProperties.Add("StartDate", fieldHashtable); fieldHashtable = new Dictionary<string, string>(); _fieldsCustomProperties.Add("StockedQty", fieldHashtable); fieldHashtable = new Dictionary<string, string>(); _fieldsCustomProperties.Add("WorkOrderId", fieldHashtable); } #endregion /// <summary> Removes the sync logic for member _product</summary> /// <param name="signalRelatedEntity">If set to true, it will call the related entity's UnsetRelatedEntity method</param> /// <param name="resetFKFields">if set to true it will also reset the FK fields pointing to the related entity</param> private void DesetupSyncProduct(bool signalRelatedEntity, bool resetFKFields) { this.PerformDesetupSyncRelatedEntity( _product, new PropertyChangedEventHandler( OnProductPropertyChanged ), "Product", AdventureWorks.Dal.RelationClasses.StaticWorkOrderRelations.ProductEntityUsingProductIdStatic, true, signalRelatedEntity, "WorkOrders", resetFKFields, new int[] { (int)WorkOrderFieldIndex.ProductId } ); _product = null; } /// <summary> setups the sync logic for member _product</summary> /// <param name="relatedEntity">Instance to set as the related entity of type entityType</param> private void SetupSyncProduct(IEntityCore relatedEntity) { if(_product!=relatedEntity) { DesetupSyncProduct(true, true); _product = (ProductEntity)relatedEntity; this.PerformSetupSyncRelatedEntity( _product, new PropertyChangedEventHandler( OnProductPropertyChanged ), "Product", AdventureWorks.Dal.RelationClasses.StaticWorkOrderRelations.ProductEntityUsingProductIdStatic, true, new string[] { } ); } } /// <summary>Handles property change events of properties in a related entity.</summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnProductPropertyChanged( object sender, PropertyChangedEventArgs e ) { switch( e.PropertyName ) { default: break; } } /// <summary> Removes the sync logic for member _scrapReason</summary> /// <param name="signalRelatedEntity">If set to true, it will call the related entity's UnsetRelatedEntity method</param> /// <param name="resetFKFields">if set to true it will also reset the FK fields pointing to the related entity</param> private void DesetupSyncScrapReason(bool signalRelatedEntity, bool resetFKFields) { this.PerformDesetupSyncRelatedEntity( _scrapReason, new PropertyChangedEventHandler( OnScrapReasonPropertyChanged ), "ScrapReason", AdventureWorks.Dal.RelationClasses.StaticWorkOrderRelations.ScrapReasonEntityUsingScrapReasonIdStatic, true, signalRelatedEntity, "WorkOrders", resetFKFields, new int[] { (int)WorkOrderFieldIndex.ScrapReasonId } ); _scrapReason = null; } /// <summary> setups the sync logic for member _scrapReason</summary> /// <param name="relatedEntity">Instance to set as the related entity of type entityType</param> private void SetupSyncScrapReason(IEntityCore relatedEntity) { if(_scrapReason!=relatedEntity) { DesetupSyncScrapReason(true, true); _scrapReason = (ScrapReasonEntity)relatedEntity; this.PerformSetupSyncRelatedEntity( _scrapReason, new PropertyChangedEventHandler( OnScrapReasonPropertyChanged ), "ScrapReason", AdventureWorks.Dal.RelationClasses.StaticWorkOrderRelations.ScrapReasonEntityUsingScrapReasonIdStatic, true, new string[] { } ); } } /// <summary>Handles property change events of properties in a related entity.</summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnScrapReasonPropertyChanged( object sender, PropertyChangedEventArgs e ) { switch( e.PropertyName ) { default: break; } } /// <summary> Initializes the class with empty data, as if it is a new Entity.</summary> /// <param name="validator">The validator object for this WorkOrderEntity</param> /// <param name="fields">Fields of this entity</param> private void InitClassEmpty(IValidator validator, IEntityFields2 fields) { OnInitializing(); this.Fields = fields ?? CreateFields(); this.Validator = validator; InitClassMembers(); // __LLBLGENPRO_USER_CODE_REGION_START InitClassEmpty // __LLBLGENPRO_USER_CODE_REGION_END OnInitialized(); } #region Class Property Declarations /// <summary> The relations object holding all relations of this entity with other entity classes.</summary> public static WorkOrderRelations Relations { get { return new WorkOrderRelations(); } } /// <summary> The custom properties for this entity type.</summary> /// <remarks>The data returned from this property should be considered read-only: it is not thread safe to alter this data at runtime.</remarks> public static Dictionary<string, string> CustomProperties { get { return _customProperties;} } /// <summary> Creates a new PrefetchPathElement2 object which contains all the information to prefetch the related entities of type 'WorkOrderRouting' for this entity.</summary> /// <returns>Ready to use IPrefetchPathElement2 implementation.</returns> public static IPrefetchPathElement2 PrefetchPathWorkOrderRoutings { get { return new PrefetchPathElement2( new EntityCollection<WorkOrderRoutingEntity>(EntityFactoryCache2.GetEntityFactory(typeof(WorkOrderRoutingEntityFactory))), (IEntityRelation)GetRelationsForField("WorkOrderRoutings")[0], (int)AdventureWorks.Dal.EntityType.WorkOrderEntity, (int)AdventureWorks.Dal.EntityType.WorkOrderRoutingEntity, 0, null, null, null, null, "WorkOrderRoutings", SD.LLBLGen.Pro.ORMSupportClasses.RelationType.OneToMany); } } /// <summary> Creates a new PrefetchPathElement2 object which contains all the information to prefetch the related entities of type 'Location' for this entity.</summary> /// <returns>Ready to use IPrefetchPathElement2 implementation.</returns> public static IPrefetchPathElement2 PrefetchPathLocationCollectionViaWorkOrderRouting { get { IEntityRelation intermediateRelation = Relations.WorkOrderRoutingEntityUsingWorkOrderId; intermediateRelation.SetAliases(string.Empty, "WorkOrderRouting_"); return new PrefetchPathElement2(new EntityCollection<LocationEntity>(EntityFactoryCache2.GetEntityFactory(typeof(LocationEntityFactory))), intermediateRelation, (int)AdventureWorks.Dal.EntityType.WorkOrderEntity, (int)AdventureWorks.Dal.EntityType.LocationEntity, 0, null, null, GetRelationsForField("LocationCollectionViaWorkOrderRouting"), null, "LocationCollectionViaWorkOrderRouting", SD.LLBLGen.Pro.ORMSupportClasses.RelationType.ManyToMany); } } /// <summary> Creates a new PrefetchPathElement2 object which contains all the information to prefetch the related entities of type 'Product' for this entity.</summary> /// <returns>Ready to use IPrefetchPathElement2 implementation.</returns> public static IPrefetchPathElement2 PrefetchPathProduct { get { return new PrefetchPathElement2(new EntityCollection(EntityFactoryCache2.GetEntityFactory(typeof(ProductEntityFactory))), (IEntityRelation)GetRelationsForField("Product")[0], (int)AdventureWorks.Dal.EntityType.WorkOrderEntity, (int)AdventureWorks.Dal.EntityType.ProductEntity, 0, null, null, null, null, "Product", SD.LLBLGen.Pro.ORMSupportClasses.RelationType.ManyToOne); } } /// <summary> Creates a new PrefetchPathElement2 object which contains all the information to prefetch the related entities of type 'ScrapReason' for this entity.</summary> /// <returns>Ready to use IPrefetchPathElement2 implementation.</returns> public static IPrefetchPathElement2 PrefetchPathScrapReason { get { return new PrefetchPathElement2(new EntityCollection(EntityFactoryCache2.GetEntityFactory(typeof(ScrapReasonEntityFactory))), (IEntityRelation)GetRelationsForField("ScrapReason")[0], (int)AdventureWorks.Dal.EntityType.WorkOrderEntity, (int)AdventureWorks.Dal.EntityType.ScrapReasonEntity, 0, null, null, null, null, "ScrapReason", SD.LLBLGen.Pro.ORMSupportClasses.RelationType.ManyToOne); } } /// <summary> The custom properties for the type of this entity instance.</summary> /// <remarks>The data returned from this property should be considered read-only: it is not thread safe to alter this data at runtime.</remarks> [Browsable(false), XmlIgnore] protected override Dictionary<string, string> CustomPropertiesOfType { get { return CustomProperties;} } /// <summary> The custom properties for the fields of this entity type. The returned Hashtable contains per fieldname a hashtable of name-value pairs. </summary> /// <remarks>The data returned from this property should be considered read-only: it is not thread safe to alter this data at runtime.</remarks> public static Dictionary<string, Dictionary<string, string>> FieldsCustomProperties { get { return _fieldsCustomProperties;} } /// <summary> The custom properties for the fields of the type of this entity instance. The returned Hashtable contains per fieldname a hashtable of name-value pairs. </summary> /// <remarks>The data returned from this property should be considered read-only: it is not thread safe to alter this data at runtime.</remarks> [Browsable(false), XmlIgnore] protected override Dictionary<string, Dictionary<string, string>> FieldsCustomPropertiesOfType { get { return FieldsCustomProperties;} } /// <summary> The DueDate property of the Entity WorkOrder<br/><br/></summary> /// <remarks>Mapped on table field: "WorkOrder"."DueDate"<br/> /// Table field type characteristics (type, precision, scale, length): DateTime, 0, 0, 0<br/> /// Table field behavior characteristics (is nullable, is PK, is identity): false, false, false</remarks> public virtual System.DateTime DueDate { get { return (System.DateTime)GetValue((int)WorkOrderFieldIndex.DueDate, true); } set { SetValue((int)WorkOrderFieldIndex.DueDate, value); } } /// <summary> The EndDate property of the Entity WorkOrder<br/><br/></summary> /// <remarks>Mapped on table field: "WorkOrder"."EndDate"<br/> /// Table field type characteristics (type, precision, scale, length): DateTime, 0, 0, 0<br/> /// Table field behavior characteristics (is nullable, is PK, is identity): true, false, false</remarks> public virtual Nullable<System.DateTime> EndDate { get { return (Nullable<System.DateTime>)GetValue((int)WorkOrderFieldIndex.EndDate, false); } set { SetValue((int)WorkOrderFieldIndex.EndDate, value); } } /// <summary> The ModifiedDate property of the Entity WorkOrder<br/><br/></summary> /// <remarks>Mapped on table field: "WorkOrder"."ModifiedDate"<br/> /// Table field type characteristics (type, precision, scale, length): DateTime, 0, 0, 0<br/> /// Table field behavior characteristics (is nullable, is PK, is identity): false, false, false</remarks> public virtual System.DateTime ModifiedDate { get { return (System.DateTime)GetValue((int)WorkOrderFieldIndex.ModifiedDate, true); } set { SetValue((int)WorkOrderFieldIndex.ModifiedDate, value); } } /// <summary> The OrderQty property of the Entity WorkOrder<br/><br/></summary> /// <remarks>Mapped on table field: "WorkOrder"."OrderQty"<br/> /// Table field type characteristics (type, precision, scale, length): Int, 10, 0, 0<br/> /// Table field behavior characteristics (is nullable, is PK, is identity): false, false, false</remarks> public virtual System.Int32 OrderQty { get { return (System.Int32)GetValue((int)WorkOrderFieldIndex.OrderQty, true); } set { SetValue((int)WorkOrderFieldIndex.OrderQty, value); } } /// <summary> The ProductId property of the Entity WorkOrder<br/><br/></summary> /// <remarks>Mapped on table field: "WorkOrder"."ProductID"<br/> /// Table field type characteristics (type, precision, scale, length): Int, 10, 0, 0<br/> /// Table field behavior characteristics (is nullable, is PK, is identity): false, false, false</remarks> public virtual System.Int32 ProductId { get { return (System.Int32)GetValue((int)WorkOrderFieldIndex.ProductId, true); } set { SetValue((int)WorkOrderFieldIndex.ProductId, value); } } /// <summary> The ScrappedQty property of the Entity WorkOrder<br/><br/></summary> /// <remarks>Mapped on table field: "WorkOrder"."ScrappedQty"<br/> /// Table field type characteristics (type, precision, scale, length): SmallInt, 5, 0, 0<br/> /// Table field behavior characteristics (is nullable, is PK, is identity): false, false, false</remarks> public virtual System.Int16 ScrappedQty { get { return (System.Int16)GetValue((int)WorkOrderFieldIndex.ScrappedQty, true); } set { SetValue((int)WorkOrderFieldIndex.ScrappedQty, value); } } /// <summary> The ScrapReasonId property of the Entity WorkOrder<br/><br/></summary> /// <remarks>Mapped on table field: "WorkOrder"."ScrapReasonID"<br/> /// Table field type characteristics (type, precision, scale, length): SmallInt, 5, 0, 0<br/> /// Table field behavior characteristics (is nullable, is PK, is identity): true, false, false</remarks> public virtual Nullable<System.Int16> ScrapReasonId { get { return (Nullable<System.Int16>)GetValue((int)WorkOrderFieldIndex.ScrapReasonId, false); } set { SetValue((int)WorkOrderFieldIndex.ScrapReasonId, value); } } /// <summary> The StartDate property of the Entity WorkOrder<br/><br/></summary> /// <remarks>Mapped on table field: "WorkOrder"."StartDate"<br/> /// Table field type characteristics (type, precision, scale, length): DateTime, 0, 0, 0<br/> /// Table field behavior characteristics (is nullable, is PK, is identity): false, false, false</remarks> public virtual System.DateTime StartDate { get { return (System.DateTime)GetValue((int)WorkOrderFieldIndex.StartDate, true); } set { SetValue((int)WorkOrderFieldIndex.StartDate, value); } } /// <summary> The StockedQty property of the Entity WorkOrder<br/><br/></summary> /// <remarks>Mapped on table field: "WorkOrder"."StockedQty"<br/> /// Table field type characteristics (type, precision, scale, length): Int, 10, 0, 0<br/> /// Table field behavior characteristics (is nullable, is PK, is identity): false, false, false</remarks> public virtual System.Int32 StockedQty { get { return (System.Int32)GetValue((int)WorkOrderFieldIndex.StockedQty, true); } } /// <summary> The WorkOrderId property of the Entity WorkOrder<br/><br/></summary> /// <remarks>Mapped on table field: "WorkOrder"."WorkOrderID"<br/> /// Table field type characteristics (type, precision, scale, length): Int, 10, 0, 0<br/> /// Table field behavior characteristics (is nullable, is PK, is identity): false, true, true</remarks> public virtual System.Int32 WorkOrderId { get { return (System.Int32)GetValue((int)WorkOrderFieldIndex.WorkOrderId, true); } set { SetValue((int)WorkOrderFieldIndex.WorkOrderId, value); } } /// <summary> Gets the EntityCollection with the related entities of type 'WorkOrderRoutingEntity' which are related to this entity via a relation of type '1:n'. If the EntityCollection hasn't been fetched yet, the collection returned will be empty.<br/><br/></summary> [TypeContainedAttribute(typeof(WorkOrderRoutingEntity))] public virtual EntityCollection<WorkOrderRoutingEntity> WorkOrderRoutings { get { return GetOrCreateEntityCollection<WorkOrderRoutingEntity, WorkOrderRoutingEntityFactory>("WorkOrder", true, false, ref _workOrderRoutings); } } /// <summary> Gets the EntityCollection with the related entities of type 'LocationEntity' which are related to this entity via a relation of type 'm:n'. If the EntityCollection hasn't been fetched yet, the collection returned will be empty.<br/><br/></summary> [TypeContainedAttribute(typeof(LocationEntity))] public virtual EntityCollection<LocationEntity> LocationCollectionViaWorkOrderRouting { get { return GetOrCreateEntityCollection<LocationEntity, LocationEntityFactory>("WorkOrderCollectionViaWorkOrderRouting", false, true, ref _locationCollectionViaWorkOrderRouting); } } /// <summary> Gets / sets related entity of type 'ProductEntity' which has to be set using a fetch action earlier. If no related entity is set for this property, null is returned..<br/><br/></summary> [Browsable(false)] public virtual ProductEntity Product { get { return _product; } set { if(this.IsDeserializing) { SetupSyncProduct(value); } else { SetSingleRelatedEntityNavigator(value, "WorkOrders", "Product", _product, true); } } } /// <summary> Gets / sets related entity of type 'ScrapReasonEntity' which has to be set using a fetch action earlier. If no related entity is set for this property, null is returned..<br/><br/></summary> [Browsable(false)] public virtual ScrapReasonEntity ScrapReason { get { return _scrapReason; } set { if(this.IsDeserializing) { SetupSyncScrapReason(value); } else { SetSingleRelatedEntityNavigator(value, "WorkOrders", "ScrapReason", _scrapReason, true); } } } /// <summary> Gets the type of the hierarchy this entity is in. </summary> protected override InheritanceHierarchyType LLBLGenProIsInHierarchyOfType { get { return InheritanceHierarchyType.None;} } /// <summary> Gets or sets a value indicating whether this entity is a subtype</summary> protected override bool LLBLGenProIsSubType { get { return false;} } /// <summary>Returns the AdventureWorks.Dal.EntityType enum value for this entity.</summary> [Browsable(false), XmlIgnore] protected override int LLBLGenProEntityTypeValue { get { return (int)AdventureWorks.Dal.EntityType.WorkOrderEntity; } } #endregion #region Custom Entity code // __LLBLGENPRO_USER_CODE_REGION_START CustomEntityCode // __LLBLGENPRO_USER_CODE_REGION_END #endregion #region Included code #endregion } }
net-industry/llblgen-training
AdventureWorks.Dal/DatabaseGeneric/EntityClasses/WorkOrderEntity.cs
C#
mit
39,776
<?php require_once('vendor/autoload.php'); use B2Backblaze\B2Service; use B2Backblaze\B2API; require_once('utils/KeysUtil.php'); require_once('utils/photos.php'); $GLOBALS['b2BasePath'] = array(); $GLOBALS['b2BasePath']['base'] = "https://data.wethinkadventure.rocks/file/adventure/data/"; $GLOBALS['b2BasePath']['photos'] = $GLOBALS['b2BasePath']['base'] . 'photos'; $GLOBALS['b2BasePath']['360photos'] = $GLOBALS['b2BasePath']['base'] . '360photos'; $GLOBALS['b2BasePath']['timeline'] = $GLOBALS['b2BasePath']['base'] . 'timeline'; $GLOBALS['b2InternalPath']['photos'] = 'data/photos'; $GLOBALS['b2InternalPath']['360photos'] = 'data/360photos'; $GLOBALS['b2InternalPath']['photo']['source'] = 'source'; $GLOBALS['b2InternalPath']['photo']['meta'] = 'meta'; $GLOBALS['b2InternalPath']['photo']['blurred_image'] = 'blurred.jpg'; $GLOBALS['b2InternalPath']['photo']['thumbnail_image'] = 'thumbnail.jpg'; $GLOBALS['b2InternalPath']['photo']['resized_base'] = 'resized_'; function getB2Client() { $keys = getKeys(); return new B2Service($keys->b2->account_id, $keys->b2->application_id); } function b2GetPublic360Photo( $fileId ) { return $GLOBALS['b2BasePath']['360photos'] . '/' . $fileId . '/' . $fileId . '.jpg'; } function b2GetPublic360PhotoPreview( $fileId ) { return $GLOBALS['b2BasePath']['360photos'] . '/' . $fileId . '/preview.jpg'; } function b2GetPublicTimelinePhoto( $file ) { return $GLOBALS['b2BasePath']['timeline'] . '/' . $file; } function b2GetPublicPhotoOriginalUrl( $id, $imageType ) { return $GLOBALS['b2BasePath']['photos'] . '/' . $id . '/' . $GLOBALS['b2InternalPath']['photo']['source'] . '.' . $imageType; } function b2GetPublicThumbnailUrl( $id ) { return $GLOBALS['b2BasePath']['photos'] . '/' . $id . '/' . $GLOBALS['b2InternalPath']['photo']['meta'] . '/' . $GLOBALS['b2InternalPath']['photo']['thumbnail_image']; } function b2GetPublicBlurUrl( $id ) { return $GLOBALS['b2BasePath']['photos'] . '/' . $id . '/' . $GLOBALS['b2InternalPath']['photo']['meta'] . '/' . $GLOBALS['b2InternalPath']['photo']['blurred_image']; } function b2GetPublicResizedUrl( $id, $width, $height, $imageType ) { return $GLOBALS['b2BasePath']['photos'] . '/' . $id . '/' . $GLOBALS['b2InternalPath']['photo']['meta'] . '/' . $GLOBALS['b2InternalPath']['photo']['resized_base'] . $width . '_' . $height . '.' . $imageType; } function getB2PhotoMetaResizedPath( $id, $width, $height, $imageType ) { return getB2PhotoMetaPath( $id ) . '/' . $GLOBALS['b2InternalPath']['photo']['resized_base'] . $width . '_' . $height . '.' . $imageType; } function b2GetPublicMetaUrl( $id, $fileName ) { return $GLOBALS['b2BasePath']['photos'] . '/' . $id . '/' . $GLOBALS['b2InternalPath']['photo']['meta'] . '/' . $fileName; } /* function b2PhotoExists( $id, $targetBucketId = null ) { if( $targetBucketId == null ) { $targetBucketId = getKeys()->b2->bucket_id; } $fileName = getB2PhotoFilename( $id ); $b2Client = getB2Client(); return $b2Client->exists( $targetBucketId, $fileName ); } function b2PhotoMetaExists( $id, $fileName, $targetBucketId = null ) { if( $targetBucketId == null ) { $keys = getKeys(); $targetBucketId = $keys->b2->bucket_id; } $fileName = getB2PhotoMetaPath( $id ) . '/' . $fileName; $b2Client = getB2Client(); $b2Client->authorize(); $file = $b2Client->get($targetBucketId, $fileName, false, true); //var_dump( $file ); //return $file != null; return $b2Client->exists( $targetBucketId, $fileName ); } */ function getB2ThumbnailFilename( $id ) { return getB2PhotoMetaPath( $id ) . '/' . $GLOBALS['b2InternalPath']['photo']['thumbnail_image']; } function getB2PhotoFilename( $id ) { return getB2PhotoPath( $id ) . '/' . $GLOBALS['b2InternalPath']['photo']['source']; } function getB2PhotoPath( $id ) { return $GLOBALS['b2InternalPath']['photos'] . '/' . $id; } function getB2PhotoMetaPath( $id ) { return getB2PhotoPath( $id ) . '/' . $GLOBALS['b2InternalPath']['photo']['meta']; } function uploadB2File( $inputFilePath, $targetPath, $targetBucketId = null ) { $b2Client = getB2Client(); if( $targetBucketId == null ) { $targetBucketId = getKeys()->b2->bucket_id; } $fileToUpload = file_get_contents($inputFilePath); $result = $b2Client->insert($targetBucketId, $fileToUpload, $targetPath); return $result == true; } function deleteB2File( $targetFile, $targetBucketId = null ) { $b2Client = getB2Client(); $b2Client->authorize(); if( $targetBucketId == null ) { $targetBucketId = getKeys()->b2->bucket_id; } $result = $b2Client->delete('adventure', $targetFile); return $result == true; } function listMetaFiles( $photoId ) { $keys = getKeys(); $client = new B2API($keys->b2->account_id, $keys->b2->application_id, 2000); $targetBucketId = getKeys()->b2->bucket_id; $authResponse = $client->b2AuthorizeAccount(); if ($authResponse->isOk()) { $apiURL = $authResponse->get('apiUrl'); $token = $authResponse->get('authorizationToken'); $downloadURL = $authResponse->get('downloadUrl'); $minimumPartSize = $authResponse->get('minimumPartSize'); $fileNames = array(); //public function b2ListFileNames($URL, $token, $bucketId, $startFileName = null, $maxFileCount = 100, $prefix = null, $delimiter = null) $fileNamesResponse = $client->b2ListFileNames( $apiURL, $token, $targetBucketId, $startFileName = null, $maxFileCount = 100, $prefix = getB2PhotoMetaPath( $photoId ) ); if( $fileNamesResponse->isOK() ) { $data = $fileNamesResponse->getData(); foreach( $data['files'] as $file ) { $parts = explode( '/', $file['fileName'] ); $filename = end( $parts ); $fileNames[] = $filename; } } return $fileNames; } else { return false; } } function listAllFilesInternal( $photoId ) { $keys = getKeys(); $client = new B2API($keys->b2->account_id, $keys->b2->application_id, 2000); $targetBucketId = getKeys()->b2->bucket_id; $authResponse = $client->b2AuthorizeAccount(); if ($authResponse->isOk()) { $apiURL = $authResponse->get('apiUrl'); $token = $authResponse->get('authorizationToken'); $fileNames = array(); $fileNamesResponse = $client->b2ListFileNames( $apiURL, $token, $targetBucketId, $startFileName = null, $maxFileCount = 100, $prefix = getB2PhotoPath( $photoId ) ); if( $fileNamesResponse->isOK() ) { $data = $fileNamesResponse->getData(); foreach( $data['files'] as $file ) { $fileNames[] = $file['fileName']; } } return $fileNames; } else { return false; } } function listMetaFilesInternal( $photoId ) { $keys = getKeys(); $client = new B2API($keys->b2->account_id, $keys->b2->application_id, 2000); $targetBucketId = getKeys()->b2->bucket_id; $authResponse = $client->b2AuthorizeAccount(); if ($authResponse->isOk()) { $apiURL = $authResponse->get('apiUrl'); $token = $authResponse->get('authorizationToken'); $fileNames = array(); $fileNamesResponse = $client->b2ListFileNames( $apiURL, $token, $targetBucketId, $startFileName = null, $maxFileCount = 100, $prefix = getB2PhotoMetaPath( $photoId ) ); if( $fileNamesResponse->isOK() ) { $data = $fileNamesResponse->getData(); foreach( $data['files'] as $file ) { $fileNames[] = $file['fileName']; } } return $fileNames; } else { return false; } } ?>
AdventureProject/AdventureServer
utils/b2_util.php
PHP
mit
7,574
<div class="content"> <div class="left"> <?PHP include('modules/left/danhsach2.php'); ?> </div> <div class="right"> <?PHP if(isset($_GET['xem'])){ $tam=$_GET['xem']; }else{ $tam=''; }if($tam=='chitietsp'){ include('modules/right/chitietsp.php'); }elseif($tam=='userinfo2'){ include('modules/right/userinfo2.php'); }else include('modules/right/tatcasp.php'); ?> </div> </div> <div class="clear"></div>
goupbaocao4305/trang-web-ban-hang
modules/content2.php
PHP
mit
618
/* CSS Reset by Eric Meyer - Released under Public Domain http://meyerweb.com/eric/tools/css/reset/ */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { margin: 0; padding: 0; border: 0; outline: 0; font-size: 100%; vertical-align: baseline; background: transparent; } body { line-height: 1; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } :focus { outline: 0; } ins { text-decoration: none; } del { text-decoration: line-through; } table { border-collapse: collapse; border-spacing: 0; }
tryles/tryles
css/_reset.css
CSS
mit
936
import { Injectable, Inject } from '@angular/core'; import { Http } from '@angular/http'; import { GapiLoadIndicatorService } from "./GapiLoadIndicatorService"; import { AsyncSubject, Observable } from 'rxjs'; import 'rxjs/add/operator/toPromise'; import 'rxjs/add/operator/map'; @Injectable() export class GoogleAuthService { private readonly clientIdUrl = "/appAuth/clientId"; private readonly clientIdPromise = this.getClientId(); private readonly auth2LibLoaded: Promise<void>; private googleAuth: gapi.auth2.GoogleAuth; private _userSignedIn: AsyncSubject<boolean> = new AsyncSubject<boolean>(); public userBasicProfile: Observable<gapi.auth2.BasicProfile>; constructor( @Inject(GapiLoadIndicatorService) gapiLoadIndicator: GapiLoadIndicatorService, @Inject(Http) private http: Http ) { this.auth2LibLoaded = new Promise((resolve, reject) => gapiLoadIndicator.gapiLoaded .then(gapi => gapi.load("client:auth2"), () => resolve())); Promise.all([this.clientIdPromise, this.auth2LibLoaded]) .then(resultVector => gapi.auth2.init({client_id: resultVector[0]})) .then(() => this.startAuthorization()); // this.userBasicProfile = this.userSignedIn.map<gapi.auth2.BasicProfile>((isSignedIn: boolean, idx:number) => // this.googleAuth.currentUser.get().getBasicProfile()); } private startAuthorization() { this.googleAuth = gapi.auth2.getAuthInstance(); this.googleAuth.isSignedIn.listen(isSignedId => this.updateSigninStatus(isSignedId)); this.updateSigninStatus(this.googleAuth.isSignedIn.get()); } private updateSigninStatus(isSignedIn: boolean) { //this._userSignedIn.onNext(isSignedIn); } private getClientId(): Promise<string> { return this.http.get(this.clientIdUrl) .map(res => res.json().data) .toPromise(); } public get userSignedIn(): Observable<boolean> { return this._userSignedIn; } public get profile(): gapi.auth2.BasicProfile { return this.googleAuth.currentUser.get().getBasicProfile(); } }
gsipos/Split-the-bill
src/client/service/auth/GoogleAuthService.ts
TypeScript
mit
1,974
<div class="col-md-6"> <div class="form-group{{ $errors->first('interview_criteria', ' has-error') }}"> <label class="col-lg-4 col-md-4 control-label"> Interview criteria <span class="error">*</span></label> <div class="col-lg-8 col-md-8"> {!! Form::text('interview_criteria',null, ['class' => 'form-control form-cascade-control input-small']) !!} <span class="label label-danger">{{ $errors->first('interview_criteria', ':message') }}</span> </div> </div> <div class="form-group"> <label class="col-lg-4 col-md-4 control-label"></label> <div class="col-lg-8 col-md-8"> {!! Form::submit('Save', ['class'=>'btn btn-primary text-white']) !!} </div> </div> </div>
krsdata/inesport
packages/modules/Admin/views/criteria/form.blade.php
PHP
mit
780
using System; namespace ImageTools.Utilities { public static class Bin { /// <summary> /// Return the smalles number that is a power-of-two /// greater than or equal to the input /// </summary> public static uint NextPow2(uint c) { c--; c |= c >> 1; c |= c >> 2; c |= c >> 4; c |= c >> 8; c |= c >> 16; return ++c; } /// <summary> /// Return the smalles number that is a power-of-two /// greater than or equal to the input /// </summary> public static int NextPow2(int c) { return (int)NextPow2((uint)c); } /// <summary> /// Render a human-friendly string for a file size in bytes /// </summary> /// <param name="byteLength"></param> /// <returns></returns> public static string Human(long byteLength) { double size = byteLength; var prefix = new []{ "b", "kb", "mb", "gb", "tb", "pb" }; int i; for (i = 0; i < prefix.Length; i++) { if (size < 1024) break; size /= 1024; } return size.ToString("#0.##") + prefix[i]; } /// <summary> /// Pin number to range /// </summary> public static int Pin(this int v, int lower, int upper) { if (v < lower) return lower; if (v > upper) return upper; return v; } /// <summary> /// Pin number to range, with exclusive upper bound /// </summary> public static int PinXu(this int v, int lower, int exclusiveUpper) { if (v < lower) return lower; if (v >= exclusiveUpper) return exclusiveUpper - 1; return v; } /// <summary> /// Approximate Math.Pow using bitwise tricks /// </summary> /// <param name="b">base</param> /// <param name="e">exponent</param> /// <returns>Approximation of b^e</returns> public static double FPow(double b, double e) { var head = BitConverter.DoubleToInt64Bits(b); var bitwise = (long)(e * (head - 4606921280493453312L)) + 4606921280493453312L; return BitConverter.Int64BitsToDouble(bitwise); } /*public static double pow(final double a, final double b) { final long tmp = Double.doubleToLongBits(a); final long tmp2 = (long)(b * (tmp - 4606921280493453312L)) + 4606921280493453312L; return Double.longBitsToDouble(tmp2); }*/ } }
i-e-b/ImageTools
src/ImageTools/Utilities/Bin.cs
C#
mit
2,825
<!DOCTYPE HTML> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (11.0.10) on Thu Apr 15 10:34:57 CEST 2021 --> <title>Uses of Class com.wrapper.spotify.requests.data.browse.GetCategorysPlaylistsRequest.Builder (Spotify Web API Java Client 6.5.3 API)</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="dc.created" content="2021-04-15"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../../../../jquery/jquery-ui.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> <script type="text/javascript" src="../../../../../../../jquery/jszip/dist/jszip.min.js"></script> <script type="text/javascript" src="../../../../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script> <!--[if IE]> <script type="text/javascript" src="../../../../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script> <![endif]--> <script type="text/javascript" src="../../../../../../../jquery/jquery-3.5.1.js"></script> <script type="text/javascript" src="../../../../../../../jquery/jquery-ui.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.wrapper.spotify.requests.data.browse.GetCategorysPlaylistsRequest.Builder (Spotify Web API Java Client 6.5.3 API)"; } } catch(err) { } //--> var pathtoroot = "../../../../../../../"; var useModuleDirectories = true; loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <header role="banner"> <nav role="navigation"> <div class="fixedNav"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a id="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a id="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../index.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../GetCategorysPlaylistsRequest.Builder.html" title="class in com.wrapper.spotify.requests.data.browse">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses.html">All&nbsp;Classes</a></li> </ul> <ul class="navListSearch"> <li><label for="search">SEARCH:</label> <input type="text" id="search" value="search" disabled="disabled"> <input type="reset" id="reset" value="reset" disabled="disabled"> </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> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a id="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> </div> <div class="navPadding">&nbsp;</div> <script type="text/javascript"><!-- $('.navPadding').css('padding-top', $('.fixedNav').css("height")); //--> </script> </nav> </header> <main role="main"> <div class="header"> <h2 title="Uses of Class com.wrapper.spotify.requests.data.browse.GetCategorysPlaylistsRequest.Builder" class="title">Uses of Class<br>com.wrapper.spotify.requests.data.browse.GetCategorysPlaylistsRequest.Builder</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary"> <caption><span>Packages that use <a href="../GetCategorysPlaylistsRequest.Builder.html" title="class in com.wrapper.spotify.requests.data.browse">GetCategorysPlaylistsRequest.Builder</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <th class="colFirst" scope="row"><a href="#com.wrapper.spotify">com.wrapper.spotify</a></th> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="#com.wrapper.spotify.requests.data.browse">com.wrapper.spotify.requests.data.browse</a></th> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"> <section role="region"><a id="com.wrapper.spotify"> <!-- --> </a> <h3>Uses of <a href="../GetCategorysPlaylistsRequest.Builder.html" title="class in com.wrapper.spotify.requests.data.browse">GetCategorysPlaylistsRequest.Builder</a> in <a href="../../../../package-summary.html">com.wrapper.spotify</a></h3> <table class="useSummary"> <caption><span>Methods in <a href="../../../../package-summary.html">com.wrapper.spotify</a> that return <a href="../GetCategorysPlaylistsRequest.Builder.html" title="class in com.wrapper.spotify.requests.data.browse">GetCategorysPlaylistsRequest.Builder</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colSecond" scope="col">Method</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../GetCategorysPlaylistsRequest.Builder.html" title="class in com.wrapper.spotify.requests.data.browse">GetCategorysPlaylistsRequest.Builder</a></code></td> <th class="colSecond" scope="row"><span class="typeNameLabel">SpotifyApi.</span><code><span class="memberNameLink"><a href="../../../../SpotifyApi.html#getCategorysPlaylists(java.lang.String)">getCategorysPlaylists</a></span>&#8203;(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang" class="externalLink">String</a>&nbsp;category_id)</code></th> <td class="colLast"> <div class="block">Get the playlists from a specific category.</div> </td> </tr> </tbody> </table> </section> </li> <li class="blockList"> <section role="region"><a id="com.wrapper.spotify.requests.data.browse"> <!-- --> </a> <h3>Uses of <a href="../GetCategorysPlaylistsRequest.Builder.html" title="class in com.wrapper.spotify.requests.data.browse">GetCategorysPlaylistsRequest.Builder</a> in <a href="../package-summary.html">com.wrapper.spotify.requests.data.browse</a></h3> <table class="useSummary"> <caption><span>Methods in <a href="../package-summary.html">com.wrapper.spotify.requests.data.browse</a> that return <a href="../GetCategorysPlaylistsRequest.Builder.html" title="class in com.wrapper.spotify.requests.data.browse">GetCategorysPlaylistsRequest.Builder</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colSecond" scope="col">Method</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../GetCategorysPlaylistsRequest.Builder.html" title="class in com.wrapper.spotify.requests.data.browse">GetCategorysPlaylistsRequest.Builder</a></code></td> <th class="colSecond" scope="row"><span class="typeNameLabel">GetCategorysPlaylistsRequest.Builder.</span><code><span class="memberNameLink"><a href="../GetCategorysPlaylistsRequest.Builder.html#category_id(java.lang.String)">category_id</a></span>&#8203;(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang" class="externalLink">String</a>&nbsp;category_id)</code></th> <td class="colLast"> <div class="block">The categroy ID setter.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../GetCategorysPlaylistsRequest.Builder.html" title="class in com.wrapper.spotify.requests.data.browse">GetCategorysPlaylistsRequest.Builder</a></code></td> <th class="colSecond" scope="row"><span class="typeNameLabel">GetCategorysPlaylistsRequest.Builder.</span><code><span class="memberNameLink"><a href="../GetCategorysPlaylistsRequest.Builder.html#country(com.neovisionaries.i18n.CountryCode)">country</a></span>&#8203;(com.neovisionaries.i18n.CountryCode&nbsp;country)</code></th> <td class="colLast"> <div class="block">The country code setter.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../GetCategorysPlaylistsRequest.Builder.html" title="class in com.wrapper.spotify.requests.data.browse">GetCategorysPlaylistsRequest.Builder</a></code></td> <th class="colSecond" scope="row"><span class="typeNameLabel">GetCategorysPlaylistsRequest.Builder.</span><code><span class="memberNameLink"><a href="../GetCategorysPlaylistsRequest.Builder.html#limit(java.lang.Integer)">limit</a></span>&#8203;(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html?is-external=true" title="class or interface in java.lang" class="externalLink">Integer</a>&nbsp;limit)</code></th> <td class="colLast"> <div class="block">The limit setter.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../GetCategorysPlaylistsRequest.Builder.html" title="class in com.wrapper.spotify.requests.data.browse">GetCategorysPlaylistsRequest.Builder</a></code></td> <th class="colSecond" scope="row"><span class="typeNameLabel">GetCategorysPlaylistsRequest.Builder.</span><code><span class="memberNameLink"><a href="../GetCategorysPlaylistsRequest.Builder.html#offset(java.lang.Integer)">offset</a></span>&#8203;(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html?is-external=true" title="class or interface in java.lang" class="externalLink">Integer</a>&nbsp;offset)</code></th> <td class="colLast"> <div class="block">The offset setter.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../GetCategorysPlaylistsRequest.Builder.html" title="class in com.wrapper.spotify.requests.data.browse">GetCategorysPlaylistsRequest.Builder</a></code></td> <th class="colSecond" scope="row"><span class="typeNameLabel">GetCategorysPlaylistsRequest.Builder.</span><code><span class="memberNameLink"><a href="../GetCategorysPlaylistsRequest.Builder.html#self()">self</a></span>()</code></th> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </section> </li> </ul> </li> </ul> </div> </main> <footer role="contentinfo"> <nav role="navigation"> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a id="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a id="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../index.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../GetCategorysPlaylistsRequest.Builder.html" title="class in com.wrapper.spotify.requests.data.browse">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses.html">All&nbsp;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> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a id="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </nav> <p class="legalCopy"><small>Copyright &#169; 2021. All rights reserved.</small></p> </footer> </body> </html>
thelinmichael/spotify-web-api-java
docs/com/wrapper/spotify/requests/data/browse/class-use/GetCategorysPlaylistsRequest.Builder.html
HTML
mit
12,273
/* Design by Free CSS Templates http://www.freecsstemplates.org Released for free under a Creative Commons Attribution 2.5 License */ body { margin: 0px; padding: 0px; background: #3D5D68 url(images/img01.jpg) repeat-x; font: 13px "Trebuchet MS", Arial, Helvetica, sans-serif; color: #333333; } h1, h2, h3 { font: 1.82em; font-weight: normal; font-family: Arial, Helvetica, sans-serif; letter-spacing: -1px; color: #514F42; } p, ol, ul { line-height: 1.67em; } a { color: #669900; } a:hover { text-decoration: none; } hr { display: none; } /* Header */ #header { width: 940px; height: 270px; margin: 0px auto; } /* Logo */ #logo { float: left; padding: 40px 0 0 0; } #logo h1 { margin: 0; height: 160px; padding: 80px 0 0 170px; background: url(../../../images/pc_logo.png) no-repeat left top; text-transform: uppercase; letter-spacing: -2px; font-size: 4em; font-weight: normal; color: #FFFFFF; } #logo h1 a { display: block; text-decoration: none; color: #FFFFFF; } #logo p { margin: -113px 0 0 173px; text-transform: uppercase; font-family: Tahoma, Arial, Helvetica, sans-serif; font-weight: bold; font-size: 11px; } #logo a { display: block; text-decoration: none; color: #FFFFFF; } /* Menu */ #menu { float: right; } #menu ul { margin: 0px; padding: 176px 0px 0px 0px; list-style: none; } #menu li { display: inline; } #menu a { display: block; float: left; margin-left: 5px; padding: 5px 20px; background: #FFFFFF; text-decoration: none; text-transform: uppercase; border-top: 2px solid #EBEAD1; font-family: Arial, Helvetica, sans-serif; font-weight: bold; font-size: 11px; color: #182C33; } #menu a:hover, .active a { } /* Page */ #wrapper { background: #EBEAD1 url(images/img02.jpg) repeat-x left bottom; } #page { width: 940px; margin: 0px auto; padding: 0; } /* Content */ #content { float: left; width: 650px; margin-bottom: 50px; } /* Post */ .post { margin-top: 20px; } .post .date { float: left; width: 76px; height: 58px; margin: 0; margin-right: 20px; padding-top: 2px; background: #514F42; line-height: normal; text-transform: uppercase; text-align: center; font-size: 10px; font-weight: bold; color: #FFFFFF; } .post .date b { margin: 0; padding: 0; display: block; margin-top: -5px; font-size: 40px; } .post .title { margin: 0; padding: 0px 0 0 0; margin-left: 10px; padding-left: 50px; font-size: 1.8em; } .post .title h2 { padding: 0; margin: 0; } .post .hr1 { } .post .meta { margin: 0 0 30px 20px; padding: 0; color: #979680; line-height:normal; } .post .meta a { color: #828170; } .post .entry { margin: 0; padding: 0 0 20px 0; border-bottom: 1px dashed #666633; } /* Sidebar */ #sidebar { float: right; width: 240px; margin-bottom: 20px; } #sidebar ul { margin: 0; padding: 0; list-style: none; } #sidebar li { margin-bottom: 30px; } #sidebar li ul { border-top: 1px dashed #666633; } #sidebar li li { margin: 0; padding: 4px 0 4px 0; } #sidebar li li a { } #sidebar h2 { padding: 0; margin: 0 0 6px 0; } #sidebar a { text-decoration: none; } #sidebar a:hover { text-decoration: underline; } /* Calendar */ #calendar_wrap { border-top: 1px dashed #666633; } #calendar caption { padding-top: 5px; font-weight: bold; } #calendar table { width: 100%; border: 1px solid #E8E8E8; font-family: Arial, Helvetica, sans-serif; } #calendar thead { background: #514F42; } #calendar tbody td { border: 1px solid #514F42; text-align: center; } #today { font-weight: bold; } #prev { } #next { text-align: right; } /* Footer */ #wrapper2 { background: #422C21; } #footer { width: 940px; margin: 0 auto; padding-top: 20px; padding-bottom: 20px; color: #FFFFFF; } #footer a { font-family: Tahoma, Arial, Helvetica, sans-serif; text-decoration: none; font-size: 11px; color: #FFFFFF; } #footer ul { margin: 0; padding: 0; list-style: none; } #footer li { display: block; float: left; width: 300px; padding-left: 20px; } #footer li.first { padding-left: 0; } #footer li ul { margin: 0; margin-bottom: 30px; } #footer li li { display: list-item; float: none; margin: 0; padding: 2px 0; border-bottom: 1px solid #573D30; } #footer li li a { } #footer h2 { margin-top: 0; color: #FFFFFF; } #legal { clear: both; margin: 0; padding: 10px 0; text-align: center; font-family: Tahoma, Arial, Helvetica, sans-serif; font-size: 10px; color: #525252; background: black; } #legal a { border-bottom: 1px dotted #939393; text-decoration: none; color: #939393; }
frankyrumple/smc
static/plugin_layouts/layouts/Interlude/default.css
CSS
mit
4,584
#nullable enable using System; using System.Buffers; using System.IO; namespace Nerdbank.GitVersioning.ManagedGit { internal class GitPackMemoryCacheStream : Stream { private Stream stream; private readonly MemoryStream cacheStream = new MemoryStream(); private long length; public GitPackMemoryCacheStream(Stream stream) { this.stream = stream ?? throw new ArgumentNullException(nameof(stream)); this.length = this.stream.Length; } public override bool CanRead => true; public override bool CanSeek => true; public override bool CanWrite => false; public override long Length => this.length; public override long Position { get => this.cacheStream.Position; set => throw new NotSupportedException(); } public override void Flush() { throw new NotSupportedException(); } #if NETSTANDARD2_0 public int Read(Span<byte> buffer) #else /// <inheritdoc/> public override int Read(Span<byte> buffer) #endif { if (this.cacheStream.Length < this.length && this.cacheStream.Position + buffer.Length > this.cacheStream.Length) { var currentPosition = this.cacheStream.Position; var toRead = (int)(buffer.Length - this.cacheStream.Length + this.cacheStream.Position); int actualRead = this.stream.Read(buffer.Slice(0, toRead)); this.cacheStream.Seek(0, SeekOrigin.End); this.cacheStream.Write(buffer.Slice(0, actualRead)); this.cacheStream.Seek(currentPosition, SeekOrigin.Begin); this.DisposeStreamIfRead(); } return this.cacheStream.Read(buffer); } public override int Read(byte[] buffer, int offset, int count) { return this.Read(buffer.AsSpan(offset, count)); } public override long Seek(long offset, SeekOrigin origin) { if (origin != SeekOrigin.Begin) { throw new NotSupportedException(); } if (offset > this.cacheStream.Length) { var toRead = (int)(offset - this.cacheStream.Length); byte[] buffer = ArrayPool<byte>.Shared.Rent(toRead); int read = this.stream.Read(buffer, 0, toRead); this.cacheStream.Seek(0, SeekOrigin.End); this.cacheStream.Write(buffer, 0, read); ArrayPool<byte>.Shared.Return(buffer); this.DisposeStreamIfRead(); return this.cacheStream.Position; } else { return this.cacheStream.Seek(offset, origin); } } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } protected override void Dispose(bool disposing) { if (disposing) { this.stream.Dispose(); this.cacheStream.Dispose(); } base.Dispose(disposing); } private void DisposeStreamIfRead() { if (this.cacheStream.Length == this.stream.Length) { this.stream.Dispose(); } } } }
AArnott/Nerdbank.GitVersioning
src/NerdBank.GitVersioning/ManagedGit/GitPackMemoryCacheStream.cs
C#
mit
3,596
SwaggerEngine.configure do |config| config.json_files = { v1: "lib/swagger_engine/swagger.json" } end
batdevis/guaivo
config/initializers/swagger_engine.rb
Ruby
mit
110
// CrdTransTIsoSolid.h // created by Kuangdai on 19-May-2017 // coordinate transformation between (s, phi, z) and (theta, phi, r) #pragma once #include "eigenc.h" #include "eigenp.h" class CrdTransTIsoSolid { public: CrdTransTIsoSolid(const RDMatPP &theta); ~CrdTransTIsoSolid() {}; void transformSPZ_RTZ(vec_ar6_CMatPP &u, int Nu) const; void transformRTZ_SPZ(vec_ar6_CMatPP &u, int Nu) const; void transformSPZ_RTZ(vec_ar9_CMatPP &u, int Nu) const; void transformRTZ_SPZ(vec_ar9_CMatPP &u, int Nu) const; private: // t: theta of GLL-points RMatPP mSin1t; RMatPP mCos1t; RMatPP mSin2t; RMatPP mCos2t; };
kuangdai/AxiSEM3D
SOLVER/src/core/element/crd/CrdTransTIsoSolid.h
C
mit
679
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using CommandSenderApi.Areas.HelpPage.ModelDescriptions; using CommandSenderApi.Areas.HelpPage.Models; namespace CommandSenderApi.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
AtmosphereMessaging/Cumulus
src/Samples/CommandSenderApi/Areas/HelpPage/HelpPageConfigurationExtensions.cs
C#
mit
24,094
<!DOCTYPE html> <html> <body> <p>Click the button to do a loop which will skip the step where i is equal to 3.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var text = ""; var i; for (i = 0; i < 5; i++) { if (i === 3) { continue; } text += "The number is " + i + "<br>"; } document.getElementById("demo").innerHTML = text; } </script> <?php //Bu kod bir döngünün belli bir değeri atlayıp devam etmesini sağlar. Burada 3 değeri atlanmıştır. ?> </body> </html>
Javascript-Denizli/jsDocs
statement/continuestatement_.php
PHP
mit
585
import logging import time from collections import namedtuple from datetime import datetime import mock import pytest from database import db as _db from factory import create_app from pytz import timezone from pytz import utc from yelp_beans import send_email from yelp_beans.logic.subscription import get_specs_from_subscription from yelp_beans.logic.subscription import store_specs_from_subscription from yelp_beans.models import MeetingSubscription from yelp_beans.models import Rule from yelp_beans.models import SubscriptionDateTime from yelp_beans.models import User from yelp_beans.models import UserSubscriptionPreferences FAKE_USER = [{ 'first_name': 'Darwin', 'last_name': 'Yelp', 'email': '[email protected]', 'photo_url': ( 'https://s3-media4.fl.yelpcdn.com/assets/' 'srv0/yelp_large_assets/3f74899c069c' '/assets/img/illustrations/mascots/[email protected]' ), 'department': 'Consumer', 'business_title': 'Engineer', }] @pytest.fixture(scope='session', autouse=True) def mock_config(): with open('tests/test_data/config.yaml') as config_file: data = config_file.read() with mock.patch( 'yelp_beans.logic.config.open', mock.mock_open(read_data=data) ): yield @pytest.fixture(scope='session', autouse=True) def sendgrid_mock(): """This is active to prevent from sending a emails when testing""" with mock.patch.object(send_email, 'send_single_email'): yield @pytest.fixture(scope='session') def app(request): """Session-wide test `Flask` application writing to test database.""" app = create_app() app.testing = True # Establish an application context before running the tests. ctx = app.app_context() ctx.push() def teardown(): ctx.pop() request.addfinalizer(teardown) return app @pytest.fixture(scope='session') def db(app, request): """Session-wide test database.""" def teardown(): _db.drop_all() _db.app = app _db.create_all() request.addfinalizer(teardown) return _db @pytest.fixture(scope='function') def session(db, request): """Creates a new database session for a test.""" connection = db.engine.connect() transaction = connection.begin() options = dict(bind=connection, binds={}) session = db.create_scoped_session(options=options) db.session = session def teardown(): transaction.rollback() connection.close() session.remove() request.addfinalizer(teardown) return session @pytest.fixture def subscription(session): yield _subscription(session) def _subscription(session): zone = 'America/Los_Angeles' preference_1 = SubscriptionDateTime(datetime=datetime(2017, 1, 20, 23, 0, tzinfo=utc)) # Easier to think/verify in Pacific time since we are based in SF assert preference_1.datetime.astimezone(timezone(zone)).hour == 15 preference_1.datetime = preference_1.datetime.replace(tzinfo=None) session.add(preference_1) preference_2 = SubscriptionDateTime(datetime=datetime(2017, 1, 20, 19, 0, tzinfo=utc)) # Easier to think/verify in Pacific time since we are based in SF assert preference_2.datetime.astimezone(timezone(zone)).hour == 11 preference_2.datetime = preference_2.datetime.replace(tzinfo=None) session.add(preference_2) rule = Rule(name='office', value='USA: CA SF New Montgomery Office') session.add(rule) subscription = MeetingSubscription( title='Yelp Weekly', size=2, location='8th Floor', office='USA: CA SF New Montgomery Office', timezone=zone, datetime=[preference_1, preference_2], user_rules=[rule] ) session.add(subscription) session.commit() return subscription @pytest.fixture def database(session, subscription): MeetingInfo = namedtuple('MeetingInfo', ['sub', 'specs', 'prefs']) week_start, specs = get_specs_from_subscription(subscription) store_specs_from_subscription(subscription, week_start, specs) return MeetingInfo( subscription, specs, [ subscription.datetime[0], subscription.datetime[1] ] ) @pytest.fixture def database_no_specs(session, subscription): MeetingInfo = namedtuple('MeetingInfo', ['sub', 'specs', 'prefs']) return MeetingInfo( subscription, [], [ subscription.datetime[0], subscription.datetime[1] ] ) @pytest.fixture def employees(): with open('tests/test_data/employees.json') as test_file: return test_file.read() @pytest.fixture def data_source(): yield [ { 'first_name': 'Sam', 'last_name': 'Smith', 'email': '[email protected]', 'photo_url': 'www.cdn.com/SamSmith.png', 'metadata': { 'department': 'Engineering', 'title': 'Engineer', 'floor': '10', 'desk': '100', 'manager': 'Bo Demillo' } }, { 'first_name': 'Derrick', 'last_name': 'Johnson', 'email': '[email protected]', 'photo_url': 'www.cdn.com/DerrickJohnson.png', 'metadata': { 'department': 'Design', 'title': 'Designer', 'floor': '12', 'desk': '102', 'manager': 'Tracy Borne' } } ] @pytest.fixture def data_source_by_key(): yield { '[email protected]': { 'first_name': 'Sam', 'last_name': 'Smith', 'email': '[email protected]', 'photo_url': 'www.cdn.com/SamSmith.png', 'metadata': { 'department': 'Engineering', 'title': 'Engineer', 'floor': '10', 'desk': '100', 'manager': 'Bo Demillo' } }, '[email protected]': { 'first_name': 'Derrick', 'last_name': 'Johnson', 'email': '[email protected]', 'photo_url': 'www.cdn.com/DerrickJohnson.png', 'metadata': { 'department': 'Design', 'title': 'Designer', 'floor': '12', 'desk': '102', 'manager': 'Derrick Johnson' } } } @pytest.fixture def fake_user(session): yield _fake_user(session) def _fake_user(session): user_list = [] subscription = MeetingSubscription.query.first() for user in FAKE_USER: preferences = UserSubscriptionPreferences( preference=subscription.datetime[0], subscription=subscription, ) session.add(preferences) user_entity = User( first_name=user['first_name'], last_name=user['last_name'], email=user['email'], photo_url=user['photo_url'], meta_data={ 'department': user['department'], 'office': 'USA: CA SF New Montgomery Office', 'company_profile_url': 'https://www.yelp.com/user_details?userid=nkN_do3fJ9xekchVC-v68A', }, subscription_preferences=[preferences], ) session.add(user_entity) user_list.append(user_entity) session.commit() return user_list[0] def create_dev_data(session): email = FAKE_USER[0]['email'] user = User.query.filter(User.email == email).first() if not user: _subscription(session) time.sleep(2) _fake_user(session) subscription = MeetingSubscription.query.first() week_start, specs = get_specs_from_subscription(subscription) store_specs_from_subscription(subscription, week_start, specs) logging.info('generated fake date for dev')
Yelp/beans
api/tests/conftest.py
Python
mit
7,950
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; import Ember from 'ember'; moduleForComponent('if-component', 'Integration | Component | if component', { integration: true, setup: function () { let { registry } = this; registry.register('component:i-do-exist', Ember.Component.extend()); } }); test('The main block is renderd if the component name resolves to a component', function(assert) { this.render(hbs`{{#if-component "i-do-exist"}}Yay{{/if-component}}`); assert.equal(this.$().text().trim(), 'Yay'); }); test('the {{else}} block is rendered if the component name does not resolve', function(assert) { this.render(hbs`{{#if-component "not-available"}}Yay{{else}}Damn{{/if-component}}`); assert.equal(this.$().text().trim(), 'Damn', 'The else block is rendered'); this.render(hbs`{{#if-component "not-available"}}Yay{{/if-component}}`); assert.equal(this.$().text().trim(), '', 'nothing is rendered if no {{else}} block is provided'); }); test('it renders {{else}} if no component name is provided', function (assert) { this.render(hbs`{{#if-component}}Yay{{else}}Damn{{/if-component}}`); assert.equal(this.$().text().trim(), 'Damn', '{{else}} block is rendered'); this.set('myComponent', ''); this.render(hbs`{{#if-component myComponent}}Yay{{else}}Damn{{/if-component}}`); assert.equal(this.$().text().trim(), 'Damn', '{{else}} block is rendered with an empty bound property'); }); test('it can switch blocks when used with a bound property', function (assert) { this.set('myComponent', 'i-do-exist'); this.render(hbs`{{#if-component myComponent}}Yay{{else}}Damn{{/if-component}}`); assert.equal(this.$().text().trim(), 'Yay', 'The main block is rendered'); this.set('myComponent', 'not-available'); assert.equal(this.$().text().trim(), 'Damn', 'It switches to the {{else}} block'); this.set('myComponent', 'i-do-exist'); assert.equal(this.$().text().trim(), 'Yay', 'Back to the main block'); });
greyhwndz/ember-cli-if-component
tests/integration/components/if-component-test.js
JavaScript
mit
2,021
<?php /** * Boost - A PHP data structures and algorithms enhancement library * * @author [email protected] * @link https://github.com/panlatent/boost * @license https://opensource.org/licenses/MIT */ namespace Panlatent\Boost; class BQueue extends \SplQueue { }
panlatent/boost
src/BQueue.php
PHP
mit
276
<html><body> <pre style="margin: 0em;background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 1 </span><span style="font-family: monospace"></span><span style="color: #cc0066;">import</span> java.awt.Color;</pre> <pre style="margin: 0em;background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 2 </span><span style="font-family: monospace"></span><span style="color: #cc0066;">import</span> java.awt.Graphics2D;</pre> <pre style="margin: 0em;background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 3 </span><span style="font-family: monospace"></span><span style="color: #cc0066;">import</span> java.awt.Rectangle;</pre> <pre style="margin: 0em;background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 4 </span><span style="font-family: monospace"></span><span style="color: #cc0066;">import</span> java.awt.geom.Line2D;</pre> <pre style="margin: 0em;background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 5 </span><span style="font-family: monospace"></span></pre> <pre style="margin: 0em;background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 6 </span><span style="font-family: monospace"></span><span style="color: #cc0066;">public</span> <span style="color: #cc0066;">class</span> ItalianFlag</pre> <pre style="margin: 0em;background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 7 </span><span style="font-family: monospace">{</span></pre> <pre style="margin: 0em;background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 8 </span><span style="font-family: monospace"> </span><span style="color: #cc0066;">private</span> <span style="color: #cc0066;">int</span> xLeft;</pre> <pre style="margin: 0em;background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 9 </span><span style="font-family: monospace"> </span><span style="color: #cc0066;">private</span> <span style="color: #cc0066;">int</span> yTop;</pre> <pre style="margin: 0em;background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 10 </span><span style="font-family: monospace"> </span><span style="color: #cc0066;">private</span> <span style="color: #cc0066;">int</span> width;</pre> <pre style="margin: 0em;background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 11 </span><span style="font-family: monospace"> </span></pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 12 </span></span><span style="font-family: monospace"> </span><span style="color: #cc0066;">public</span> ItalianFlag(<span style="color: #cc0066;">int</span> x, <span style="color: #cc0066;">int</span> y, <span style="color: #cc0066;">int</span> aWidth)</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 13 </span></span><span style="font-family: monospace"> {</span></pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 14 </span></span><span style="font-family: monospace"> </span>xLeft = x;</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 15 </span></span><span style="font-family: monospace"> </span>yTop = y;</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 16 </span></span><span style="font-family: monospace"> </span>width = aWidth;</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 17 </span></span><span style="font-family: monospace"> }</span></pre> <pre style="margin: 0em;background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 18 </span><span style="font-family: monospace"></span></pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 19 </span></span><span style="font-family: monospace"> </span><span style="color: #cc0066;">public</span> <span style="color: #cc0066;">void</span> draw(Graphics2D g2)</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 20 </span></span><span style="font-family: monospace"> {</span></pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 21 </span></span><span style="font-family: monospace"> </span>Rectangle leftRectangle = <span style="color: #cc0066;">new</span> Rectangle(</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 22 </span></span><span style="font-family: monospace"> </span>xLeft, yTop,</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 23 </span></span><span style="font-family: monospace"> </span>width / <span style="color: #66ff19;">3</span>, width * <span style="color: #66ff19;">2</span> / <span style="color: #66ff19;">3</span>);</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 24 </span></span><span style="font-family: monospace"> </span>Rectangle rightRectangle = <span style="color: #cc0066;">new</span> Rectangle(</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 25 </span></span><span style="font-family: monospace"> </span>xLeft + <span style="color: #66ff19;">2</span> * width / <span style="color: #66ff19;">3</span>, yTop,</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 26 </span></span><span style="font-family: monospace"> </span>width / <span style="color: #66ff19;">3</span>, width * <span style="color: #66ff19;">2</span> / <span style="color: #66ff19;">3</span>);</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 27 </span></span><span style="font-family: monospace"> </span>Line2D.Double topLine = <span style="color: #cc0066;">new</span> Line2D.Double(</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 28 </span></span><span style="font-family: monospace"> </span>xLeft + width / <span style="color: #66ff19;">3</span>, yTop,</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 29 </span></span><span style="font-family: monospace"> </span>xLeft + width * <span style="color: #66ff19;">2</span> / <span style="color: #66ff19;">3</span>, yTop);</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 30 </span></span><span style="font-family: monospace"> </span>Line2D.Double bottomLine = <span style="color: #cc0066;">new</span> Line2D.Double(</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 31 </span></span><span style="font-family: monospace"> </span>xLeft + width / <span style="color: #66ff19;">3</span>, yTop + width * <span style="color: #66ff19;">2</span> / <span style="color: #66ff19;">3</span>,</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 32 </span></span><span style="font-family: monospace"> </span>xLeft + width * <span style="color: #66ff19;">2</span> / <span style="color: #66ff19;">3</span>, yTop + width * <span style="color: #66ff19;">2</span> / <span style="color: #66ff19;">3</span>);</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 33 </span></span><span style="font-family: monospace"> </span></pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 34 </span></span><span style="font-family: monospace"> </span>g2.setColor(Color.GREEN);</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 35 </span></span><span style="font-family: monospace"> </span>g2.fill(leftRectangle);</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 36 </span></span><span style="font-family: monospace"> </span>g2.setColor(Color.RED);</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 37 </span></span><span style="font-family: monospace"> </span>g2.fill(rightRectangle);</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 38 </span></span><span style="font-family: monospace"> </span>g2.setColor(Color.BLACK);</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 39 </span></span><span style="font-family: monospace"> </span>g2.draw(topLine);</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 40 </span></span><span style="font-family: monospace"> </span>g2.draw(bottomLine);</pre> <pre style="margin: 0em;"><span style="background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 41 </span></span><span style="font-family: monospace"> }</span></pre> <pre style="margin: 0em;background: #ededed"><span style="color: #0073ff; font-weight: bold;"> 42 </span><span style="font-family: monospace">}</span></pre> </body></html>
raeffu/prog1
src/ch02/flag/ItalianFlag.java.html
HTML
mit
9,782
/* * This file is generated by jOOQ. */ package top.zbeboy.isy.domain.tables.pojos; import java.io.Serializable; import javax.annotation.Generated; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.10.7" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class GraduationDesignReleaseFile implements Serializable { private static final long serialVersionUID = -983991061; private String graduationDesignReleaseId; private String fileId; public GraduationDesignReleaseFile() {} public GraduationDesignReleaseFile(GraduationDesignReleaseFile value) { this.graduationDesignReleaseId = value.graduationDesignReleaseId; this.fileId = value.fileId; } public GraduationDesignReleaseFile( String graduationDesignReleaseId, String fileId ) { this.graduationDesignReleaseId = graduationDesignReleaseId; this.fileId = fileId; } @NotNull @Size(max = 64) public String getGraduationDesignReleaseId() { return this.graduationDesignReleaseId; } public void setGraduationDesignReleaseId(String graduationDesignReleaseId) { this.graduationDesignReleaseId = graduationDesignReleaseId; } @NotNull @Size(max = 64) public String getFileId() { return this.fileId; } public void setFileId(String fileId) { this.fileId = fileId; } @Override public String toString() { StringBuilder sb = new StringBuilder("GraduationDesignReleaseFile ("); sb.append(graduationDesignReleaseId); sb.append(", ").append(fileId); sb.append(")"); return sb.toString(); } }
zbeboy/ISY
src/main/java/top/zbeboy/isy/domain/tables/pojos/GraduationDesignReleaseFile.java
Java
mit
1,891
<?php namespace WScore\Pile\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; interface ForgedControllerInterface extends ControllerInterface { /** * @return ForgedControllerInterface|Mixed */ public static function forge(); }
asaokamei/Pile
experimental/old-src/Controller/ForgedControllerInterface.php
PHP
mit
301
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("RightmoveProperties")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RightmoveProperties")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5ef01dd5-84a1-49f3-9232-067440288455")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("00.00.01.*")] [assembly: AssemblyFileVersion("00.00.01.*")]
wjonesy/RightmoveProperties
Properties/AssemblyInfo.cs
C#
mit
1,340
<?php /* +--------------------------------------------------------------------------+ | Zephir Language | +--------------------------------------------------------------------------+ | Copyright (c) 2013-2015 Zephir Team and contributors | +--------------------------------------------------------------------------+ | This source file is subject the MIT license, that is bundled with | | this package in the file LICENSE, and is available through the | | world-wide-web at the following url: | | http://zephir-lang.com/license.html | | | | If you did not receive a copy of the MIT license and are unable | | to obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +--------------------------------------------------------------------------+ */ namespace Zephir\Operators\Arithmetical; use Zephir\Operators\BaseOperator; use Zephir\CompilationContext; use Zephir\Expression; use Zephir\CompilerException; use Zephir\CompiledExpression; /** * DivOperator * * Generates an arithmetical operation according to the operands */ class DivOperator extends ArithmeticalBaseOperator { protected $_operator = '/'; protected $_bitOperator = '-'; protected $_zvalOperator = 'div_function'; /** * Compiles the arithmetical division operation * * @param array $expression * @param CompilationContext $compilationContext */ public function compile($expression, CompilationContext $compilationContext) { if (!isset($expression['left'])) { throw new \Exception("Missing left part of the expression"); } if (!isset($expression['right'])) { throw new \Exception("Missing right part of the expression"); } $leftExpr = new Expression($expression['left']); $leftExpr->setReadOnly(true); $left = $leftExpr->compile($compilationContext); $rightExpr = new Expression($expression['right']); $rightExpr->setReadOnly(true); $right = $rightExpr->compile($compilationContext); $compilationContext->headersManager->add('kernel/operators'); switch ($left->getType()) { case 'int': case 'uint': case 'long': case 'ulong': switch ($right->getType()) { case 'int': case 'uint': case 'long': case 'ulong': return new CompiledExpression('double', 'zephir_safe_div_long_long(' . $left->getCode() . ', ' . $right->getCode() . ' TSRMLS_CC)', $expression); case 'double': return new CompiledExpression('double', 'zephir_safe_div_long_double((double) ' . $left->getCode() . ', ' . $right->getCode() . ' TSRMLS_CC)', $expression); case 'bool': return new CompiledExpression('bool', '(' . $left->getCode() . ' - ' . $right->getBooleanCode() . ')', $expression); case 'variable': $variableRight = $compilationContext->symbolTable->getVariableForRead($right->getCode(), $compilationContext, $expression); switch ($variableRight->getType()) { case 'int': case 'uint': case 'long': case 'ulong': return new CompiledExpression('double', 'zephir_safe_div_long_long(' . $left->getCode() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); case 'bool': return new CompiledExpression('double', 'zephir_safe_div_long_long(' . $left->getCode() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); case 'double': return new CompiledExpression('double', 'zephir_safe_div_long_double(' . $left->getCode() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); case 'variable': if ($variableRight->isLocalOnly()) { return new CompiledExpression('double', 'zephir_safe_div_long_zval(' . $left->getCode() . ', &' . $variableRight->getName() . ' TSRMLS_CC)', $expression); } else { return new CompiledExpression('double', 'zephir_safe_div_long_zval(' . $left->getCode() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); } break; default: throw new CompilerException("Cannot operate variable('int') with variable('" . $variableRight->getType() . "')", $expression); } break; default: throw new CompilerException("Cannot operate 'int' with '" . $right->getType() . "'", $expression); } break; case 'bool': switch ($right->getType()) { case 'int': case 'uint': case 'long': case 'ulong': case 'double': return new CompiledExpression('long', '(' . $left->getBooleanCode() . ' - ' . $right->getCode() . ')', $expression); case 'bool': return new CompiledExpression('bool', '(' . $left->getBooleanCode() . ' ' . $this->_bitOperator . ' ' . $right->getBooleanCode() . ')', $expression); default: throw new CompilerException("Cannot operate 'bool' with '" . $right->getType() . "'", $expression); } break; case 'double': switch ($right->getType()) { case 'int': case 'uint': case 'long': case 'ulong': return new CompiledExpression('double', 'zephir_safe_div_double_long(' . $left->getCode() . ', (double) (' . $right->getCode() . ') TSRMLS_CC)', $expression); case 'double': return new CompiledExpression('double', 'zephir_safe_div_double_long(' . $left->getCode() . ', ' . $right->getCode() . ' TSRMLS_CC)', $expression); case 'bool': return new CompiledExpression('double', 'zephir_safe_div_double_long(' . $left->getCode() . ', ' . $right->getBooleanCode() . ' TSRMLS_CC)', $expression); case 'variable': $variableRight = $compilationContext->symbolTable->getVariableForRead($right->getCode(), $compilationContext, $expression); switch ($variableRight->getType()) { case 'int': case 'uint': case 'long': case 'ulong': return new CompiledExpression('double', 'zephir_safe_div_double_long(' . $left->getCode() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); case 'bool': return new CompiledExpression('double', 'zephir_safe_div_double_long(' . $left->getCode() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); case 'double': return new CompiledExpression('double', 'zephir_safe_div_double_double(' . $left->getCode() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); case 'variable': $compilationContext->headersManager->add('kernel/operators'); if ($variableRight->isLocalOnly()) { return new CompiledExpression('double', 'zephir_safe_div_double_zval(' . $left->getCode() . ', &' . $variableRight->getName() . ' TSRMLS_CC)', $expression); } else { return new CompiledExpression('double', 'zephir_safe_div_double_zval(' . $left->getCode() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); } break; default: throw new CompilerException("Cannot operate variable('double') with variable('" . $variableRight->getType() . "')", $expression); } break; default: throw new CompilerException("Cannot operate 'double' with '" . $right->getType() . "'", $expression); } break; case 'string': switch ($right->getType()) { default: throw new CompilerException("Operation is not supported between strings", $expression); } break; case 'array': switch ($right->getType()) { default: throw new CompilerException("Operation is not supported between arrays", $expression); } break; case 'variable': $variableLeft = $compilationContext->symbolTable->getVariableForRead($left->resolve(null, $compilationContext), $compilationContext, $expression); switch ($variableLeft->getType()) { case 'int': case 'uint': case 'long': case 'ulong': switch ($right->getType()) { case 'int': case 'uint': case 'long': case 'ulong': return new CompiledExpression('double', 'zephir_safe_div_long_long(' . $left->getCode() . ', ' . $right->getCode() . ' TSRMLS_CC)', $expression); case 'double': return new CompiledExpression('double', 'zephir_safe_div_long_double(' . $left->getCode() . ', ' . $right->getCode() . ' TSRMLS_CC)', $expression); case 'variable': $variableRight = $compilationContext->symbolTable->getVariableForRead($right->getCode(), $compilationContext, $expression['right']); switch ($variableRight->getType()) { case 'int': case 'uint': case 'long': case 'ulong': return new CompiledExpression('double', 'zephir_safe_div_long_long(' . $variableLeft->getName() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); case 'bool': return new CompiledExpression('double', 'zephir_safe_div_long_long(' . $variableLeft->getName() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); case 'double': return new CompiledExpression('double', 'zephir_safe_div_long_double(' . $variableLeft->getName() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); case 'variable': $compilationContext->headersManager->add('kernel/operators'); if ($variableRight->isLocalOnly()) { return new CompiledExpression('double', 'zephir_safe_div_long_zval(' . $variableLeft->getName() . ', &' . $variableRight->getName() . ' TSRMLS_CC)', $expression); } else { return new CompiledExpression('double', 'zephir_safe_div_long_zval(' . $variableLeft->getName() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); } break; default: throw new CompilerException("Cannot operate variable('int') with variable('" . $variableRight->getType() . "')", $expression); } break; default: throw new CompilerException("Cannot operate variable('int') with '" . $right->getType() . "'", $expression); } break; case 'bool': switch ($right->getType()) { case 'int': case 'uint': case 'long': case 'ulong': return new CompiledExpression('bool', '(' . $left->getCode() . ', ' . $right->getCode() . ')', $expression); case 'bool': return new CompiledExpression('bool', '(' . $left->getCode() . ' ' . $this->_bitOperator . ' ' . $right->getBooleanCode() . ')', $expression); case 'variable': $variableRight = $compilationContext->symbolTable->getVariableForRead($right->getCode(), $compilationContext, $expression['right']); switch ($variableRight->getType()) { case 'int': case 'uint': case 'long': case 'ulong': return new CompiledExpression('double', 'zephir_safe_div_long_long(' . $variableLeft->getName() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); case 'double': return new CompiledExpression('double', 'zephir_safe_div_long_double(' . $variableLeft->getName() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); case 'bool': return new CompiledExpression('double', 'zephir_safe_div_long_long(' . $variableLeft->getName() . ' ' . $this->_bitOperator . ' ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); case 'variable': $compilationContext->headersManager->add('kernel/operators'); if ($variableRight->isLocalOnly()) { return new CompiledExpression('double', 'zephir_safe_div_long_zval(' . $variableLeft->getName() . ', &' . $variableRight->getName() . ' TSRMLS_CC)', $expression); } else { return new CompiledExpression('double', 'zephir_safe_div_long_zval(' . $variableLeft->getName() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); } break; default: throw new CompilerException("Cannot operate variable('int') with variable('" . $variableRight->getType() . "')", $expression); } break; default: throw new CompilerException("Cannot operate variable('int') with '" . $right->getType() . "'", $expression); } break; case 'double': switch ($right->getType()) { case 'int': case 'uint': case 'long': case 'ulong': return new CompiledExpression('double', 'zephir_safe_div_double_long(' . $left->getCode() . ', ' . $right->getCode() . ' TSRMLS_CC)', $expression); case 'double': return new CompiledExpression('double', 'zephir_safe_div_double_long(' . $left->getCode() . ', ' . $right->getCode() . ' TSRMLS_CC)', $expression); case 'bool': return new CompiledExpression('bool', '(' . $left->getCode() . ' ' . $this->_bitOperator . ' ' . $right->getBooleanCode() . ')', $expression); case 'variable': $variableRight = $compilationContext->symbolTable->getVariableForRead($right->getCode(), $compilationContext, $expression['right']); switch ($variableRight->getType()) { case 'int': case 'uint': case 'long': case 'ulong': return new CompiledExpression('double', 'zephir_safe_div_double_long(' . $variableLeft->getName() . ', (double) ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); case 'double': return new CompiledExpression('double', 'zephir_safe_div_double_long(' . $variableLeft->getName() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); case 'bool': return new CompiledExpression('bool', '(' . $variableLeft->getName() . ' ' . $this->_bitOperator . ' ' . $variableRight->getName() . ')', $expression); case 'variable': $compilationContext->headersManager->add('kernel/operators'); if ($variableRight->isLocalOnly()) { return new CompiledExpression('double', 'zephir_safe_div_double_zval(' . $variableLeft->getName() . ', &' . $variableRight->getName() . ' TSRMLS_CC)', $expression); } else { return new CompiledExpression('double', 'zephir_safe_div_double_zval(' . $variableLeft->getName() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); } break; default: throw new CompilerException("Cannot operate variable('double') with variable('" . $variableRight->getType() . "')", $expression); } break; default: throw new CompilerException("Cannot operate variable('int') with '" . $right->getType() . "'", $expression); } break; case 'string': throw new CompilerException("Cannot operate string variables'", $expression); case 'array': throw new CompilerException("Cannot operate array variables'", $expression); case 'variable': switch ($right->getType()) { /* a + 1 */ case 'int': case 'uint': case 'long': case 'ulong': $compilationContext->headersManager->add('kernel/operators'); if ($variableLeft->isLocalOnly()) { $op1 = '&' . $variableLeft->getName(); } else { $op1 = $variableLeft->getName(); } $op2 = $right->getCode(); if ($right->getType() == 'double') { return new CompiledExpression('double', 'zephir_safe_div_zval_long(' . $op1 . ', ' . $op2 . ' TSRMLS_CC)', $expression); } else { return new CompiledExpression('double', 'zephir_safe_div_zval_long(' . $op1 . ', ' . $op2 . ' TSRMLS_CC)', $expression); } break; case 'double': $compilationContext->headersManager->add('kernel/operators'); if ($variableLeft->isLocalOnly()) { $op1 = '&' . $variableLeft->getName(); } else { $op1 = $variableLeft->getName(); } $op2 = $right->getCode(); if ($right->getType() == 'double') { return new CompiledExpression('double', 'zephir_safe_div_zval_double(' . $op1 . ', ' . $op2 . ' TSRMLS_CC)', $expression); } else { return new CompiledExpression('double', 'zephir_safe_div_zval_double(' . $op1 . ', ' . $op2 . ' TSRMLS_CC)', $expression); } break; /* a(var) + a(x) */ case 'variable': $variableRight = $compilationContext->symbolTable->getVariableForRead($right->resolve(null, $compilationContext), $compilationContext, $expression); switch ($variableRight->getType()) { /* a(var) + a(int) */ case 'int': case 'uint': case 'long': case 'ulong': $compilationContext->headersManager->add('kernel/operators'); if ($variableLeft->isLocalOnly()) { return new CompiledExpression('double', 'zephir_safe_div_zval_long(&' . $variableLeft->getName() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); } else { return new CompiledExpression('double', 'zephir_safe_div_zval_long(' . $variableLeft->getName() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); } break; /* a(var) + a(bool) */ case 'bool': $compilationContext->headersManager->add('kernel/operators'); if ($variableLeft->isLocalOnly()) { return new CompiledExpression('int', 'zephir_safe_div_zval_long(&' . $variableLeft->getName() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); } else { return new CompiledExpression('int', 'zephir_safe_div_zval_long(' . $variableLeft->getName() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); } break; /* a(var) + a(var) */ case 'variable': $compilationContext->headersManager->add('kernel/operators'); if ($variableLeft->isLocalOnly()) { $op1 = '&' . $variableLeft->getName(); } else { $op1 = $variableLeft->getName(); } if ($variableRight->isLocalOnly()) { $op2 = '&' . $variableRight->getName(); } else { $op2 = $variableRight->getName(); } $expected = $this->getExpected($compilationContext, $expression); if ($expected->isLocalOnly()) { $compilationContext->codePrinter->output($this->_zvalOperator . '(&' . $expected->getName() . ', ' . $op1 . ', ' . $op2 . ' TSRMLS_CC);'); } else { $compilationContext->codePrinter->output($this->_zvalOperator . '(' . $expected->getName() . ', ' . $op1 . ', ' . $op2 . ' TSRMLS_CC);'); } if ($variableLeft->isTemporal()) { $variableLeft->setIdle(true); } if ($variableRight->isTemporal()) { $variableRight->setIdle(true); } return new CompiledExpression('variable', $expected->getName(), $expression); default: throw new CompilerException("Cannot operate 'variable' with variable ('" . $variableRight->getType() . "')", $expression); } break; default: throw new CompilerException("Cannot operate 'variable' with '" . $right->getType() . "'", $expression); } break; case 'variable': switch ($right->getType()) { case 'int': case 'uint': case 'long': case 'ulong': $compilationContext->headersManager->add('kernel/operators'); if ($variableLeft->isLocalOnly()) { $op1 = '&' . $variableLeft->getName(); } else { $op1 = $variableLeft->getName(); } $op2 = $right->getCode(); return new CompiledExpression('double', 'zephir_safe_div_zval_long(' . $op1 . ', ' . $op2 . ' TSRMLS_CC)', $expression); case 'double': $compilationContext->headersManager->add('kernel/operators'); if ($variableLeft->isLocalOnly()) { $op1 = '&' . $variableLeft->getName(); } else { $op1 = $variableLeft->getName(); } $op2 = $right->getCode(); return new CompiledExpression('double', 'zephir_safe_div_zval_double(' . $op1 . ', ' . $op2 . ' TSRMLS_CC)', $expression); case 'variable': $variableRight = $compilationContext->symbolTable->getVariableForRead($right->resolve(null, $compilationContext), $compilationContext, $expression); switch ($variableRight->getType()) { case 'int': case 'uint': case 'long': case 'ulong': $compilationContext->headersManager->add('kernel/operators'); if ($variableLeft->isLocalOnly()) { return new CompiledExpression('double', 'zephir_safe_div_zval_long(&' . $variableLeft->getName() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); } else { return new CompiledExpression('double', 'zephir_safe_div_zval_long(' . $variableLeft->getName() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); } break; case 'bool': $compilationContext->headersManager->add('kernel/operators'); if ($variableLeft->isLocalOnly()) { return new CompiledExpression('double', 'zephir_safe_div_zval_long(&' . $variableLeft->getName() . '), ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); } else { return new CompiledExpression('double', 'zephir_safe_div_zval_long(' . $variableLeft->getName() . '), ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); } break; case 'variable': $variableRight = $compilationContext->symbolTable->getVariableForRead($variableRight->getCode(), $compilationContext, $expression); switch ($variableRight->getType()) { case 'int': return new CompiledExpression('double', 'zephir_safe_div_zval_long(' . $variableLeft->getName() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); case 'double': return new CompiledExpression('double', 'zephir_safe_div_zval_double(' . $variableLeft->getName() . ', ' . $variableRight->getName() . ' TSRMLS_CC)', $expression); case 'bool': return new CompiledExpression('bool', $variableLeft->getName() . ' ' . $this->_bitOperator . ' ' . $variableRight->getName(), $expression); case 'variable': $compilationContext->headersManager->add('kernel/operators'); if ($variableLeft->isLocalOnly()) { $op1 = '&' . $variableLeft->getName(); } else { $op1 = $variableLeft->getName(); } if ($variableRight->isLocalOnly()) { $op2 = '&' . $variableRight->getName(); } else { $op2 = $variableRight->getName(); } $expected = $this->getExpected($compilationContext, $expression); $compilationContext->codePrinter->output($this->_zvalOperator . '(' . $expected->getName() . ', ' . $op1 . ', ' . $op2 . ');'); return new CompiledExpression('variable', $expected->getName(), $expression); default: throw new CompilerException("Cannot operate variable('double') with variable('" . $variableRight->getType() . "')", $expression); } break; default: throw new CompilerException("Cannot operate 'variable' with variable ('" . $variableRight->getType() . "')", $expression); } break; default: throw new CompilerException("Cannot operate 'variable' with '" . $right->getType() . "'", $expression); } break; default: throw new CompilerException("Unknown '" . $variableLeft->getType() . "'", $expression); } break; default: throw new CompilerException("Unsupported type: " . $left->getType(), $expression); } } }
ovr/zephir
Library/Operators/Arithmetical/DivOperator.php
PHP
mit
34,000
<!DOCTYPE html> <html> <head> <title> SimpleModal Contact Form </title> <meta name='author' content='Eric Martin' /> <meta name='copyright' content='2013 - Eric Martin' /> <!-- Page styles --> <link type='text/css' href='style/demo.css' rel='stylesheet' media='screen' /> <!-- Contact Form CSS files --> <link type='text/css' href='style/contact.css' rel='stylesheet' media='screen' /> <!-- JS files are loaded at the bottom of the page --> </head> <body> <div id='container'> <div id='logo'> <h1>Simple<span>Modal</span></h1> <span class='title'>A Modal Dialog Framework Plugin for jQuery</span> </div> <div id='content'> <div id='contact-form'> <h3>Contact Form</h3> <p>A contact form built on SimpleModal. Demonstrates the use of the <code>onOpen</code>, <code>onShow</code> and <code>onClose</code> callbacks, as well as the use of Ajax with SimpleModal.</p> <p>To use: open <code>data/contact.php</code> and modify the <code>$to</code> and <code>$subject</code> values. To enable/disable information about the user, configure the <code>$extra</code> array.</p> <p><strong>Note:</strong> This demo must be run from a web server with PHP enabled.</p> <input type='button' name='contact' value='Demo' class='contact demo'/> or <a href='#' class='contact'>Demo</a> </div> <!-- preload the images --> <div style='display:none'> <img src='img/contact/loading.gif' alt='' /> </div> </div> <div id='footer'> &copy; 2013 <a href='http://www.ericmmartin.com/'>Eric Martin</a><br/> <a href='https://github.com/ericmmartin/simplemodal'>SimpleModal on GitHub</a><br/> <a href='http://twitter.com/ericmmartin'>@ericmmartin</a> | <a href='http://twitter.com/simplemodal'>@simplemodal</a> </div> </div> <!-- Load JavaScript files --> <script type='text/javascript' src='js/jquery.js'></script> <script type='text/javascript' src='js/jquery.simplemodal.js'></script> <script type='text/javascript' src='js/contact.js'></script> </body> </html>
jorjoh/Varden
frontend/contact/index.html
HTML
mit
1,978
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ms_MY" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Nodes</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;Nodes&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The Nodes developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or &lt;a href=&quot;http://www.opensource.org/licenses/mit-license.php&quot;&gt;http://www.opensource.org/licenses/mit-license.php&lt;/a&gt;. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (&lt;a href=&quot;https://www.openssl.org/&quot;&gt;https://www.openssl.org/&lt;/a&gt;) and cryptographic software written by Eric Young (&lt;a href=&quot;mailto:[email protected]&quot;&gt;[email protected]&lt;/a&gt;) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>Klik dua kali untuk mengubah alamat atau label</translation> </message> <message> <location line="+24"/> <source>Create a new address</source> <translation>Cipta alamat baru</translation> </message> <message> <location line="+10"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Salin alamat terpilih ke dalam sistem papan klip</translation> </message> <message> <location line="-7"/> <source>&amp;New Address</source> <translation>Alamat baru</translation> </message> <message> <location line="-43"/> <source>These are your Nodes addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign a message to prove you own a Nodes address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Verify a message to ensure it was signed with a specified Nodes address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Delete</source> <translation>&amp;Padam</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Fail yang dipisahkan dengan koma</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+145"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation>Alamat</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation type="unfinished"/> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Kata laluan</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Kata laluan baru</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Ulang kata laluan baru</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+38"/> <source>Encrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Confirm wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;ten or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Nodes will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation type="unfinished"/> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation type="unfinished"/> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+297"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Show general overview of wallet</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation>Buku Alamat</translation> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-18"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>E&amp;xit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Quit application</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Show information about Nodes</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>Pilihan</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-55"/> <source>Send coins to a Nodes address</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>Modify configuration options for Nodes</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-214"/> <location line="+551"/> <source>Nodes</source> <translation type="unfinished"/> </message> <message> <location line="-551"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>&amp;About Nodes</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Tabs toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <location line="+9"/> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+58"/> <source>Nodes client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+70"/> <source>%n active connection(s) to Nodes network</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+488"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message> <location line="-808"/> <source>&amp;Dashboard</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+273"/> <source>Up to date</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid Nodes address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Wallet is &lt;b&gt;not encrypted&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+91"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="-429"/> <location line="+433"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="-456"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+27"/> <location line="+433"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="-429"/> <location line="+6"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+0"/> <source>%1 and %2</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+0"/> <source>%n year(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+324"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+104"/> <source>A fatal error occurred. Nodes can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+110"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+552"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation>Alamat</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+317"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+155"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <location line="+66"/> <source>(no label)</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Alamat</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>Alamat</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Nodes address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+426"/> <location line="+12"/> <source>Nodes-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start Nodes after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start Nodes on system login</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the Nodes client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the Nodes network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Nodes.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Whether to select the coin outputs randomly or with minimal coin age.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Minimize weight consumption (experimental)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use black visual theme (requires restart)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Nodes.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <location line="+247"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Nodes network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-173"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-113"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Total:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-118"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-32"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start Nodes: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-194"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+197"/> <source>&amp;Network Traffic</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Clear</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Totals</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>In:</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Out:</source> <translation type="unfinished"/> </message> <message> <location line="-383"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the Nodes-Qt help message to get a list with possible Nodes command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-237"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>Nodes - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Nodes Core</source> <translation type="unfinished"/> </message> <message> <location line="+256"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the Nodes debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="+325"/> <source>Welcome to the Nodes RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> <message> <location line="+127"/> <source>%1 B</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 KB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 MB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 GB</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>%1 m</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>%1 h</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 h %2 m</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+181"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 NODES</source> <translation type="unfinished"/> </message> <message> <location line="-191"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Balance:</source> <translation>Baki</translation> </message> <message> <location line="+16"/> <source>123.456 NODES</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a Nodes address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+247"/> <source>WARNING: Invalid Nodes address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Nodes address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Nodes address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Nodes address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Nodes address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter Nodes signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <location filename="../trafficgraphwidget.cpp" line="+75"/> <source>KB/s</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+25"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-36"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+71"/> <source>unknown</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+231"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation>Alamat</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation type="unfinished"/> </message> <message> <location line="+194"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+54"/> <location line="+17"/> <source>All</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Today</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This week</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Last month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This year</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Range...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>To yourself</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Other</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Min amount</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+138"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Fail yang dipisahkan dengan koma</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Address</source> <translation>Alamat</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+208"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+173"/> <source>Nodes version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send command to -server or d</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <location line="-147"/> <source>Options:</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify configuration file (default: Nodes.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: d.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=rpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Nodes Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Always query for peer addresses via DNS lookup (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-37"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+65"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 25715)</source> <translation type="unfinished"/> </message> <message> <location line="-17"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+96"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="-103"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Nodes will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+132"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-18"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+101"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="-91"/> <source>Sync checkpoints policy (default: strict)</source> <translation type="unfinished"/> </message> <message> <location line="+89"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-88"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="-17"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+30"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-35"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="-43"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+116"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation type="unfinished"/> </message> <message> <location line="-86"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="-26"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="-54"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-56"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-32"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Output debugging information (default: 0, supplying &lt;category&gt; is optional)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&lt;category&gt; can be:</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wait for RPC server to start</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Initialization sanity check failed. Nodes is shutting down.</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation type="unfinished"/> </message> <message> <location line="-174"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+104"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-133"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+126"/> <source>Loading addresses...</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of Nodes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart Nodes to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="-40"/> <source>Loading block index...</source> <translation type="unfinished"/> </message> <message> <location line="-110"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="+125"/> <source>Unable to bind to %s on this computer. Nodes is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-101"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Minimize weight consumption (experimental) (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>How many blocks to check at startup (default: 500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Keep at most &lt;n&gt; unconnectable blocks in memory (default: %u)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Nodes is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Loading wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Done loading</source> <translation type="unfinished"/> </message> <message> <location line="-161"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="+188"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="-18"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
NodesForAll/live
src/qt/locale/bitcoin_ms_MY.ts
TypeScript
mit
109,437
package me.coley.recaf.plugin.api; /** * Allow plugins to intercept and modify loaded classes and files. * * @author Matt */ public interface LoadInterceptorPlugin extends BasePlugin { /** * Intercept the given class. * * @param name * Internal name of class. * @param code * Raw bytecode of class. * * @return Bytecode of class to load. */ byte[] interceptClass(String name, byte[] code); /** * Intercept the given class. This class however, cannot be parsed by ASM. * * @param entryName * File name. * @param code * Raw bytecode of class. * * @return Bytecode of class to load. */ byte[] interceptInvalidClass(String entryName, byte[] code); /** * Intercept the given file. * * @param entryName * File name. * @param value * Raw data of file. * * @return Raw data to load. */ byte[] interceptFile(String entryName, byte[] value); }
Col-E/Recaf
src/main/java/me/coley/recaf/plugin/api/LoadInterceptorPlugin.java
Java
mit
913
using System; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Math; namespace Org.BouncyCastle.Asn1.Pkcs { public class MacData : Asn1Encodable { internal DigestInfo digInfo; internal byte[] salt; internal IBigInteger iterationCount; public static MacData GetInstance( object obj) { if (obj is MacData) { return (MacData) obj; } if (obj is Asn1Sequence) { return new MacData((Asn1Sequence) obj); } throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj"); } private MacData( Asn1Sequence seq) { this.digInfo = DigestInfo.GetInstance(seq[0]); this.salt = ((Asn1OctetString) seq[1]).GetOctets(); if (seq.Count == 3) { this.iterationCount = ((DerInteger) seq[2]).Value; } else { this.iterationCount = BigInteger.One; } } public MacData( DigestInfo digInfo, byte[] salt, int iterationCount) { this.digInfo = digInfo; this.salt = (byte[]) salt.Clone(); this.iterationCount = BigInteger.ValueOf(iterationCount); } public DigestInfo Mac { get { return digInfo; } } public byte[] GetSalt() { return (byte[]) salt.Clone(); } public IBigInteger IterationCount { get { return iterationCount; } } /** * <pre> * MacData ::= SEQUENCE { * mac DigestInfo, * macSalt OCTET STRING, * iterations INTEGER DEFAULT 1 * -- Note: The default is for historic reasons and its use is deprecated. A * -- higher value, like 1024 is recommended. * </pre> * @return the basic DERObject construction. */ public override Asn1Object ToAsn1Object() { Asn1EncodableVector v = new Asn1EncodableVector(digInfo, new DerOctetString(salt)); if (!iterationCount.Equals(BigInteger.One)) { v.Add(new DerInteger(iterationCount)); } return new DerSequence(v); } } }
SchmooseSA/Schmoose-BouncyCastle
Crypto/asn1/pkcs/MacData.cs
C#
mit
2,264
class GalleryKeyword < ActiveRecord::Base has_and_belongs_to_many :gallery_items, :join_table => "gallery_items_keywords", :foreign_key => "keyword_id", :uniq => true, :class_name => "GalleryItem", :association_foreign_key => "gallery_item_id" has_and_belongs_to_many :galleries, :join_table => "galleries_keywords", :foreign_key => "keyword_id", :uniq => true, :class_name => "Gallery", :association_foreign_key => "gallery_id" end
pilu/radiant-gallery
app/models/gallery_keyword.rb
Ruby
mit
521
<div class="col-lg-7 col-md-8 col-sm-8" id="butor-products-image"> <?php if(isset($product_result[0][0])):?> <h3 class="butor-caption"><?php if(isset($product_result[0][0]->CaMainTitle)) echo $product_result[0][0]->CaMainTitle; elseif (isset($product_result[0][0]->CaTitle)) echo $product_result[0][0]->CaTitle; else echo "Termékkategória";?></h3> <div id="thumb-container" class="container-fluid"> <?php if((isset($product_result[0][0]->smallPrImg) || isset($product_result[0][0]->CaTopText) || isset($product_result[0][0]->CaText)) && ($product_result[0][0]->smallPrImg || $product_result[0][0]->CaTopText || $product_result[0][0]->CaText)): ?> <?php foreach($product_result as $product_result_item): ?> <div class="row"> <h4 class="subcategory-title"><?php if(isset($product_result_item[0]->CaMainTitle)) echo $product_result_item[0]->CaTitle; ?></h4> <?php if(isset($product_result_item[0]->CaTopText) && $product_result_item[0]->CaTopText ) : ?> <div id="top-text"> <p class="text-center"> <?php echo $product_result_item[0]->CaTopText;?> </p> </div> <?php endif; ?> <?php if(isset($product_result_item[0]->smallPrImg) && $product_result_item[0]->smallPrImg): ?> <?php foreach($product_result_item as $resultItem): ?> <?php if(isset($resultItem->sep) && $resultItem->sep): ?> </div> <div class="row"> <p style="margin-left:12px"><?php echo $resultItem->sep ?></p> </div> <div class="row"> <?php endif; ?> <div class="col-lg-4 col-md-4 col-sm-6"> <div class="thumbnail"> <a href="<?php echo base_url(); if(isset($resultItem->isPV) && $resultItem->isPV) echo "termek-valtozatok/".$category."/"; else echo "termek/".$category."/"; if(isset($subcategory))echo $subcategory.'/'; else echo '0/'; echo $resultItem->name; echo "/".$resultItem->id;?>"><img src="<?php echo base_url();?>content/images/<?php echo $resultItem->smallPrImg;?>"></a> <h6><a href="<?php echo base_url(); if(isset($resultItem->isPV) && $resultItem->isPV) echo "termek-valtozatok/".$category."/"; else echo "termek/".$category."/"; if(isset($subcategory))echo $subcategory.'/'; else echo '0/'; echo $resultItem->name; echo "/".$resultItem->id;?>"><?php echo $resultItem->title; ?></h6></a> </div> </div> <?php endforeach; ?> <?php endif; ?> </div> <?php if($product_result_item[0]->CaText): ?> <p class="text-center"> <?php echo $product_result_item[0]->CaText;?> </p> <?php endif; ?> <?php endforeach; ?> <?php endif; ?> <?php if(isset($result) && $result[0]->text): ?> <br><br> <p class="text-center"> <?php echo $result[0]->text;?> </p> <?php endif; ?> </div> <?php else:?> <h3 class="butor-caption">Hiba</h3> <div class="container-fluid" id="subcategory-container"> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-6"> <div class="thumbnail"> <h4>Nincs megjeleníthető elem ebben az alkategoriában</h4> </div> </div> </div> </div> <?php endif;?> </div>
Szabi313/Butor
application/views/butor/butor_catetgory_content.php
PHP
mit
3,491
var chai = require('chai'); var assert = chai.assert; var util = require('util'); var QueryParser = require('../../../lib/query/queryParser'); var EsQueryBuilder = require('../../../lib/query/es/esQueryBuilder'); describe('ElasticSearch Query Builder', function() { var sut; // sut = "System under test" var dummyIndexNameBuilder; var queryParser; var dummyTemplateQuery; var dummyQueryInfo; var dummyParamValues; beforeEach(function() { dummyIndexNameBuilder = { buildIndexName: function(params) { // Note: these index names are just for tests return [ util.format('logstash-%s-%s', params.tenantId, params.from), util.format('logstash-%s-%s', params.tenantId, params.to) ]; } }; sut = new EsQueryBuilder(dummyIndexNameBuilder); queryParser = new QueryParser(); // Set up some dummy value that will let us easily invoke sut.parse when we don't care about query values: dummyTemplateQuery = { foo: "PARAMS.bar" }; dummyQueryInfo = queryParser.parse(dummyTemplateQuery); dummyParamValues = { bar: 'bar-value' }; }); // Sanity check that we call the underlying queryBuilder.build method: it('can replace parameter values in template query', function() { var templateQuery = { foo: "${params.bar}" }; var queryInfo = queryParser.parse(templateQuery); var paramValues = { params: { bar: 'bar-value' } }; var query = sut.build(templateQuery, queryInfo.params, paramValues); assert.deepEqual(query.queryObj, { foo: "bar-value" }); }); it('can generate ES index name', function() { var templateQuery = { foo: "PARAMS.bar" }; var queryInfo = queryParser.parse(templateQuery); var paramValues = { bar: 'bar-value', tenantId: 'T1', from: 111, to: 222 }; var query = sut.build(templateQuery, queryInfo.params, paramValues); assert.deepEqual(query.index, ['logstash-T1-111', 'logstash-T1-222']); }); it('can use defaults to set ES query metadata', function() { var sut = new EsQueryBuilder(dummyIndexNameBuilder, { defaults: { type: 'events', searchType: 'count' } }); var query = sut.build(dummyTemplateQuery, dummyQueryInfo.params, dummyParamValues); assert.equal(query.type, 'events'); assert.equal(query.searchType, 'count'); }); it('can override ES query metadata defaults', function() { var sut = new EsQueryBuilder(dummyIndexNameBuilder, { defaults: { type: 'events', searchType: 'count' } }); var query = sut.build(dummyTemplateQuery, dummyQueryInfo.params, dummyParamValues, { type: 'x', searchType: 'y' }); assert.equal(query.type, 'x'); assert.equal(query.searchType, 'y'); }); });
panoptix-za/hotrod-dash-data
tests/query/es/esQueryBuilderTests.js
JavaScript
mit
3,121
<?php namespace SVGPHPDOMExtender\Attributes; class XChannelSelectorAttr extends AbstractAttr { public static $name = 'xChannelSelector'; }
Arlisaha/SVG-PHP-DOM-Extender
src/Attributes/XChannelSelectorAttr.php
PHP
mit
142
package xlU_go const ( DEFAULT_BUFFER_SIZE = 256 * 1024 ) type DirStruc int const ( DIR_FLAT DirStruc = iota DIR16x16 DIR256x256 )
jddixon/xlU_go
const.go
GO
mit
138
# -*- encoding:utf-8 -*- module DocbookFiles # :stopdoc: LIBPATH = ::File.expand_path(::File.dirname(__FILE__)) + ::File::SEPARATOR PATH = ::File.dirname(LIBPATH) + ::File::SEPARATOR VERSION = ::File.read(PATH + 'version.txt').strip # :startdoc: # Returns the library path for the module. If any arguments are given, # they will be joined to the end of the libray path using # <tt>File.join</tt>. # def self.libpath( *args ) rv = args.empty? ? LIBPATH : ::File.join(LIBPATH, args.flatten) if block_given? begin $LOAD_PATH.unshift LIBPATH rv = yield ensure $LOAD_PATH.shift end end return rv end # Returns the lpath for the module. If any arguments are given, # they will be joined to the end of the path using # <tt>File.join</tt>. # def self.path( *args ) rv = args.empty? ? PATH : ::File.join(PATH, args.flatten) if block_given? begin $LOAD_PATH.unshift PATH rv = yield ensure $LOAD_PATH.shift end end return rv end # Utility method used to require all files ending in .rb that lie in the # directory below this file that has the same name as the filename passed # in. Optionally, a specific _directory_ name can be passed in such that # the _filename_ does not have to be equivalent to the directory. # def self.require_all_libs_relative_to( fname, dir = nil ) dir ||= ::File.basename(fname, '.*') search_me = ::File.expand_path( ::File.join(::File.dirname(fname), dir, '**', '*.rb')) Dir.glob(search_me).sort.each {|rb| require rb} end end # module DocbookFiles DocbookFiles.require_all_libs_relative_to(__FILE__)
rvolz/docbook_files
lib/docbook_files.rb
Ruby
mit
1,712
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF 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 com.app.lab35; import android.os.Bundle; import org.apache.cordova.*; public class MainActivity extends CordovaActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set by <content src="index.html" /> in config.xml loadUrl(launchUrl); } }
alejo8591/unipiloto-am-2
labs/lab35/platforms/android/src/com/app/lab35/MainActivity.java
Java
mit
1,206
class Download COUNT_KEY = "downloads" TODAY_KEY = "downloads:today" YESTERDAY_KEY = "downloads:yesterday" def self.incr(name, full_name) $redis.incr(COUNT_KEY) $redis.incr(rubygem_key(name)) $redis.incr(version_key(full_name)) $redis.zincrby(TODAY_KEY, 1, full_name) end def self.count $redis.get(COUNT_KEY).to_i end def self.today(version) $redis.zscore(TODAY_KEY, version.full_name).to_i end def self.for(what) $redis.get(key(what)).to_i end def self.for_rubygem(name) $redis.get(rubygem_key(name)).to_i end def self.for_version(full_name) $redis.get(version_key(full_name)).to_i end def self.most_downloaded_today items = $redis.zrevrange(TODAY_KEY, 0, 4, :with_scores => true) items.in_groups_of(2).collect do |full_name, downloads| version = Version.find_by_full_name(full_name) [version, downloads.to_i] end end def self.key(what) case what when Version version_key(what.full_name) when Rubygem rubygem_key(what.name) end end def self.history_key(what) case what when Version "downloads:version_history:#{what.full_name}" when Rubygem "downloads:rubygem_history:#{what.name}" end end def self.rollover $redis.rename TODAY_KEY, YESTERDAY_KEY yesterday = 1.day.ago.to_date.to_s versions = Version.includes(:rubygem).inject({}) do |hash, v| hash[v.full_name] = v hash end downloads = Hash[*$redis.zrange(YESTERDAY_KEY, 0, -1, :with_scores => true)] downloads.each do |key, score| version = versions[key] $redis.hincrby history_key(version), yesterday, score.to_i $redis.hincrby history_key(version.rubygem), yesterday, score.to_i version.rubygem.increment! :downloads, score.to_i end end def self.version_key(full_name) "downloads:version:#{full_name}" end def self.rubygem_key(name) "downloads:rubygem:#{name}" end end
alloy/gemcutter
app/models/download.rb
Ruby
mit
1,990
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <!-- /fasttmp/mkdist-qt-4.3.5-1211793125/qtopia-core-opensource-src-4.3.5/src/gui/kernel/qsound.cpp --> <head> <title>Qt 4.3: Qt 3 Support Members for QSound</title> <link href="classic.css" rel="stylesheet" type="text/css" /> </head> <body> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td align="left" valign="top" width="32"><a href="http://www.trolltech.com/products/qt"><img src="images/qt-logo.png" align="left" width="32" height="32" border="0" /></a></td> <td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">All&nbsp;Classes</font></a>&nbsp;&middot; <a href="mainclasses.html"><font color="#004faf">Main&nbsp;Classes</font></a>&nbsp;&middot; <a href="groups.html"><font color="#004faf">Grouped&nbsp;Classes</font></a>&nbsp;&middot; <a href="modules.html"><font color="#004faf">Modules</font></a>&nbsp;&middot; <a href="functions.html"><font color="#004faf">Functions</font></a></td> <td align="right" valign="top" width="230"><a href="http://www.trolltech.com"><img src="images/trolltech-logo.png" align="right" width="203" height="32" border="0" /></a></td></tr></table><h1 align="center">Qt 3 Support Members for QSound</h1> <p><b>The following class members are part of the <a href="qt3support.html">Qt 3 support layer</a>.</b> They are provided to help you port old code to Qt 4. We advise against using them in new code.</p> <p><ul><li><a href="qsound.html">QSound class reference</a></li></ul></p> <h3>Public Functions</h3> <ul> <li><div class="fn"/><b><a href="qsound-qt3.html#QSound-2">QSound</a></b> ( const QString &amp; <i>filename</i>, QObject * <i>parent</i>, const char * <i>name</i> )</li> </ul> <ul> <li><div class="fn"/>8 public functions inherited from <a href="qobject.html#public-functions">QObject</a></li> </ul> <h3>Static Public Members</h3> <ul> <li><div class="fn"/>bool <b><a href="qsound-qt3.html#available">available</a></b> ()</li> </ul> <hr /> <h2>Member Function Documentation</h2> <h3 class="fn"><a name="QSound-2"></a>QSound::QSound ( const <a href="qstring.html">QString</a> &amp; <i>filename</i>, <a href="qobject.html">QObject</a> * <i>parent</i>, const char * <i>name</i> )</h3> <p>Constructs a <a href="qsound.html">QSound</a> object from the file specified by the given <i>filename</i> and with the given <i>parent</i> and <i>name</i>. Use the <a href="qsound.html#QSound">QSound</a>() construcor and <a href="qobject.html#objectName-prop">QObject::setObjectName</a>() instead.</p> <p>For example, if you have code like</p> <pre><font color="#404040"> QSound *mySound = new QSound(filename, parent, name);</font></pre> <p>you can rewrite it as</p> <pre> QSounc *mySound = new QSound(filename, parent); mySound-&gt;setObjectName(name);</pre> <h3 class="fn"><a name="available"></a>bool QSound::available ()&nbsp;&nbsp;<tt> [static]</tt></h3> <p>Use the <a href="qsound.html#isAvailable">isAvailable</a>() function instead.</p> <p /><address><hr /><div align="center"> <table width="100%" cellspacing="0" border="0"><tr class="address"> <td width="30%">Copyright &copy; 2008 <a href="trolltech.html">Trolltech</a></td> <td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td> <td width="30%" align="right"><div align="right">Qt 4.3.5</div></td> </tr></table></div></address></body> </html>
misizeji/StudyNote_201308
webserver/html/qsound-qt3.html
HTML
mit
3,618
var mongoose = require('mongoose'); var questions = require('../controllers/Questions.js'); module.exports = function(app) { app.post('/question/add', function(req,res){ questions.createQuestion(req,res) }); app.post('/question/delete', function(req,res){ questions.destroyQuestion(req,res) }); app.get('/question', function(req,res){ questions.showQuestion(req,res) }); }
Cindjor/Riddle-Me-Quiz
server/config/routes.js
JavaScript
mit
380
/** * This exports the string that is used for managing module loading in a bundle. * It also handles loading bundles that need to be loaded dynamically */ module.exports.BUNDLE_MODULE_LOADER = function (moduleMap, entries) { var results = {}; function get(id) { if (!results.hasOwnProperty(id)) { var meta = { exports: {} }; var load = moduleMap[id][0]; var deps = moduleMap[id][1]; results[id] = meta.exports; load(dependencyGetter(deps), meta, meta.exports); results[id] = meta.exports; } return results[id]; } function has(id) { return moduleMap[id]; } function dependencyGetter(depsByName) { return function getDependency(name) { var id = depsByName[name]; if (has(id)) { return get(id); } for (var _next = get.next; _next; _next = _next.next) { if (_next.has(id)) { return _next.get(id); } } for (var _prev = get.prev; _prev; _prev = _prev.prev) { if (_prev.has(id)) { return _prev.get(id); } } throw new Error("Module '" + name + "' with id " + id + " was not found"); }; } get.get = get; get.has = has; get.next = typeof _bb$iter === "undefined" ? null : _bb$iter; if (entries.length) { for (var _prev = get, _next = get.next; _next;) { _next.prev = _prev; _prev = _next; _next = _next.next; } } entries.forEach(get); return get; }.toString(); module.exports.REQUIRE_NAME = "_bb$req"; module.exports.BUNDLE_ITERATOR_NAME = "_bb$iter";
MiguelCastillo/bit-bundler
src/bundler/bundleConstants.js
JavaScript
mit
1,582
/** * @author Brandon Choi, James Mosca */ package userInterface; import java.io.IOException; import java.util.List; import java.util.ResourceBundle; import worldController.WorldController; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Button; import javafx.scene.control.TextArea; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.StackPane; public class UI { /** * UI represents the user interface of a single instance of SLogo. Multiple instances can be * added by creating a new tab in UIManager */ public static final int PANEL_WIDTH = 200; public static final int PANEL_HEIGHT = 500; private static final String PLAY_BUTTON = "resources/images/PlayButton.jpg"; private static final int INPUT_WIDTH = 450; private static final int INPUT_HEIGHT = 300; private WorldController myController; private BorderPane myView, myCenterView; private HBox myCommandField; private TextArea myInput; private boolean firstClick; private RightPanel myRightPanel; private LeftPanel myLeftPanel; private Canvas myCanvas; private GraphicsContext myGC; private StackPane canvasPane; private StringProperty inputText; private List<ObjectProperty> myBindings; private ObjectProperty<ResourceBundle> myLanguage; private ObjectProperty<String> myCanvasColor; public UI (List<ObjectProperty> bindings) { initialize(bindings); } /** * @return BorderPane myView */ public Pane getUI () { return myView; } /** * initializes the UI by creating border panes and setting up necessary components such as the * command field * * @param List<ObjectProperty> bindings */ private void initialize (List<ObjectProperty> bindings) { myBindings = bindings; myLanguage = myBindings.get(UIManager.LANGUAGE_INDEX); myCanvasColor = myBindings.get(UIManager.CANVAS_INDEX); myView = new BorderPane(); myView = new BorderPane(); myView.setPadding(new Insets(10, 10, 10, 10)); myCenterView = new BorderPane(); myCenterView.setPadding(new Insets(5, 5, 5, 5)); setUpCommandField(); setUpPane(); setUpController(); myView.setCenter(myCenterView); myView.setRight(myRightPanel.getInstance().getPanel()); myView.setLeft(myLeftPanel.getInstance().getPanel()); myCenterView.setCenter(canvasPane); myCenterView.setBottom(myCommandField); myCenterView.setAlignment(myInput, Pos.CENTER); } /** * sets up the WorldController */ private void setUpController () { try { myController = new WorldController(this, myRightPanel, myLeftPanel, inputText, myBindings); } catch (IOException e) { e.printStackTrace(); } } /** * sets up the command field which will be cleared the first time it is clicked and whenever it * is played * * binding between inputText and myInput allows the user to double click a saved or previous * command and have it appear in the command box */ private void setUpCommandField () { myCommandField = new HBox(15); myInput = new TextArea(myLanguage.getValue().getString("InputText")); inputText = new SimpleStringProperty(); inputText = myInput.textProperty(); firstClick = true; myInput.setMaxSize(INPUT_WIDTH, INPUT_HEIGHT); myInput.setOnMouseClicked(e -> { if (firstClick) { myInput.clear(); firstClick = false; } }); myCommandField.setAlignment(Pos.CENTER); myCommandField.getChildren().addAll(myInput, makeRunButton()); } /** * creates run button * @return Button play */ private Button makeRunButton () { Button play = new Button(); Image playImage = new Image(PLAY_BUTTON); ImageView playView = new ImageView(playImage); play.setGraphic(playView); play.setOnAction(e -> runCommand()); return play; } /** * sets up the canvas pane with the canvas and graphics context */ private void setUpPane () { canvasPane = new StackPane(); canvasPane.setPadding(new Insets(10, 10, 10, 10)); myCanvas = new Canvas(); myGC = myCanvas.getGraphicsContext2D(); canvasPane.getChildren().add(myCanvas); canvasPane.styleProperty().bind(myCanvasColor); } /** * called to run whatever command(s) are in the command field */ private void runCommand () { myController.update(inputText.getValue()); myInput.clear(); } public GraphicsContext getGraphics () { return myGC; } public Canvas getCanvas () { return myCanvas; } public StackPane getPane () { return canvasPane; } }
brandonnchoii/SLogo
src/userInterface/UI.java
Java
mit
5,412
# (c) 2017 Gregor Mitscha-Baude """Random walks in Pugh pore on 2D proxy geometry, to determine distribution of attempt time needed to fit binding parameters.""" import numpy as np import scipy as sp import matplotlib.pyplot as plt import tangent import dolfin import nanopores import nanopores.models.randomwalk as randomwalk from nanopores.tools.polygons import Rectangle from nanopores.tools import fields, statistics fields.set_dir_mega() params = nanopores.user_params( # general params # geo geoname = "pughcyl", dim = 2, diamPore = 6., rMolecule = 2.0779, R = 40., Htop = 60., Hbot = 35., geop = dict(R=40., Htop=60., Hbot=35.), x0 = None, # physics Qmol = 5., bulkcon = 1000., dnaqsdamp = 0.7353, bV = -0.1, posDTarget = True, # solver h = 2., frac = 0.5, Nmax = 5e4, imax = 30, tol = 1e-3, cheapest = False, stokesiter = False, #True hybrid = True, reconstruct = False, # random walk params N = 100, # number of (simultaneous) random walks dt = .2, # time step [ns] walldist = 1., # in multiples of radius, should be >= 1 margtop = 15., # 35 is about the maximum margbot = 0., rstart = 5., initial = "sphere", # receptor params bind_everywhere = False, lbind = 8., # length of binding zone for long binding [nm] ra = .2, # binding zone radius [nm] (1nm means whole channel) collect_stats_mode = True, ) ########### WHAT TO DO ########### todo = nanopores.user_params( test_solver = False, plot_dolfin = False, plot_streamlines = False, video = True, plot_distribution = False, fit_experiments = False, fit_gamma = False, fit_long = False, fit_long_gamma = False, ) ########### SETUP ########### NAME = "rw_pugh_0" def binding_(params): # TODO: make other params dependent on additional **args return dict( binding = True, bind_type = "zone", collect_stats_mode = params["collect_stats_mode"], t = 1e9, # mean of exponentially distributed binding duration [ns] ka = 1e9, # (bulk) association rate constant [1/Ms] ra = params["ra"], # radius of the association zone [nm] use_force = True, # if True, t_mean = t*exp(-|F|*dx/kT) dx = 0.1, # width of bond energy barrier [nm] ) def setup_rw(params, **_): pore = nanopores.get_pore(**params) rw = randomwalk.RandomWalk(pore, **params) binding_params = binding_(params) if params["bind_everywhere"]: rw.add_wall_binding(**binding_params) else: r = pore.params.l3/2. z = -pore.params.hpore/2. + pore.params.h4 wbind = 1. lbind = params["lbind"] bindsite = Rectangle((r, r + wbind), (z, z + lbind)) rw.add_domain(bindsite, exclusion=False, **binding_params) #rw.domains[0].__dict__.update(exclusion=True, binding=True, # bind_type="collision", eps=0., p=1., walldist=1.) return rw ########### TEST AND PLOT SOLVER ########### if todo.test_solver: import nanopores.models.nanopore as nanopore setup = nanopore.Setup(**params) _, pnps = nanopore.solve(setup, True) dolfin.interactive() if todo.plot_dolfin: rw = setup_rw(params) dolfin.plot(rw.D[1]) dolfin.plot(rw.F) dolfin.interactive() if todo.plot_streamlines: rw = setup_rw(params) rw.plot_streamlines(both=True, R=20, Hbot=30, Htop=35, maxvalue=1e-10, figsize=(5, 5)) plt.figure("D") dolfin.plot(rw.D[1], backend="matplotlib") #plt.show() if todo.video: rw = setup_rw(params) randomwalk.run(rw) ########### PLOT ATTEMPT TIME DISTRIBUTION ########### def NLS(ti, yi, t0=0., tol=1e-14): "nonlinear least squares to fit exponential distribution with mean exp(x)" xi = np.log(ti) def f(x, xi, yi): return np.sum((1. - np.exp(-np.exp(xi - x)) - yi)**2) # minimize f by solving df(x) = 0 with newton method df = tangent.grad(f) ddf = tangent.grad(df) x = np.log(t0) while np.abs(df(x, xi, yi)) > tol: x -= df(x, xi, yi)/ddf(x, xi, yi) #print "|f(x)|", np.abs(df(x, xi, yi)) return np.exp(x) def NLS2(ti, yi, t10=1., t20=100., w0=0.5, tol=1e-14): "nonlinear least squares to fit DOUBLE exponential distribution" xi = np.log(ti) # find: characteristic times exp(x1), exp(x2) and weights w1, w2 def f(theta, xi, yi): w = theta[0] x1, x2 = theta[1], theta[2] z = w*np.exp(-np.exp(xi - x1)) + (1.-w)*np.exp(-np.exp(xi - x2)) return np.sum((1. - z - yi)**2) # minimize f by solving df(x) = 0 with newton method df = tangent.grad(f) ddf = tangent.grad(df, mode="forward") def Jf(theta, xi, yi): return np.array([ddf(theta, xi, yi, 1., [1,0,0]), ddf(theta, xi, yi, 1., [0,1,0]), ddf(theta, xi, yi, 1., [0,0,1])]) theta = np.array([w0, np.log(t10), np.log(t20)]) dftheta = df(theta, xi, yi) while np.linalg.norm(dftheta) > tol: print "|(grad f)(theta)|", np.linalg.norm(dftheta) theta -= np.linalg.solve(Jf(theta, xi, yi), dftheta) dftheta = df(theta, xi, yi) return theta[0], np.exp(theta[1]), np.exp(theta[2]) def NLS_general(F, xi, yi, p0=1., tol=1e-12): "nonlinear least squares to fit arbitrary f with any number of parameters" # F = F(x, p), p0 MUST match len(p), F takes array of x # F must be compatible with tangent module def f(p, xi, yi): return np.sum((F(xi, p) - yi)**2) # minimize f by solving df(x) = 0 with newton method n = len(p0) df = tangent.grad(f) ddf = tangent.grad(df, mode="forward") ei = lambda i: np.eye(1, n, i)[0, :] def Jf(p, xi, yi): return np.array([ddf(p, xi, yi, 1., ei(i)) for i in range(n)]) p = np.array(p0) dfp = df(p, xi, yi) while np.linalg.norm(dfp) > tol: print "|grad f|", np.linalg.norm(dfp) p -= np.linalg.solve(Jf(p, xi, yi), dfp) dfp = df(p, xi, yi) return tuple(p) def NLS_bruteforce(F, xi, yi, p, width=1., N=100): # make p 1d array p = np.atleast_1d(p) # create parameter range # TODO: this currently only applies to len(p)==2 x = np.logspace(-width, width, N) xx = np.column_stack((np.repeat(x[:, None], len(x), 0), np.tile(x[:, None], [len(x), 1]))) pp = p[None, :] * xx f = np.sum((F(xi[None, :], pp) - yi)**2, 1) i = np.argmin(f) print "minimum:", f[i] print "parameters:", pp[i, :] return tuple(pp[i, :]) def NLS_annealing(F, xi, yi, p, N=100, n=10, sigma=5.,factor=0.5): # N = size of population in one iteration # n = number of iterations # sigma = initial (multiplicative) standard deviation # factor = factor to reduce sigma per iteration print "initial", p p = np.atleast_1d(p) dim = len(p) # make initial sigma act like multiplication by sigma^(+-1) sigma = np.log(sigma)*np.ones(dim) for k in range(n): # create new population by adding multiplicative gaussian noise P = p[None, :] * np.exp(np.random.randn(N, dim) * sigma[None, :]) # compute mean square loss on population f = np.mean((F(xi[None, :], P) - yi)**2, 1) # replace p by new best guess p = P[np.argmin(f), :] # update sigma sigma *= factor print "parameters:", p print "minimum", min(f) return tuple(p) def fit_gamma(ti): mu = ti.mean() sigma = ti.std() C = mu**2/sigma**2 def f(x): return np.exp(x)/(2.*np.expm1(x)/x - 1.) def f1(x): y = 2.*np.expm1(x)/x - 1. z = 2./x**2*(x*np.exp(x) - np.expm1(x)) return np.exp(x)*(1 - z/y)/y # newton solve K = 2.*C # initial value #print "Newton iteration:" for i in range(10): dK = -(f(K) - C)/f1(K) K = K + dK # print i, "Residual", f(K) - C, "Value K =", K #print tau = mu*(1. - np.exp(-K))/K return K, tau from scipy.special import iv class CompoundGamma(object): def __init__(self, ti): self.ti = ti self.K, self.tau = self.fit_brute(ti) def fit_todo(self, ti, n=40): pass def fit_naive(self, ti): return fit_gamma(ti) def fit_brute(self, ti, n=100): # first guess to get orders of magnitude right p = np.array(fit_gamma(ti)) # define problem # TODO: #xi = np.sort(ti)[int(len(ti)/n/2)::int(len(ti)/n)] #yi = np.arange(len(xi))/float(len(xi)) bins = np.logspace(np.log10(min(ti)), np.log10(max(ti)), n) hist, _ = np.histogram(ti, bins=bins) xi = 0.5*(bins[:-1] + bins[1:]) yi = np.cumsum(hist)/float(np.sum(hist)) # minimize #K, tau = NLS_bruteforce(self.cfd_vec, xi, yi, p, width=1., N=100) K, tau = NLS_annealing(self.cfd_vec, xi, yi, p, N=100, n=20) return K, tau def pdf_direct(self, tt, N=50): a = self.K t = tt/self.tau S = np.ones_like(t) s = np.ones_like(t) for k in range(1, N): s *= (a*t)/(k*(k+1.)) S += s return np.exp(-t)*a/np.expm1(a) * S /self.tau def pdf_bessel(self, tt): a = self.K t = tt/self.tau return np.exp(-t)*np.sqrt(a/t)*iv(1., 2.*np.sqrt(a*t))/self.tau/np.expm1(a) def cdf(self, tt, N=50): a = self.K tau = self.tau gamma = sp.stats.gamma.cdf S = np.zeros_like(tt) s = 1. for k in range(1, N): s *= a/k S += s*gamma(tt, k, scale=tau) return 1./np.expm1(a) * S def cfd_vec(self, tt, p, N=50): # cdf that takes parameter as vector input, for fitting a = p[:, 0:1] tau = p[:, 1:2] gamma = sp.stats.gamma.cdf S = np.ones((p.shape[0], tt.shape[1])) s = np.ones((1, tt.shape[0])) for k in range(1, N): s = s*a/k S = S + s*gamma(tt, k, scale=tau) return 1./np.expm1(a) * S def gammainc(self, tt, k,tau): # TODO: can not differentiate wrt k # implement fitting yourself #for j in range(k): pass class Compound2Gamma2(CompoundGamma): "fit one or two compound^2 gammas with possibly cut off events" def __init__(self, ti, ta=None, n_gammas=1, cutoff=False, use_ta_model=True): self.ti = ti self.n_gammas = n_gammas self.cutoff = cutoff # fitting of gamma (bind time) parameters if ta is None: # fit parameters tau, na, ga = ka*taua directly # deduce ka for any given choice of taua pass else: if use_ta_model: # first fit attempt times to get na, taua, # then fit bind times for tau, ga and deduce ka = ga/taua pass else: # just simulate gamma-poisson distributed bind-times by drawing # poisson/exp random numbers in forward mode, creating an # simulated cdf to be matched with the experimental one pass self.fit(ti) def fit(self, ti): pass def pdf_direct(self, tt, N=50): # g = ka * taua # q = g / (1 + g) # P(N>0) = (1 - np.exp(-qa)) # P(N=n) = np.exp(-a) q**n/n! * Sk # Sk = sum_k>=1 1/k!(n+k-1)!/(k-1)! (1-q)**k a**k # f(t)* = np.exp(-t)/P(N>0) sum_n>=1 t**(n-1)/(n-1)! P(N=n) # F(t)* = 1/P(N>0) sum_n>=1 Gamma(n,t) P(N=n) pass def cdf(self, tt, N=50): pass def pn_vec(self, n, ka, taua=None, na=None): # ka = association rate in binding zone # taua, na = parameters of attempt time distribution, determined by # simulations if taua is None: taua = self.taua if na is None: na = self.na #n = np.arange() def cdf_vec(self, tt, p, N=50): # cdf that takes parameter as vector input, for fitting a = p[:, 0:1] tau = p[:, 1:2] gamma = sp.stats.gamma.cdf S = np.ones((p.shape[0], tt.shape[1])) s = np.ones((1, tt.shape[0])) for k in range(1, N): s = s*a/k S = S + s*gamma(tt, k, scale=tau) return 1./np.expm1(a) * S if todo.plot_distribution: N = 10000 params0 = dict(params, N=N) rw = randomwalk.get_rw(NAME, params0, setup=setup_rw) ta = rw.attempt_times ta1 = ta[ta > 0.] tmean = ta1.mean() bins = np.logspace(np.log10(min(ta1)), np.log10(max(ta1)), 35) #bins = np.logspace(-3., 2., 35) hist, _ = np.histogram(ta1, bins=bins) cfd = np.cumsum(hist)/float(np.sum(hist)) t = 0.5*(bins[:-1] + bins[1:]) #n = 100 #t = np.sort(ta1)[int(len(ta1)/n/2)::int(len(ta1)/n)] #cfd = np.arange(len(t))/float(len(t)) plt.figure("ta_cfd", figsize=(4,3)) tt = np.logspace(np.log10(min(ta1)), np.log10(max(ta1)), 100) plt.semilogx(t, cfd, "v", label="Simulations") # naive exp. fit #plt.semilogx(tt, 1. - np.exp(-tt/tmean), label="Simple exp. fit") # proper exp. fit toff = NLS(t, cfd, t0=tmean) #plt.semilogx(tt, 1. - np.exp(-tt/toff), label="Exp. fit") # ML gamma fit #K, _, tau = sp.stats.gamma.fit(ta1) K = (tmean/ta1.std())**2 tau = tmean/K #plt.semilogx(tt, sp.stats.gamma.cdf(tt, K, scale=tau), label="Simple Gamma fit") gamma = CompoundGamma(ta1) plt.semilogx(tt, gamma.cdf(tt), label="Compound Gamma fit") # double exponential fit #w, toff1, toff2 = NLS2(t, cfd, t10=toff/2., t20=toff*2., w0=.4) #plt.semilogx(tt, 1. - w*np.exp(-tt/toff1) - (1.-w)*np.exp(-tt/toff2), # label="Double exp. fit") plt.xlabel("Attempt time [ns]") plt.ylabel("Cumulative frequency") plt.xlim(xmin=1.) plt.legend() xlog = False plt.figure("ta_hist", figsize=(4,3)) #tt = np.logspace(-1, 4., 20) bins = np.linspace(0., 200., 30) tt = np.linspace(0., 200., 300) plt.figure("ta_hist", figsize=(4,3)) plt.hist(ta1, bins=bins, normed=True, log=False, label="Simulations") #tt0 = tt if xlog else 1. #plt.plot(tt, tt0/tmean * np.exp(-tt/tmean), # label="Simple exp. fit, mean=%.3gns" % tmean) #plt.plot(tt, tt0/toff * np.exp(-tt/toff), # label="Exp. fit, mean=%.3gns" % toff) #dt = rw.dt #kk = np.arange(1000) #k0 = tmean/dt #plt.plot(tt, sp.stats.gamma.pdf(tt, K, scale=tau), # label="Simple Gamma fit") plt.plot(tt, gamma.pdf_direct(tt), label="Compound Gamma fit") #plt.plot(tt, gamma.pdf_bessel(tt), ".k", label="Compound Gamma fit") #plt.plot(kk*dt, poisson.pmf(kk, k0), label="Poisson fit") #plt.plot(tt) if xlog: plt.xscale("log") #plt.ylim(ymin=1e-10) #plt.yscale("log") plt.xlabel("Attempt time [ns]") plt.ylabel("Rel. frequency") plt.legend() if todo.fit_experiments: # get data drop, tsample = fields.get("events_pugh_experiment", "drop", "t") tsample = tsample.load() log = True std = False cutoff = 0.1 # [ms], detection limit cutoff # plot data with indication of two clusters sep = 2. large = tsample >= sep toosmall = tsample < cutoff plt.figure("data_scatter", figsize=(4, 3)) plt.scatter(tsample[toosmall], drop[toosmall], color="r") plt.scatter(tsample[~toosmall], drop[~toosmall]) #plt.scatter(tsample[~large & ~toosmall], drop[~large & ~toosmall]) #plt.scatter(tsample[large], drop[large], color="g") plt.axvline(x=cutoff, color="r") plt.xscale("log") plt.xlabel(r"$\tau$ off [ms]") plt.ylabel(r"$A/I_0$ [%]") # cut off data at detection limit threshold tsample = tsample[~toosmall] # fit with different methods and compare T = statistics.LeftTruncatedExponential(tau=None, tmin=cutoff) T2 = statistics.LeftTruncatedDoubleExponential( tau1=None, tau2=None, w=None, tmin=cutoff) T.fit(tsample, method="cdf", log=True, sigma=2., factor=0.9, n_it=50) T2.fit(tsample, method="cdf", log=True, sigma=2., factor=0.9, n_it=50) t = statistics.grid(tsample, 15, 0, log=log) tt = statistics.grid(tsample, 100, 0, log=log) ecdf = statistics.empirical_cdf(t, tsample) t1 = statistics.grid(tsample, 15, 0, log=log) tc, epdf = statistics.empirical_pdf(t1, tsample, log=log) plt.figure("data_fit_cdf", figsize=(4, 3)) plt.plot(t, ecdf, "o", label="Experiment") T.plot_cdf(tt, label="Truncated exp. fit", std=std) T2.plot_cdf(tt, ":", label="Trunc. double exp. fit", std=std) plt.xscale("log") plt.ylabel("Cumulative probability") plt.xlabel(r"$\tau$ off [ms]") plt.legend(frameon=False) print "CDF fit:", T2 #T.fit(tsample, method="pdf", log=True, sigma=2., factor=0.9, n_it=50) #T2.fit(tsample, method="cdf", log=True, sigma=2., factor=0.9, n_it=50) plt.figure("data_fit_pdf", figsize=(4, 3)) #plt.plot(tc, epdf, "o") plt.bar(tc, epdf, 0.8*np.diff(t1), alpha=0.5, label="Experiment") #T.plot_pdf(tt, "C1", log=log, label="Truncated exp. fit") T2.plot_pdf(tt, ":C2", log=log, label="Trunc. double exp. fit", std=std) plt.xscale("log") plt.ylabel("Rel. frequency") plt.xlabel(r"$\tau$ off [ms]") plt.legend(loc="upper right", frameon=False) #print "PDF fit:", T2 if todo.fit_long: # now we focus only on the long-time cluster and fit that with different methods drop, tsample = fields.get("events_pugh_experiment", "drop", "t") tsample = tsample.load() log = True std = False cutoff = 2. # [ms] sep = 2. large = tsample >= sep toosmall = tsample < cutoff plt.figure("data_scatter_long", figsize=(4, 3)) plt.scatter(tsample[toosmall], drop[toosmall], color="r") plt.scatter(tsample[~toosmall], drop[~toosmall]) #plt.scatter(tsample[~large & ~toosmall], drop[~large & ~toosmall]) #plt.scatter(tsample[large], drop[large], color="g") plt.axvline(x=cutoff, color="r") plt.xscale("log") plt.xlabel(r"$\tau$ off [ms]") plt.ylabel(r"$A/I_0$ [%]") # cut off data at detection limit threshold tsample = tsample[~toosmall] # fit with different methods and compare T = dict() T["exp"] = statistics.Exponential(tau=None) T["truncexp"] = statistics.LeftTruncatedExponential(tau=None, tmin=cutoff) #K = statistics.ZeroTruncatedPoisson(a=None) #T["compoundgamma"] = statistics.Gamma(tau=None, K=K) for k in T: T[k].fit(tsample, method="cdf", log=True, sigma=2., factor=0.9, n_it=50) t = np.logspace(-0.2, 2.3, 18) tt = np.logspace(-0.2, 2.3, 100) #t = statistics.grid(tsample, 15, 0, log=log) #tt = statistics.grid(tsample, 100, 0, log=log) ecdf = statistics.empirical_cdf(t, tsample) #log = False #t1 = statistics.grid(tsample, 8, 0, log=log) t1 = np.logspace(np.log10(2.), 2.3, 10) tt1 = np.logspace(np.log10(2.), 2.3, 100) tc, epdf = statistics.empirical_pdf(t1, tsample, log=log) plt.figure("data_long_fit_cdf", figsize=(4, 3)) plt.plot(t, ecdf, "o", label="Experiment (> 2ms)") T["exp"].plot_cdf(tt, std=std, label="Exponential fit") T["truncexp"].plot_cdf(tt, ":", std=std, label="Truncated exp. fit") #T["compoundgamma"].plot_cdf(tt, "--", std=std, label="Compound Gamma fit") plt.xscale("log") plt.ylabel("Cumulative probability") plt.xlabel(r"$\tau$ off [ms]") plt.legend(frameon=False) print "CDF fit:", T plt.figure("data_long_fit_pdf", figsize=(4, 3)) plt.bar(tc, epdf, 0.8*np.diff(t1), alpha=0.5, label="Experiment (> 2ms)") #T["exp"].plot_pdf(tt1, "C1", label="Exponential fit", log=log, std=std) T["truncexp"].plot_pdf(tt1, ":C2", label="Truncated exp. fit", std=std, log=log) #T["compoundgamma"].plot_pdf(tt, "--C3", label="Compound Gamma fit", std=std, log=log) plt.xscale("log") plt.xlim(xmin=1.5) plt.ylabel("Rel. frequency") plt.xlabel(r"$\tau$ off [ms]") plt.legend(loc="lower center") if todo.fit_long_gamma: # now we focus only on the long-time cluster and fit that with different methods drop, tsample = fields.get("events_pugh_experiment", "drop", "t") tsample = tsample.load() log = True std = False cutoff = 2. # [ms] sep = 2. large = tsample >= sep toosmall = tsample < cutoff plt.figure("data_scatter_long", figsize=(4, 3)) plt.scatter(tsample[toosmall], drop[toosmall], color="r") plt.scatter(tsample[~toosmall], drop[~toosmall]) #plt.scatter(tsample[~large & ~toosmall], drop[~large & ~toosmall]) #plt.scatter(tsample[large], drop[large], color="g") plt.axvline(x=cutoff, color="r") plt.xscale("log") plt.xlabel(r"$\tau$ off [ms]") plt.ylabel(r"$A/I_0$ [%]") # cut off data at detection limit threshold tsample = tsample[~toosmall] # get empirical attempt time disribution N = 10000 params0 = dict(params, N=N) rw = randomwalk.get_rw(NAME, params0, setup=setup_rw) ta = rw.attempt_times ta1 = 1e-9*ta[ta > 0.] Ta = statistics.Empirical(ta1) # get cb = 1/Vb cb = 1./rw.domains[2].Vbind # [M] # fit with different methods and compare from collections import OrderedDict T = OrderedDict() ka = [1e6,1e7, 1e8, 1e9] kastr = [r"$10^{%d}$" % (np.round(np.log10(ka_)),) for ka_ in ka] kaformat = r"$k_a$ = %s/Ms" I = range(len(ka)) rvalues = ["66", "99", "cc", "ff"] linestyles = ["-.", "--", ":", "-"] colors = ["#%s0000" % r_ for r_ in rvalues] a_attempts = 4.1 # mean no. attempts for binding site length 8nm tamean = ta1.mean() p_binding_prob = OrderedDict() for i in I: Ra = ka[i] * cb K = statistics.ZeroTruncatedPoisson(a=Ra*Ta) T[i] = statistics.LeftTruncatedGamma(tau=None, K=K, tmin=cutoff) p_binding_prob[i] = tamean * Ra / a_attempts for i in T: T[i].fit(tsample, method="cdf", log=True, sigma=2., factor=0.6, n_it=20) ka1 = np.logspace(3.8, 11.2, 20) T1 = OrderedDict() error = [] for ka_ in ka1: Ra = ka_ * cb K = statistics.ZeroTruncatedPoisson(a=Ra*Ta) T1[ka_] = statistics.LeftTruncatedGamma(tau=None, K=K, tmin=cutoff) err = T1[ka_].fit(tsample, method="cdf", log=True, sigma=2., factor=0.6, n_it=20) error.append(err) for ka_, err in zip(T1, error): print T1[ka_].X.K.a.sample(10000).mean(), print ("%.4g" % ka_), print err t = np.logspace(-0.2, 2.3, 18) tt = np.logspace(-0.2, 2.3, 100) #t = statistics.grid(tsample, 15, 0, log=log) #tt = statistics.grid(tsample, 100, 0, log=log) ecdf = statistics.empirical_cdf(t, tsample) #log = False #t1 = statistics.grid(tsample, 8, 0, log=log) t1 = np.logspace(np.log10(2.), 2.3, 10) tt1 = np.logspace(np.log10(2.), 2.3, 100) tc, epdf = statistics.empirical_pdf(t1, tsample, log=log) plt.figure("data_long_gammafit_cdf", figsize=(4, 3)) ########## for i in T: #if i==0: # T[i].plot_cdf(tt, std=std, label=r"$k_a = 10^7$/Ms", color=colors[i]) #else: T[i].plot_cdf(tt, std=std, label=kaformat % kastr[i], color=colors[i], linestyle=linestyles[i]) plt.plot(t, ecdf, "o", label="Experiment") plt.xscale("log") plt.ylabel("Cumulative probability") plt.xlabel(r"$\tau$ off [ms]") plt.xlim(xmin=0.5) plt.legend(loc="upper left", frameon=False) print "CDF fit:", T plt.figure("data_long_gammafit_pdf", figsize=(4, 3)) ######### for i in T: T[i].plot_pdf(tt, label=kaformat % kastr[i], std=std, log=log, color=colors[i], linestyle=linestyles[i]) plt.bar(tc, epdf, 0.8*np.diff(t1), alpha=0.5, label="Experiment") plt.xscale("log") plt.ylabel("Rel. frequency") plt.xlabel(r"$\tau$ off [ms]") plt.xlim(xmin=0.1) plt.legend(loc="upper left", frameon=False) plt.figure("data_long_gammafit_error", figsize=(4, 3)) plt.semilogx(ka1, error, "o") plt.xlabel(r"$k_a$ [M$^{-1}$s$^{-1}$]") plt.ylabel("Fitting error") if todo.fit_gamma: # now we focus only on the long-time cluster and fit that with different methods drop, tsample = fields.get("events_pugh_experiment", "drop", "t") tsample = tsample.load() log = True std = False cutoff = 0.1 # [ms] # cut off data at detection limit threshold toosmall = tsample < cutoff tsample = tsample[~toosmall] # get empirical attempt time disributions N = 10000 params0 = dict(params, N=N, bind_everywhere=False) rw1 = randomwalk.get_rw(NAME, params0, setup=setup_rw) ta1 = 1e-9*rw1.attempt_times Ta1 = statistics.Empirical(ta1[ta1 > 0.]) cb = 1./rw1.domains[2].Vbind # [M] params1 = dict(params, N=N, bind_everywhere=True) rw2 = randomwalk.get_rw(NAME, params1, setup=setup_rw) ta2 = 1e-9*rw2.attempt_times Ta2 = statistics.Empirical(ta2[ta2 > 0.]) # fit with different methods and compare from collections import OrderedDict T = OrderedDict() ka = [1e6,1e7,1e8,1e9] #kastr = [("%.3g" % ka_) for ka_ in ka] kastr = [r"$10^{%d}$" % (np.round(np.log10(ka_)),) for ka_ in ka] #kastr = ["$10^6$", "$10^8$", "$10^9$", "$10^{10}$"] kaformat = r"$k_a$ = %s/Ms" I = range(len(ka)) rvalues = ["66", "99", "cc", "ff"]*4 linestyles = ["-.", "--", ":", "-"]*4 colors = ["#%s0000" % r_ for r_ in rvalues] a_attempts = 4.1 # mean no. attempts for binding site length 8nm tamean = ta1.mean() p_binding_prob = OrderedDict() error = [] def P2(ra): colon = slice(None) n = ra.ndim #tta = np.random.choice(ta2, size=1000) tta = ta2 tmp = ra[(colon,)*n + (None,)] * tta[(None,)*n + (colon,)] tmp = np.exp(-tmp).mean(axis=n) return 1. - tmp for i in I: ka1 = ka[i] Ra1 = ka1 * cb a1 = Ra1 * Ta1 p1 = 1 - np.exp(-Ra1*ta1).mean() ka2 = statistics.Constant(c=None) ka2.update(c=ka1/30.) Ra2 = ka2 * cb a2 = Ra2 * Ta2 #p2 = Ra2 * ta2.mean() p2 = statistics.Function(P2, Ra2) w = (1./p1 - 1.) * p2 K1 = statistics.ZeroTruncatedPoisson(a=a1) K2 = statistics.ZeroTruncatedPoisson(a=a2) T1 = statistics.LeftTruncatedGamma(K=K1, tau=None, tmin=cutoff) T2 = statistics.LeftTruncatedGamma(K=K2, tau=None, tmin=cutoff) # initial guesses to bias fit T1.X.update(tau=10.) T2.X.update(tau=0.1) T[i] = statistics.OneOf(X=T2, Y=T1, w=w) for i in T: err = T[i].fit(tsample, method="cdf", log=True, sigma=2., factor=0.8, n_it=40) error.append(err) # ka1 = np.logspace(7., 12., 10) # for ka_ in ka1: # Ra = ka_ * cb # K = statistics.ZeroTruncatedPoisson(a=Ra*Ta) # Ti = statistics.LeftTruncatedGamma(tau=None, K=K, tmin=cutoff) # err = Ti.fit(tsample, method="cdf", log=True, sigma=2., factor=0.6, n_it=20) # error.append(err) t = statistics.grid(tsample, 15, 0, log=log) tt = statistics.grid(tsample, 100, 0, log=log) ecdf = statistics.empirical_cdf(t, tsample) t1 = statistics.grid(tsample, 15, 0, log=log) tt1 = tt tc, epdf = statistics.empirical_pdf(t1, tsample, log=log) plt.figure("data_gammafit_cdf", figsize=(4, 3)) ########## for i in T: #if i==0: # T[i].plot_cdf(tt, std=std, label=r"$k_a = 10^7$/Ms", color=colors[i]) #else: T[i].plot_cdf(tt, std=std, label=kaformat % kastr[i], color=colors[i], linestyle=linestyles[i]) plt.plot(t, ecdf, "o", label="Experiment") plt.xscale("log") plt.ylabel("Cumulative probability") plt.xlabel(r"$\tau$ off [ms]") #plt.xlim(xmin=0.5) plt.legend(loc="lower right", frameon=False) print "CDF fit:", T plt.figure("data_gammafit_pdf", figsize=(4, 3)) ######### for i in T: T[i].plot_pdf(tt, label=kaformat % kastr[i], std=std, log=log, color=colors[i], linestyle=linestyles[i]) plt.bar(tc, epdf, 0.8*np.diff(t1), alpha=0.5, label="Experiment") plt.xscale("log") plt.ylabel("Rel. frequency") plt.xlabel(r"$\tau$ off [ms]") #plt.xlim(xmin=0.1) plt.legend(loc="upper right", frameon=False) plt.figure("data_gammafit_error", figsize=(4, 3)) plt.semilogx(ka, error, "o") plt.xlabel(r"$k_a$") plt.ylabel("Fitting error") import folders nanopores.savefigs("rw_cyl", folders.FIGDIR + "/pugh", ending=".pdf")
mitschabaude/nanopores
scripts/pughpore/rw.py
Python
mit
29,100
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <title>Excel Add-In with Commands Sample</title> <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script> <script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js" type="text/javascript"></script> <!-- To enable offline debugging using a local reference to Office.js, use: --> <!-- <script src="Scripts/Office/MicrosoftAjax.js" type="text/javascript"></script> --> <!-- <script src="Scripts/Office/1/office.js" type="text/javascript"></script> --> <script src="Home.js" type="text/javascript"></script> <link href="Home.css" rel="stylesheet" type="text/css" /> <link href="../Content/Button.css" rel="stylesheet" type="text/css" /> <link href="../Content/MessageBanner.css" rel="stylesheet" type="text/css" /> <!-- For Office UI Fabric Core, go to https://aka.ms/office-ui-fabric to learn more. --> <link rel="stylesheet" href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-core/9.6.0/css/fabric.min.css"> <!-- To enable the offline use of Office UI Fabric Core, use: --> <!-- link rel="stylesheet" href="Content/fabric.min.css" --> </head> <!-- Office UI Fabric JS and it's components are no longer actively supported. Please see https://aka.ms/PnP-OfficeFabricReact for recommended Patterns and Practices --> <!-- <link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/2.1.0/fabric.components.min.css"> --> <body class="ms-Fabric" dir="ltr"> <button id="btnShowUnicode" onclick="showUnicode()">Show Unicode</button> <p>Result:</p> <div id="txtResult"></div> </body> </html>
OfficeDev/PnP-OfficeAddins
Samples/VSTO-shared-code-migration/completed/CellAnalyzerWebAddinWeb/Home.html
HTML
mit
1,950
Rules --------------- This lab test is designed to show your understanding of the course so far, but primarily is focused around you understanding your way around creating a basic core app that implements a UITableView, network requests, segues, etc. **> NOTE <** Unlike the OOP1 test, consulting online resources apart from the lecture notes and the Apple documentation is forbidden. You may also use any of your own notes. - https://developer.apple.com/library/mac/navigation/index.html#section=Resource%20Types&topic=Reference - https://github.com/zdavison/DIT.iOS1 - https://github.com/zdavison/DIT.OOP1 No usage of messenger programs like GChat, Facebook Chat, AIM, MSN, etc is permitted, any breach of either of these will result in a mark of 0. Requirements --------------- You are required to create an app that fulfills the following requirements: - A `UITabBarController` with 2 tabs to display 2 different **view controllers**, these having: - A `UITableView`, along with a data source to display some data. - A `UIViewController` containing a button that when pressed, performs a `push segue` to another `UIViewController`. Hint: You will need to use a `UINavigationController`. - The first view controller with the tableview should load the `json` file from the following URL: https://raw.githubusercontent.com/zdavison/DIT.iOS1/master/Week4/sample.json - It should then display this data in the UITableView, inside UITableViewCells. Each cell should contain the following (all of which is contained within the `json` data which you will need to consult, you are free to format/display it as you wish, style is not important). - Name of the user who posted the tweet. - Date the tweet was posted. - Text of the tweet. - A list of any hashtags mentioned in the tweet. Marking --------------- - The UITableView, including loading data from the web, is worth 60%. - The UIViewController / segue section is worth 30%. - The remaining 10% is distributed for clean code and organisation. Instructions --------------- Create your project in XCode. The `AFNetworking` library is provided [here in a zip file](https://github.com/zdavison/DIT.OOP1/blob/master/Week4/AFNetworking.zip?raw=true) for you to use. Remember to copy the files to the project when you add them. You must submit your solution to a GitHub repository and email me the link to `[email protected]`. If you cannot do this, you may email your solution to me in a zip file, but a penalty of **10%** will be deducted from your mark.
zdavison/DIT.iOS1
Week7/labtest.md
Markdown
mit
2,533
################################################################################ ##################### Set Inital Image to work from ############################ # work from latest LTS ubuntu release FROM ubuntu:18.04 # set variables ENV r_version 3.6.0 # run update RUN apt-get update -y && apt-get install -y \ gfortran \ libreadline-dev \ libpcre3-dev \ libcurl4-openssl-dev \ build-essential \ zlib1g-dev \ libbz2-dev \ liblzma-dev \ openjdk-8-jdk \ wget \ libssl-dev \ libxml2-dev \ libnss-sss \ git \ build-essential \ cmake \ python3 ################################################################################ ##################### Add Container Labels ##################################### LABEL "Regtools_License"="MIT" LABEL "Description"="Software package which integrate DNA-seq and RNA-seq data\ to help interpret mutations in a regulatory and splicing\ context." ################################################################################ ####################### Install R ############################################## # change working dir WORKDIR /usr/local/bin # install R RUN wget https://cran.r-project.org/src/base/R-3/R-${r_version}.tar.gz RUN tar -zxvf R-${r_version}.tar.gz WORKDIR /usr/local/bin/R-${r_version} RUN ./configure --prefix=/usr/local/ --with-x=no RUN make RUN make install # install R packages RUN R --vanilla -e 'install.packages(c("data.table", "plyr", "tidyverse"), repos = "http://cran.us.r-project.org")' ################################################################################ ##################### Install Regtools ######################################### # add repo source ADD . /regtools # make a build directory for regtools WORKDIR /regtools # compile from source RUN mkdir build && cd build && cmake .. && make ################################################################################ ###################### set environment path ################################# # make a build directory for regtools WORKDIR /scripts/ # add regtools executable to path ENV PATH="/regtools/build:/usr/local/bin/R-${r_version}:${PATH}"
griffithlab/regtools
Dockerfile
Dockerfile
mit
2,189
#!/usr/bin/env python from glob import glob from subprocess import Popen, PIPE from valgrindwrapper import ValgrindWrapper import difflib import os import re import shlex import shutil import sys import tempfile import unittest class IntegrationTest(): exe_path = None def setUp(self): self.test_dir = os.path.dirname(sys.argv[0]) self.data_dir = os.path.join(self.test_dir, "data") self.tmp_dir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.tmp_dir) def inputFiles(self, *names): rv = [] for n in names: rv.extend(sorted(glob(os.path.join(self.data_dir, n)))) if len(rv) == 0: raise IOError("No file matching %s not found in %s" %( ", ".join(names), self.data_dir) ) return rv def execute(self, args): print("args ", args) cmdline = "%s %s" %(self.exe_path, " ".join(args)) vglog_file = self.tempFile("valgrind.log") return ValgrindWrapper(shlex.split(cmdline), vglog_file).run() def tempFile(self, name): return os.path.join(self.tmp_dir, name) def assertFilesEqual(self, first, second, msg=None, filter_regex=None): first_data = open(first).readlines() second_data = open(second).readlines() if filter_regex: first_data = [x for x in first_data if not re.match(filter_regex, x)] second_data = [x for x in second_data if not re.match(filter_regex, x)] self.assertMultiLineEqual("".join(first_data), "".join(second_data)) def assertMultiLineEqual(self, first, second, msg=None): """Assert that two multi-line strings are equal. If they aren't, show a nice diff. """ self.assertTrue(isinstance(first, str), 'First argument is not a string') self.assertTrue(isinstance(second, str), 'Second argument is not a string') if first != second: message = ''.join(difflib.ndiff(first.splitlines(True), second.splitlines(True))) if msg: message += " : " + msg self.fail("Multi-line strings are unequal:\n" + message) def main(): if len(sys.argv) < 2: print('Error: required argument (path to test executable) missing') sys.exit(1) IntegrationTest.exe_path = sys.argv.pop() unittest.main()
griffithlab/regtools
build-common/python/integrationtest.py
Python
mit
2,472
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy from typing import Any, Optional, TYPE_CHECKING from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient from msrest import Deserializer, Serializer from . import models from ._configuration import StorageManagementConfiguration from .operations import Operations, SkusOperations, StorageAccountsOperations, UsageOperations if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential class StorageManagement: """The Azure Storage Management API. :ivar operations: Operations operations :vartype operations: azure.mgmt.storage.v2017_10_01.operations.Operations :ivar skus: SkusOperations operations :vartype skus: azure.mgmt.storage.v2017_10_01.operations.SkusOperations :ivar storage_accounts: StorageAccountsOperations operations :vartype storage_accounts: azure.mgmt.storage.v2017_10_01.operations.StorageAccountsOperations :ivar usage: UsageOperations operations :vartype usage: azure.mgmt.storage.v2017_10_01.operations.UsageOperations :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: Gets subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. :type subscription_id: str :param base_url: Service URL. Default value is 'https://management.azure.com'. :type base_url: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( self, credential: "TokenCredential", subscription_id: str, base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = StorageManagementConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.skus = SkusOperations(self._client, self._config, self._serialize, self._deserialize) self.storage_accounts = StorageAccountsOperations(self._client, self._config, self._serialize, self._deserialize) self.usage = UsageOperations(self._client, self._config, self._serialize, self._deserialize) def _send_request( self, request, # type: HttpRequest **kwargs: Any ) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") <HttpRequest [GET], url: 'https://www.example.org/'> >>> response = client._send_request(request) <HttpResponse: 200 OK> For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart :param request: The network request you want to make. Required. :type request: ~azure.core.rest.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.rest.HttpResponse """ request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) return self._client.send_request(request_copy, **kwargs) def close(self): # type: () -> None self._client.close() def __enter__(self): # type: () -> StorageManagement self._client.__enter__() return self def __exit__(self, *exc_details): # type: (Any) -> None self._client.__exit__(*exc_details)
Azure/azure-sdk-for-python
sdk/storage/azure-mgmt-storage/azure/mgmt/storage/v2017_10_01/_storage_management.py
Python
mit
4,702
'use strict'; var grunt = require('grunt'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports.dust_render = { setUp: function(done) { // setup here if necessary done(); }, default_options: function(test) { test.expect(1); var actual = grunt.file.read('tmp/default_options'); var expected = grunt.file.read('test/expected/default_options'); test.equal(actual, expected, 'should describe what the default behavior is.'); test.done(); }, custom_options: function(test) { test.expect(1); var actual = grunt.file.read('tmp/custom_options'); var expected = grunt.file.read('test/expected/custom_options'); test.equal(actual, expected, 'should describe what the custom option(s) behavior is.'); test.done(); }, };
dig3/grunt-dust-render
test/dust_render_test.js
JavaScript
mit
1,351
--- layout: page title: Carpenter - Wiggins Wedding date: 2016-05-24 author: Jack Levy tags: weekly links, java status: published summary: Vivamus imperdiet feugiat orci, non commodo nulla. banner: images/banner/people.jpg booking: startDate: 01/22/2018 endDate: 01/23/2018 ctyhocn: KANKSHX groupCode: CWW published: true --- Phasellus sagittis condimentum quam, nec scelerisque massa varius ac. Duis dapibus, enim id rhoncus lobortis, mauris dolor tempus nulla, in accumsan urna sem ut nulla. Mauris ut diam justo. Aliquam ut lectus et arcu porta mattis pharetra id libero. Mauris sit amet tortor elementum, posuere nisl et, tempor ante. Vestibulum eros augue, lobortis non vehicula at, maximus et mi. Fusce convallis leo scelerisque augue posuere, quis tristique nibh tincidunt. Nunc feugiat pellentesque maximus. Suspendisse eget scelerisque enim, viverra varius nunc. Ut laoreet leo at odio porttitor auctor. Sed maximus orci sed metus auctor molestie. Aliquam arcu libero, vehicula id ipsum nec, mattis volutpat purus. Phasellus pellentesque sollicitudin bibendum. Proin convallis libero eu vulputate lacinia. Cras et suscipit mi. Nulla vel orci et leo faucibus cursus non eu ligula. Sed lobortis pharetra diam, in fringilla augue dictum non. Sed ultricies, magna tempor laoreet vestibulum, libero ipsum rutrum libero, non hendrerit ex lorem ut felis. Vestibulum luctus nunc enim, ac aliquam neque tristique at. Fusce nec diam nec tellus congue ornare. Cras eget tristique leo, sed venenatis ex. Donec luctus magna hendrerit libero semper, a vulputate nunc tincidunt. In molestie ligula mauris, at pharetra lacus finibus vel. Quisque et vestibulum nunc, nec gravida elit. Sed interdum, mi et lacinia elementum, arcu ex cursus urna, in ornare nulla enim nec nisi. Nam augue velit, rutrum ac mi ac, viverra viverra nibh. Nulla imperdiet erat a feugiat consectetur. Donec eget erat libero. Nam tortor orci, blandit vitae scelerisque in, pharetra sed odio. * Praesent nec libero ac mauris pulvinar fringilla * Proin nec lorem finibus, vehicula nisl eu, imperdiet massa * Curabitur ultricies nisi sit amet euismod aliquam * Morbi sodales nisi vitae pharetra egestas * Sed placerat tellus nec finibus tincidunt * Quisque ac erat eu ex facilisis sagittis. Nulla ultricies sem cursus nibh scelerisque, eu luctus tortor semper. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse venenatis lorem quis massa ullamcorper scelerisque. Morbi at vehicula erat, eget euismod lorem. Nullam bibendum ipsum eget erat lacinia, ut gravida ex cursus. Cras scelerisque eget nulla non vestibulum. Nullam interdum libero quis mauris convallis, non gravida lorem faucibus. Suspendisse congue eleifend nisl in accumsan. Nulla hendrerit elit vitae neque luctus, in tristique massa auctor. Proin iaculis, nibh eget vestibulum fermentum, lorem odio malesuada magna, at eleifend ligula tellus at mi. Praesent eu sollicitudin diam. Curabitur tempus arcu tortor, at placerat urna sagittis ac. Aliquam vel dictum lacus. Pellentesque sodales luctus ipsum, ut fermentum enim dictum sit amet. Praesent quis efficitur nunc. Fusce non mi arcu. Sed aliquet, sapien vel vulputate consectetur, ante neque egestas urna, in tempus massa dui nec nibh. Sed dui lectus, pharetra ut accumsan quis, imperdiet in sapien. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus fringilla, lacus at efficitur porta, elit justo vehicula ipsum, vitae consequat velit metus in purus. Suspendisse non justo id dui sodales faucibus eget at mauris.
KlishGroup/prose-pogs
pogs/K/KANKSHX/CWW/index.md
Markdown
mit
3,566
<div class=" col-md-10 col-md-offset-1"> <!-- Modal --> <div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content col-md-10 col-md-offset-1"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Masa Corporal</h4> </div> <div class="modal-body"> <!-- Bootstrap Design --> <div class="row"> <div class="block-content block-content-narrow"> <input type="hidden" id="nc_id" name="nc_id" value="" /> <div class="form-group"> <div class="col-md-12"> <textarea class="form-control" id="nc_nota_muestra" name="nc_nota_muestra" placeholder="Masa Corporal..." readonly rows="20" cols="20"></textarea> </div> </div> </div> </div> </div> </div> </div> </div> </div>
emleonardelli/proyecto2016
application/views/masacorporal/masacorporal_ver.php
PHP
mit
1,055
import Ember from 'ember'; import layout from '../templates/components/collapsible-navbar'; export default Ember.Component.extend({ layout: layout, classNames: ['navbar-wrapper'], init: function() { this._super.apply(this, arguments); this._onNavClick = function() { var toggle = this.$('.navbar-toggle'); if (toggle && toggle.is(':visible')){ toggle.trigger('click'); } }.bind(this); }, didInsertElement: function() { this.$('.nav').on('click', 'a', this._onNavClick); }, willDestroyElement: function() { this.$('.nav').off('click', 'a', this._onNavClick); } });
rew-ca/ember-cli-collapsible-navbar
addon/components/collapsible-navbar.js
JavaScript
mit
632
# Departures from [Aqua](https://github.com/jedireza/aqua) - Following Hapi [code style](https://gist.github.com/hueniverse/a06f6315ea736ed1b46d), except opting instead to use 2-spaces (not 4-spaces). # Aqua A website and user system starter. Implemented with Hapi, React and Flux. [![Build Status](https://travis-ci.org/jedireza/aqua.svg?branch=master)](https://travis-ci.org/jedireza/aqua) [![Dependency Status](https://david-dm.org/jedireza/aqua.svg?style=flat)](https://david-dm.org/jedireza/aqua) [![devDependency Status](https://david-dm.org/jedireza/aqua/dev-status.svg?style=flat)](https://david-dm.org/jedireza/aqua#info=devDependencies) ## Technology Server side, Aqua is built with the [hapi.js](https://hapijs.com/) framework and toolset. We're using [MongoDB](http://www.mongodb.org/) as a data store. We also use [Nodemailer](http://www.nodemailer.com/) for email transport. The front-end is built with [React](http://facebook.github.io/react/). We're using a totally vanilla [Flux](https://facebook.github.io/flux/) implementation. Client side routing is done with [React Router](https://github.com/rackt/react-router). We're using [Gulp](http://gulpjs.com/) for the asset pipeline. ## Live demo | url | username | password | |:---------------------------------------------------------------- |:-------- |:-------- | | [https://getaqua.herokuapp.com/](https://getaqua.herokuapp.com/) | root | root | __Note:__ The live demo has been modified so you cannot change the root user, the root user's linked admin role or the root admin group. This was done in order to keep the app ready to use at all times. ## Requirements You need [Node.js](http://nodejs.org/download/) and [MongoDB](http://www.mongodb.org/downloads) installed and running. We use [`bcrypt`](https://github.com/ncb000gt/node.bcrypt.js) for hashing secrets. If you have issues during installation related to `bcrypt` then [refer to this wiki page](https://github.com/jedireza/aqua/wiki/bcrypt-Installation-Trouble). ## Installation ```bash $ git clone [email protected]:jedireza/aqua.git && cd ./aqua $ npm install ``` ## Setup __WARNING:__ This will clear all data in existing `users`, `admins` and `adminGroups` MongoDB collections. It will also overwrite `/config.js` if one exists. ```bash $ npm run setup # > [email protected] setup /Users/jedireza/projects/aqua # > ./setup.js # Project name: (Aqua) # MongoDB URL: (mongodb://localhost:27017/aqua) # Root user email: [email protected] # Root user password: # System email: ([email protected]) # SMTP host: (smtp.gmail.com) # SMTP port: (465) # SMTP username: ([email protected]) # SMTP password: # Setup complete. ``` ## Running the app ```bash $ npm start # > [email protected] start /Users/jedireza/projects/aqua # > gulp react && gulp # [23:41:44] Using gulpfile ~/projects/aqua/gulpfile.js # [23:41:44] Starting 'react'... # [23:41:44] Finished 'react' after 515 ms # [23:41:45] Using gulpfile ~/projects/aqua/gulpfile.js # [23:41:45] Starting 'watch'... # [23:41:45] Finished 'watch' after 82 ms # [23:41:45] Starting 'less'... # [23:41:45] Finished 'less' after 15 ms # [23:41:45] Starting 'webpack'... # [23:41:45] Starting 'react'... # [23:41:45] Starting 'nodemon'... # [23:41:45] Finished 'nodemon' after 1.01 ms # [23:41:45] Starting 'media'... # [gulp] [nodemon] v1.3.7 # [gulp] [nodemon] to restart at any time, enter `rs` # [gulp] [nodemon] watching: *.* # [gulp] [nodemon] starting `node server.js` # Started the plot device. # [23:41:47] Finished 'media' after 2.16 s # [23:42:01] [webpack] Hash: 746152d2793c42fb1240 # ... # [23:42:01] Finished 'webpack' after 16 s ``` This will start the app using [`nodemon`](https://github.com/remy/nodemon). `nodemon` will watch for changes and restart the app as needed. Now you should be able to point your browser to http://localhost:8000/ and see the welcome page. ## Philosophy - Create a website and user system - Write code in a simple and consistent way - It's just JavaScript - 100% test coverage ## Features - Basic front end web pages - Contact page has form to email - Account signup page - Login system with forgot password and reset password - Abusive login attempt detection - User roles for accounts and admins - Facilities for notes and status updates - Admin groups with shared permissions - Admin level permissions that override group permissions ## Questions and contributing Any issues or questions (no matter how basic), open an issue. Please take the initiative to include basic debugging information like operating system and relevant version details such as: ```bash $ npm version # { aqua: '0.0.0', # npm: '2.5.1', # http_parser: '2.3', # modules: '14', # node: '0.12.0', # openssl: '1.0.1l', # uv: '1.0.2', # v8: '3.28.73', # zlib: '1.2.8' } ``` Contributions are welcome. Your code should: - include 100% test coverage - follow the [hapi.js coding conventions](http://hapijs.com/styleguide) If you're changing something non-trivial, you may want to submit an issue first. ## Running tests [Lab](https://github.com/hapijs/lab) is part of the hapi.js toolset and what we use to write all of our tests. For command line output: ```bash $ npm test # > [email protected] test /Users/jedireza/projects/aqua # > lab -c -L ./test/client-before.js ./test/client/ ./test/client-after.js ./test/misc/ ./test/server/ # .................................................. # .................................................. # .................................................. # .................................................. # .................................................. # .................................................. # .................................................. # .................................................. # .................................................. # .................................................. # .................................................. # .................................................. # .................................................. # .................................................. # .................................................. # .................................................. # .................................................. # .................................................. # .................................................. # .................................................. # ...... # 1006 tests complete # Test duration: 11004 ms # No global variable leaks detected # Coverage: 100.00% # Linting results: No issues ``` With html code coverage report: ```bash $ npm run test-cover # > [email protected] test-cover /Users/jedireza/projects/aqua # > lab -c -r html -o ./test/artifacts/coverage.html ./test/client-before.js ./test/client/ ./test/client-after.js ./test/misc/ ./test/server/ && open ./test/artifacts/coverage.html ``` This will run the tests and open a web browser to the visual code coverage artifacts. The generated source can be found in `/tests/artifacts/coverage.html`. ## License MIT ## Don't forget What you build with Aqua is more important than Aqua.
williamle8300/aqua
README.md
Markdown
mit
7,201
const INITIAL_STATE ={ items: [], shipping_value: 0 }; export default function cart(state = INITIAL_STATE, action){ switch(action.type){ case 'ADD': return { ...state, items: [...state.items, { price: Math.floor(Math.random() * 400 ) + 1 } ]} case 'DEL': return {...state, items: [ ...state.items.slice(0,action.index), ...state.items.slice(action.index + 1) ] }; case 'SET_SHIPPING': return { ...state, shipping_value: Math.floor(Math.random() * 100 ) + 1} default: return state; } }
igormontezano/testes
teste-redux-react/src/store/cart.js
JavaScript
mit
637
% Author: Thomas Stroeder % terminating %query: subset(o,i). subset(X,Y) :- subsetchecked(X,[],Y). subsetchecked([],_,_). subsetchecked([X|Xs],Ys,Zs) :- member(X,Zs), not_member(X,Ys), subsetchecked(Xs,[X|Ys],Zs). member(X,[X|_]). member(X,[_|Xs]) :- member(X,Xs). not_member(X,Y) :- member(X,Y),!,failure(a). not_member(_,_). failure(b).
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Logic_Programming_with_Cut/Stroeder_09/subset-oi.pl
Perl
mit
358
/** * Class representing a node * @private */ class Node { /** * Quickly create nodes for linked lists * * @constructor * * @param {*} value - value held by node * * @property {*} value - value held by node * @property {Object|Null} next - point to next node in list */ constructor(value) { this.value = value; this.next = null; } } /** Class representing a linked list */ class LinkedList { /** * Track head, tail and key features of linked list. Provides access to tail * so tail operations can occur in constant time. Provides size property for * constant time access. * * @constructor * * @property {Object|Null} head - first node in linked list * @property {Object|Null} tail - last node in linked list * @property {Number} size - length of linked list */ constructor() { this.head = null; this.tail = null; this.size = 0; } /** * @description Add nodes with given value to end of list. * * Strategy: Since we have access to tail, append newly created Node to tail * and move tail pointer to new node. * * Edge case(s): empty list, inappropriate inputs * * Time complexity: O(1) * Space complexity: O(1) * * @param {*} value - value to be inserted into new node */ push(value) { if (value === null || value === undefined) { throw new Error( "This Linked List does not allow empty values like null and undefined" ); } const node = new Node(value); this.size++; // Edge case: empty list if (this.head === null) { this.head = this.tail = node; return; } this.tail.next = node; this.tail = node; } /** * @description Check if node with given value exists in list. * * Strategy: Loop through list checking if value of any node equals input * value. End loop when we reach the last node. * * Time complexity: O(N) * Space complexity: O(1) * * @param {*} value - checked if exists in list * * @returns {Boolean} - whether or not value exists in list */ contains(value) { let curr = this.head; while (curr !== null) { if (curr.value === value) { return true; } curr = curr.next; } return false; } /** * @description Remove first node with given value from list. * * Strategy: Loop through LL tracking previous and current nodes so you can * remove reference to target node by pointing prev's next at current's next. * * Edge case(s): empty list, one node, remove head or tail, value not in list * * Time complexity: O(N) * Space complexity: O(1) * * @param {*} value - value to be removed from list * * @returns {Object} - node removed */ remove(value) { // Edge case: empty list if (this.size === 0) { throw new Error("This Linked List is already empty"); } // Edge case: if head matches, need to update head if (this.head.value === value) { const node = this.head; this.head = this.head.next; // Edge case: if removing final node in list if (this.size === 1) { this.tail = null; } this.size--; return node; } let prev = this.head; let curr = this.head.next; while (curr !== null) { if (curr.value === value) { // Edge case: if tail matches, need to update tail if (curr === this.tail) { this.tail = prev; } const node = curr; prev.next = curr.next; this.size--; return node; } prev = curr; curr = curr.next; } throw new Error("That value does not exist in this Linked List"); } } module.exports = LinkedList;
ganorberg/data-structures-javascript
structures/linked-list.js
JavaScript
mit
3,750
#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of Karesansui Core. # # Copyright (C) 2009-2012 HDE, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # """ <comment-ja> ユーティリティ関数群を定義する </comment-ja> <comment-en> Define the utility functions </comment-en> @file: utils.py @author: Taizo ITO <[email protected]> @copyright: """ import string import os import os.path import stat import random import subprocess import shutil import time import datetime import re import pwd import grp import sys import math import glob import fcntl import gzip import karesansui import karesansui.lib.locale from karesansui import KaresansuiLibException from karesansui.lib.const import CHECK_DISK_QUOTA from karesansui.lib.networkaddress import NetworkAddress def preprint_r(var,indent=2,depth=None,return_var=False): import pprint pp = pprint.PrettyPrinter(indent=indent,depth=depth) if return_var is True: return pp.pformat(var) else: pp.pprint(var) return True def dotsplit(val): """<comment-ja> ドット(.)区切りで文字列分割する。ドット(.)は) </comment-ja> <comment-en> TODO: English Comment </comment-en> """ rf = val.rfind('.') if rf == -1: return val, '' else: return val[:rf], val[rf+1:] def toplist(val): """<comment-ja> リスト型に変換する。 </comment-ja> <comment-en> TODO: English Comment </comment-en> """ if type(val) is list: return val else: return [val,] def comma_split(s): """<comment-ja> カンマ(,)単位で文字列分割しリスト型に変換する。 </comment-ja> <comment-en> TODO: English Comment </comment-en> """ ret = [] for y in [x.strip() for x in s.split(',') if x]: ret.append(y) return ret def uniq_sort(array): """<comment-ja> 配列の要素をソートし重複した要素を取り除く @param array: 配列 @return: 配列 @rtype: list </comment-ja> <comment-en> run a unique sort and return an array of sorted @param array: list @return: list </comment-en> """ array = sorted(array) #array = [x for i,x in enumerate(array) if array.index(x) == i] array = [_x for _x, _y in zip(array, array[1:] + [None]) if _x != _y] return array def dict_ksort(dt): """<comment-ja> 辞書配列をキーを元にソートし重複する @param dt: 辞書 @type dt: dict @return: ソート後の辞書配列 @rtype: dict </comment-ja> <comment-en> run a key sort in dict </comment-en> """ new_dict = {} for k,v in sorted(dt.iteritems(), lambda x,y : cmp(x[0], y[0])): new_dict[k] = v return new_dict def dict_search(search_key, dt): """<comment-ja> 辞書配列から指定した値に対応するキーを取得する @param dt: 辞書 @type dt: dict @return: 取得したキーを要素とする配列 @rtype: array </comment-ja> <comment-en> Searches the dictionary for a given value and returns the corresponding key. </comment-en> """ def map_find(_x, _y): if _y == search_key: return _x def except_None(_z): return _z <> None rlist = map(map_find, dt.keys(), dt.values()) return filter(except_None, rlist) def dec2hex(num): """<comment-ja> 整数値を16進数の文字列に変換する @param num: 整数値 @return: 16進数の文字列 @rtype: str </comment-ja> <comment-en> TODO: English Comment </comment-en> """ return "%X" % num def dec2oct(num): """<comment-ja> 整数値を8進数の文字列に変換する @param num:整数値 @return: 8進数の文字列 @rtype: str </comment-ja> <comment-en> TODO: English Comment </comment-en> """ return "%o" % num def hex2dec(s): """<comment-ja> 16進数の文字列を整数値に変換する @param string:16進数の文字列 @return int16 @rtype: int </comment-ja> <comment-en> TODO: English Comment </comment-en> """ return int(s, 16) def oct2dec(string): """<comment-ja> 8進数の文字列を整数値に変換する @param string:8進数の文字列 @rtype: integer </comment-ja> <comment-en> TODO: English Comment </comment-en> """ return int(string, 8) def float_from_string(string): """<comment-ja> 浮動小数点表記の文字列を数値に変換する @param string: 浮動小数点表記 @rtype: float </comment-ja> <comment-en> TODO: English Comment </comment-en> >>> from karesansui.lib.utils import float_from_string >>> >>> float_from_string("9.95287e+07") # 99528700 99528700.0 >>> float_from_string("2.07499e+08") # 207499000 207499000.0 >>> float_from_string("-2.07499e+02") # -207.499 -207.499 >>> float_from_string("+2.07499e+02") # 207.499 207.499 >>> float_from_string("+2.07499e-02") # 0.0207499 0.0207499 >>> float_from_string("3.39112632978e+001") # 3391126329780.0 33.9112632978 """ if type(string) != str: return False regex = re.compile("^([\+\-]?)(([0-9]+|[0-9]*[\.][0-9]+))([eE])([\+\-]?)([0-9]+)$") m = regex.match(string) if m: sign = m.group(1) mantissa = float(m.group(2)) sign_exponent = m.group(5) exponent = int(m.group(6)) data = float(1) if sign == "-": data = data * -1 if sign_exponent == "-": exponent = -1 * exponent data = data * mantissa * (10**exponent) else: return False return data def ucfirst(string): return string[0].upper() + string[1:] def lcfirst(string): return string[0].lower() + string[1:] def next_number(min,max,exclude_numbers): """ <comment-ja> 指定範囲内における除外対象整数以外の次の整数を取得する @param min: 範囲中の最小の整数 @param max: 範囲中の最大の整数 @param exclude_numbers: 除外対象整数を要素にもつ配列 @return: 整数 @rtype: int </comment-ja> <comment-en> @param min: Minimum interger in specified range @param max: Maximum interger in specified range @param exclude_numbers: array that has the element of exclusive interger @return: Interger </comment-en> """ for _x in range(min,max): if not _x in exclude_numbers: return _x def isset(string, vars=globals(), verbose=False): """ bool isset(str string [,bool verbose=False]) <comment-ja> 変数名がセットされていることを検査する @param string: 変数名を示す文字列 @type string: str @param vars: 検査対象の変数配列 @type vars: dict @param verbose: エラーメッセージを表示する場合はTrue @type verbose: bool @return: 変数名がセットされていればTrue、いなければFalse @rtype: bool </comment-ja> <comment-en> Determine if a variable is set. @param string: The variable name, as a string. @type string: str @param vars: all variables available in scope @type vars: dict @param verbose: If used and set to True, isset() will output error messages. @type verbose: bool @return: Returns True if a variable is set, False otherwise. @rtype: bool </comment-en> """ retval = False try: for _k,_v in vars.iteritems(): exec("%s = _v" % _k) exec("%s" % string) retval = True except NameError, e: if verbose is True: print _("Notice: Undefined variable \"%s\"") % str(e.args) except KeyError, e: if verbose is True: print _("Notice: Undefined index \"%s\"") % str(e.args) except Exception, e: if verbose is True: print _("Notice: Undefined variable \"%s\"") % str(e.args) pass return retval def is_uuid(uuid=None): """<comment-ja> KaresansuiのUUIDフォーマットに対応しているか。 </comment-ja> <comment-en> TODO: English Comment </comment-en> """ uuid_regex = re.compile(r"""^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$""") if uuid != None and uuid_regex.match(uuid): return True return False def generate_uuid(): """ <comment-ja> ランダムなUUIDを生成する @return: UUID用の16個のバイト要素を持つ配列 </comment-ja> <comment-en> Generate UUID @return: Array UUID </comment-en> """ uuid = [] for _x in range(0, 16): uuid.append(random.randint(0x00,0xff)) return uuid def string_from_uuid(uuid): """ <comment-ja> UUIDデータを文字列に変換する @param uuid: generate_uuid関数等で生成されたUUIDデータ @return: UUID文字列 </comment-ja> <comment-en> Convert UUID data to string @param uuid: UUID data that was generated by certain function like as generate_uuid() @return: The string that stands for uuid </comment-en> """ tuuid = tuple(uuid) return "-".join(["%02x"*4 % tuuid[0:4], "%02x"*2 % tuuid[4:6], "%02x"*2 % tuuid[6:8], "%02x"*2 % tuuid[8:10], "%02x"*6 % tuuid[10:16] ]); def string_to_uuid(string): """ <comment-ja> 文字列をUUIDデータに変換する @param string: UUID文字列 @return: UUIDデータ </comment-ja> <comment-en> Convert string to UUID data @param string: The string that stands for uuid @return: UUID data </comment-en> """ string = string.replace('-', '') return [ int(string[i : i + 2], 16) for i in range(0, 32, 2) ] def generate_mac_address(type="XEN"): """ <comment-ja> ランダムなMACアドレスを生成する (XENなら、00:16:3e:00:00:00 から 00:16:3e:7f:ff:ff の範囲) (KVMなら、52:54:00:00:00:00 から 52:54:00:ff:ff:ff の範囲) @param type: ハイパーバイザのタイプ (XEN or KVM) @return: MACアドレス </comment-ja> <comment-en> Generate random MAC address (if hypervisor is XEN, generates address by range between 00:16:3e:00:00:00 and 00:16:3e:7f:ff:ff) (if hypervisor is KVM, generates address by range between 52:54:00:00:00:00 and 52:54:00:ff:ff:ff) @param type: The type of hypervisor (XEN or KVM) @return: The string that stands for MAC address </comment-en> """ if type == "KVM": mac = [ 0x52, 0x54, 0x00, random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff) ] else: mac = [ 0x00, 0x16, 0x3e, random.randint(0x00, 0x7f), random.randint(0x00, 0xff), random.randint(0x00, 0xff) ] return ':'.join(map(lambda x: "%02x" % x, mac)) def generate_phrase(len,letters=None): """<comment-ja> ランダムな文字列を生成する @param len: 文字列の長さ @return: ランダム文字列 @rtype: str </comment-ja> <comment-en> Generate random string @param len: length of string @return: The generated string @rtype: str </comment-en> """ if letters is None: letters = string.digits + string.letters + '-.' random.seed() return ''.join(random.choice(letters) for i in xrange(len)) def detect_encoding(string,encoding_list=None): """ <comment-ja> 文字エンコーディングを検出する @param string: 検出する文字列データ @param encoding_list: エンコーディングのリスト。エンコーディング検出の順番を配列で指定。省略時は、[ 'euc-jp', 'utf-8', 'shift-jis', 'iso2022-jp' ] @return: 検出した文字エンコーディング </comment-ja> <comment-en> Detect character encoding @param string: The string being detected @param encoding_list: list of character encoding. Encoding order will be specified by array. if it is omitted, detect order is [ 'euc-jp', 'utf-8', 'shift-jis', 'iso2022-jp' ] @return: The detected character encoding </comment-en> """ func = lambda data,encoding: data.decode(encoding) and encoding if not encoding_list: encoding_list = [ 'euc-jp', 'utf-8', 'shift-jis', 'iso2022-jp' ] for encoding in encoding_list: try: return func(string, encoding) except: pass return None def execute_command(command_args,user=None,env=None): """ <comment-ja> コマンドを実行する @param command_args: 実行するコマンドとその引数を要素とする配列 @param user: 実行するユーザー名 (省略時はgetuidによる) @param env: 実行時に適用する環境変数の辞書配列 @return: 終了ステータスと実行時の出力結果の配列 </comment-ja> <comment-en> Execute command @param command_args: The array that consists of command name and its arguments. @param user: the effective user id @param env: dictionary of environ variables @return: The return status of the executed command </comment-en> """ ret = -1 res = [] curdir = os.getcwd() if user is None: homedir = pwd.getpwuid(os.getuid())[5] else: try: int(user) homedir = pwd.getpwuid(int(user))[5] except: try: homedir = pwd.getpwnam(user)[5] except: homedir = pwd.getpwuid(os.getuid())[5] subproc_args = { 'stdin': subprocess.PIPE, 'stdout': subprocess.PIPE, 'stderr': subprocess.STDOUT, # 'shell': True, 'cwd': homedir, 'close_fds': True, } if env is not None: subproc_args['env'] = env try: pp = subprocess.Popen(command_args, **subproc_args) except OSError, e: #raise KaresansuiLibException("Failed to execute command: %s" % command_args[0]) return [ret,res] (stdouterr, stdin) = (pp.stdout, pp.stdin) while True: line = stdouterr.readline() if not line: break line = line.rstrip() try: res.append(unicode(line, detect_encoding(line)).encode("utf-8")) except: res.append(line) try: ret = pp.wait() except: ret = 0 return [ret,res] def pipe_execute_command(commands): """ <comment-ja> PIPE付きコマンドを実行する @param commands: パイプ付きのコマンドを分割した、配列 example) [['rpm', '-qa'], ['grep', 'karesansui'],] @return: 終了ステータスと実行時の出力結果の配列 </comment-ja> <comment-en> </comment-en> """ ret = -1 res = [] out = [] for cmd in commands: subproc_args = {'stdin': subprocess.PIPE, 'stdout': subprocess.PIPE, } if 0 < len(out): subproc_args['stdin'] = out[len(out)-1] pp = subprocess.Popen(cmd, **subproc_args) (stdout, stdin) = (pp.stdout, pp.stdin) out.append(stdout) ret = pp.wait() res = out[len(out)-1].read() return (ret,res) def create_file(file, value) : """ <comment-ja> ファイルを作成する。 @param file: 作成するファイル名 @param value: 書き込む値 @return: なし </comment-ja> <comment-en> create file @param file: The name of generated file @param value: The value of generated file @return: None </comment-en> """ if os.path.exists(file): raise KaresansuiLibException("Error: %s already exists" % file) fd = open(file, 'w') try: try: fd.write(value) except IOError, err: raise KaresansuiLibException("IOError: %s" % str(err)) finally: fd.close() def remove_file(file) : """ <comment-ja> ファイルを削除する。 @param file: 削除するファイル名 @return: なし </comment-ja> <comment-en> remove file @param file: The name of removed file @return: None </comment-en> """ if not os.path.exists(file): raise KaresansuiLibException("Error: %s not exists" % file) try: os.remove(file) except OSError, err: raise KaresansuiLibException("OSError: %s" % str(err)) def create_raw_disk_img(file,size,is_sparse=True) : """ <comment-ja> rawディスクファイルを生成する @param file: 生成するファイル名 @param size: ファイルサイズ(MB) @param sparse: スパースファイル? @return: なし </comment-ja> <comment-en> Create raw disk file @param file: The name of generated file @param size: The size of generated file @return: None </comment-en> """ if is_sparse is True: command_args = [ "dd", "if=/dev/zero", "of=%s" % file, "seek=%s" % str(size), "bs=1M", "count=0", ] else: command_args = [ "dd", "if=/dev/zero", "of=%s" % file, "bs=1M", "count=%s" % str(size) , ] (rc,res) = execute_command(command_args) if rc != 0: return None return rc # if os.path.exists(file): # raise KaresansuiLibException("Error: %s already exists" % file) # # try: # fd = open(file, 'w') # try: # fd.truncate(1024L * 1024L * size) # except IOError, err: # raise KaresansuiLibException("IOError: %s" % str(err)) # finally: # fd.close() def create_qemu_disk_img(file,size,type="raw") : """ <comment-ja> qemu用ディスクイメージファイルを生成する @param file: 生成するファイル名 @param size: ファイルサイズ(MB) @param type: ディスクイメージのタイプ raw/qcow/qcow2/cow/vmdk/cloop @return: なし </comment-ja> <comment-en> Create qemu disk image file @param file: The name of generated file @param size: The size of generated file @return: None </comment-en> """ from karesansui.lib.const import DISK_QEMU_FORMAT #available_formats = [ "raw","qcow","qcow2","cow","vmdk","cloop" ] available_formats = DISK_QEMU_FORMAT.values() if type in available_formats: command_args = [ "qemu-img", "create", "-f", type, file, "%sM" % str(size), ] (rc,res) = execute_command(command_args) if rc != 0: return None else: rc = None return rc def create_disk_img(file,size,type="raw",is_sparse=True) : """ <comment-ja> ディスクイメージファイルを生成する @param file: 生成するファイル名 @param size: ファイルサイズ(MB) @param type: ディスクイメージのタイプ raw/qcow/qcow2/cow/vmdk/cloop @param sparse: スパースファイル?(rawのときのみ) @return: なし </comment-ja> <comment-en> Create disk image file @param file: The name of generated file @param size: The size of generated file @return: None </comment-en> """ from karesansui.lib.const import DISK_QEMU_FORMAT #available_formats = [ "raw","qcow","qcow2","cow","vmdk","cloop" ] available_formats = DISK_QEMU_FORMAT.values() if type in available_formats: if type == "raw": rc = create_raw_disk_img(file,size,is_sparse) else: rc = create_qemu_disk_img(file,size,type) else: rc = None raise KaresansuiLibException("Unsupported disk image format. [%s]" % type) return rc def copy_file(src_file,dest_file): """ <comment-ja> ファイルをコピーする @param src_file: コピー元ファイル名 @param dest_file: コピー先ファイル名 @return: コピー先ファイル名 </comment-ja> <comment-en> Copy file @param src_file: Path to the source file @param dest_file: The destination path @return: The destination path </comment-en> """ #ret = shutil.copy2(src_file, dest_file) ret = False if os.path.exists(src_file): try: if dest_file[0] != "/": dest_path = "%s/%s" % (os.getcwd(),os.path.dirname(dest_file),) else: dest_path = os.path.dirname(dest_file) if not os.path.exists(dest_path): os.makedirs(dest_path) (ret, res) = execute_command(["cp","-rfp",src_file,dest_file]) if ret == 0: ret = True except: return False else: return False return ret def copy_file_cb(src,dst,callback=None,sparse=False,each=True): default_block_size = 4096 if type(src) == str: src = [src] if type(dst) == str: dst = [dst] if len(src) != len(dst): raise if each is not True: all_bytes = 0 for _src in src: all_bytes = all_bytes + os.path.getsize(_src) text = "Copying" callback.start(filename=None, size=long(all_bytes), text=text) cnt = 0 i = 0 all_bytes = 0 for _src in src: try: _dst = str(dst[i]) except: _dst = dst[i] if os.path.exists(os.path.dirname(_dst)) is False: os.makedirs(os.path.dirname(_dst)) bytes = os.path.getsize(_src) all_bytes = all_bytes + bytes if each is True: text = _("Copying %s") % os.path.basename(_src) callback.start(filename=_src, size=long(bytes), text=text) cnt = 0 if os.path.exists(_dst) is False and sparse is True: block_size = default_block_size fd = None try: fd = os.open(_dst, os.O_WRONLY|os.O_CREAT) os.ftruncate(fd, bytes) finally: if fd: os.close(fd) else: block_size = 1024*1024*10 #nulls = '\0' * default_block_size nulls = 0x00 * default_block_size src_fd = None dst_fd = None try: try: src_fd = os.open(_src, os.O_RDONLY) dst_fd = os.open(_dst, os.O_WRONLY|os.O_CREAT) while 1: data = os.read(src_fd, block_size) sz = len(data) if sz == 0: if each is True: callback.end(bytes) else: callback.update(all_bytes) break if sparse and nulls == data: os.lseek(dst_fd, sz, 1) else: b = os.write(dst_fd, data) if sz != b: if each is True: callback.end(cnt) else: callback.update(cnt) break cnt += sz if cnt < bytes: callback.update(cnt) except OSError, e: raise RuntimeError(_("ERROR: copying %s to %s: %s") % (_src,_dst,str(e))) finally: if src_fd is not None: os.close(src_fd) if dst_fd is not None: os.close(dst_fd) i = i + 1 callback.end(all_bytes) def move_file(src_file,dest_file): """ <comment-ja> ファイルを移動する @param src_file: 移動元ファイル名 @param dest_file: 移動先ファイル名 @return: 移動先先ファイル名 </comment-ja> <comment-en> Copy file @param src_file: Path to the source file @param dest_file: The destination path @return: The destination path </comment-en> """ #ret = shutil.copy2(src_file, dest_file) ret = False if os.path.exists(src_file): try: if dest_file[0] != "/": dest_path = "%s/%s" % (os.getcwd(),os.path.dirname(dest_file),) else: dest_path = os.path.dirname(dest_file) if not os.path.exists(dest_path): os.makedirs(dest_path) (ret, res) = execute_command(["mv","-f",src_file,dest_file]) if ret == 0: ret = True except: return False else: return False return ret def get_xml_parse(file): from xml.dom import minidom if os.path.exists(file): document = minidom.parse(file) else: document = minidom.parseString(file) return document def get_xml_xpath(document, expression): """ <comment-ja> XPathロケーションパスを評価する @param document: xml.dom.minidom.Document @param expression: 実行する XPath 式 @return: 与えられた XPath 式 にマッチするすべてのノードを含む ノード一覧 </comment-ja> <comment-en> Evaluates the XPath Location Path in the given string @param file: Path to XML file @param expression: The XPath expression to execute @return: Returns node list containing all nodes matching the given XPath expression </comment-en> """ from xml import xpath result = None for i in xpath.Evaluate(expression, document.documentElement): result = i.nodeValue return result def get_nums_xml_xpath(document, expression): """ <comment-ja> XPathロケーションパスを評価する @param file: XMLファイルパス、または、XMLデータそのもの @param expression: 実行する XPath 式 @return: 与えられた XPath 式 にマッチするすべてのノードを含む ノード数 </comment-ja> <comment-en> Evaluates the XPath Location Path in the given string @param file: Path to XML file @param expression: The XPath expression to execute @return: Returns the number of node containing all nodes matching the given XPath expression </comment-en> """ from xml import xpath result = None return xpath.Evaluate('count(%s)' % expression, document.documentElement) def gettimeofday(): """ <comment-ja> 現在の時刻を取得する @return: 紀元 (the Epoch: time(2) を参照) からの秒とマイクロ秒 </comment-ja> <comment-en> Get current time @return: the number of seconds and microseconds since the Epoch (see time(2)) </comment-en> """ d = datetime.datetime.now() return int(time.mktime(d.timetuple())),d.microsecond def load_locale(): import karesansui import gettext try: t = gettext.translation('messages', karesansui.dirname + "/locale") except IOError, err: old_lang = os.environ['LANG'] os.environ['LANG'] = 'en' t = gettext.translation('messages', karesansui.dirname + "/locale") os.environ['LANG'] = old_lang return t.gettext def get_no_overlap_list(target_list): """ <comment-ja> リストから重複要素を取り除く @param target_list: 重複要素を取り除きたいリスト @return: 重複が取り除かれたリスト(順番は保存されない) </comment-ja> <comment-en> delete overlap element in list @param target_list: list that has overlap element @return: list that delete overlap element (not keep original number) </comment-en> """ return list(set(target_list)) def is_int(val): """<comment-ja> int型かどうか。 @return: bool </comment-ja> <comment-en> TODO: English Comment </comment-en> """ try: ret = int(val) return True except (TypeError, ValueError): return False def is_param(input, name, empty=False): """ <comment-ja> リクエストデータ(self.input or web.input)に指定したパラメタが存在しているか。 @param input: @type input @param @type @return: bool </comment-ja> <comment-en> TODO: English </comment-en> """ try: if input.has_key(name) is True: if empty is True: if is_empty(input[name]) is True: return False else: # has (name)key and input[name] is not empty return True else: # has (name)key and empty arg is False return True else: # does not have (name)key return False except: return False def is_ascii(value): for x in xrange(len(value)): # Printable characters ASCII is between 0x20(SP) and 0x7e(~) if ord(value[x]) < 0x20 or 0x7e < ord(value[x]): return False return True def str2datetime(src, format, whole_day=False): """<comment-ja> フォーマット(format)に一致した文字列(src)をdatetime型にキャストして M D Y のみのdatetimeを取得します。 @param src: 変換文字列 @type src: str @param format: 文字列フォーマット @type format: str @param whole_day: 一日の最終時刻まで @type whole_day: boolean @return: datetime型 @rtype: datetime </comment-ja> <comment-en> TODO: English Comment </comment-en> """ _t = time.strptime(src, format) if whole_day is True: target = datetime.datetime(_t.tm_year, _t.tm_mon, _t.tm_mday, 23, 59) else: target = datetime.datetime(_t.tm_year, _t.tm_mon, _t.tm_mday) return target def unixtime(): """<comment-ja> UTCのエポックタイムを返却します。 @rtype: float </comment-ja> <comment-en> TODO: English Comment </comment-en> """ return time.time() def unixtime_str(): """<comment-ja> UTCのエポックタイムを文字列として返却します。 @rtype: str </comment-ja> <comment-en> TODO: English Comment </comment-en> """ return "%f" % unixtime() def getfilesize(filepath): """<comment-ja> 指定されたファイルのサイズを返却します。 @rtype: long </comment-ja> <comment-en> TODO: English Comment </comment-en> """ return os.stat(filepath)[stat.ST_SIZE] def getfilesize_str(filepath): """<comment-ja> 指定されたファイルのサイズを文字列で返却します。 @rtype: str </comment-ja> <comment-en> TODO: English Comment </comment-en> """ return "%ld" % getfilesize(filepath) def get_filesize_MB(size): """ <comment-ja> サイズ(str)をMBに変換する。 @param size: サイズ @type size: str @return: MB @rtype: long </comment-ja> <comment-en> English Comment </comment-en> """ return long(math.ceil(float(size) / 1024 / 1024)) def replace_None(obj, replace_item): """<comment-ja> __dict__から要素がNone, あるいは空文字('')のものを指定の要素に置き換えます @param __dict__をもつオブジェクト @rtype: object </comment-ja> <comment-en> TODO: English Comment </comment-en> """ for k,v in obj.__dict__.iteritems(): if v == None or v == '': obj.__dict__[k] = replace_item return obj def is_readable(path): """<comment-ja> 指定されたパスが読み込み可能かどうか判定する @param path:ファイルパス @return: 可能ならTrue、不可能ならFalse @rtype: bool </comment-ja> <comment-en> test the readability of path </comment-en> """ return os.access(path, os.R_OK) def is_writable(path): """<comment-ja> 指定されたパスが書き込み可能かどうか判定する @param path:ファイルパス @return: 可能ならTrue、不可能ならFalse @rtype: bool </comment-ja> <comment-en> test the readability of path </comment-en> """ return os.access(path, os.W_OK) def is_executable(path): """<comment-ja> 指定されたパスが実行可能かどうか判定する @param path:ファイルパス @return: 可能ならTrue、不可能ならFalse @rtype: bool </comment-ja> <comment-en> test the readability of path </comment-en> """ return os.access(path, os.X_OK) def r_chown(path,owner): """<comment-ja> 指定されたパス配下のディレクトリのオーナーを再帰的に変更する @param path:オーナーを変更したいパス @param owner:ユーザー名もしくがユーザーID、「:」で続けてグループを指定可能 @return: 成功ならTrue、失敗ならFalse @rtype: bool </comment-ja> <comment-en> TODO: English Comment </comment-en> """ owner = str(owner) if not os.path.exists(path): return False if ':' in owner: user, group = owner.split(':') else: user, group = [owner,None ] if is_int(user) is not True: try: pw = pwd.getpwnam(user) except: return False else: try: pw = pwd.getpwuid(int(user)) except: return False uid = pw[2] if group == None: statinfo = os.stat(path) gid = statinfo.st_gid else: if is_int(group) is not True: try: gr = grp.getgrnam(group) except: return False else: try: gr = grp.getgrgid(int(group)) except: return False gid = gr[2] if os.path.isfile(path) or os.path.islink(path): try: os.chown(path,uid,gid) except: return False elif os.path.isdir(path): try: os.chown(path,uid,gid) except: return False for name in os.listdir(path): sub_path = os.path.join(path, name) r_chown(sub_path,owner) return True def r_chgrp(path,group): """<comment-ja> 指定されたパス配下のディレクトリのグループを再帰的に変更する @param path:グループを変更したいパス @param group:グループ名もしくがグループID @return: 成功ならTrue、失敗ならFalse @rtype: bool </comment-ja> <comment-en> TODO: English Comment </comment-en> """ group = str(group) if not os.path.exists(path): return False statinfo = os.stat(path) uid = statinfo.st_uid if is_int(group) is not True: try: gr = grp.getgrnam(group) except: return False else: try: gr = grp.getgrgid(int(group)) except: return False gid = gr[2] if os.path.isfile(path) or os.path.islink(path): try: os.chown(path,uid,gid) except: return False elif os.path.isdir(path): try: os.chown(path,uid,gid) except: return False for name in os.listdir(path): sub_path = os.path.join(path, name) r_chgrp(sub_path,group) return True def r_chmod(path,perm): """<comment-ja> 指定されたパス配下のディレクトリのグループを再帰的に変更する @param path:グループを変更したいパス @param perm:パーミッション @return: 成功ならTrue、失敗ならFalse @rtype: bool </comment-ja> <comment-en> TODO: English Comment </comment-en> """ perm_regex = re.compile(r"""^(?P<user>[ugo]{0,3})(?P<action>[\+\-])(?P<value>[rwxst]{1,3})$""") user_table = {"u":"USR","g":"GRP","o":"OTH"} perm_table = {"r":"R","w":"W","x":"X"} if not os.path.exists(path): return False original_perm = perm if is_int(perm): if type(perm) == str: perm = oct2dec(perm) new_perm = perm else: s = os.lstat(path) new_perm = stat.S_IMODE(s.st_mode) m = perm_regex.match(perm) if m: user = m.group('user') action = m.group('action') value = m.group('value') if user == "": user = "ugo" mask_perm = 0 for k,v in user_table.iteritems(): if k in user: for k2,v2 in perm_table.iteritems(): if k2 in value: exec("bit = stat.S_I%s%s" % (v2,v,)) mask_perm = mask_perm | bit if "t" in value: bit = stat.S_ISVTX mask_perm = mask_perm | bit if "s" in value: if "u" in user: bit = stat.S_ISUID mask_perm = mask_perm | bit if "g" in user: bit = stat.S_ISGID mask_perm = mask_perm | bit #print "new_perm1:" + dec2oct(new_perm) #print "mask_perm:" + dec2oct(mask_perm) if action == "-": new_perm = new_perm & (~ mask_perm) elif action == "+": new_perm = new_perm | mask_perm #print "new_perm2:" + dec2oct(new_perm) else: return False if os.path.isfile(path) or os.path.islink(path): try: os.chmod(path,new_perm) except: return False elif os.path.isdir(path): try: os.chmod(path,new_perm) except: return False for name in os.listdir(path): sub_path = os.path.join(path, name) r_chmod(sub_path,original_perm) return True def is_dict_value(value, dic): """<comment-ja> 指定された値が辞書にあるか調べる @param value:調べたい値 @param dic:辞書 @return: 辞書にあればTrue、ないならFalse @rtype: bool </comment-ja> <comment-en> TODO: English Comment </comment-en> """ for key in dic.keys(): if value == dic[key]: return True return False #def is_number(string): # """<comment-ja> # 文字列が数字のみで構成されているか調べる # @param string:調べたい文字列 # @return: 数字のみならTrue、そうでないならFalse # @rtype: bool # </comment-ja> # <comment-en> # TODO: English Comment # </comment-en> # """ # pattern = re.compile('^[\d]+$') # if pattern.match(string): # return True # return False def is_empty(string): """<comment-ja> 文字列が空かどうか調べる @param string: 調べたい文字列 @return: 文字列が空ならTrue、そうでないならFalse </comment-ja> <comment-en> TODO: English Comment </comment-en> """ if string and 0 < len(string.strip()): return False else: return True def uniq_filename(): """<comment-ja> ユニークなファイル名を返却する。 @param filename: 既存のファイル名 @return: ユニークなファイル名 </comment-ja> <comment-en> TODO: English Comment </comment-en> """ return unixtime_str() def get_model_name(model): """<comment-ja> モデル名を返却する。 @param model: モデル @return: モデル名 </comment-ja> <comment-en> TODO: English Comment </comment-en> """ if hasattr(model, "__repr__"): return repr(model).split("<")[0] else: return None def chk_create_disk(target, disk_size): """<comment-ja> 指定されたフォルダ/ファイルが属するパーティションに、指定したサイズのファイルが作成できるか。 比較単位はMB @param target: 調べるファイル/フォルダパス @type target: str @param disk_size: @return: OK=True | NG=False @rtype: bool </comment-ja> <comment-en> English Comment </comment-en> """ partition = get_partition_info(target, header=False) available = long(partition[3][0]) if 0 < (available * CHECK_DISK_QUOTA - float(disk_size)): return True else: return False def get_partition_info(target, header=False): """<comment-ja> 指定したファイル/フォルダパスのパーティション情報(dfコマンドの結果)を取得する。 - return - 0: 'Filesystem' デバイス名 - 1: '1048576-blocks' 最大サイズ - 2: 'Used' 使用サイズ - 3: 'Available' ディスク残量 - 4: 'Capacity' 使用率 - 5: 'Mounted' マウント先 値はすべてMB @param target: 調べるファイル/フォルダパス @type target: str @param header: ヘッダ情報を表示するか @type header: bool @rtype: dict </comment-ja> <comment-en> English Comment </comment-en> """ if os.path.exists(target) is True: ret = {} if header is True: pipe = os.popen("LANG=C /bin/df -P -m " + target) try: data = [] for line in pipe.readlines(): data.append(re.sub(r'[ \t]', ' ', line).split()) finally: pipe.close() for i in range(0,6): ret[i] = (data[0][i], data[1][i]) else: pipe = os.popen("LANG=C /bin/df -P -m %s | /bin/sed -n 2p" % target) try: line = pipe.read() finally: pipe.close() data = re.sub(r'[ \t]', ' ', line).split() for i in range(0,6): ret[i] = (data[i],) return ret else: return None def uni_force(string, system="utf-8"): """ <comment-ja> systemで指定された文字コードもしくは、["ascii", "utf-8", "euc-jp", "cp932", "shift-jis"]で強制的にunicodeへ変換します。 @param string: 変換文字列 @type string: str @param system: 文字コード @type system: str @return: Unicode文字列 @rtype: str </comment-ja> <comment-en> English Comment </comment-en> """ if isinstance(string, unicode) is True: return string else: try: return unicode(string, system) except: encodings = ["ascii", "utf-8", "euc-jp", "cp932", "shift-jis"] for encode in encodings: try: return unicode(string, encode) except: pass raise KaresansuiLibException("Character code that can be converted to unicode.") def get_ifconfig_info(name=None): """ <comment-ja> ネットワークデバイス情報を取得する @param name: 取得したいデバイス名(省略時は全デバイス情報が指定されたとみなす) 「regex:^eth」のようにプレフィックスにregex:を付けると正規表現にマッチしたデバイス名の情報を全て取得できる。 @return: デバイス情報が格納されたdict配列 配列の内容例 {'eth0': { 'bcast': '172.16.0.255', 'device': 'eth0', 'hwaddr': '00:1D:09:D7:30:4B', 'ipaddr': '172.16.0.10', 'ipv6addr': 'fe80::21d:9ff:fed7:304b/64', 'link': 'Ethernet', 'mask': '255.255.255.0', 'metric': '1', 'mtu': '1500', 'running': True, 'scope': 'Link', 'up': True, 'use_bcast': 'BROADCAST', 'use_mcast': 'MULTICAST'}} </comment-ja> <comment-en> Get computer's network interface information @param name: network device name @return: a dict with: ipaddr, hwaddr, bcast, mask etc... @rtype: dict </comment-en> """ info = {} _ifconfig = '/sbin/ifconfig' command_args = [_ifconfig,'-a'] old_lang = os.environ['LANG'] os.environ['LANG'] = 'C' (ret,res) = execute_command(command_args) os.environ['LANG'] = old_lang if ret != 0: return info device_regex = re.compile(r"""^(?P<device>[\S\:]+)\s+Link encap:(?P<link>(\S+ ?\S+))(\s+HWaddr (?P<hwaddr>[0-9a-fA-F:]+))?""") ipv4_regex = re.compile(r"""^\s+inet addr:\s*(?P<ipaddr>[0-9\.]+)(\s+Bcast:(?P<bcast>[0-9\.]+))?\s+Mask:(?P<mask>[0-9\.]+)""") ipv6_regex = re.compile(r"""^\s+inet6 addr:\s*(?P<ipv6addr>[0-9a-fA-F\:\/]+)\s+Scope:(?P<scope>\S+)""") status_regex = re.compile(r"""^\s+((?P<up>UP)\s+)?((?P<use_bcast>(BROADCAST|LOOPBACK))\s+)?((?P<running>RUNNING)\s+)?((?P<use_mcast>(MULTICAST|NOARP))\s+)?MTU:(?P<mtu>[0-9]+)\s+Metric:(?P<metric>[0-9]+)""") _info = {} for aline in res: if aline.strip() == "": cidr = None netlen = None if ipaddr is not None and mask is not None: netaddr = NetworkAddress("%s/%s" % (ipaddr,mask,)) cidr = netaddr.get('cidr') netlen = netaddr.get('netlen') _info[device] = { "device":device, "link":link, "hwaddr":hwaddr, "ipaddr":ipaddr, "bcast":bcast, "mask":mask, "ipv6addr":ipv6addr, "scope":scope, "up":up, "running":running, "use_bcast":use_bcast, "use_mcast":use_mcast, "mtu":mtu, "metric":metric, "cidr":cidr, "netlen":netlen, } m = device_regex.match(aline) if m: device = m.group('device') link = m.group('link') hwaddr = m.group('hwaddr') ipaddr = None bcast = None mask = None ipv6addr = None scope = None up = False running = False use_bcast = None use_mcast = None mtu = None metric = None m = ipv4_regex.match(aline) if m: ipaddr = m.group('ipaddr') bcast = m.group('bcast') mask = m.group('mask') m = ipv6_regex.match(aline) if m: ipv6addr = m.group('ipv6addr') scope = m.group('scope') m = status_regex.match(aline) if m: if m.group('up') == 'UP': up = True use_bcast = m.group('use_bcast') if m.group('running') == 'RUNNING': running = True use_mcast = m.group('use_mcast') mtu = m.group('mtu') metric = m.group('metric') all_info = dict_ksort(_info) #import pprint #pp = pprint.PrettyPrinter(indent=4) #pp.pprint(all_info) if name == None: return all_info regex_regex = re.compile(r"""^regex:(?P<regex>.*)""") m = regex_regex.match(name) for dev,value in all_info.iteritems(): if m == None: if dev == name: info[dev] = value return info else: regex = m.group('regex') query_regex = re.compile(r""+regex+"") n = query_regex.search(dev) if n != None: info[dev] = value return info def get_proc_meminfo(path="/proc/meminfo"): if os.path.isfile(path) is False: return None fp = open(path, "r") try: ret = {} for line in fp.readlines(): val = line.split(":") key = re.sub(r'[\t\n]', '', val[0].strip()) value = re.sub(r'[\t\n]', '', val[1]).strip() invalue = value.split(" ") if len(invalue) > 1: ret[key] = (invalue[0], invalue[1]) else: ret[key] = (invalue[0]) return ret except: return None def get_proc_cpuinfo(path="/proc/cpuinfo"): if os.path.isfile(path) is False: return None fp = open(path, "r") try: ret = {} i = 0 ret[i] = {} for line in fp.readlines(): if len(line.strip()) <= 0: i += 1 ret[i] = {} else: val = line.split(":") key = re.sub(r'[\t\n]', '', val[0].strip()) value = re.sub(r'[\t\n]', '', val[1]).strip() ret[i][key] = value if len(ret[len(ret)-1]) <= 0: ret.pop(len(ret)-1) return ret except: return None def get_process_id(command=None,regex=False): """ <comment-ja> 指定した文字列のプロセスIDを取得する @param command: コマンド文字列 @type command: str @param regex: 正規表現による指定かどうか @type regex: boolean @return: プロセスIDのリスト @rtype: list </comment-ja> <comment-en> English Comment </comment-en> >>> from ps_match import get_process_id >>> get_process_id("libvirtd",regex=True) ['26859'] >>> get_process_id("/usr/sbin/libvirtd --daemon --config /etc/libvirt/libvirtd.conf --listen --pid-file=/var/run/libvirtd.pid",regex=False) ['26859'] """ retval = [] proc_dir = "/proc" cmdline_file_glob = "%s/[0-9]*/cmdline" % (proc_dir,) for _file in glob.glob(cmdline_file_glob): try: data = open(_file).read() data = re.sub("\0"," ",data) pid = os.path.basename(os.path.dirname(_file)) if regex is False: if data.strip() == command: retval.append(pid) else: if re.search(command,data): retval.append(pid) except: pass return retval def json_dumps(obj, **kw): """ <comment-ja> PythonオブジェクトをJSONオブジェクトに変換する。 @param obj: Pythonオブジェクト @type obj: str or dict or list or tuple or None or bool @param kw: 追加引数 @type kw: str or dict or list or tuple or None or bool @return: JSONオブジェクト @rtype: str </comment-ja> <comment-en> English Comment </comment-en> """ import simplejson as json return json.dumps(obj, ensure_ascii=False, encoding="utf-8", **kw) def is_path(target): """ <comment-ja> 指定された値が、パス名かどうか @param target: 調べるパス名 @type target: str @return: OK=True | NG=False @rtype: bool </comment-ja> <comment-en> English Comment </comment-en> """ _path, _file = os.path.split(target) if _path != "": return True else: return False def get_keymaps(dir_path='/usr/share/xen/qemu/keymaps'): """<comment-ja> 指定されたKeymapフォルダのファイル名からKeymapのリストを取得する。 </comment-ja> <comment-en> English Comment </comment-en> """ ret = [] if os.path.isdir(dir_path) is True: for _file in os.listdir(dir_path): if len(_file)==2 or (len(_file)==5 and _file[2:3]=='-'): ret.append(_file) return sorted(ret) def findFile(dir, pattern): fullPattern = os.path.join(dir,pattern) return glob.glob(fullPattern) def findFileRecursive(topdir=None, pattern="*.*", nest=False, verbose=False): allFilenames = list() # current dir if verbose: print "*** %s" %topdir if topdir is None: topdir = os.getcwd() filenames = findFile(topdir, pattern) if verbose: for filename in [os.path.basename(d) for d in filenames]: print " %s" %filename allFilenames.extend(filenames) # possible sub dirs names = [os.path.join(topdir, dir) for dir in os.listdir(topdir)] dirs = [n for n in names if os.path.isdir(n)] if verbose: print "--> %s" % [os.path.basename(d) for d in dirs] if len(dirs) > 0: for dir in dirs: filenames = findFileRecursive(dir, pattern, nest, verbose) if nest: allFilenames.append(filenames) else: allFilenames.extend(filenames) # final result return allFilenames def available_kernel_modules(): ret = [] modules_dir = "/lib/modules/%s" % os.uname()[2] if os.path.isdir(modules_dir) is True: for k in findFileRecursive(modules_dir,"*.ko"): ret.append(os.path.basename(k)[0:-3]) for k in findFileRecursive(modules_dir,"*.o"): ret.append(os.path.basename(k)[0:-2]) ret = sorted(ret) ret = [p for p, q in zip(ret, ret[1:] + [None]) if p != q] return ret def loaded_kernel_modules(): proc_modules = "/proc/modules" if os.path.isfile(proc_modules) is False: return None ret = [] fp = open(proc_modules, "r") try: for line in fp.readlines(): if len(line.strip()) > 0: val = line.split(" ") ret.append(val[0]) fp.close() except: return None return ret def is_loaded_kernel_module(module=None): return module in loaded_kernel_modules() def loaded_kernel_module_dependencies(module=None): if not module in loaded_kernel_modules(): return None proc_modules = "/proc/modules" if os.path.isfile(proc_modules) is False: return None ret = [] fp = open(proc_modules, "r") try: for line in fp.readlines(): if len(line.strip()) > 0: val = line.split(" ") if val[0] == module and val[3] != "-": ret = val[3].split(",") ret.pop() fp.close() except: return None return ret def load_kernel_module(module=None): if is_loaded_kernel_module(module): return False if module in available_kernel_modules(): command_args = ["/sbin/modprobe",module] ret = execute_command(command_args) if is_loaded_kernel_module(module) is False: return False else: return False return True def unload_kernel_module(module=None,force=False): if is_loaded_kernel_module(module) is False: return False else: if force is True: for k in loaded_kernel_module_dependencies(module): unload_kernel_module(k,force) command_args = ["/sbin/rmmod",module] ret = execute_command(command_args) if is_loaded_kernel_module(module): return False return True def available_virt_mechs(): """<comment-ja> </comment-ja> <comment-en> get list of usable virtualization mechanisms </comment-en> """ ret = [] if os.access("/proc/xen", os.R_OK): ret.append("XEN") if is_loaded_kernel_module("kvm"): ret.append("KVM") return sorted(ret) def sh_config_read(filename): import re regex = re.compile("\s*=\s*") value_quote_regex = re.compile("\".*\"") ret = {} try: fp = open(filename,"r") fcntl.lockf(fp.fileno(), fcntl.LOCK_SH) for line in fp.readlines(): line = line.strip() if len(line) <= 0 or line[0] == "#": continue key, value = regex.split(line,1) #ret[key] = value value = re.sub(r"^\"(.*)\"$", r"\1", value) value = re.sub(r"^'(.*)'$", r"\1", value) ret[key] = value fcntl.lockf(fp.fileno(), fcntl.LOCK_UN) fp.close() except: ret = False return ret def sh_config_write(filename,opts): ret = True res = {} if type(opts) == dict: res = opts else: for k in dir(opts): res[k] = getattr(opts,k) try: fp = open(filename,"w") fcntl.lockf(fp.fileno(), fcntl.LOCK_EX) for k,v in res.iteritems(): if type(v) == str and k[0:2] != "__" and k[0:4] != "pass": fp.write("%s = %s\n" % (k, v,)) fcntl.lockf(fp.fileno(), fcntl.LOCK_UN) fp.close() except: ret = False return ret def available_virt_uris(): """<comment-ja> </comment-ja> <comment-en> get list of libvirt's uri </comment-en> """ from karesansui.lib.const import VIRT_LIBVIRTD_CONFIG_FILE, \ VIRT_LIBVIRT_SOCKET_RW, VIRT_LIBVIRT_SOCKET_RO, \ KVM_VIRT_URI_RW, KVM_VIRT_URI_RO, \ XEN_VIRT_URI_RW, XEN_VIRT_URI_RO uris = {} mechs = available_virt_mechs() if len(mechs) == 0: mechs = ['KVM'] for _mech in mechs: hostname = "127.0.0.1" if _mech == "XEN": uris[_mech] = XEN_VIRT_URI_RW if _mech == "KVM": if os.path.exists(VIRT_LIBVIRTD_CONFIG_FILE): opts = sh_config_read(VIRT_LIBVIRTD_CONFIG_FILE) uri_prefix = "qemu" uri_suffix = "" uri_args = "" try: if opts["listen_tcp"] == "1": uri_prefix = "qemu+tcp" try: opts["tcp_port"] port_number = opts["tcp_port"] except: port_number = "16509" except: pass try: if opts["listen_tls"] == "1": uri_prefix = "qemu+tls" try: opts["tls_port"] port_number = opts["tls_port"] except: port_number = "16514" uri_args += "?no_verify=1" hostname = os.uname()[1] except: pass try: port_number uri_suffix += ":%s/system%s" % (port_number, uri_args,) except: uri_suffix += "/system%s" % (uri_args,) #print "%s://%s%s" % (uri_prefix,hostname,uri_suffix,) uris[_mech] = "%s://%s%s" % (uri_prefix,hostname,uri_suffix,) else: uris[_mech] = KVM_VIRT_URI_RW return uris def file_type(file): command_args = [ "file", file, ] (rc,res) = execute_command(command_args) if rc != 0: return None else: return res[0].replace("%s: " % file, "") def is_vmdk_format(file): try: f = open(file, "rb") return f.read(4) == "KDMV" except: return False def is_iso9660_filesystem_format(file): retval = False magic = "CD001" extra_magic = "EL TORITO SPECIFICATION" # bootable offset = 32769 label_offset = 32808 extra_offset = 34823 if not os.path.exists(file) or os.stat(file).st_size < offset+len(magic): return retval try: regex = re.compile(r"""\S""") f = open(file,"rb") f.seek(offset) header = f.read(len(magic)) if header != magic: return retval label = "" step = 0 for cnt in xrange(label_offset, label_offset + 100): f.seek(cnt) char = f.read(1) #print cnt, #print "%x" % ord(char) if ord(char) == 0 or char == '\0': step = step + 1 if step == 2: break #elif regex.match(char): else: label += char label = label.strip() f.seek(extra_offset) data = f.read(len(extra_magic)) if data == extra_magic: label += "(bootable)" f.close() retval = label except: pass return retval def is_windows_bootable_iso(file): retval = False regexes = { "Windows XP Home" :"WXH(CCP|FPP|OEM|VOL|OCCP)_[A-Z]{2}", "Windows XP Professional" :"WXP(CCP|FPP|OEM|VOL|OCCP)_[A-Z]{2}", "Windows XP Home (SP1)" :"XRMH(CCP|FPP|OEM|VOL|OCCP)_[A-Z]{2}", "Windows XP Professional (SP1)" :"XRMP(CCP|FPP|OEM|VOL|OCCP)_[A-Z]{2}", "Windows XP Home (SP1a)" :"X1AH(CCP|FPP|OEM|VOL|OCCP)_[A-Z]{2}", "Windows XP Professional (SP1a)" :"X1AP(CCP|FPP|OEM|VOL|OCCP)_[A-Z]{2}", "Windows XP Home (SP2)" :"VRMH(CCP|FPP|OEM|VOL)_[A-Z]{2}", "Windows XP Professional (SP2)" :"VRMP(CCP|FPP|OEM|VOL)_[A-Z]{2}", "Windows XP Home (SP2b)" :"VX2H(CCP|FPP|OEM|VOL)_[A-Z]{2}", "Windows XP Professional (SP2b)" :"VX2P(CCP|FPP|OEM|VOL)_[A-Z]{2}", "Windows XP Home (SP3)" :"GRTMH(CCP|FPP|OEM|VOL)_[A-Z]{2}", "Windows XP Home K (SP3)" :"GRTMHK(CCP|FPP|OEM|VOL)_[A-Z]{2}", "Windows XP Home KN (SP3)" :"GRTMHKN(CCP|FPP|OEM|VOL)_[A-Z]{2}", "Windows XP Professional (SP3)" :"GRTMP(CCP|FPP|OEM|VOL)_[A-Z]{2}", "Windows XP Professional K (SP3)" :"GRTMPK(CCP|FPP|OEM|VOL)_[A-Z]{2}", "Windows XP Professional KN (SP3)" :"GRTMPKN(CCP|FPP|OEM|VOL)_[A-Z]{2}", "Windows XP from Dell" :"XP2_(PER|PRO)_ENG", "Windows 7 Professional" :"WIN_7_PROFESSIONAL", "Windows 7" :"WIN7", } label = is_iso9660_filesystem_format(file) if label is not False: for k,v in regexes.iteritems(): regex_str = "%s.*\(bootable\)" % v regex = re.compile(regex_str) if regex.search(label): retval = k break return retval def is_linux_bootable_iso(file): retval = False regexes = { "Asianux" :"Asianux", "MIRACLE LINUX \\1.\\2" :"MLSE([0-9])([0-9])", "Turbolinux" :"Turbolinux", "Fedora Core \\1" :"^FC/([0-9\.]*)", "Fedora \\1 \\2" :"^Fedora ([0-9\.]+) (i386|x86_64)", "CentOS \\2" :"CentOS( \-_)([0-9].[0-9])", "Red Hat Enterprise Linux \\2 \\3":"RHEL(/|\-)([0-9\.\-U]) (i386|x86_64)", "Red Hat Linux/\\1" :"Red Hat Linux/(.+)", "openSUSE-\\1.\\2" :"^SU(1[0-3])([0-9])0.00", "Debian \\1" :"^Debian (.+)", "Buildix" :"^Buildix", "Ubuntu \\1" :"^Ubuntu ([0-9].+)", "Ubuntu Server \\1" :"^Ubuntu-Server (.+)", } label = is_iso9660_filesystem_format(file) if label is not False: for k,v in regexes.iteritems(): regex_str = "%s.*\(bootable\)" % v regex = re.compile(regex_str) if regex.search(label): retval = re.sub(r"""%s\(bootable\)""" % v,k,label).strip() break return retval def is_darwin_bootable_iso(file): retval = False regexes = { "DARWIN \\1" :"^DARWIN(.+)", } label = is_iso9660_filesystem_format(file) if label is not False: for k,v in regexes.iteritems(): regex_str = "%s.*\(bootable\)" % v regex = re.compile(regex_str) if regex.search(label): retval = re.sub(r"""%s\(bootable\)""" % v,k,label).strip() break return retval def sizeunit_to_byte(string): import re import math unit_map = { "b" : 1024**0, "k" : 1024**1, "m" : 1024**2, "g" : 1024**3 } p = re.compile(r"""^(?P<bytes>[\d\.]+)(?P<unit>[gmkb]?)$""", re.IGNORECASE) m = p.match(string) if not m: return None size = float(m.group("bytes")) * unit_map.get(m.group("unit").lower(), 1) #return math.round(size) return int(math.floor(size)) def sizeunit_format(size,unit="b",digit=1): import re import math unit_map = { "b" : 1024**0, "k" : 1024**1, "m" : 1024**2, "g" : 1024**3 } string = float (size) / unit_map.get(unit, 1) return "%s%c" % (round(string,digit), unit.upper(),) def get_disk_img_info(file): import re if not os.path.exists(file): return None command_args = [ "qemu-img", "info", file, ] (rc,res) = execute_command(command_args) if rc != 0: ret = {} ftype = file_type(file) if ftype != None: if re.match(r'^QEMU Copy-On-Write disk image version 1', ftype): ret["file_format"] = "qcow" elif re.match(r'^QEMU Copy-On-Write disk image version 2', ftype): ret["file_format"] = "qcow2" elif re.match(r'^User-mode Linux COW file, version 2', ftype): ret["file_format"] = "cow" elif re.match(r'^data', ftype): if is_vmdk_format(file): ret["file_format"] = "vmdk" else: ret["file_format"] = "raw" else: ret["file_format"] = "unknown" ret["real_size"] = os.path.getsize(file) return ret else: regex = re.compile(":\s*") regex_bracket = re.compile(r"""^(?P<unitformat>.+) \((?P<bytes>[0-9\.]+) bytes\)""") ret = {} for line in res: try: key, value = regex.split(line,1) if key == "file format": ret["file_format"] = value elif key == "virtual size": m = regex_bracket.match(value) ret["virtual_size"] = int(m.group("bytes")) elif key == "disk size": ret["disk_size"] = sizeunit_to_byte(value) elif key == "cluster_size": ret["cluster_size"] = int(value) except: pass ret["real_size"] = os.path.getsize(file) return ret def array_replace(array, pattern=None, replace=None, mode="og"): if type(array) != list: return array regex_mode = 0 once_match_only = False search_cnt = 1 cnt = 0 while cnt < len(mode): if mode[cnt] == 'o': once_match_only = True if mode[cnt] == 'g': search_cnt = 0 if mode[cnt] == 'i': regex_mode = re.IGNORECASE cnt += 1 if type(pattern) is str and type(replace) is str: pattern = [pattern] replace = [replace] if type(pattern) is list and type(replace) is list and len(pattern) == len(replace): new_array = [] for k in array: cnt = 0 #print k, #print " => ", while cnt < len(pattern): p = re.compile("%s" % pattern[cnt],regex_mode) if p.search(k): k = p.sub(replace[cnt], k, search_cnt) if once_match_only is True: break cnt += 1 #print k new_array.append(k) return new_array else: return array def file_contents_replace(filename, new_filename, pattern=None, replace=None, mode="og"): lines = [] try: fp = open(filename,"r") fcntl.lockf(fp.fileno(), fcntl.LOCK_SH) for line in fp.readlines(): lines.append(line) fcntl.lockf(fp.fileno(), fcntl.LOCK_UN) fp.close() except: return False if len(lines) > 0: lines = array_replace(lines,pattern,replace,mode) try: fp = open(new_filename,"w") fcntl.lockf(fp.fileno(), fcntl.LOCK_EX) for line in lines: fp.write(line) fcntl.lockf(fp.fileno(), fcntl.LOCK_UN) fp.close() except: return False return True def get_inspect_stack(prettyprint=False): import inspect stack_content = [ 'frame obj ', 'file name ', 'line num ', 'function ', 'context ', 'index ', ] context, frame = 1, 2 retval = dict(zip(stack_content, inspect.stack(context)[frame])) if prettyprint is True: preprint_r(retval) return retval def get_dom_list(): from karesansui.lib.const import VIRT_XML_CONFIG_DIR retval = [] for _name in os.listdir(VIRT_XML_CONFIG_DIR): if _name[-4:] == ".xml": _path = os.path.join(VIRT_XML_CONFIG_DIR, _name) doc = get_xml_parse(_path) domain_name = get_xml_xpath(doc,'/domain/name/text()') retval.append(domain_name) return retval def get_dom_type(domain): from karesansui.lib.const import VIRT_XML_CONFIG_DIR retval = None _path = os.path.join(VIRT_XML_CONFIG_DIR, domain+".xml") if os.path.exists(_path): doc = get_xml_parse(_path) retval = get_xml_xpath(doc,'/domain/@type') return retval def base64_encode(string=""): import base64 if type(string) == unicode: string = string.encode("utf-8") elif type(string) == str: pass else: raise return base64.b64encode(string) def base64_decode(string=""): import base64 if type(string) == str: pass else: raise return base64.b64decode(string) def get_system_user_list(): """<comment-ja> 登録されているシステムユーザリストを/etc/passwd形式で取得します。 </comment-ja> <comment-en> TODO: English Comment </comment-en> """ info = [] _getent = '/usr/bin/getent' command_args = [_getent,'passwd'] old_lang = os.environ['LANG'] os.environ['LANG'] = 'C' (ret,res) = execute_command(command_args) os.environ['LANG'] = old_lang if ret != 0: return info for user in res: info.append(user.split(':')) return info def get_system_group_list(): """<comment-ja> 登録されているシステムグループリストを/etc/group形式で取得します。 </comment-ja> <comment-en> TODO: English Comment </comment-en> """ info = [] _getent = '/usr/bin/getent' command_args = [_getent,'group'] old_lang = os.environ['LANG'] os.environ['LANG'] = 'C' (ret,res) = execute_command(command_args) os.environ['LANG'] = old_lang if ret != 0: return {} for group in res: info.append(group.split(':')) return info def str_repeat(string="",count=1): """<comment-ja> 文字列を繰り返す </comment-ja> <comment-en> TODO: English Comment </comment-en> """ retval = "" for _cnt in range(0,count): retval = "%s%s" % (retval,string,) return retval def _php_array_to_python_dict(string=""): """<comment-ja> PHPのvar_export形式の文字列をpythonの辞書文字列に変換する </comment-ja> <comment-en> TODO: English Comment </comment-en> """ lines = string.split("\n") array_depth = 0 regex_array_s = " *array *\(" regex_array_e = " *\)(?P<comma>,?)" regex_list = " *[0-9]+ *=> *(?P<value>.+)" regex_dict = " *(?P<key>'.+') *=> *" array_types = [] _b_array = False new_lines = [] for _aline in lines: indent = "" if array_depth > 0: indent = str_repeat(" ",array_depth-1) m_array_s = re.match(regex_array_s,_aline.rstrip()) m_array_e = re.match(regex_array_e,_aline.rstrip()) m_list = re.match(regex_list ,_aline) m_dict = re.match(regex_dict ,_aline) if m_array_s is not None: array_depth = array_depth + 1 _b_array = True continue elif m_array_e is not None: array_depth = array_depth - 1 array_type = array_types.pop() if array_type == "list": new_aline = "%s]%s" % (indent,m_array_e.group('comma'),) if array_type == "dict": new_aline = "%s}%s" % (indent,m_array_e.group('comma'),) _b_array = False elif m_list is not None: if _b_array is True: array_types.append("list") new_aline = "%s[" % indent new_lines.append(new_aline) value = m_list.group('value') new_aline = "%s%s" % (indent,re.sub("'","\'",value),) _b_array = False elif m_dict is not None: if _b_array is True: array_types.append("dict") new_aline = "%s{" % indent new_lines.append(new_aline) key = m_dict.group('key') value = re.sub(regex_dict,"%s:" % key, _aline) new_aline = "%s%s" % (indent,value,) _b_array = False else: new_aline = "%s%s" % (indent,_aline,) _b_array = False new_aline = re.sub("':false,","':False,", new_aline) new_aline = re.sub("':true," ,"':True," , new_aline) new_lines.append(new_aline) #print "\n".join(new_lines) return "\n".join(new_lines) def python_dict_to_php_array(dictionary={},var_name=""): """<comment-ja> pythonの辞書配列をPHPの連想配列(できればvar_export形式)の文字列に変換する </comment-ja> <comment-en> TODO: English Comment </comment-en> """ import signal dict_str = preprint_r(dictionary,return_var=True) dict_str = dict_str.replace('{','array(') dict_str = dict_str.replace('\':','\' =>') dict_str = dict_str.replace('}',')') dict_str = dict_str.replace('=> [','=> array(') dict_str = dict_str.replace('])','))') dict_str = re.sub("\)$",')',dict_str) php_start = "<?php\n" php_end = "?>\n" # Convert var_export format _php = "/usr/bin/php" if is_executable(_php): _script = "\"<?php var_export(%s); ?>\"" % (re.sub("[\r\n]"," ",dict_str),) signal.alarm(10) proc = subprocess.Popen(_php, bufsize=1, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) proc.stdin.write(_script) output = proc.communicate() ret = proc.wait() signal.alarm(0) if ret == 0: dict_str = "".join(output) dict_str = re.sub("^\"","",dict_str) dict_str = re.sub("\"$","",dict_str) header = php_start; if var_name != "": header = "%s$%s = " % (header,var_name,) footer = php_end return "%s%s;\n%s" % (header,dict_str,footer,) def php_array_to_python_dict(string=""): """<comment-ja> PHPの連想配列(var_export形式)の文字列をpythonの辞書配列に変換する </comment-ja> <comment-en> TODO: English Comment </comment-en> """ retval = False string = re.sub("^<[\?%](php)?" ,'' ,string.lstrip()) string = re.sub("[\?%]>$" ,'' ,string.rstrip()) string = re.sub("^\\$[a-zA-Z0-9_]+ *= *",'' ,string.lstrip()) dict_str = string dict_str = dict_str.replace('array(' ,'{') dict_str = dict_str.replace('\' =>' ,'\':') dict_str = dict_str.replace(')' ,'}') dict_str = dict_str.replace('=> array(' ,'=> [') dict_str = dict_str.replace('))' ,'])') dict_str = re.sub("{'(.*':.*)'}" ,"['\\1']" ,dict_str) dict_str = re.sub("\);" ,')',dict_str) try: exec("retval = %s" % dict_str) except: try: # Read by var_export format exec("retval = %s" % _php_array_to_python_dict(string)) except: raise return retval def get_karesansui_version(): import karesansui return karesansui.__version__ + '.' + karesansui.__release__ def get_blocks(d='/dev'): """<comment-ja> 指定したフォルダに存在するブロックデバイス名一覧を取得します。 </comment-ja> <comment-en> TODO: English Comment </comment-en> """ ret = [] for f in os.listdir(d): if stat.S_ISBLK(os.stat("%s/%s" % (d, f))[stat.ST_MODE]) is True: ret.append(f) return set(ret) def get_hdd_list(_prefix='/dev'): """<comment-ja> OSで認識しているハードディスク名一覧を取得します。 </comment-ja> <comment-en> TODO: English Comment </comment-en> """ from karesansui.lib.const import HDD_TYPES_REGEX blocks = get_blocks(_prefix) ret = [] for _type in HDD_TYPES_REGEX: _regex = re.compile(_type) for _b in blocks: if _regex.match(_b): ret.append(_b) return ret def get_fs_info(): """<comment-ja> OSで認識しているファイルシステムの情報(dfコマンドの結果)を取得します。 </comment-ja> <comment-en> TODO: English Comment </comment-en> """ ret = [] tmp_dict = {} pipe = os.popen("LANG=C /bin/df -m -P") try: data = [] for line in pipe.readlines(): data.append(re.sub(r'[ \t]', ' ', line).split()) finally: pipe.close() for i in range(1, len(data)): for j in range(0,6): tmp_dict[data[0][j]] = data[i][j] ret.append(tmp_dict) tmp_dict = {} return ret def read_file(filepath): """<comment-ja> 指定されたファイルの中身を取得します。 </comment-ja> <comment-en> TODO: English Comment </comment-en> """ ret = "" try: fp = open(filepath, "r") fcntl.lockf(fp.fileno(), fcntl.LOCK_SH) for line in fp.readlines(): ret = ret + line fcntl.lockf(fp.fileno(), fcntl.LOCK_UN) fp.close() except: ret = False return ret def create_epochsec(year, month, day, hour=0, minute=0, second=0): return str(int(time.mktime(datetime.datetime(year, month, day, hour, minute, second).timetuple()))) def get_hostname(): import socket # return socket.gethostname() return socket.getfqdn() def host2ip(host): import socket return socket.gethostbyname(host) def uri_split(uri): """ Basic URI Parser """ import re regex = '^(([^:/?#]+):)?(//(([^:]+)(:(.+))?@)?([^/?#:]*)(:([0-9]+))?)?([^?#]*)(\?([^#]*))?(#(.*))?' p = re.match(regex, uri).groups() scheme, user, passwd, host, port, path, query, fragment = p[1], p[4], p[6], p[7], p[9], p[10], p[12], p[14] if not path: path = None return { "scheme" :scheme, "user" :user, "passwd" :passwd, "host" :host, "port" :port, "path" :path, "query" :query, "fragment":fragment, } def uri_join(segments,without_auth=False): """ Reverse of uri_split() """ result = '' try: result += segments["scheme"] + '://' except: pass if without_auth is False: try: result += segments["user"] try: result += ':' + segments["passwd"] except: pass result += '@' except: pass try: result += segments["host"] except: pass try: result += ':' + segments["port"] except: pass try: if segments["path"] is None or segments["path"] == "": segments["path"] = "/" if result != "": result += segments["path"] except: pass try: result += '?' + segments["query"] except: pass try: result += '#' + segments["fragment"] except: pass return result def locale_dummy(str): return str def symlink2real(symlink): """<comment-ja> シンボリック先の実体ファイルのファイル名を取得します。 </comment-ja> <comment-en> TODO: English Comment </comment-en> """ path = os.path.realpath(symlink) filename = os.path.basename(path) sfilename = filename.split(".") if len(sfilename) < 2: return (os.path.dirname(path), sfilename[0], "") else: name = "" for x in xrange(len(sfilename)-1): name = os.path.join(name, sfilename[x]) return (os.path.dirname(path), name, sfilename[len(sfilename)-1]) def get_filelist(dir_path="/"): """<comment-ja> 指定したディレクトリに存在するファイル名の一覧を取得します。 </comment-ja> <comment-en> TODO: English Comment </comment-en> """ if os.path.isdir(dir_path): filelist = os.listdir(dir_path) else: filelist = [] return filelist def get_bonding_info(name=None): """ <comment-ja> bondingデバイス情報を取得する @param name: 取得したいデバイス名(省略時は全デバイス情報が指定されたとみなす) 「regex:bond0」のようにプレフィックスにregex:を付けると正規表現にマッチしたデバイス名の情報を全て取得できる。 @return: デバイス情報が格納されたdict配列 配列の内容例 {'bond0': { 'mode' : 'fault-tolerance (active-backup)', 'primary' : 'eth0', 'active' : 'eth0', 'slave' : ['eth0', 'eth1'], } </comment-ja> <comment-en> Get computer's bonding interface information @param name: bonding device name @return: a dict with: mode, slave etc... @rtype: dict </comment-en> """ info = {} _info = {} _proc_bonding_dir = '/proc/net/bonding' mode_regex = re.compile(r"""^Bonding Mode:\s*(?P<mode>.+)""") primary_regex = re.compile(r"""^Primary Slave:\s*(?P<primary>eth[0-9]+)""") active_regex = re.compile(r"""^Currently Active Slave:\s*(?P<active>eth[0-9]+)""") slave_regex = re.compile(r"""^Slave Interface:\s*(?P<slave>eth[0-9]+)""") for device in get_filelist(_proc_bonding_dir): _info[device] = {} _info[device]['slave'] = [] for aline in read_file("%s/%s" % (_proc_bonding_dir, device)).split("\n"): if aline.strip() == "": continue m = mode_regex.match(aline) if m: _info[device]['mode'] = m.group('mode') m = primary_regex.match(aline) if m: _info[device]['primary'] = m.group('primary') m = active_regex.match(aline) if m: _info[device]['active'] = m.group('active') m = slave_regex.match(aline) if m: _info[device]['slave'].append(m.group('slave')) all_info = dict_ksort(_info) if name == None: return all_info regex_regex = re.compile(r"""^regex:(?P<regex>.*)""") m = regex_regex.match(name) for dev,value in all_info.iteritems(): if m == None: if dev == name: info[dev] = value return info else: regex = m.group('regex') query_regex = re.compile(r""+regex+"") n = query_regex.search(dev) if n != None: info[dev] = value return info def get_bridge_info(name=None): """ <comment-ja> Bridgeデバイス情報を取得する @param name: 取得したいデバイス名(省略時は全デバイス情報が指定されたとみなす) @return: デバイス情報が格納されたdict配列 配列の内容例 {'eth0': ['peth0'] } </comment-ja> <comment-en> Get computer's bridge interface information @param name: bridge device name @return: a dict with: bridge name @rtype: dict </comment-en> """ info = {} _sys_bridge_dir_tpl = '/sys/class/net/%s/bridge' _sys_brif_dir_tpl = '/sys/class/net/%s/brif' if_list = get_ifconfig_info() for dev in if_list: if os.path.exists(_sys_bridge_dir_tpl % (dev)): if os.path.exists(_sys_brif_dir_tpl % (dev)): info[dev] = get_filelist(_sys_brif_dir_tpl % (dev)) if name is not None: if name in info: return info[name] return info def get_pwd_info(): """ <comment-ja> 全てのユーザ情報を取得する </comment-ja> <comment-en> TODO: English Comment </comment-en> """ return pwd.getpwall() def get_grp_info(): """ <comment-ja> 全てのグループ情報を取得する </comment-ja> <comment-en> TODO: English Comment </comment-en> """ return grp.getgrall() def get_filesystem_info(): """ <comment-ja> 使用できるファイルシステムを取得する </comment-ja> <comment-en> TODO: English Comment </comment-en> """ ret = [] _filesystem_path = "/etc/filesystems" nodev_regex = re.compile("^nodev") data = read_file(_filesystem_path) if data: for line in data.split("\n"): line = line.strip() if line == "": continue if nodev_regex.match(line): continue ret.append(line) return ret def karesansui_database_exists(): from karesansui.db import get_session from karesansui.db.model.user import User session = get_session() try: email = session.query(User).first().email except: return False return True class ReverseFile(object): def __init__(self, fp): self.fp = fp if isinstance(self.fp ,gzip.GzipFile): self.fp.readlines() self.end = self.fp.size self.fp.seek(self.end) else: self.fp.seek(0, 2) self.end = self.fp.tell() def __enter__(self): return self def __exit__(self, exception_type, exception_value, exception_traceback): self.fp.close() def __iter__(self): return self def next(self): if self.end == 0: raise StopIteration start = self.end - 2 while start >= 0: self.fp.seek(start) if self.fp.read(1) == '\n': end = self.end self.end = start return self.fp.read(end - start) start -= 1 end = self.end + 1 self.end = 0 self.fp.seek(0) return self.fp.read(end) def readline(self): return self.next() def fileno(self): return self.fp.fileno() def close(self): return self.fp.close() reverse_file = ReverseFile if __name__ == '__main__': pass
karesansui/karesansui
karesansui/lib/utils.py
Python
mit
89,043
**Design pattern:** **Chain of responsibility** **Type of pattern:** Behavioral > Describes pattern of communication and responsibility between objects/classes **Intent:** > Avoid coupling the class making request to class servicing request. Allows dynamic chains of responsibility for servicing request that may change at run time. **Motivation: Real examples** > **Context sensitive help** user presses F1 for help within screen. What help is displayed may depend on a number of things. For example: 1. Check if there is help related to the specific button that the mouse is over, if not?... 2. Check if there is help related to that area of the screen, if not?... 3. Check if there is help related to that screen, if not?... 4. Check if there is help related to the previous screen, if not?... 5. Return help for the application in general Key aspect here is that when help is requested which component should respond to the request for help information isn't known ahead of time. For example, what the "previous screen" is may be completely independent of the screen they are currently on but relevant to the general task they were performing. Trying to code for every possible combination is not good or potentially even possible. **Java Exception architecture** Handling of exceptions propagates up call stack allowing each calling component an opportunity to handle the exception. Given that there can be a huge number of potential paths to how a common method may be called having the responsibility passed up the chain of the call stack is far more flexible than it being hard coded. **Structure** ![](./media/image1.gif) **Consequences:** - Reduced coupling - Added flexibility - Receipt isn't guaranteed
ccsu-cs407F15/CourseInfo
Lecture slides/CS407-Lecture006-ChainOfResponsibility.md
Markdown
mit
1,811
@(title: String)(content: Html)(isCookiePage: Boolean)(implicit footerCategories: Html = Html(""), lang: Lang, request:play.api.mvc.Request[AnyContent],flash:Flash, messages: play.api.i18n.Messages) @import app.ConfigProperties._ @import utils.helpers.OriginTagHelper._ @landingPage = @{ if (request.path.contains("circumstances")) messages("circsLandingURL") else messages("claimLandingURL") } <!DOCTYPE html> <!--[if IE 6]> <html class="ie ie6" lang="en"> <![endif]--> <!--[if IE 7]> <html class="ie ie7" lang="en"> <![endif]--> <!--[if IE 8]> <html class="ie ie8" lang="en"> <![endif]--> <!--[if IE 9]> <html class="ie ie9" lang="en"> <![endif]--> <!--[if gt IE 9]><!--> <html class="no-js" lang="en"> <!--<![endif]--> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <title>@title</title> <!-- Styles for old Internet Explorer Browsers --> <!--[if IE 6]><link @nonCachingHref("stylesheets/header-footer-only-ie6.css") media="screen" rel="stylesheet" type="text/css"><![endif]--> <!--[if IE 7]><link @nonCachingHref("stylesheets/header-footer-only-ie7.css") media="screen" rel="stylesheet" type="text/css"><![endif]--> <!--[if IE 8]><link @nonCachingHref("stylesheets/header-footer-only-ie8.css") media="screen" rel="stylesheet" type="text/css"><![endif]--> <!-- Carer's Allowance stylesheet --> <link rel="stylesheet" media="screen" @nonCachingHref("styles/app_t.min.css")/> <!-- Print stylesheet --> <link @nonCachingHref("stylesheets/print.css") media="print" rel="stylesheet" type="text/css"> <!-- To prevent call to /browserconfig.xml from IE11 and higher. We do not use notifications. --> <meta name="msapplication-config" content="none" /> <!--[if IE 8]> <script type="text/javascript"> (function(){if(window.opera){return;} setTimeout(function(){var a=document,g,b={families:(g= ["nta"]),urls:["<link @nonCachingHref("stylesheets/fonts-ie8.css")]}, c="@routes.Assets.at("javascripts/webfont-debug.js")",d="script", e=a.createElement(d),formData=a.getElementsByTagName(d)[0],h=g.length;WebFontConfig ={custom:b},e.src=c,formData.parentNode.insertBefore(e,formData);for(;h=h-1;a.documentElement .className+=' wf-'+g[h].replace(/\s/g,'').toLowerCase()+'-n4-loading');},0) })() </script> <![endif]--> <!--[if gte IE 9]><!--> <link @nonCachingHref("stylesheets/fonts.css") media="all" rel="stylesheet" type="text/css"> <!--<![endif]--> <!--[if lt IE 9]> <script @nonCachingSrc("javascripts/ie.js") type="text/javascript"></script> <![endif]--> <link rel="shortcut icon" href="@routes.Assets.at("images/favicon-447e4ac1ab790342660eacfe3dcce264.ico")" type="image/x-icon"> <link rel="icon" href="@routes.Assets.at("images/favicon-447e4ac1ab790342660eacfe3dcce264.ico")" type="image/x-icon"> <!-- For third-generation iPad with high-resolution Retina display: --> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="@routes.Assets.at("images/apple-touch-icon-144x144-4e306e01c31e237722b82b7aa7130082.png")"> <!-- For iPhone with high-resolution Retina display: --> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="@routes.Assets.at("images/apple-touch-icon-114x114-f1d7ccdc7b86d923386b373a9ba5e3db.png")"> <!-- For first- and second-generation iPad: --> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="@routes.Assets.at("images/apple-touch-icon-72x72-2ddbe540853e3ba0d30fbad2a95eab3c.png")"> <!-- For non-Retina iPhone, iPod Touch, and Android 2.1+ devices: --> <link rel="apple-touch-icon-precomposed" href="@routes.Assets.at("images/apple-touch-icon-57x57-37527434942ed8407b091aae5feff3f3.png")"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="text/javascript"> var landingURL = "@landingPage" </script> <script @nonCachingSrc("javascripts/jquery/jquery-1.9.1.js") type="text/javascript"></script> <script @nonCachingSrc("javascripts/date.js") type="text/javascript"></script> @if(getBooleanProperty("back-forward-button")) { <script @nonCachingSrc("javascripts/bb.js") type="text/javascript"></script> } <script @nonCachingSrc("javascripts/stageprompt-2.0.1.js") type="text/javascript"></script> <script @nonCachingSrc("javascripts/custom.js")></script> <!--[if (lt IE 9) & (!IEMobile)]> <script @nonCachingSrc("javascripts/respond.min.js")></script> <![endif]--> @if(play.Configuration.root().getBoolean("analytics.enabled", true)) { @views.html.ga.setup() } </head> <body> <script type="text/javascript"> document.body.className = ((document.body.className) ? document.body.className + ' js-enabled' : 'js-enabled'); </script> <a href="#main" class="visuallyhidden">@Html(messages("skipToMainContent"))</a> <header role="banner" class="global-header" id="global-header"> <div class="wrapper clearfix"> <a href="https://www.gov.uk" title="@Html(messages("logo.help"))" target="govlink" class="crown">GOV.UK</a> <h1 class="heading-medium">@Html(messages("siteHeader"))</h1> </div> </header> <!--end header--> @if(!isCookiePage) { <div id="global-cookie-message"> <p>@messages("cookiePolicy") <a rel="external" target="_blank" href="@routes.Cookies.page(lang.language)" @views.html.ga.trackClickEvent(linkName = "Cookies - from banner")>@messages("cookiePolicyAnchor")</a></p> </div> } <div id="global-browser-prompt"> <p>@Html(messages("latestBrowserUpdate"))</p> </div> <main class="container" role="main" id="main"> @content </main> <footer class="global-footer" id="global-footer"> <div class="container clearfix"> <div> <nav class="footer-nav language"> @if(isOriginGB) { @if(getBooleanProperty("galluogi.cymraeg")) { @if((request.uri.startsWith("/allowance/benefits")) || (request.uri.startsWith("/circumstances/report-changes/change-selection"))) { @if(lang.language == "cy") { <a id="lang-en" href="/change-language/en" aria-label="@Html(messages("english.helper"))" @views.html.ga.trackClickEvent(linkName = "Language Selection English")>@Html(messages("english"))</a> } else { <a id="lang-cy" href="/change-language/cy" aria-label="@Html(messages("welsh.helper"))" @views.html.ga.trackClickEvent(linkName = "Language Selection Welsh")>@Html(messages("welsh"))</a> } } } } <a id="cookies" rel="external" target="_blank" href="@routes.Cookies.page(lang.language)" @views.html.ga.trackClickEvent(linkName = "Cookies - from footer")>@messages("cookies")</a> <a id="privacy" rel="external" target="privacyLink" href="https://www.gov.uk/government/organisations/department-for-work-pensions/about/personal-information-charter" @views.html.ga.trackClickEvent(linkName = "Privacy")>@messages("privacyLink")</a> @common.feedbackLink() </nav> <p>@Html(messages("leftcol.helpline"))</p> @if(isOriginGB) { <p>@Html(messages("leftcol.callcharges"))</p> } <p>@Html(messages("madePreston"))</p> <p class="ogl">@Html(messages("openGovLicensea")) <a rel="external" href="http://www.nationalarchives.gov.uk/doc/open-government-licence/version/3" target="openGovLink" @views.html.ga.trackClickEvent(linkName = "Open Government Licence")>@Html(messages("openGovLicenseb"))</a>@Html(messages("openGovLicensec"))</p> </div> <div class="fr"> <a class="crown" href="http://www.nationalarchives.gov.uk/information-management/our-services/crown-copyright.htm" target="crownLink" @views.html.ga.trackClickEvent(linkName = "Crown Copyright")>&copy; @Html(messages("crownCopyright"))</a> </div> </div> </footer> <!--/ footer --> <div id="global-app-error" class="app-error hidden"></div> @if(flash.get("hash").isDefined){ <script type="text/javascript"> $(function(){ window.location = '#'+'@{flash.get("hash").get}'; }); </script> } </body> </html>
Department-for-Work-and-Pensions/ClaimCapture
c3/app/views/common/govMainDefault.scala.html
HTML
mit
9,201
namespace DevO2.UI { partial class ValidatorControls { /// <summary> /// Variable del diseñador requerida. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Limpiar los recursos que se estén utilizando. /// </summary> /// <param name="disposing">true si los recursos administrados se deben eliminar; false en caso contrario, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Código generado por el Diseñador de componentes /// <summary> /// Método necesario para admitir el Diseñador. No se puede modificar /// el contenido del método con el editor de código. /// </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); } #endregion } }
emarva/workbase-dotnet
UI/ValidatorControls.Designer.cs
C#
mit
1,103
/* @flow */ import React, { Component } from 'react'; import {observer} from 'mobx-react'; import {Link} from 'react-router'; @observer export default class PackageList extends Component { render() { return ( <div className="list-group"> <Link to="/flow-runtime" className="list-group-item list-group-item-action"> <h5 className="list-group-item-heading"> flow-runtime </h5> <p className="list-group-item-text">The core runtime library, responsible for representing types, validation, error messages etc.</p> </Link> <Link to="/babel-plugin-flow-runtime" className="list-group-item list-group-item-action"> <h5 className="list-group-item-heading"> babel-plugin-flow-runtime </h5> <p className="list-group-item-text"> A babel plugin which transforms static type annotations into <samp>flow-runtime</samp> type declarations. </p> </Link> <Link to="/flow-runtime-cli" className="list-group-item list-group-item-action"> <h5 className="list-group-item-heading"> flow-runtime-cli </h5> <p className="list-group-item-text">A command line utility to make it easier to work with Flow and flow-runtime.</p> </Link> <Link to="/flow-runtime-validators" className="list-group-item list-group-item-action"> <h5 className="list-group-item-heading"> flow-runtime-validators </h5> <p className="list-group-item-text"> A collection of common validators (length, date, email, url etc) for use with flow-runtime. </p> </Link> <Link to="/flow-runtime-mobx" className="list-group-item list-group-item-action"> <h5 className="list-group-item-heading"> flow-runtime-mobx </h5> <p className="list-group-item-text"> Adds mobx support to flow-runtime. </p> </Link> <Link to="/flow-config-parser" className="list-group-item list-group-item-action"> <h5 className="list-group-item-heading"> flow-config-parser </h5> <p className="list-group-item-text"> Parses <samp>.flowconfig</samp> files and makes them available to JavaScript. </p> </Link> </div> ); } }
codemix/flow-runtime
packages/flow-runtime-docs/src/components/PackageList.js
JavaScript
mit
2,393
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* // Hellgate Framework // Copyright © Uniqtem Co., Ltd. //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* using UnityEditor; using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Data; using Mono.Data.Sqlite; using Hellgate; namespace HellgateEditor { public class SqliteEditor : EditorWindow { private const string HELLGATE_DB_NAME = "HellgateDBName"; public static string dbName = ""; public void OnEnable () { dbName = PlayerPrefs.GetString (HELLGATE_DB_NAME); } public void OnGUI () { GUILayout.Label ("Create Sqlite DB", EditorStyles.boldLabel); dbName = EditorGUILayout.TextField ("Sqlite DB name :", dbName); if (GUILayout.Button ("Create", GUILayout.Height (40))) { if (dbName != "") { Create (); } } } [MenuItem ("Window/Hellgate/Create Sqlite DB", false, 13)] public static void ShowWindow () { EditorWindow.GetWindow (typeof(SqliteEditor)); } public static void Create () { Sqlite sqlite = new Sqlite (); sqlite.AutoDDL (dbName, true); Debug.Log ("StreamingAssets Create Sqlite DB : " + dbName); } } }
namseungngil/HellgateFramework
Unity/Assets/Hellgate/Scripts/Editor/Sqlite/SqliteEditor.cs
C#
mit
1,447
package main import ( "net/http" "strconv" log "github.com/Sirupsen/logrus" "github.com/bstaijen/mariadb-for-microservices/profile-service/app/http/routes" "github.com/bstaijen/mariadb-for-microservices/profile-service/config" "github.com/bstaijen/mariadb-for-microservices/profile-service/database" negronilogrus "github.com/meatballhat/negroni-logrus" "github.com/urfave/negroni" // go-sql-driver/mysql is needed for the database connection _ "github.com/go-sql-driver/mysql" _ "github.com/joho/godotenv/autoload" ) func main() { log.SetLevel(log.DebugLevel) // Get config cnf := config.LoadConfig() // Get database connection, err := db.OpenConnection(cnf) if err != nil { log.Fatal(err) } defer db.CloseConnection(connection) // Set the REST API routes routes := routes.InitRoutes(connection, cnf) n := negroni.Classic() n.Use(negronilogrus.NewMiddleware()) n.UseHandler(routes) // Start and listen on port in cbf.Port log.Info("Starting server on port " + strconv.Itoa(cnf.Port)) log.Fatal(http.ListenAndServe(":"+strconv.Itoa(cnf.Port), n)) }
bstaijen/mariadb-for-microservices
profile-service/main.go
GO
mit
1,090