repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
PiranhaCMS/piranha.core | core/Piranha/Models/RoutedContentBase.cs | 4470 | /*
* Copyright (c) .NET Foundation and Contributors
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
* https://github.com/piranhacms/piranha.core
*
*/
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Piranha.Extend.Fields;
namespace Piranha.Models
{
/// <summary>
/// Abstract base class for templated content with a route.
/// </summary>
[Serializable]
public abstract class RoutedContentBase : ContentBase, IBlockContent, IMeta, ICommentModel
{
/// <summary>
/// Gets/sets the unique slug.
/// </summary>
[StringLength(128)]
public string Slug { get; set; }
/// <summary>
/// Gets/sets the public permalink.
/// </summary>
public string Permalink { get; set; }
/// <summary>
/// Gets/sets the optional meta title.
/// </summary>
[StringLength(128)]
public string MetaTitle { get; set; }
/// <summary>
/// Gets/sets the optional meta keywords.
/// </summary>
[StringLength(128)]
public string MetaKeywords { get; set; }
/// <summary>
/// Gets/sets the optional meta description.
/// </summary>
[StringLength(256)]
public string MetaDescription { get; set; }
/// <summary>
/// Gets/sets the meta index.
/// </summary>
public bool MetaIndex { get; set; } = true;
/// <summary>
/// Gets/sets the meta follow.
/// </summary>
public bool MetaFollow { get; set; } = true;
/// <summary>
/// Gets/sets the meta priority.
/// </summary>
public double MetaPriority { get; set; } = 0.5;
/// <summary>
/// Gets/sets the optional open graph title.
/// </summary>
[StringLength(128)]
public string OgTitle { get; set; }
/// <summary>
/// Gets/sets the optional open graph description.
/// </summary>
[StringLength(256)]
public string OgDescription { get; set; }
/// <summary>
/// Gets/sets the optional open graph image.
/// </summary>
public ImageField OgImage { get; set; } = new ImageField();
/// <summary>
/// Gets/sets the optional primary image.
/// </summary>
public ImageField PrimaryImage { get; set; } = new ImageField();
/// <summary>
/// Gets/sets the optional excerpt.
/// </summary>
public string Excerpt { get; set; }
/// <summary>
/// Gets/sets the optional route used by the middleware.
/// </summary>
[StringLength(256)]
public string Route { get; set; }
/// <summary>
/// Gets/sets the optional redirect.
/// </summary>
[StringLength(256)]
public string RedirectUrl { get; set; }
/// <summary>
/// Gets/sets the redirect type.
/// </summary>
public RedirectType RedirectType { get; set; }
/// <summary>
/// Gets/sets the available blocks.
/// </summary>
public IList<Extend.Block> Blocks { get; set; } = new List<Extend.Block>();
/// <summary>
/// Gets/sets if comments should be enabled.
/// </summary>
/// <value></value>
public bool EnableComments { get; set; }
/// <summary>
/// Gets/sets after how many days after publish date comments
/// should be closed. A value of 0 means never.
/// </summary>
public int CloseCommentsAfterDays { get; set; }
/// <summary>
/// Gets/sets the comment count.
/// </summary>
public int CommentCount { get; set; }
/// <summary>
/// Checks if comments are open for this page.
/// </summary>
public bool IsCommentsOpen => EnableComments && Published.HasValue && (CloseCommentsAfterDays == 0 || Published.Value.AddDays(CloseCommentsAfterDays) > DateTime.Now);
/// <summary>
/// Gets/sets the published date.
/// </summary>
public DateTime? Published { get; set; }
/// <summary>
/// Checks of the current content is published.
/// </summary>
public bool IsPublished => Published.HasValue && Published.Value <= DateTime.Now;
}
}
| mit |
bknopper/TSPEvolutionaryAlgorithmsDemo | TSPEADemo/backend/src/main/java/nl/bknopper/tspeademo/ea/SingleThreadedAlgorithmRunner.java | 1402 | package nl.bknopper.tspeademo.ea;
import org.springframework.stereotype.Component;
@Component
public class SingleThreadedAlgorithmRunner implements AlgorithmRunner {
private Algorithm algorithm;
public SingleThreadedAlgorithmRunner() {
}
@Override
public synchronized void startAlgorithm(AlgorithmOptions options) {
algorithm = new Algorithm(options.getMutationProbability(),
options.getPopulationSize(),
options.getNrOfGenerations(),
options.getFitnessThreshold(),
options.getParentSelectionSize(),
options.getParentPoolSize());
algorithm.startAlgorithm();
}
@Override
public synchronized void stopAlgorithm() {
algorithm.stopAlgorithm();
}
@Override
public synchronized CandidateSolution getCurrentBest(boolean forceRetrieval) throws IllegalStateException {
if(forceRetrieval || isStillRunning()) {
return algorithm.getCurrentBest();
}
throw new IllegalStateException("No Algorithm running at this point in time. Please start one.");
}
@Override
public synchronized Boolean isStillRunning() {
if(algorithm == null) {
throw new IllegalStateException("No Algorithm running at this point in time. Please start one.");
}
return algorithm.isStillRunning();
}
}
| mit |
stevefsp/Lizitt-Unity3D-Utilities | Source/Plugins/Lizitt/Utils/Core/DefaultTag.cs | 2393 | /*
* Copyright (c) 2015 Stephen A. Pratt
*
* 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.
*/
namespace com.lizitt
{
/// <summary>
/// The string values for the default Unity tags.
/// </summary>
public static class DefaultTag
{
/// <summary>
/// The default tag name representing player objects.
/// </summary>
public const string Player = "Player";
/// <summary>
/// The tag name for the main camera.
/// </summary>
public const string MainCamera = "MainCamera";
/// <summary>
/// The default tag name for untagged objected.
/// </summary>
public const string Untagged = "Untagged";
/// <summary>
/// The default tag name for respawn objects.
/// </summary>
public const string Respawn = "Respawn";
/// <summary>
/// The default tag name for finish objects.
/// </summary>
public const string Finish = "Finish";
/// <summary>
/// The tag for objects that are not to be included in non-editor builds.
/// </summary>
public const string EditorOnly = "EditorOnly";
/// <summary>
/// The default tag name for game controller objects.
/// </summary>
public const string GameController = "GameController";
}
} | mit |
gazzlab/LSL-gazzlab-branch | liblsl/external/lslboost/mpl/modulus.hpp | 667 |
#ifndef BOOST_MPL_MODULUS_HPP_INCLUDED
#define BOOST_MPL_MODULUS_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.lslboost.org/LICENSE_1_0.txt)
//
// See http://www.lslboost.org/libs/mpl for documentation.
// $Id: modulus.hpp 49267 2008-10-11 06:19:02Z agurtovoy $
// $Date: 2008-10-11 02:19:02 -0400 (Sat, 11 Oct 2008) $
// $Revision: 49267 $
#define AUX778076_OP_NAME modulus
#define AUX778076_OP_TOKEN %
#define AUX778076_OP_ARITY 2
#include <lslboost/mpl/aux_/arithmetic_op.hpp>
#endif // BOOST_MPL_MODULUS_HPP_INCLUDED
| mit |
destiny1020/java-learning-notes-cn | Image & Video/video/XuggleTest.java | 9894 | package video;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.ShortBuffer;
import javax.imageio.ImageIO;
import org.junit.Test;
import com.xuggle.mediatool.IMediaDebugListener.Event;
import com.xuggle.mediatool.IMediaReader;
import com.xuggle.mediatool.IMediaTool;
import com.xuggle.mediatool.IMediaWriter;
import com.xuggle.mediatool.MediaToolAdapter;
import com.xuggle.mediatool.ToolFactory;
import com.xuggle.mediatool.event.IAudioSamplesEvent;
import com.xuggle.mediatool.event.IVideoPictureEvent;
import com.xuggle.xuggler.ICodec;
import com.xuggle.xuggler.IContainer;
import com.xuggle.xuggler.IStream;
import com.xuggle.xuggler.IStreamCoder;
public class XuggleTest {
private static final String filename = "D:/worksap/HUE-kickoff/team-introduction/SRE.MTS";
private static final String targetFilename = "D:/worksap/HUE-kickoff/team-introduction/SRE.mp4";
private static final String targetAvi = "D:/worksap/HUE-kickoff/team-introduction/SRE.avi";
private static final String targetImage = "D:/worksap/HUE-kickoff/team-introduction/worksLogo.png";
@Test
public void testBasicInfo() {
// first we create a Xuggler container object
IContainer container = IContainer.make();
// we attempt to open up the container
int result = container.open(filename, IContainer.Type.READ, null);
// check if the operation was successful
if (result < 0)
throw new RuntimeException("Failed to open media file");
// query how many streams the call to open found
int numStreams = container.getNumStreams();
// query for the total duration
long duration = container.getDuration();
// query for the file size
long fileSize = container.getFileSize();
// query for the bit rate
long bitRate = container.getBitRate();
System.out.println("Number of streams: " + numStreams);
System.out.println("Duration (ms): " + duration);
System.out.println("File Size (bytes): " + fileSize);
System.out.println("Bit Rate: " + bitRate);
// iterate through the streams to print their meta data
for (int i = 0; i < numStreams; i++) {
// find the stream object
IStream stream = container.getStream(i);
// get the pre-configured decoder that can decode this stream;
IStreamCoder coder = stream.getStreamCoder();
System.out.println("*** Start of Stream Info ***");
System.out.printf("stream %d: ", i);
System.out.printf("type: %s; ", coder.getCodecType());
System.out.printf("codec: %s; ", coder.getCodecID());
System.out.printf("duration: %s; ", stream.getDuration());
System.out.printf("start time: %s; ", container.getStartTime());
System.out.printf("timebase: %d/%d; ", stream.getTimeBase()
.getNumerator(), stream.getTimeBase().getDenominator());
System.out.printf("coder tb: %d/%d; ", coder.getTimeBase()
.getNumerator(), coder.getTimeBase().getDenominator());
System.out.println();
if (coder.getCodecType() == ICodec.Type.CODEC_TYPE_AUDIO) {
System.out.printf("sample rate: %d; ", coder.getSampleRate());
System.out.printf("channels: %d; ", coder.getChannels());
System.out.printf("format: %s", coder.getSampleFormat());
} else if (coder.getCodecType() == ICodec.Type.CODEC_TYPE_VIDEO) {
System.out.printf("width: %d; ", coder.getWidth());
System.out.printf("height: %d; ", coder.getHeight());
System.out.printf("format: %s; ", coder.getPixelType());
System.out.printf("frame-rate: %5.2f; ", coder.getFrameRate()
.getDouble());
}
System.out.println();
System.out.println("*** End of Stream Info ***");
}
}
@Test
public void testTranscoding() {
IMediaReader mediaReader = ToolFactory.makeReader(filename);
IMediaWriter mediaWriter = ToolFactory.makeWriter(targetFilename,
mediaReader);
mediaReader.addListener(mediaWriter);
// create a media viewer with stats enabled
// IMediaViewer mediaViewer = ToolFactory.makeViewer(true);
//
// mediaReader.addListener(mediaViewer);
while (mediaReader.readPacket() == null)
;
}
// reader -> addStaticImage -> reduceVolume -> writer
@Test
public void testModifyMedia() {
IMediaReader mediaReader = ToolFactory.makeReader(targetFilename);
// configure it to generate buffer images
mediaReader
.setBufferedImageTypeToGenerate(BufferedImage.TYPE_3BYTE_BGR);
IMediaWriter mediaWriter = ToolFactory.makeWriter(targetAvi,
mediaReader);
IMediaTool imageMediaTool = new StaticImageMediaTool(targetImage);
IMediaTool audioVolumeMediaTool = new VolumeAdjustMediaTool(0.3);
mediaReader.addListener(imageMediaTool);
imageMediaTool.addListener(audioVolumeMediaTool);
audioVolumeMediaTool.addListener(mediaWriter);
while (mediaReader.readPacket() == null)
;
}
private static class StaticImageMediaTool extends MediaToolAdapter {
private BufferedImage logoImage;
public StaticImageMediaTool(String imageFile) {
try {
logoImage = ImageIO.read(new File(imageFile));
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("could not open file");
}
}
@Override
public void onVideoPicture(IVideoPictureEvent event) {
BufferedImage image = event.getImage();
long ts = event.getTimeStamp();
if (ts / 1000000 > 15) {
if (ts / 1000000 % 2 == 1) {
Graphics2D g = image.createGraphics();
Rectangle2D bounds = new Rectangle2D.Float(0, 0,
logoImage.getWidth(), logoImage.getHeight());
// compute the amount to inset the time stamp and translate the image to that position
double insetX = bounds.getWidth();
double insetY = bounds.getHeight();
// g.translate(inset, event.getImage().getHeight() - inset);
g.translate(insetX, insetY);
g.setColor(Color.WHITE);
g.fill(bounds);
g.setColor(Color.BLACK);
g.drawImage(logoImage, 0, 0, null);
}
// call parent which will pass the video to next tool in chain
super.onVideoPicture(event);
}
}
}
private static class VolumeAdjustMediaTool extends MediaToolAdapter {
private double mVolume;
public VolumeAdjustMediaTool(double volume) {
mVolume = volume;
}
@Override
public void onAudioSamples(IAudioSamplesEvent event) {
long ts = event.getTimeStamp();
if (ts / 1000000 > 15) {
ShortBuffer buffer = event.getAudioSamples().getByteBuffer()
.asShortBuffer();
for (int i = 0; i < buffer.limit(); ++i) {
buffer.put(i, (short) (buffer.get(i) * mVolume));
}
super.onAudioSamples(event);
}
}
}
@Test
public void testSplittingIntoTwo() {
String source = "D:/worksap/HUE-kickoff/team-introduction/SRE.mp4";
String target1 = "D:/worksap/HUE-kickoff/team-introduction/SRE-1.mp4";
String target2 = "D:/worksap/HUE-kickoff/team-introduction/SRE-2.mp4";
IMediaReader reader = ToolFactory.makeReader(source);
CutChecker cutChecker = new CutChecker();
reader.addListener(cutChecker);
IMediaWriter writer = ToolFactory.makeWriter(target1, reader);
cutChecker.addListener(writer);
boolean updated = false;
while (reader.readPacket() == null) {
// 15 below is the point to split, in seconds
if ((cutChecker.currentTimestamp >= 15 * 1000000) && (!updated)) {
cutChecker.removeListener(writer);
writer.close();
writer = ToolFactory.makeWriter(target2, reader);
cutChecker.addListener(writer);
updated = true;
}
}
}
private static class CutChecker extends MediaToolAdapter {
public long currentTimestamp = 0L;
@Override
public void onVideoPicture(IVideoPictureEvent event) {
currentTimestamp = event.getTimeStamp();
super.onVideoPicture(event);
}
}
@Test
public void testSplittingOnlyOne() {
String source = "D:/worksap/HUE-kickoff/team-introduction/SRE.mp4";
String target3 = "D:/worksap/HUE-kickoff/team-introduction/SRE-3.mp4";
IMediaReader reader = ToolFactory.makeReader(source);
CutChecker cutChecker = new CutChecker();
reader.addListener(cutChecker);
boolean updated = false;
while (reader.readPacket() == null) {
// 15 below is the point to split, in seconds
if ((cutChecker.currentTimestamp >= 15 * 1000000) && (!updated)) {
IMediaWriter writer = ToolFactory.makeWriter(target3, reader);
cutChecker.addListener(writer);
updated = true;
}
}
}
}
| mit |
zladovan/scalagine | engine/resource/src/main/scala/sk/scalagine/resource/ResourceImplicitConversions.scala | 273 | package sk.scalagine.resource
/**
* Created with IntelliJ IDEA.
* User: zladovan
* Date: 9/6/14
* Time: 6:33 PM
*/
object ResourceImplicitConversions {
implicit final def resourceToTextResource(resource: ResourceLoader): TextResource = new TextResource(resource)
}
| mit |
haciel/sistema_comtable | vendor/tcpdf/examples/barcodes/example_1d_svgi.php | 2105 | <?php
//============================================================+
// File name : example_1d_svgi.php
// Version : 1.0.000
// Begin : 2011-07-21
// Last Update : 2013-03-17
// Author : Nicola Asuni - Tecnick.com LTD - Manor Coach House, Church Hill, Aldershot, Hants, GU12 4RQ, UK - www.tecnick.com - [email protected]
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2009-2013 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
// -------------------------------------------------------------------
//
// Description : Example for tcpdf_barcodes_1d.php class
//
//============================================================+
/**
* @file
* Example for tcpdf_barcodes_1d.php class
* @package com.tecnick.tcpdf
* @author Nicola Asuni
* @version 1.0.000
*/
// include 1D barcode class
require_once(dirname(__FILE__).'/../../tcpdf_barcodes_1d.php');
// set the barcode content and type
$barcodeobj = new TCPDFBarcode('http://www.tcpdf.org', 'C128');
// output the barcode as SVG inline code
echo $barcodeobj->getBarcodeSVGcode(2, 40, 'black');
//============================================================+
// END OF FILE
//============================================================+
| mit |
koalasw/UBCCourseScheduler | json-test.js | 7070 | /**
* Created by Tiffy on 15-08-28.
*/
var course = [
{
"hasSection": true,
"hasTutorial": false,
"hasLaboratory": true,
"sections1": ["CPSC 213 101"],
"sections2": ["CPSC 213 203", "CPSC 213 204"],
"tutorials1": [],
"tutorials2": [],
"labs1": ["CPSC 213 L1A", "CPSC 213 L1B", "CPSC 213 L1C", "CPSC 213 L1D", "CPSC 213 L1E", "CPSC 213 L1F"],
"labs2": ["CPSC 213 L2A", "CPSC 213 L2B", "CPSC 213 L2C", "CPSC 213 L2H", "CPSC 213 L2J", "CPSC 213 L2K", "CPSC 213 L2M", "CPSC 213 L2N", "CPSC 213 L2P"],
"sections_term1": [
{
"status": "Full",
"start": "15:00",
"term": 1,
"end": "16:00",
"activity": "Lecture",
"section": "CPSC 213 101",
"interval": "",
"days": [
"Mon",
"Wed",
"Fri"
]
}],
"sections_term2": [
{
"status": "Full",
"start": "15:00",
"term": 2,
"end": "16:00",
"activity": "Lecture",
"section": "CPSC 213 203",
"interval": "",
"days": [
"Mon",
"Wed",
"Fri"
]
},
{
"status": "Full",
"start": "9:00",
"term": 2,
"end": "10:00",
"activity": "Lecture",
"section": "CPSC 213 204",
"interval": "",
"days": [
"Mon",
"Wed",
"Fri"
]
}],
"tutorials_term1": [],
"tutorials_term2": [],
"labs_term1": [
{
"status": "",
"start": "16:00",
"term": 1,
"end": "17:00",
"activity": "Laboratory",
"section": "CPSC 213 L1A",
"interval": "",
"days": [
"Tue"
]
},
{
"status": "",
"start": "11:00",
"term": 1,
"end": "12:00",
"activity": "Laboratory",
"section": "CPSC 213 L1B",
"interval": "",
"days": [
"Wed"
]
},
{
"status": "",
"start": "10:00",
"term": 1,
"end": "11:00",
"activity": "Laboratory",
"section": "CPSC 213 L1C",
"interval": "",
"days": [
"Wed"
]
},
{
"status": "Full",
"start": "15:00",
"term": 1,
"end": "16:00",
"activity": "Laboratory",
"section": "CPSC 213 L1D",
"interval": "",
"days": [
"Tue"
]
},
{
"status": "Full",
"start": "11:30",
"term": 1,
"end": "12:30",
"activity": "Laboratory",
"section": "CPSC 213 L1E",
"interval": "",
"days": [
"Tue"
]
},
{
"status": "Full",
"start": "14:00",
"term": 1,
"end": "15:00",
"activity": "Laboratory",
"section": "CPSC 213 L1F",
"interval": "",
"days": [
"Wed"
]
}],
"labs_term2": [
{
"status": "Full",
"start": "12:00",
"term": 2,
"end": "13:00",
"activity": "Laboratory",
"section": "CPSC 213 L2A",
"interval": "",
"days": [
"Mon"
]
},
{
"status": "Full",
"start": "11:00",
"term": 2,
"end": "12:00",
"activity": "Laboratory",
"section": "CPSC 213 L2B",
"interval": "",
"days": [
"Mon"
]
},
{
"status": "Full",
"start": "11:00",
"term": 2,
"end": "12:00",
"activity": "Laboratory",
"section": "CPSC 213 L2C",
"interval": "",
"days": [
"Tue"
]
},
{
"status": "Full",
"start": "14:00",
"term": 2,
"end": "15:00",
"activity": "Laboratory",
"section": "CPSC 213 L2H",
"interval": "",
"days": [
"Mon"
]
},
{
"status": "Full",
"start": "10:00",
"term": 2,
"end": "11:00",
"activity": "Laboratory",
"section": "CPSC 213 L2J",
"interval": "",
"days": [
"Wed"
]
},
{
"status": "Full",
"start": "10:00",
"term": 2,
"end": "11:00",
"activity": "Laboratory",
"section": "CPSC 213 L2K",
"interval": "",
"days": [
"Mon"
]
},
{
"status": "Full",
"start": "13:00",
"term": 2,
"end": "14:00",
"activity": "Laboratory",
"section": "CPSC 213 L2M",
"interval": "",
"days": [
"Mon"
]
},
{
"status": "Full",
"start": "15:00",
"term": 2,
"end": "16:00",
"activity": "Laboratory",
"section": "CPSC 213 L2N",
"interval": "",
"days": [
"Tue"
]
},
{
"status": "Full",
"start": "16:00",
"term": 2,
"end": "17:00",
"activity": "Laboratory",
"section": "CPSC 213 L2P",
"interval": "",
"days": [
"Tue"
]
}]
}
];
| mit |
chasethenag420/sbs | src/main/java/com/asu/cse545/group12/dao/RoleDaoImpl.java | 1113 | package com.asu.cse545.group12.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import com.asu.cse545.group12.domain.Authorization;
import com.asu.cse545.group12.domain.Role;
public class RoleDaoImpl implements RoleDao{
@Autowired
SessionFactory sessionfactory;
@Override
public Role getRowById(int RoleId) {
// TODO Auto-generated method stub
Session session = sessionfactory.openSession();
Role role = session.load(Role.class, RoleId);
return role;
}
@Override
public int getRoleid(String roledesc) {
// TODO Auto-generated method stub
List<Role> role;
Session session = sessionfactory.openSession();
Criteria cr = session.createCriteria(Role.class);
cr.add(Restrictions.eq("roleDescription", roledesc));
role = cr.list();
return role.get(0).getRoleId();
}
}
| mit |
togusafish/vehicle-history-_-npm-vehicle-history-model | lib/mapHelper.js | 1079 | var assert = require('assert-plus');
var logger = require('./logger/logger').logger;
var exports = {};
exports.getMapValue = function (map, field) {
assert.object(map, 'map');
assert.string(field, 'field');
if (map.hasOwnProperty(field)) {
var value = map[field];
if (value === null) {
logger.info('MapHelper.getMapValue: Null value for "%s" field', field);
}
return value;
}
logger.info('MapHelper.getMapValue: Unable to get value from map for "%s" field', field);
return null;
};
exports.updateMapValue = function (map, field, value) {
assert.object(map, 'map');
assert.string(field, 'field');
map[field] = value;
};
exports.onlyNullValues = function () {
if (arguments) {
for (var i in arguments) {
if (arguments.hasOwnProperty(i)) {
var arg = arguments[i];
if (arg !== null) {
return false;
}
}
}
}
return true;
};
exports.getNaturalValueOrNull = function (value) {
if (!value || value < 1) {
return null;
}
return ~~value;
};
module.exports = exports; | mit |
yiweimatou/doctor-antd | src/components/Avatar/index.js | 3372 | import React, {
Component,
PropTypes
} from 'react'
function getStyles(props) {
const {
backgroundColor,
color,
size,
src
} = props
const avatar = {
color: '#00bcd4',
backgroundColor: 'white'
}
const styles = {
root: {
color: color || avatar.color,
backgroundColor: backgroundColor || avatar.backgroundColor,
userSelect: 'none',
display: 'inline-block',
textAlign: 'center',
lineHeight: `${size}px`,
fontSize: size / 2,
borderRadius: '50%',
height: size,
width: size,
},
icon: {
color: color || avatar.color,
width: size * 0.6,
height: size * 0.6,
fontSize: size * 0.6,
margin: size * 0.2,
},
}
if (src) {
Object.assign(styles.root, {
background: `url(${src})`,
backgroundSize: size,
backgroundOrigin: 'border-box',
border: 'solid 1px rgba(128, 128, 128, 0.15)',
height: size - 2,
width: size - 2
})
}
return styles
}
class Avatar extends Component {
static propTypes = {
/**
* The backgroundColor of the avatar. Does not apply to image avatars.
*/
backgroundColor: PropTypes.string,
/**
* Can be used, for instance, to render a letter inside the avatar.
*/
children: PropTypes.node,
/**
* The css class name of the root `div` or `img` element.
*/
className: PropTypes.string,
/**
* The icon or letter's color.
*/
color: PropTypes.string,
/**
* This is the SvgIcon or FontIcon to be used inside the avatar.
*/
icon: PropTypes.element,
/**
* This is the size of the avatar in pixels.
*/
size: PropTypes.number,
/**
* If passed in, this component will render an img element. Otherwise, a div will be rendered.
*/
src: PropTypes.string,
/**
* Override the inline-styles of the root element.
*/
style: PropTypes.object,
}
static defaultProps = {
size: 40,
}
render() {
const {
icon,
src,
style,
className,
...other,
} = this.props
const styles = getStyles(this.props)
if(src){
return (
<div
style = {
styles.root
}
{...other}
className= {className}
/>
)
}else {
return (
<div
{...other}
style={(Object.assign(styles.root, style))}
className={className}
>
{
icon && React.cloneElement(icon, {
color: styles.icon.color,
style: Object.assign(styles.icon, icon.props.style),
})
}
{this.props.children}
</div>
)
}
}
}
export default Avatar
| mit |
periaptio/empress | app/Base/Controller.php | 661 | <?php
/**
* app/Base/Controller.php
*
* Local Controller class for controllers to extend.
*
* @author Vince Kronlein <[email protected]>
* @license https://github.com/periaptio/empress/blob/master/LICENSE
* @copyright Periapt, LLC. All Rights Reserved.
*/
namespace Empress\Base;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
| mit |
igormironchik/components-observation | samples/qtreeview_client/treeview.cpp | 2435 |
/*!
\file
\author Igor Mironchik (igor.mironchik at gmail dot com).
Copyright (c) 2012 Igor Mironchik
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.
*/
// QTreeViewClient include.
#include "treeview.hpp"
#include "model.hpp"
// Qt include.
#include <QPainter>
#include <QHeaderView>
//
// TreeView::TreeViewPrivate
//
struct TreeView::TreeViewPrivate {
explicit TreeViewPrivate( Model * model )
: m_model( model )
{
}
Model * m_model;
}; // struct TreeView::TreeViewPrivate
//
// TreeView
//
TreeView::TreeView( Model * model, QWidget * parent )
: QTreeView( parent )
, d( new TreeViewPrivate( model ) )
{
init();
}
TreeView::~TreeView()
{
}
void
TreeView::init()
{
setRootIsDecorated( false );
setSortingEnabled( true );
setWordWrap( true );
setAllColumnsShowFocus( true );
sortByColumn( 0, Qt::AscendingOrder );
}
void
TreeView::drawRow( QPainter * painter,
const QStyleOptionViewItem & option,
const QModelIndex & index ) const
{
const QColor c = d->m_model->color( index );
painter->fillRect( option.rect, c );
QTreeView::drawRow( painter, option, index );
}
void
TreeView::dataChanged( const QModelIndex & topLeft,
const QModelIndex & bottomRight )
{
QTreeView::dataChanged( topLeft, bottomRight );
for( int i = topLeft.column(); i <= bottomRight.column(); ++i )
resizeColumnToContents( i );
}
| mit |
gagle/node-speedy | examples/typeof.js | 641 | "use strict";
var speedy = require ("../lib");
var s = "string";
//1 closure lookup and 1 variable definition per test
speedy.run ({
cache: function (){
var type = typeof s;
type === "number";
type === "string";
},
"no-cache": function (){
var str = s;
typeof str === "number";
typeof str === "string";
}
});
/*
File: typeof.js
Node v0.10.20
V8 v3.14.5.9
Speedy v0.1.1
Tests: 2
Timeout: 1000ms (1s 0ms)
Samples: 3
Total time per test: ~3000ms (3s 0ms)
Total time: ~6000ms (6s 0ms)
Higher is better (ops/sec)
cache
82,518,276 ± 0.0%
no-cache
148,560,774 ± 0.0%
Elapsed time: 6054ms (6s 54ms)
*/ | mit |
sphereority/sphereority | Extasys/Network/TCP/Server/Listener/TCPListenerThread.java | 2389 | /*Copyright (c) 2008 Nikos Siatras
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.*/
package Extasys.Network.TCP.Server.Listener;
import java.net.ServerSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
/**
*
* @author Nikos Siatras
*/
public class TCPListenerThread implements Runnable
{
private ServerSocket fSocket;
private TCPListener fMyListener;
public TCPListenerThread(ServerSocket socket, TCPListener myListener)
{
fSocket = socket;
fMyListener = myListener;
}
public void run()
{
while (fMyListener.isActive())
{
try
{
TCPClientConnection client = new TCPClientConnection(fSocket.accept(), fMyListener, fMyListener.isMessageCollectorInUse(), fMyListener.getMessageSplitter());
if (fMyListener.getConnectedClients().size() >= fMyListener.getMaxConnections())
{
client.DisconnectMe();
}
}
catch (SocketTimeoutException socketTimeoutException)
{
}
catch (SocketException socketException)
{
}
catch (SecurityException securityException)
{
}
catch (Exception ex)
{
}
}
System.out.println("Listener thread interrupted.");
}
}
| mit |
mitoma/tplot | lib/tplot.rb | 60 | require_relative "tplot/version"
module Tplot
# noop
end
| mit |
nirdobovizki/MiniMvc | MiniMvc/DefaultPipelineFIlter.cs | 1506 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MiniMvc
{
public class DefaultPipelineFilter : IPipelineFilter
{
public void BeginRequest(string controllerName, string actionName, Dictionary<string, object> parameters)
{
}
public void BeforeAction(ControllerBase controller, string controllerName, string actionName, Dictionary<string, object> parameters)
{
}
public void ActionError(ControllerBase controller, string controllerName, string actionName, Dictionary<string, object> parameters, Exception error)
{
}
public void AfterAction(ControllerBase controller, string controllerName, string actionName, Dictionary<string, object> parameters)
{
}
public void BeforeView(ControllerBase controller, string controllerName, string actionName, Dictionary<string, object> parameters)
{
}
public void ViewError(ControllerBase controller, string controllerName, string actionName, Dictionary<string, object> parameters, Exception error)
{
}
public void AfterView(ControllerBase controller, string controllerName, string actionName, Dictionary<string, object> parameters)
{
}
public void RequestComplete(ControllerBase controller, string controllerName, string actionName, Dictionary<string, object> parameters)
{
}
}
}
| mit |
almadaocta/lordbike-production | app/code/community/Inovarti/Onestepcheckout/Block/Onestep/Form/Review/Terms.php | 403 | <?php
/**
*
* @category Inovarti
* @package Inovarti_Onestepcheckout
* @author Suporte <[email protected]>
*/
class Inovarti_Onestepcheckout_Block_Onestep_Form_Review_Terms extends Mage_Checkout_Block_Agreements {
public function canShow() {
if (count($this->getAgreements()) === 0) {
return false;
}
return true;
}
}
| mit |
djmaze/twister-core | libtorrent/include/libtorrent/aux_/session_impl.hpp | 39297 | /*
Copyright (c) 2006, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_SESSION_IMPL_HPP_INCLUDED
#define TORRENT_SESSION_IMPL_HPP_INCLUDED
#include <algorithm>
#include <vector>
#include <set>
#include <list>
#include <stdarg.h> // for va_start, va_end
#ifndef TORRENT_DISABLE_GEO_IP
#ifdef WITH_SHIPPED_GEOIP_H
#include "libtorrent/GeoIP.h"
#else
#include <GeoIP.h>
#endif
#endif
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/pool/object_pool.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/ip_voter.hpp"
#include "libtorrent/torrent_handle.hpp"
#include "libtorrent/entry.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/peer_id.hpp"
#include "libtorrent/tracker_manager.hpp"
#include "libtorrent/debug.hpp"
#include "libtorrent/piece_block_progress.hpp"
#include "libtorrent/ip_filter.hpp"
#include "libtorrent/config.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/session_status.hpp"
#include "libtorrent/add_torrent_params.hpp"
#include "libtorrent/stat.hpp"
#include "libtorrent/file_pool.hpp"
#include "libtorrent/bandwidth_manager.hpp"
#include "libtorrent/socket_type.hpp"
#include "libtorrent/connection_queue.hpp"
#include "libtorrent/disk_io_thread.hpp"
#include "libtorrent/udp_socket.hpp"
#include "libtorrent/assert.hpp"
#include "libtorrent/thread.hpp"
#include "libtorrent/policy.hpp" // for policy::peer
#include "libtorrent/alert_manager.hpp" // for alert_manager
#include "libtorrent/deadline_timer.hpp"
#include "libtorrent/socket_io.hpp" // for print_address
#include "libtorrent/address.hpp"
#include "libtorrent/utp_socket_manager.hpp"
#include "libtorrent/bloom_filter.hpp"
#include "libtorrent/rss.hpp"
#include "libtorrent/alert_dispatcher.hpp"
#include "libtorrent/kademlia/dht_observer.hpp"
#if TORRENT_COMPLETE_TYPES_REQUIRED
#include "libtorrent/peer_connection.hpp"
#endif
#ifdef TORRENT_USE_OPENSSL
#include <boost/asio/ssl/context.hpp>
#endif
#if defined TORRENT_STATS && defined __MACH__
#include <mach/vm_statistics.h>
#include <mach/mach_init.h>
#include <mach/host_info.h>
#include <mach/mach_host.h>
#endif
namespace libtorrent
{
struct plugin;
class upnp;
class natpmp;
class lsd;
struct fingerprint;
class torrent;
class alert;
namespace dht
{
struct dht_tracker;
}
struct bencode_map_entry;
struct listen_socket_t
{
listen_socket_t(): external_port(0), ssl(false) {}
// this is typically empty but can be set
// to the WAN IP address of NAT-PMP or UPnP router
address external_address;
// this is typically set to the same as the local
// listen port. In case a NAT port forward was
// successfully opened, this will be set to the
// port that is open on the external (NAT) interface
// on the NAT box itself. This is the port that has
// to be published to peers, since this is the port
// the client is reachable through.
int external_port;
// set to true if this is an SSL listen socket
bool ssl;
// the actual socket
boost::shared_ptr<socket_acceptor> sock;
};
namespace aux
{
struct session_impl;
#if defined TORRENT_STATS && !defined __MACH__
struct vm_statistics_data_t
{
boost::uint64_t active_count;
boost::uint64_t inactive_count;
boost::uint64_t wire_count;
boost::uint64_t free_count;
boost::uint64_t pageins;
boost::uint64_t pageouts;
boost::uint64_t faults;
};
#endif
struct thread_cpu_usage
{
ptime user_time;
ptime system_time;
};
#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
struct tracker_logger;
#endif
// used to initialize the g_current_time before
// anything else
struct initialize_timer
{
initialize_timer();
};
TORRENT_EXPORT std::pair<bencode_map_entry*, int> settings_map();
// this is the link between the main thread and the
// thread started to run the main downloader loop
struct TORRENT_EXTRA_EXPORT session_impl
: alert_dispatcher
, dht::dht_observer
, boost::noncopyable
, initialize_timer
, udp_socket_observer
, boost::enable_shared_from_this<session_impl>
{
#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
// this needs to be destructed last, since other components may log
// things as they are being destructed. That's why it's declared at
// the top of session_impl
boost::shared_ptr<logger> m_logger;
#endif
// the size of each allocation that is chained in the send buffer
enum { send_buffer_size = 128 };
#ifdef TORRENT_DEBUG
friend class ::libtorrent::peer_connection;
#endif
friend struct checker_impl;
friend class invariant_access;
typedef std::set<boost::intrusive_ptr<peer_connection> > connection_map;
typedef std::map<sha1_hash, boost::shared_ptr<torrent> > torrent_map;
session_impl(CLevelDB &swarmDb,
std::pair<int, int> listen_port_range
, fingerprint const& cl_fprint
, char const* listen_interface
, boost::uint32_t alert_mask
, char const* ext_ip);
virtual ~session_impl();
void update_dht_announce_interval();
void init();
void start_session();
#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
void set_log_path(std::string const& p) { m_logpath = p; }
#endif
#ifndef TORRENT_DISABLE_EXTENSIONS
void add_extension(boost::function<boost::shared_ptr<torrent_plugin>(
torrent*, void*)> ext);
void add_ses_extension(boost::shared_ptr<plugin> ext);
#endif
#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS
bool has_peer(peer_connection const* p) const
{
TORRENT_ASSERT(is_network_thread());
return std::find_if(m_connections.begin(), m_connections.end()
, boost::bind(&boost::intrusive_ptr<peer_connection>::get, _1) == p)
!= m_connections.end();
}
// this is set while the session is building the
// torrent status update message
bool m_posting_torrent_updates;
#endif
void main_thread();
void open_listen_port(int flags, error_code& ec);
// prioritize this torrent to be allocated some connection
// attempts, because this torrent needs more peers.
// this is typically done when a torrent starts out and
// need the initial push to connect peers
void prioritize_connections(boost::weak_ptr<torrent> t);
// if we are listening on an IPv6 interface
// this will return one of the IPv6 addresses on this
// machine, otherwise just an empty endpoint
tcp::endpoint get_ipv6_interface() const;
tcp::endpoint get_ipv4_interface() const;
void async_accept(boost::shared_ptr<socket_acceptor> const& listener, bool ssl);
void on_accept_connection(boost::shared_ptr<socket_type> const& s
, boost::weak_ptr<socket_acceptor> listener, error_code const& e, bool ssl);
void on_socks_accept(boost::shared_ptr<socket_type> const& s
, error_code const& e);
void incoming_connection(boost::shared_ptr<socket_type> const& s);
#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS
bool is_network_thread() const
{
#if defined BOOST_HAS_PTHREADS
if (m_network_thread == 0) return true;
return m_network_thread == pthread_self();
#endif
return true;
}
#endif
feed_handle add_feed(feed_settings const& feed);
void remove_feed(feed_handle h);
void get_feeds(std::vector<feed_handle>* f) const;
boost::weak_ptr<torrent> find_torrent(sha1_hash const& info_hash) const;
boost::weak_ptr<torrent> find_torrent(std::string const& uuid) const;
boost::weak_ptr<torrent> find_disconnect_candidate_torrent() const;
peer_id const& get_peer_id() const { return m_peer_id; }
void close_connection(peer_connection const* p, error_code const& ec);
void set_settings(session_settings const& s);
session_settings const& settings() const { return m_settings; }
#ifndef TORRENT_DISABLE_DHT
void add_dht_node_name(std::pair<std::string, int> const& node);
void add_dht_node(udp::endpoint n);
void add_dht_router(std::pair<std::string, int> const& node);
void set_dht_settings(dht_settings const& s);
dht_settings const& get_dht_settings() const { return m_dht_settings; }
void start_dht();
void stop_dht();
void start_dht(entry const& startup_state);
// this is called for torrents when they are started
// it will prioritize them for announcing to
// the DHT, to get the initial peers quickly
void prioritize_dht(boost::weak_ptr<torrent> t);
void dht_putDataSigned(std::string const &username, std::string const &resource, bool multi,
entry const &p, std::string const &sig_p, std::string const &sig_user, bool local);
void dht_getData(std::string const &username, std::string const &resource, bool multi);
#ifndef TORRENT_NO_DEPRECATE
entry dht_state() const;
#endif
void on_dht_announce(error_code const& e);
void on_dht_router_name_lookup(error_code const& e
, tcp::resolver::iterator host);
#endif
void maybe_update_udp_mapping(int nat, int local_port, int external_port);
#ifndef TORRENT_DISABLE_ENCRYPTION
void set_pe_settings(pe_settings const& settings);
pe_settings const& get_pe_settings() const { return m_pe_settings; }
#endif
void on_port_map_log(char const* msg, int map_transport);
void on_lsd_announce(error_code const& e);
// called when a port mapping is successful, or a router returns
// a failure to map a port
void on_port_mapping(int mapping, address const& ip, int port
, error_code const& ec, int nat_transport);
bool is_aborted() const { return m_abort; }
bool is_paused() const { return m_paused; }
void pause();
void resume();
void set_ip_filter(ip_filter const& f);
ip_filter const& get_ip_filter() const;
void set_port_filter(port_filter const& f);
void listen_on(
std::pair<int, int> const& port_range
, error_code& ec
, const char* net_interface = 0
, int flags = 0);
bool is_listening() const;
torrent_handle add_torrent(add_torrent_params const&, error_code& ec);
torrent_handle add_torrent_impl(add_torrent_params const&, error_code& ec);
void async_add_torrent(add_torrent_params* params);
void remove_torrent(torrent_handle const& h, int options);
void remove_torrent_impl(boost::shared_ptr<torrent> tptr, int options);
void get_torrent_status(std::vector<torrent_status>* ret
, boost::function<bool(torrent_status const&)> const& pred
, boost::uint32_t flags) const;
void refresh_torrent_status(std::vector<torrent_status>* ret
, boost::uint32_t flags) const;
void post_torrent_updates();
std::vector<torrent_handle> get_torrents() const;
void queue_check_torrent(boost::shared_ptr<torrent> const& t);
void dequeue_check_torrent(boost::shared_ptr<torrent> const& t);
void set_alert_mask(boost::uint32_t m);
size_t set_alert_queue_size_limit(size_t queue_size_limit_);
std::auto_ptr<alert> pop_alert();
void pop_alerts(std::deque<alert*>* alerts);
void set_alert_dispatch(boost::function<void(std::auto_ptr<alert>)> const&);
void post_alert(const alert& alert_);
alert const* wait_for_alert(time_duration max_wait);
#ifndef TORRENT_NO_DEPRECATE
int upload_rate_limit() const;
int download_rate_limit() const;
int local_upload_rate_limit() const;
int local_download_rate_limit() const;
void set_local_download_rate_limit(int bytes_per_second);
void set_local_upload_rate_limit(int bytes_per_second);
void set_download_rate_limit(int bytes_per_second);
void set_upload_rate_limit(int bytes_per_second);
void set_max_half_open_connections(int limit);
void set_max_connections(int limit);
void set_max_uploads(int limit);
int max_connections() const;
int max_uploads() const;
int max_half_open_connections() const;
#endif
int num_uploads() const { return m_num_unchoked; }
int num_connections() const
{ return m_connections.size(); }
void unchoke_peer(peer_connection& c);
void choke_peer(peer_connection& c);
session_status status() const;
void set_peer_id(peer_id const& id);
void set_key(int key);
address listen_address() const;
boost::uint16_t listen_port() const;
boost::uint16_t ssl_listen_port() const;
void abort();
torrent_handle find_torrent_handle(sha1_hash const& info_hash);
void announce_lsd(sha1_hash const& ih, int port, bool broadcast = false);
void save_state(entry* e, boost::uint32_t flags) const;
void load_state(lazy_entry const* e);
void set_proxy(proxy_settings const& s);
proxy_settings const& proxy() const { return m_proxy; }
#ifndef TORRENT_NO_DEPRECATE
void set_peer_proxy(proxy_settings const& s) { set_proxy(s); }
void set_web_seed_proxy(proxy_settings const& s) { set_proxy(s); }
void set_tracker_proxy(proxy_settings const& s) { set_proxy(s); }
proxy_settings const& peer_proxy() const { return proxy(); }
proxy_settings const& web_seed_proxy() const { return proxy(); }
proxy_settings const& tracker_proxy() const { return proxy(); }
#ifndef TORRENT_DISABLE_DHT
void set_dht_proxy(proxy_settings const& s) { set_proxy(s); }
proxy_settings const& dht_proxy() const { return proxy(); }
#endif
#endif // TORRENT_NO_DEPRECATE
#ifndef TORRENT_DISABLE_DHT
bool is_dht_running() const { return m_dht; }
#endif
#if TORRENT_USE_I2P
void set_i2p_proxy(proxy_settings const& s)
{
m_i2p_conn.open(s, boost::bind(&session_impl::on_i2p_open, this, _1));
open_new_incoming_i2p_connection();
}
void on_i2p_open(error_code const& ec);
proxy_settings const& i2p_proxy() const
{ return m_i2p_conn.proxy(); }
void open_new_incoming_i2p_connection();
void on_i2p_accept(boost::shared_ptr<socket_type> const& s
, error_code const& e);
#endif
#ifndef TORRENT_DISABLE_GEO_IP
std::string as_name_for_ip(address const& a);
int as_for_ip(address const& a);
std::pair<const int, int>* lookup_as(int as);
void load_asnum_db(std::string file);
bool has_asnum_db() const { return m_asnum_db; }
void load_country_db(std::string file);
bool has_country_db() const { return m_country_db; }
char const* country_for_ip(address const& a);
#if TORRENT_USE_WSTRING
void load_asnum_dbw(std::wstring file);
void load_country_dbw(std::wstring file);
#endif // TORRENT_USE_WSTRING
#endif // TORRENT_DISABLE_GEO_IP
void start_lsd();
natpmp* start_natpmp();
upnp* start_upnp();
void stop_lsd();
void stop_natpmp();
void stop_upnp();
int next_port();
void add_redundant_bytes(size_type b, int reason)
{
TORRENT_ASSERT(b > 0);
m_total_redundant_bytes += b;
m_redundant_bytes[reason] += b;
}
void add_failed_bytes(size_type b)
{
TORRENT_ASSERT(b > 0);
m_total_failed_bytes += b;
}
char* allocate_buffer();
void free_buffer(char* buf);
char* allocate_disk_buffer(char const* category);
void free_disk_buffer(char* buf);
enum
{
source_dht = 1,
source_peer = 2,
source_tracker = 4,
source_router = 8
};
// implements dht_observer
virtual void set_external_address(address const& ip
, address const& source);
void set_external_address(address const& ip
, int source_type, address const& source);
external_ip const& external_address() const;
bool can_write_to_disk() const
{ return m_disk_thread.can_write(); }
// used when posting synchronous function
// calls to session_impl and torrent objects
mutable libtorrent::mutex mut;
mutable libtorrent::condition_variable cond;
void inc_disk_queue(int channel)
{
TORRENT_ASSERT(channel >= 0 && channel < 2);
++m_disk_queues[channel];
}
void dec_disk_queue(int channel)
{
TORRENT_ASSERT(channel >= 0 && channel < 2);
TORRENT_ASSERT(m_disk_queues[channel] > 0);
--m_disk_queues[channel];
}
void inc_active_downloading() { ++m_num_active_downloading; }
void dec_active_downloading()
{
TORRENT_ASSERT(m_num_active_downloading > 0);
--m_num_active_downloading;
}
void inc_active_finished() { ++m_num_active_finished; }
void dec_active_finished()
{
TORRENT_ASSERT(m_num_active_finished > 0);
--m_num_active_finished;
}
#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS
bool in_state_updates(boost::shared_ptr<torrent> t)
{
return std::find_if(m_state_updates.begin(), m_state_updates.end()
, boost::bind(&boost::weak_ptr<torrent>::lock, _1) == t) != m_state_updates.end();
}
#endif
void add_to_update_queue(boost::weak_ptr<torrent> t)
{
TORRENT_ASSERT(std::find_if(m_state_updates.begin(), m_state_updates.end()
, boost::bind(&boost::weak_ptr<torrent>::lock, _1) == t.lock()) == m_state_updates.end());
m_state_updates.push_back(t);
}
// private:
// implements alert_dispatcher
virtual bool post_alert(alert* a);
void update_connections_limit();
void update_unchoke_limit();
void trigger_auto_manage();
void on_trigger_auto_manage();
void update_rate_settings();
void update_disk_thread_settings();
void on_lsd_peer(tcp::endpoint peer, sha1_hash const& ih);
void setup_socket_buffers(socket_type& s);
// the settings for the client
session_settings m_settings;
// this is a shared pool where policy_peer objects
// are allocated. It's a pool since we're likely
// to have tens of thousands of peers, and a pool
// saves significant overhead
#ifdef TORRENT_STATS
struct logging_allocator
{
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
static char* malloc(const size_type bytes)
{
allocated_bytes += bytes;
++allocations;
return (char*)::malloc(bytes);
}
static void free(char* const block)
{
--allocations;
return ::free(block);
}
static int allocations;
static int allocated_bytes;
};
boost::object_pool<
policy::ipv4_peer, logging_allocator> m_ipv4_peer_pool;
#if TORRENT_USE_IPV6
boost::object_pool<
policy::ipv6_peer, logging_allocator> m_ipv6_peer_pool;
#endif
#if TORRENT_USE_I2P
boost::object_pool<
policy::i2p_peer, logging_allocator> m_i2p_peer_pool;
#endif
#else
boost::object_pool<policy::ipv4_peer> m_ipv4_peer_pool;
#if TORRENT_USE_IPV6
boost::object_pool<policy::ipv6_peer> m_ipv6_peer_pool;
#endif
#if TORRENT_USE_I2P
boost::object_pool<policy::i2p_peer> m_i2p_peer_pool;
#endif
#endif
// this vector is used to store the block_info
// objects pointed to by partial_piece_info returned
// by torrent::get_download_queue.
std::vector<block_info> m_block_info_storage;
#ifndef TORRENT_DISABLE_POOL_ALLOCATOR
// this pool is used to allocate and recycle send
// buffers from.
boost::pool<> m_send_buffers;
#endif
// the file pool that all storages in this session's
// torrents uses. It sets a limit on the number of
// open files by this session.
// file pool must be destructed after the torrents
// since they will still have references to it
// when they are destructed.
file_pool m_files;
CLevelDB &m_swarmDb;
// this is where all active sockets are stored.
// the selector can sleep while there's no activity on
// them
mutable io_service m_io_service;
#ifdef TORRENT_USE_OPENSSL
// this is a generic SSL context used when talking to
// unauthenticated HTTPS servers
asio::ssl::context m_ssl_ctx;
#endif
// handles delayed alerts
alert_manager m_alerts;
// handles disk io requests asynchronously
// peers have pointers into the disk buffer
// pool, and must be destructed before this
// object. The disk thread relies on the file
// pool object, and must be destructed before
// m_files. The disk io thread posts completion
// events to the io service, and needs to be
// constructed after it.
disk_io_thread m_disk_thread;
// this is a list of half-open tcp connections
// (only outgoing connections)
// this has to be one of the last
// members to be destructed
connection_queue m_half_open;
// the bandwidth manager is responsible for
// handing out bandwidth to connections that
// asks for it, it can also throttle the
// rate.
bandwidth_manager m_download_rate;
bandwidth_manager m_upload_rate;
// the global rate limiter bandwidth channels
bandwidth_channel m_download_channel;
bandwidth_channel m_upload_channel;
// bandwidth channels for local peers when
// rate limits are ignored. They are only
// throttled by these global rate limiters
// and they don't have a rate limit set by
// default
bandwidth_channel m_local_download_channel;
bandwidth_channel m_local_upload_channel;
// all tcp peer connections are subject to these
// bandwidth limits. Local peers are excempted
// from this limit. The purpose is to be able to
// throttle TCP that passes over the internet
// bottleneck (i.e. modem) to avoid starving out
// uTP connections.
bandwidth_channel m_tcp_download_channel;
bandwidth_channel m_tcp_upload_channel;
bandwidth_channel* m_bandwidth_channel[2];
// the number of peer connections that are waiting
// for the disk. one for each channel.
// upload_channel means waiting to read from disk
// and download_channel is waiting to write to disk
int m_disk_queues[2];
tracker_manager m_tracker_manager;
torrent_map m_torrents;
std::map<std::string, boost::shared_ptr<torrent> > m_uuids;
// counters of how many of the active (non-paused) torrents
// are finished and downloading. This is used to weigh the
// priority of downloading and finished torrents when connecting
// more peers.
int m_num_active_downloading;
int m_num_active_finished;
typedef std::list<boost::shared_ptr<torrent> > check_queue_t;
// this has all torrents that wants to be checked in it
check_queue_t m_queued_for_checking;
// this maps sockets to their peer_connection
// object. It is the complete list of all connected
// peers.
connection_map m_connections;
// filters incoming connections
ip_filter m_ip_filter;
// filters outgoing connections
port_filter m_port_filter;
// the peer id that is generated at the start of the session
peer_id m_peer_id;
// the key is an id that is used to identify the
// client with the tracker only. It is randomized
// at startup
int m_key;
// the number of retries we make when binding the
// listen socket. For each retry the port number
// is incremented by one
int m_listen_port_retries;
// the ip-address of the interface
// we are supposed to listen on.
// if the ip is set to zero, it means
// that we should let the os decide which
// interface to listen on
tcp::endpoint m_listen_interface;
// if we're listening on an IPv6 interface
// this is one of the non local IPv6 interfaces
// on this machine
tcp::endpoint m_ipv6_interface;
tcp::endpoint m_ipv4_interface;
// since we might be listening on multiple interfaces
// we might need more than one listen socket
std::list<listen_socket_t> m_listen_sockets;
#ifdef TORRENT_USE_OPENSSL
void ssl_handshake(error_code const& ec, boost::shared_ptr<socket_type> s);
#endif
// when as a socks proxy is used for peers, also
// listen for incoming connections on a socks connection
boost::shared_ptr<socket_type> m_socks_listen_socket;
boost::uint16_t m_socks_listen_port;
void open_new_incoming_socks_connection();
#if TORRENT_USE_I2P
i2p_connection m_i2p_conn;
boost::shared_ptr<socket_type> m_i2p_listen_socket;
#endif
void setup_listener(listen_socket_t* s, tcp::endpoint ep, int& retries
, bool v6_only, int flags, error_code& ec);
// the proxy used for bittorrent
proxy_settings m_proxy;
#ifndef TORRENT_DISABLE_DHT
entry m_dht_state;
#endif
// set to true when the session object
// is being destructed and the thread
// should exit
bool m_abort;
// is true if the session is paused
bool m_paused;
// the number of unchoked peers as set by the auto-unchoker
// this should always be >= m_max_uploads
int m_allowed_upload_slots;
// the number of unchoked peers
int m_num_unchoked;
// this is initialized to the unchoke_interval
// session_setting and decreased every second.
// when it reaches zero, it is reset to the
// unchoke_interval and the unchoke set is
// recomputed.
int m_unchoke_time_scaler;
// this is used to decide when to recalculate which
// torrents to keep queued and which to activate
int m_auto_manage_time_scaler;
// works like unchoke_time_scaler but it
// is only decresed when the unchoke set
// is recomputed, and when it reaches zero,
// the optimistic unchoke is moved to another peer.
int m_optimistic_unchoke_time_scaler;
// works like unchoke_time_scaler. Each time
// it reaches 0, and all the connections are
// used, the worst connection will be disconnected
// from the torrent with the most peers
int m_disconnect_time_scaler;
// when this scaler reaches zero, it will
// scrape one of the auto managed, paused,
// torrents.
int m_auto_scrape_time_scaler;
// the index of the torrent that we'll
// refresh the next time
int m_next_explicit_cache_torrent;
// this is a counter of the number of seconds until
// the next time the read cache is rotated, if we're
// using an explicit read read cache.
int m_cache_rotation_timer;
// statistics gathered from all torrents.
stat m_stat;
int m_peak_up_rate;
int m_peak_down_rate;
// is false by default and set to true when
// the first incoming connection is established
// this is used to know if the client is behind
// NAT or not.
bool m_incoming_connection;
void on_disk_queue();
void on_tick(error_code const& e);
void try_connect_more_peers(int num_downloads, int num_downloads_peers);
void auto_manage_torrents(std::vector<torrent*>& list
, int& dht_limit, int& tracker_limit, int& lsd_limit
, int& hard_limit, int type_limit);
void recalculate_auto_managed_torrents();
void recalculate_unchoke_slots(int congested_torrents
, int uncongested_torrents);
void recalculate_optimistic_unchoke_slots();
ptime m_created;
int session_time() const { return total_seconds(time_now() - m_created); }
ptime m_last_tick;
ptime m_last_second_tick;
// used to limit how often disk warnings are generated
ptime m_last_disk_performance_warning;
ptime m_last_disk_queue_performance_warning;
// the last time we went through the peers
// to decide which ones to choke/unchoke
ptime m_last_choke;
// the time when the next rss feed needs updating
ptime m_next_rss_update;
// update any rss feeds that need updating and
// recalculate m_next_rss_update
void update_rss_feeds();
// when outgoing_ports is configured, this is the
// port we'll bind the next outgoing socket to
int m_next_port;
#ifndef TORRENT_DISABLE_DHT
boost::intrusive_ptr<dht::dht_tracker> m_dht;
dht_settings m_dht_settings;
// these are used when starting the DHT
// (and bootstrapping it), and then erased
std::list<udp::endpoint> m_dht_router_nodes;
// this announce timer is used
// by the DHT.
deadline_timer m_dht_announce_timer;
// the number of torrents there were when the
// update_dht_announce_interval() was last called.
// if the number of torrents changes significantly
// compared to this number, the DHT announce interval
// is updated again. This especially matters for
// small numbers.
int m_dht_interval_update_torrents;
#endif
bool incoming_packet(error_code const& ec
, udp::endpoint const&, char const* buf, int size);
// see m_external_listen_port. This is the same
// but for the udp port used by the DHT.
int m_external_udp_port;
rate_limited_udp_socket m_udp_socket;
utp_socket_manager m_utp_socket_manager;
// the number of torrent connection boosts
// connections that have been made this second
// this is deducted from the connect speed
int m_boost_connections;
#ifndef TORRENT_DISABLE_ENCRYPTION
pe_settings m_pe_settings;
#endif
boost::intrusive_ptr<natpmp> m_natpmp;
boost::intrusive_ptr<upnp> m_upnp;
boost::intrusive_ptr<lsd> m_lsd;
// mask is a bitmask of which protocols to remap on:
// 1: NAT-PMP
// 2: UPnP
void remap_tcp_ports(boost::uint32_t mask, int tcp_port, int ssl_port);
// 0 is natpmp 1 is upnp
int m_tcp_mapping[2];
int m_twister_tcp_mapping[2];
int m_udp_mapping[2];
#ifdef TORRENT_USE_OPENSSL
int m_ssl_mapping[2];
#endif
// the timer used to fire the tick
deadline_timer m_timer;
// torrents are announced on the local network in a
// round-robin fashion. All torrents are cycled through
// within the LSD announce interval (which defaults to
// 5 minutes)
torrent_map::iterator m_next_lsd_torrent;
#ifndef TORRENT_DISABLE_DHT
// torrents are announced on the DHT in a
// round-robin fashion. All torrents are cycled through
// within the DHT announce interval (which defaults to
// 15 minutes)
torrent_map::iterator m_next_dht_torrent;
// torrents that don't have any peers
// when added should be announced to the DHT
// as soon as possible. Such torrents are put
// in this queue and get announced the next time
// the timer fires, instead of the next one in
// the round-robin sequence.
std::deque<boost::weak_ptr<torrent> > m_dht_torrents;
#endif
// torrents prioritized to get connection attempts
std::deque<std::pair<boost::weak_ptr<torrent>, int> > m_prio_torrents;
// this announce timer is used
// by Local service discovery
deadline_timer m_lsd_announce_timer;
tcp::resolver m_host_resolver;
// the index of the torrent that will be offered to
// connect to a peer next time on_tick is called.
// This implements a round robin.
torrent_map::iterator m_next_connect_torrent;
// this is the number of attempts of connecting to
// peers we have given to the torrent pointed to
// by m_next_connect_torrent. Once this reaches
// the number of connection attempts this particular
// torrent should have, the counter is reset and
// m_next_connect_torrent takes a step forward
// to give the next torrent its connection attempts.
int m_current_connect_attempts;
// this is the round-robin cursor for peers that
// get to download again after the disk has been
// blocked
connection_map::iterator m_next_disk_peer;
#if defined TORRENT_DEBUG && !defined TORRENT_DISABLE_INVARIANT_CHECKS
void check_invariant() const;
#endif
#ifdef TORRENT_DISK_STATS
void log_buffer_usage();
// used to log send buffer usage statistics
std::ofstream m_buffer_usage_logger;
// the number of send buffers that are allocated
int m_buffer_allocations;
#endif
#ifdef TORRENT_REQUEST_LOGGING
// used to log all requests from peers
FILE* m_request_log;
#endif
#ifdef TORRENT_STATS
void rotate_stats_log();
void print_log_line(int tick_interval_ms, ptime now);
void reset_stat_counters();
void enable_stats_logging(bool s);
bool m_stats_logging_enabled;
// the last time we rotated the log file
ptime m_last_log_rotation;
// logger used to write bandwidth usage statistics
FILE* m_stats_logger;
// sequence number for log file. Log files are
// rotated every hour and the sequence number is
// incremented by one
int m_log_seq;
// the number of peers that were disconnected this
// tick due to protocol error
int m_error_peers;
int m_disconnected_peers;
int m_eof_peers;
int m_connreset_peers;
int m_connrefused_peers;
int m_connaborted_peers;
int m_perm_peers;
int m_buffer_peers;
int m_unreachable_peers;
int m_broken_pipe_peers;
int m_addrinuse_peers;
int m_no_access_peers;
int m_invalid_arg_peers;
int m_aborted_peers;
int m_piece_requests;
int m_max_piece_requests;
int m_invalid_piece_requests;
int m_choked_piece_requests;
int m_cancelled_piece_requests;
int m_piece_rejects;
int m_error_incoming_peers;
int m_error_outgoing_peers;
int m_error_rc4_peers;
int m_error_encrypted_peers;
int m_error_tcp_peers;
int m_error_utp_peers;
// the number of times the piece picker fell through
// to the end-game mode
int m_end_game_piece_picker_blocks;
int m_piece_picker_blocks;
int m_piece_picks;
int m_reject_piece_picks;
int m_unchoke_piece_picks;
int m_incoming_redundant_piece_picks;
int m_incoming_piece_picks;
int m_end_game_piece_picks;
int m_snubbed_piece_picks;
int m_connect_timeouts;
int m_uninteresting_peers;
int m_timeout_peers;
int m_no_memory_peers;
int m_too_many_peers;
int m_transport_timeout_peers;
cache_status m_last_cache_status;
size_type m_last_failed;
size_type m_last_redundant;
size_type m_last_uploaded;
size_type m_last_downloaded;
int m_connection_attempts;
int m_num_banned_peers;
int m_banned_for_hash_failure;
vm_statistics_data_t m_last_vm_stat;
thread_cpu_usage m_network_thread_cpu_usage;
sliding_average<20> m_read_ops;
sliding_average<20> m_write_ops;;
enum
{
on_read_counter,
on_write_counter,
on_tick_counter,
on_lsd_counter,
on_lsd_peer_counter,
on_udp_counter,
on_accept_counter,
on_disk_queue_counter,
on_disk_read_counter,
on_disk_write_counter,
max_messages
};
int m_num_messages[max_messages];
// 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192,
// 16384, 32768, 65536, 131072, 262144, 524288, 1048576
int m_send_buffer_sizes[18];
int m_recv_buffer_sizes[18];
#endif
// each second tick the timer takes a little
// bit longer than one second to trigger. The
// extra time it took is accumulated into this
// counter. Every time it exceeds 1000, torrents
// will tick their timers 2 seconds instead of one.
// this keeps the timers more accurate over time
// as a kind of "leap second" to adjust for the
// accumulated error
boost::uint16_t m_tick_residual;
// the number of torrents that have apply_ip_filter
// set to false. This is typically 0
int m_non_filtered_torrents;
#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
boost::shared_ptr<logger> create_log(std::string const& name
, int instance, bool append = true);
void session_log(char const* fmt, ...) const;
// this list of tracker loggers serves as tracker_callbacks when
// shutting down. This list is just here to keep them alive during
// whe shutting down process
std::list<boost::shared_ptr<tracker_logger> > m_tracker_loggers;
std::string get_log_path() const
{ return m_logpath; }
std::string m_logpath;
private:
#endif
#ifdef TORRENT_UPNP_LOGGING
std::ofstream m_upnp_log;
#endif
// state for keeping track of external IPs
external_ip m_external_ip;
#ifndef TORRENT_DISABLE_EXTENSIONS
typedef std::list<boost::shared_ptr<plugin> > ses_extension_list_t;
ses_extension_list_t m_ses_extensions;
#endif
#ifndef TORRENT_DISABLE_GEO_IP
GeoIP* m_asnum_db;
GeoIP* m_country_db;
// maps AS number to the peak download rate
// we've seen from it. Entries are never removed
// from this map. Pointers to its elements
// are kept in the policy::peer structures.
std::map<int, int> m_as_peak;
#endif
// total redundant and failed bytes
size_type m_total_failed_bytes;
size_type m_total_redundant_bytes;
// this is set to true when a torrent auto-manage
// event is triggered, and reset whenever the message
// is delivered and the auto-manage is executed.
// there should never be more than a single pending auto-manage
// message in-flight at any given time.
bool m_pending_auto_manage;
// this is also set to true when triggering an auto-manage
// of the torrents. However, if the normal auto-manage
// timer comes along and executes the auto-management,
// this is set to false, which means the triggered event
// no longer needs to execute the auto-management.
bool m_need_auto_manage;
// redundant bytes per category
size_type m_redundant_bytes[7];
std::vector<boost::shared_ptr<feed> > m_feeds;
// this is the set of (subscribed) torrents that have changed
// their states since the last time the user requested updates.
std::vector<boost::weak_ptr<torrent> > m_state_updates;
// the main working thread
boost::scoped_ptr<thread> m_thread;
#if (defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS) && defined BOOST_HAS_PTHREADS
pthread_t m_network_thread;
#endif
};
#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
struct tracker_logger : request_callback
{
tracker_logger(session_impl& ses);
void tracker_warning(tracker_request const& req
, std::string const& str);
void tracker_response(tracker_request const&
, libtorrent::address const& tracker_ip
, std::list<address> const& ip_list
, std::vector<peer_entry>& peers
, int interval
, int min_interval
, int complete
, int incomplete
, int downloaded
, address const& external_ip
, std::string const& tracker_id);
void tracker_request_timed_out(
tracker_request const&);
void tracker_request_error(tracker_request const& r
, int response_code, error_code const& ec, const std::string& str
, int retry_interval);
void debug_log(const char* fmt, ...) const;
session_impl& m_ses;
};
#endif
}
}
#endif
| mit |
hedrox/ecg-classification | old_keras_impl/run.py | 2363 | from keras.layers import Convolution1D
from keras.models import Sequential
from keras.layers import Activation, Dense, Flatten, Dropout
from data import process_data
from keras import backend as K
import numpy as np
import os
if not os.listdir('datasets/processed'):
process_data()
arrhy_data = np.loadtxt(open('datasets/processed/arrhythmia.csv', 'r'), skiprows=1)
malignant_data = np.loadtxt(open('datasets/processed/malignant-ventricular-ectopy.csv', 'r'), skiprows=1)
arrhy_data = arrhy_data[:len(malignant_data)]
arrhy_len = len(arrhy_data)/500
i = 0
X_train = []
inter_X_train = []
inter_y_train = []
y_train = []
nb_filters = 32
nb_epoch = 10
batch_size = 8
counter = 0
for _ in range(arrhy_len):
counter += 1
if not (counter % batch_size):
X_train.append(inter_X_train)
y_train.append(inter_y_train)
inter_X_train = []
inter_y_train = []
inter_X_train.append(np.asarray(arrhy_data[i:i+500]))
inter_y_train.append(0)
inter_X_train.append(np.asarray(malignant_data[i:i+500]))
inter_y_train.append(1)
i += 500
validation_size = int(0.1 * len(X_train))
# remove the bugged batch
X_train.pop(0)
y_train.pop(0)
# split training and testing sets
X_train, X_test = np.split(X_train, [len(X_train)-validation_size])
y_train, y_test = np.split(y_train, [len(y_train)-validation_size])
# checking batch lengths
for batch in X_train:
if len(batch) != 16:
print("uneven batch with len: {}".format(len(batch)))
for example in batch:
if len(example) != 500:
print("uneven example with len: {}".format(len(example)))
# shape = (X_train.shape[0], 16, 500)
shape = X_train.shape[1:]
# in numpy if arrays are not the same shape they will not appear in the .shape method
print("shape: {}".format(shape))
model = Sequential()
model.add(Convolution1D(nb_filters, 3, input_shape=shape, activation='relu'))
model.add(Dropout(0.25))
model.add(Convolution1D(nb_filters, 3, activation='relu'))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('softmax'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print("ok")
model.fit(X_train, y_train, batch_size=batch_size,
nb_epoch=nb_epoch, validation_data=(X_test, y_test)) | mit |
krawthekrow/synth-unnamed | src/utils/Utils.js | 4063 | class Vector{
constructor(x, y){
this.x = x;
this.y = y;
}
static fromPolar(r, phi){
return new Vector(
r * Math.cos(phi),
r * Math.sin(phi)
);
}
add(oVec){
return new Vector(
this.x + oVec.x,
this.y + oVec.y
);
}
subtract(oVec){
return new Vector(
this.x - oVec.x,
this.y - oVec.y
);
}
multiply(scale){
return new Vector(
this.x * scale,
this.y * scale
);
}
divide(scale){
return new Vector(
this.x / scale,
this.y / scale
);
}
equals(oVec){
return (
this.x == oVec.x &&
this.y == oVec.y
);
}
floor(){
return new Vector(
Math.floor(this.x),
Math.floor(this.y)
);
}
dot(oVec){
return this.x * oVec.x + this.y * oVec.y;
}
getLength(){
return Math.sqrt(this.dot(this));
}
getAngle(){
return Math.atan2(this.y, this.x);
}
toArray(){
return [this.x, this.y];
}
};
class Dimensions{
constructor(width, height){
this.width = width;
this.height = height;
}
contains(pos){
return isPointInRect(pos,
new Rect(
new Vector(0, 0),
this
)
);
}
getArea(){
return this.width * this.height;
}
equals(oDims){
return this.width == oDims.width && this.height == oDims.height;
}
toArray(){
return [this.width, this.height];
}
};
class Rect{
constructor(pos, dims){
this.pos = pos;
this.dims = dims;
}
get x(){
return this.pos.x;
}
get y(){
return this.pos.y;
}
get width(){
return this.dims.width;
}
get height(){
return this.dims.height;
}
get left(){
return this.pos.x;
}
get right(){
return this.pos.x + this.dims.width;
}
get top(){
return this.pos.y;
}
get bottom(){
return this.pos.y + this.dims.height;
}
static fromBounds(left, right, top, bottom){
return new Rect(
new Vector(left, top),
new Dimensions(right - left, bottom - top)
);
}
};
class Array2D{
constructor(dims, data){
this.dims = dims;
this.data = data;
}
get width(){
return this.dims.width;
}
get height(){
return this.dims.height;
}
getFlatArr(){
return Utils.flatten(this.data);
}
};
class MouseButton{
};
MouseButton.MOUSE_LEFT = 0;
MouseButton.MOUSE_MIDDLE = 1;
MouseButton.MOUSE_RIGHT = 2;
class Utils{
static isPointInRect(p, rect){
return p.x >= rect.left && p.x < rect.right &&
p.y >= rect.top && p.y < rect.bottom;
}
static compute1DArray(length, func){
return new Array(length).fill(undefined).map(
(unused, i) => func(i)
);
}
static compute2DArray(dims, func){
return Utils.compute1DArray(dims.height,
i => Utils.compute1DArray(dims.width,
i2 => func(new Vector(i2, i))
)
);
}
static compute2DArrayAsArray2D(dims, func){
return new Array2D(dims, Utils.compute2DArray(dims, func));
}
static flatten(arr){
const result = [];
for(let i = 0; i < arr.length; i++){
for(let i2 = 0; i2 < arr[i].length; i2++){
result.push(arr[i][i2]);
}
}
return result;
}
static clamp(num, min, max){
return (num <= min) ? min : ((num >= max) ? max : num);
}
};
Utils.DIRS4 = [
new Vector(1, 0),
new Vector(0, 1),
new Vector(-1, 0),
new Vector(0, -1)
];
module.exports = {
Vector: Vector,
Dimensions: Dimensions,
Rect: Rect,
Array2D: Array2D,
MouseButton: MouseButton,
Utils: Utils
};
| mit |
uhef/Oskari-Routing-frontend | bundles/framework/bundle/divmanazer/locale/uz.js | 4155 | Oskari.registerLocalization({
"lang": "uz",
"key": "DivManazer",
"value": {
"LanguageSelect": {
"title": "Til",
"tooltip": "NOT TRANSLATED",
"languages": {
"af": "afrikancha",
"ak": "akancha",
"am": "amxarcha",
"ar": "arabcha",
"az": "ozarbayjoncha",
"be": "belaruscha",
"bg": "bolgarcha",
"bm": "bambarcha",
"bn": "bengalcha",
"bo": "tibetcha",
"br": "bretoncha",
"bs": "bosniycha",
"ca": "katalancha",
"cs": "chexcha",
"cy": "uelscha",
"da": "datcha",
"de": "nemischa",
"dz": "yovoncha",
"ee": "ivicha",
"el": "yunoncha",
"en": "inglizcha",
"eo": "esperantocha",
"es": "ispancha",
"et": "estoncha",
"eu": "baskcha",
"fa": "forscha",
"fi": "fincha",
"fo": "farercha",
"fr": "fransuzcha",
"fy": "gʻarbiy friziancha",
"ga": "irlandcha",
"gl": "galitsiycha",
"gu": "gujoratcha",
"ha": "xauscha",
"he": "ibroniy",
"hi": "hindcha",
"hr": "xorvatcha",
"hu": "vengrcha",
"hy": "armancha",
"id": "indoneyzcha",
"ig": "igbocha",
"is": "islandcha",
"it": "italyancha",
"ja": "yaponcha",
"ka": "gruzincha",
"ki": "kikuycha",
"kk": "qozoqcha",
"kl": "kalallisutcha",
"km": "xmercha",
"kn": "kannadcha",
"ko": "koreyscha",
"ks": "kashmircha",
"kw": "kornishcha",
"ky": "qirgʻizcha",
"lb": "lyuksemburgcha",
"lg": "gandcha",
"ln": "lingalcha",
"lo": "laoscha",
"lt": "litovcha",
"lu": "luba-katangcha",
"lv": "latishcha",
"mg": "malagasiycha",
"mk": "makedoncha",
"ml": "malayamcha",
"mn": "mo‘g‘ulcha",
"mr": "maratcha",
"ms": "malaycha",
"mt": "maltacha",
"my": "birmancha",
"nb": "norvegcha bokmal",
"nd": "shimoliy ndebelcha",
"ne": "nepalcha",
"nl": "gollandcha",
"nn": "norvegcha ninorsk",
"om": "oromocha",
"or": "oriycha",
"pa": "panjobcha",
"pl": "polyakcha",
"ps": "pushtu tili",
"pt": "portugalcha",
"qu": "qvechuancha",
"rm": "romancha",
"rn": "rundcha",
"ro": "rumincha",
"ru": "ruscha",
"rw": "kinyarvandcha",
"se": "shimoliy semiycha",
"sg": "sangoancha",
"si": "sinholcha",
"sk": "slovakcha",
"sl": "slovencha",
"sn": "shoniycha",
"so": "somalicha",
"sq": "albancha",
"sr": "serbcha",
"sv": "shvedcha",
"sw": "svahilcha",
"ta": "tamilcha",
"te": "telugvancha",
"th": "taycha",
"ti": "tigrincha",
"to": "tongocha",
"tr": "turkcha",
"ug": "uygʻurcha",
"uk": "ukraincha",
"ur": "urducha",
"uz": "oʻzbekcha",
"vi": "vyetnamcha",
"yo": "yorubcha",
"zh": "xitoycha",
"zu": "zuluancha"
}
}
}
}); | mit |
lampaa/imageLib | modules/png-node.js | 8820 | /*
# MIT LICENSE
# Copyright (c) 2011 Devon Govett
#
# 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.
*/
(function() {
var PNG, fs, zlib;
fs = require('fs');
zlib = require('zlib');
module.exports = PNG = (function() {
function PNG(data) {
var chunkSize, colors, i, index, key, section, short, text, _ref;
this.data = data;
this.pos = 8;
this.palette = [];
this.imgData = [];
this.transparency = {};
this.text = {};
while (true) {
chunkSize = this.readUInt32();
section = ((function() {
var _results;
_results = [];
for (i = 0; i < 4; i++) {
_results.push(String.fromCharCode(this.data[this.pos++]));
}
return _results;
}).call(this)).join('');
switch (section) {
case 'IHDR':
this.width = this.readUInt32();
this.height = this.readUInt32();
this.bits = this.data[this.pos++];
this.colorType = this.data[this.pos++];
this.compressionMethod = this.data[this.pos++];
this.filterMethod = this.data[this.pos++];
this.interlaceMethod = this.data[this.pos++];
break;
case 'PLTE':
this.palette = this.read(chunkSize);
break;
case 'IDAT':
for (i = 0; i < chunkSize; i += 1) {
this.imgData.push(this.data[this.pos++]);
}
break;
case 'tRNS':
this.transparency = {};
switch (this.colorType) {
case 3:
this.transparency.indexed = this.read(chunkSize);
short = 255 - this.transparency.indexed.length;
if (short > 0) {
for (i = 0; 0 <= short ? i < short : i > short; 0 <= short ? i++ : i--) {
this.transparency.indexed.push(255);
}
}
break;
case 0:
this.transparency.grayscale = this.read(chunkSize)[0];
break;
case 2:
this.transparency.rgb = this.read(chunkSize);
}
break;
case 'tEXt':
text = this.read(chunkSize);
index = text.indexOf(0);
key = String.fromCharCode.apply(String, text.slice(0, index));
this.text[key] = String.fromCharCode.apply(String, text.slice(index + 1));
break;
case 'IEND':
this.colors = (function() {
switch (this.colorType) {
case 0:
case 3:
case 4:
return 1;
case 2:
case 6:
return 3;
}
}).call(this);
this.hasAlphaChannel = (_ref = this.colorType) === 4 || _ref === 6;
colors = this.colors + (this.hasAlphaChannel ? 1 : 0);
this.pixelBitlength = this.bits * colors;
this.colorSpace = (function() {
switch (this.colors) {
case 1:
return 'DeviceGray';
case 3:
return 'DeviceRGB';
}
}).call(this);
this.imgData = new Buffer(this.imgData);
return;
default:
this.pos += chunkSize;
}
this.pos += 4;
}
return;
}
PNG.prototype.read = function(bytes) {
var i, _results;
_results = [];
for (i = 0; 0 <= bytes ? i < bytes : i > bytes; 0 <= bytes ? i++ : i--) {
_results.push(this.data[this.pos++]);
}
return _results;
};
PNG.prototype.readUInt32 = function() {
var b1, b2, b3, b4;
b1 = this.data[this.pos++] << 24;
b2 = this.data[this.pos++] << 16;
b3 = this.data[this.pos++] << 8;
b4 = this.data[this.pos++];
return b1 | b2 | b3 | b4;
};
PNG.prototype.readUInt16 = function() {
var b1, b2;
b1 = this.data[this.pos++] << 8;
b2 = this.data[this.pos++];
return b1 | b2;
};
PNG.prototype.decodePixels = function(fn) {
var _this = this;
return zlib.inflate(this.imgData, function(err, data) {
var byte, c, col, i, left, length, p, pa, paeth, pb, pc, pixelBytes, pixels, pos, row, scanlineLength, upper, upperLeft;
if (err) throw err;
pixelBytes = _this.pixelBitlength / 8;
scanlineLength = pixelBytes * _this.width;
pixels = new Buffer(scanlineLength * _this.height);
length = data.length;
row = 0;
pos = 0;
c = 0;
while (pos < length) {
switch (data[pos++]) {
case 0:
for (i = 0; i < scanlineLength; i += 1) {
pixels[c++] = data[pos++];
}
break;
case 1:
for (i = 0; i < scanlineLength; i += 1) {
byte = data[pos++];
left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
pixels[c++] = (byte + left) % 256;
}
break;
case 2:
for (i = 0; i < scanlineLength; i += 1) {
byte = data[pos++];
col = (i - (i % pixelBytes)) / pixelBytes;
upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
pixels[c++] = (upper + byte) % 256;
}
break;
case 3:
for (i = 0; i < scanlineLength; i += 1) {
byte = data[pos++];
col = (i - (i % pixelBytes)) / pixelBytes;
left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
pixels[c++] = (byte + Math.floor((left + upper) / 2)) % 256;
}
break;
case 4:
for (i = 0; i < scanlineLength; i += 1) {
byte = data[pos++];
col = (i - (i % pixelBytes)) / pixelBytes;
left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
if (row === 0) {
upper = upperLeft = 0;
} else {
upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + (i % pixelBytes)];
}
p = left + upper - upperLeft;
pa = Math.abs(p - left);
pb = Math.abs(p - upper);
pc = Math.abs(p - upperLeft);
if (pa <= pb && pa <= pc) {
paeth = left;
} else if (pb <= pc) {
paeth = upper;
} else {
paeth = upperLeft;
}
pixels[c++] = (byte + paeth) % 256;
}
break;
default:
throw new Error("Invalid filter algorithm: " + data[pos - 1]);
}
row++;
}
return fn(pixels);
});
};
PNG.prototype.decodePalette = function() {
var c, i, length, palette, pos, ret, transparency, _ref, _ref2;
palette = this.palette;
transparency = this.transparency.indexed || [];
ret = new Buffer((transparency.length || 0) + palette.length);
pos = 0;
length = palette.length;
c = 0;
for (i = 0, _ref = palette.length; i < _ref; i += 3) {
ret[pos++] = palette[i];
ret[pos++] = palette[i + 1];
ret[pos++] = palette[i + 2];
ret[pos++] = (_ref2 = transparency[c++]) != null ? _ref2 : 255;
}
return ret;
};
PNG.prototype.copyToImageData = function(imageData, pixels) {
var alpha, colors, data, i, input, j, k, length, palette, v, _ref;
colors = this.colors;
palette = null;
alpha = this.hasAlphaChannel;
if (this.palette.length) {
palette = (_ref = this._decodedPalette) != null ? _ref : this._decodedPalette = this.decodePalette();
colors = 4;
alpha = true;
}
data = (imageData != null ? imageData.data : void 0) || imageData;
length = data.length;
input = palette || pixels;
i = j = 0;
if (colors === 1) {
while (i < length) {
k = palette ? pixels[i / 4] * 4 : j;
v = input[k++];
data[i++] = v;
data[i++] = v;
data[i++] = v;
data[i++] = alpha ? input[k++] : 255;
j = k;
}
} else {
while (i < length) {
k = palette ? pixels[i / 4] * 4 : j;
data[i++] = input[k++];
data[i++] = input[k++];
data[i++] = input[k++];
data[i++] = alpha ? input[k++] : 255;
j = k;
}
}
};
PNG.prototype.decode = function(fn) {
var ret,
_this = this;
ret = new Buffer(this.width * this.height * 4);
return this.decodePixels(function(pixels) {
_this.copyToImageData(ret, pixels);
return fn(ret);
});
};
return PNG;
})();
}).call(this);
| mit |
visualing/VisualingVideoPlayer | app/src/main/java/cn/visualing/demo/ExtendsNormalActivity.java | 1155 | package cn.visualing.demo;
import android.app.Activity;
import android.os.Bundle;
import com.squareup.picasso.Picasso;
import cn.visualing.JZVideoPlayer;
import cn.visualing.JZVideoPlayerStandard;
/**
* Created by Nathen on 2017/9/19.
*/
public class ExtendsNormalActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_extends_normal);
JZVideoPlayerStandard jzVideoPlayerStandard = (JZVideoPlayerStandard) findViewById(R.id.videoplayer);
jzVideoPlayerStandard.setUp(VideoConstant.videoUrlList[0]
, JZVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, "嫂子不信");
Picasso.with(this)
.load(VideoConstant.videoThumbList[0])
.into(jzVideoPlayerStandard.thumbImageView);
}
@Override
public void onBackPressed() {
if (JZVideoPlayer.backPress()) {
return;
}
super.onBackPressed();
}
@Override
protected void onPause() {
super.onPause();
JZVideoPlayer.releaseAllVideos();
}
}
| mit |
jameszhan/mulberry_preview | lib/mulberry_preview/version.rb | 48 | module MulberryPreview
VERSION = '0.0.10'
end
| mit |
brianbbsu/program | code archive/CF/1176F.cpp | 3416 | //{
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef double lf;
typedef pair<ll,ll> ii;
#define REP(i,n) for(ll i=0;i<n;i++)
#define REP1(i,n) for(ll i=1;i<=n;i++)
#define FILL(i,n) memset(i,n,sizeof i)
#define X first
#define Y second
#define SZ(_a) (int)_a.size()
#define ALL(_a) _a.begin(),_a.end()
#define pb push_back
#ifdef brian
#define debug(...) do{\
fprintf(stderr,"%s - %d (%s) = ",__PRETTY_FUNCTION__,__LINE__,#__VA_ARGS__);\
_do(__VA_ARGS__);\
}while(0)
template<typename T>void _do(T &&_x){cerr<<_x<<endl;}
template<typename T,typename ...S> void _do(T &&_x,S &&..._t){cerr<<_x<<" ,";_do(_t...);}
template<typename _a,typename _b> ostream& operator << (ostream &_s,const pair<_a,_b> &_p){return _s<<"("<<_p.X<<","<<_p.Y<<")";}
template<typename It> ostream& _OUTC(ostream &_s,It _ita,It _itb)
{
_s<<"{";
for(It _it=_ita;_it!=_itb;_it++)
{
_s<<(_it==_ita?"":",")<<*_it;
}
_s<<"}";
return _s;
}
template<typename _a> ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a> ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a,typename _b> ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));}
template<typename _t> void pary(_t _a,_t _b){_OUTC(cerr,_a,_b);cerr<<endl;}
#define IOS()
#else
#define debug(...)
#define pary(...)
#define endl '\n'
#define IOS() ios_base::sync_with_stdio(0);cin.tie(0);
#endif // brian
//}
const ll MAXn=1e5+5,MAXlg=__lg(MAXn)+2;
const ll MOD=1000000007;
const ll INF=ll(1e17);
ll dp[10], tdp[2][10], ndp[10];
void smax(ll &a, ll b)
{
a = max(a, b);
}
int main()
{
IOS();
REP(i, 10)dp[i] = -INF;
dp[0] = 0;
ll n;
cin>>n;
while(n--)
{
ll k;
cin>>k;
ll mx3 = 0, mx2 = 0;
vector<ll> dt1;
while(k--)
{
ll c, d;
cin>>c>>d;
if(c == 3)mx3 = max(mx3, d);
else if(c == 2)mx2 = max(mx2, d);
else dt1.pb(d);
}
sort(ALL(dt1), greater<ll>());
dt1.resize(min(SZ(dt1), 3));
REP(i, 10)ndp[i] = dp[i];
if(mx3 != 0)REP(i, 10)smax(ndp[(i + 1) % 10], dp[i] + mx3 * ((i == 9) + 1));
if(mx2 != 0)REP(i, 10)smax(ndp[(i + 1) % 10], dp[i] + mx2 * ((i == 9) + 1));
do{
ll fg = 0;
REP(i, 10)tdp[0][i] = dp[i];
REP(j, SZ(dt1)){
fg = !fg;
REP(i, 10)tdp[fg][i] = tdp[!fg][i];
REP(i, 10)smax(tdp[fg][(i + 1) % 10], tdp[!fg][i] + dt1[j] * ((i == 9) + 1));
}
REP(i, 10)smax(ndp[i], tdp[fg][i]);
}while(next_permutation(ALL(dt1), greater<ll>()));
if(mx2 != 0 && SZ(dt1) > 0)
{
dt1.resize(1);
dt1.pb(mx2);
sort(ALL(dt1));
do{
ll fg = 0;
REP(i, 10)tdp[0][i] = dp[i];
REP(j, SZ(dt1)){
fg = !fg;
REP(i, 10)tdp[fg][i] = tdp[!fg][i];
REP(i, 10)smax(tdp[fg][(i + 1) % 10], tdp[!fg][i] + dt1[j] * ((i == 9) + 1));
}
REP(i, 10)smax(ndp[i], tdp[fg][i]);
}while(next_permutation(ALL(dt1)));
}
REP(i, 10)smax(dp[i], ndp[i]);
}
ll mx = 0;
REP(i,10)smax(mx, dp[i]);
cout<<mx<<endl;
}
| mit |
tohenk/php-ntreport | src/Report.php | 23531 | <?php
/*
* The MIT License
*
* Copyright (c) 2014-2021 Toha <[email protected]>
*
* 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.
*/
namespace NTLAB\Report;
use NTLAB\Report\Config\Config;
use NTLAB\Report\Data\Data;
use NTLAB\Report\Data\Pdo as PdoData;
use NTLAB\Report\Data\Propel2 as Propel2Data;
use NTLAB\Report\Engine\Csv as CsvEngine;
use NTLAB\Report\Engine\Excel as ExcelEngine;
use NTLAB\Report\Engine\Richtext as RichtextEngine;
use NTLAB\Report\Engine\Word as WordEngine;
use NTLAB\Report\Form\FormBuilder;
use NTLAB\Report\Listener\ListenerInterface;
use NTLAB\Report\Parameter\Parameter;
use NTLAB\Report\Parameter\Boolean as BooleanParameter;
use NTLAB\Report\Parameter\Checklist as ChecklistParameter;
use NTLAB\Report\Parameter\Date as DateParameter;
use NTLAB\Report\Parameter\DateOnly as DateOnlyParameter;
use NTLAB\Report\Parameter\DateRange as DateRangeParameter;
use NTLAB\Report\Parameter\DateMonth as DateMonthParameter;
use NTLAB\Report\Parameter\DateYear as DateYearParameter;
use NTLAB\Report\Parameter\Reference as ReferenceParameter;
use NTLAB\Report\Parameter\Statix as StaticParameter;
use NTLAB\Report\Validator\Validator;
use NTLAB\Report\Script\ProviderReport;
use NTLAB\Report\Script\ReportCore;
use NTLAB\Script\Core\Script;
use NTLAB\Script\Core\Manager;
// register base engines
CsvEngine::create()->register();
ExcelEngine::create()->register();
RichtextEngine::create()->register();
WordEngine::create()->register();
// register report data
PdoData::create()->register();
Propel2Data::create()->register();
// register parameters
BooleanParameter::create()->register();
ChecklistParameter::create()->register();
DateParameter::create()->register();
DateOnlyParameter::create()->register();
DateRangeParameter::create()->register();
DateMonthParameter::create()->register();
DateYearParameter::create()->register();
ReferenceParameter::create()->register();
StaticParameter::create()->register();
// register report script
Manager::addProvider(ProviderReport::getInstance());
abstract class Report
{
const ID = 'none';
const ORDER_ASC = 'ASC';
const ORDER_DESC = 'DESC';
const STATUS_OK = 0;
const STATUS_ERR_TMPL = 1;
const STATUS_ERR_TMPL_INVALID = 2;
const STATUS_ERR_NO_DATA = 3;
const STATUS_ERR_INTERNAL = 4;
/**
* @var \DOMDocument
*/
protected $doc = null;
/**
* @var \DOMXPath
*/
protected $xpath = null;
/**
* @var string
*/
protected $title = null;
/**
* @var string
*/
protected $category = null;
/**
* @var string
*/
protected $source = null;
/**
* @var boolean
*/
protected $distinct = null;
/**
* @var array
*/
protected $parameters = [];
/**
* @var array
*/
protected $orders = [];
/**
* @var array
*/
protected $groups = [];
/**
* @var array
*/
protected $validators = [];
/**
* @var array
*/
protected $configs = [];
/**
* @var \NTLAB\Report\Data\Data
*/
protected $data = null;
/**
* @var \NTLAB\Report\Form\FormInterface
*/
protected $form = null;
/**
* @var array
*/
protected $result = null;
/**
* @var boolean
*/
protected $hasTemplate = true;
/**
* @var string
*/
protected $template = null;
/**
* @var \NTLAB\Report\Template
*/
protected $templateContent = null;
/**
* @var \NTLAB\Script\Core\Script
*/
protected $script = null;
/**
* @var mixed
*/
protected $object = null;
/**
* @var int
*/
protected $status = null;
/**
* @var \Exception
*/
protected $error = null;
/**
* @var array
*/
protected static $engines = [];
/**
* @var \NTLAB\Report\Listener\ListenerInterface[]
*/
protected static $listeners = [];
/**
* @var \NTLAB\Report\Form\FormBuilder
*/
protected static $formBuilder;
/**
* Constructor.
*/
public function __construct()
{
$this->templateContent = new Template($this);
}
/**
* Add report engine.
*
* @param string $engine The engine id
* @param string $class The report class
*/
public static function addEngine($engine, $class)
{
if (!isset(static::$engines[$engine])) {
static::$engines[$engine] = $class;
}
}
/**
* Register report listener.
*
* @param \NTLAB\Report\Listener\ListenerInterface $listener Report listener
*/
public static function addListener(ListenerInterface $listener)
{
if (!in_array($listener, static::$listeners)) {
static::$listeners[] = $listener;
}
}
/**
* Get report listeners.
*
* @return \NTLAB\Report\Listener\ListenerInterface
*/
public static function getListeners()
{
return static::$listeners;
}
/**
* Get engine class.
*
* @param string $type Engine id
* @return string
*/
public static function getEngine($type)
{
if (isset(static::$engines[$type])) {
return static::$engines[$type];
}
}
/**
* Set report form builder.
*
* @param \NTLAB\Report\Form\FormBuilder $builder The form builder
*/
public static function setFormBuilder(FormBuilder $builder)
{
static::$formBuilder = $builder;
}
/**
* Get report form builder.
*
* @return \NTLAB\Report\Form\FormBuilder
*/
public static function getFormBuilder()
{
return static::$formBuilder;
}
/**
* Load a report xml and create the instance.
*
* @param string $xml XML string
* @return \NTLAB\Report\Report
*/
public static function load($xml)
{
$doc = new \DOMDocument();
if ($doc->loadXml($xml)) {
$xpath = new \DOMXPath($doc);
if (!count($nodes = $xpath->query("//NTReport/Params/Param[@name='type']"))) {
$nodes = $xpath->query("//NTReport/Parameters/Parameter[@name='type']");
}
if (count($nodes)) {
$type = $nodes->item(0)->attributes->getNamedItem('value')->nodeValue;
if (($class = static::getEngine($type)) && class_exists($class)) {
$report = new $class();
$report->initialize($doc, $xpath);
return $report;
}
}
}
}
/**
* Create instance.
*
* @return \NTLAB\Report\Report
*/
public static function create()
{
return new static();
}
/**
* Register report engine.
*/
public function register()
{
$this->addEngine(static::ID, get_class($this));
}
/**
* Constructor.
*
* @param \DOMDocument $doc The report document
* @param \DOMXPath $xpath The xpath object
*/
public function initialize(\DOMDocument $doc, \DOMXPath $xpath)
{
$this->doc = $doc;
$this->xpath = $xpath;
// initialize report
$this->doInitialize();
// report base parameter
if (!count($nodes = $this->xpath->query('//NTReport/Params/Param'))) {
$nodes = $this->xpath->query('//NTReport/Parameters/Parameter');
}
foreach ($nodes as $node) {
switch ($this->nodeAttr($node, 'name')) {
case 'type':
break;
case 'title':
$this->title = $this->nodeAttr($node, 'value');
break;
case 'category':
$this->category = $this->nodeAttr($node, 'value');
break;
case 'model':
case 'source':
$this->source = $this->nodeAttr($node, 'value');
$this->buildSourceParams($node->childNodes);
break;
case 'distinct':
$this->distinct = (bool) $this->nodeAttr($node, 'value');
break;
case 'validator':
$this->buildValidators($node->childNodes);
break;
case 'config':
$this->buildConfigs($node->childNodes);
break;
}
}
// specific report configuration
$nodes = $this->xpath->query('//NTReport/Configuration');
$this->configure($nodes->item(0)->childNodes);
}
/**
* Report initialization.
*/
protected function doInitialize()
{
}
/**
* Get script object.
*
* @return \NTLAB\Script\Core\Script
*/
public function getScript()
{
if (null === $this->script) {
$this->script = new Script();
}
return $this->script;
}
/**
* Get report object.
*
* @return mixed the report object
*/
public function getObject()
{
return $this->object;
}
/**
* Set the report object.
*
* @param mixed $v The report object
* @return \NTLAB\Report\Report
*/
public function setObject($v)
{
$this->object = $v;
return $this;
}
/**
* Get DOMNode attribute value.
*
* @param \DOMNode $node The node
* @param string $attr The attribute
* @param mixed $default Node default value
* @return string
*/
protected function nodeAttr(\DOMNode $node, $attr, $default = null)
{
if ($node->hasAttributes() && ($nodettr = $node->attributes->getNamedItem($attr))) {
return $nodettr->nodeValue;
}
return $default;
}
/**
* Configure report.
*
* @param \DOMNodeList $nodes The configuration nodes
*/
abstract protected function configure(\DOMNodeList $nodes);
/**
* Add model parameter.
*
* @param \DOMNode $node The node parameter
*/
protected function addSourceParameter(\DOMNode $node)
{
$type = $this->nodeAttr($node, 'type', 'static');
if (null === ($class = Parameter::getHandler($type))) {
return;
}
$name = $this->nodeAttr($node, 'name');
$options = [
'name' => $name,
'column' => $this->nodeAttr($node, 'column'),
'value' => $this->nodeAttr($node, 'value'),
'is_default' => (bool) $this->nodeAttr($node, 'default', false),
'is_changeable' => (bool) $this->nodeAttr($node, 'change', true)
];
if ($operator = $this->nodeAttr($node, 'operator')) {
$options['operator'] = sprintf(' %s ', trim($operator));
}
if ($label = $this->nodeAttr($node, 'label')) {
$options['label'] = $label;
}
if ($onValue = $this->nodeAttr($node, 'getvalue')) {
$options['on_value'] = $onValue;
}
if (($parent = $this->nodeAttr($node, 'parent')) && isset($this->parameters[$parent])) {
$options['parent'] = $this->parameters[$parent];
}
$parameter = new $class();
$parameter->initialize($type, $this, $options);
$this->parameters[$name] = $parameter;
}
/**
* Add model grouping.
*
* @param \DOMNode $node The node order
*/
protected function addSourceGrouping(\DOMNode $node)
{
$column = $this->nodeAttr($node, 'name');
$this->groups[] = $column;
}
/**
* Add model sorting.
*
* @param \DOMNode $node The node order
*/
protected function addSourceOrdering(\DOMNode $node)
{
$column = $this->nodeAttr($node, 'name');
$dir = $this->nodeAttr($node, 'dir', static::ORDER_ASC);
$format = $this->nodeAttr($node, 'fmt');
$this->orders[] = [$column, $dir, $format];
}
/**
* Build model parameters.
*
* @param \DOMNodeList $nodes The node list
*/
protected function buildSourceParams(\DOMNodeList $nodes)
{
foreach ($nodes as $node) {
switch (strtolower($node->nodeName)) {
case 'param':
case 'parameter':
$this->addSourceParameter($node);
break;
case 'group':
$this->addSourceGrouping($node);
break;
case 'order':
$this->addSourceOrdering($node);
break;
}
}
}
/**
* Build report validators.
*
* @param \DOMNodeList $nodes The node list
*/
protected function buildValidators(\DOMNodeList $nodes)
{
foreach ($nodes as $node) {
if (($name = $this->nodeAttr($node, 'name')) && ($expr = $this->nodeAttr($node, 'expr'))) {
$validator = new Validator($name, $expr);
$validator->setReport($this);
$this->validators[$name] = $validator;
}
}
}
/**
* Build report configs.
*
* @param \DOMNodeList $nodes The node list
*/
protected function buildConfigs(\DOMNodeList $nodes)
{
foreach ($nodes as $node) {
if (($name = $this->nodeAttr($node, 'name')) && ($model = $this->nodeAttr($node, 'model')) && ($column = $this->nodeAttr($node, 'column'))) {
$attributes = [];
foreach ($node->attributes as $attr) {
if (!in_array($attr->nodeName, ['name', 'model', 'column', 'label', 'help', 'default', 'object', 'required'])) {
$attributes[$attr->nodeName] = $attr->nodeValue;
}
}
$config = new Config($name, $model, $column, $this->nodeAttr($node, 'label'), $this->nodeAttr($node, 'help'), $this->nodeAttr($node, 'object'), $this->nodeAttr($node, 'required'), $attributes);
$config->setReport($this);
$this->configs[$name] = $config;
}
}
}
/**
* Build report form parameter.
*
* @param array $defaults Default values
*/
protected function buildForm($defaults)
{
ReportCore::setReport($this);
static::$formBuilder->setReport($this);
$this->form = static::$formBuilder->build($defaults);
}
/**
* Get report title.
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Get report category.
*
* @return string
*/
public function getCategory()
{
return $this->category;
}
/**
* Get report model class.
*
* @return string
*/
public function getSource()
{
return $this->source;
}
/**
* Get the report data source.
*
* @return \NTLAB\Report\Data\Data
*/
public function getReportData()
{
if (null === $this->data) {
if ($data = Data::getHandler($this->getSource())) {
$data->setReport($this);
}
$this->data = $data;
}
return $this->data;
}
/**
* Get report parametes form.
*
*
* @param array $defaults Default values
* @return \NTLAB\Report\Form\FormInterface
*/
public function getForm($defaults = [])
{
if (null === $this->form) {
$this->buildForm($defaults);
}
return $this->form;
}
/**
* Get report parameters.
*
* @return \NTLAB\Report\Parameter\Parameter[]
*/
public function getParameters()
{
return $this->parameters;
}
/**
* Get orders column.
*
* @return array
*/
public function getOrders()
{
return $this->orders;
}
/**
* Get groups column.
*
* @return array
*/
public function getGroups()
{
return $this->groups;
}
/**
* Get report configurations.
*
* @return \NTLAB\Report\Config\Config[]
*/
public function getConfigs()
{
return $this->configs;
}
/**
* Get report template if available.
*
* @return string
*/
public function getTemplate()
{
return $this->template;
}
/**
* Save report configuration.
*
* @return \NTLAB\Report\Report
*/
public function saveConfigs()
{
$objects = [];
foreach ($this->configs as $name => $config) {
$var = $name;
$context = null;
if ($config->getObjectExpr()) {
$context = $this->getScript()->evaluate($config->getObjectExpr());
} else {
$context = $this->getObject();
}
$this->getScript()->getVarContext($context, $var);
if ($context && ($handler = Manager::getContextHandler($context))) {
$value = $config->getFormValue();
$method = $handler->setMethod($context, $var);
if (is_callable($method)) {
call_user_func($method, $value);
if (!in_array($context, $objects)) {
$objects[] = $context;
}
}
}
}
foreach ($objects as $object) {
if ($handler = Manager::getContextHandler($object)) {
$handler->flush($object);
}
}
return $this;
}
/**
* Get report generation status.
*
* @return int
*/
public function getStatus()
{
return $this->status;
}
/**
* Get report generation error object.
*
* @return \Exception
*/
public function getError()
{
return $this->error;
}
/**
* Is report has template.
*
* @return bool
*/
public function hasTemplate()
{
return $this->hasTemplate;
}
/**
* Set template content.
*
* @param string $content The content
* @return \NTLAB\Report\Report
*/
public function setTemplateContent($content)
{
$this->templateContent->setContent($content);
return $this;
}
/**
* Get template content.
*
* @return \NTLAB\Report\Template
*/
public function getTemplateContent()
{
return $this->templateContent;
}
/**
* Fetch report data.
*
* @return array The result
*/
protected function fetchResult()
{
if ($this->form->isValid()) {
if (!($data = $this->getReportData())) {
throw new \RuntimeException('No report data can handle '.$this->source);
}
// apply query filter
foreach ($this->getParameters() as $param) {
if (!$param->isSelected()) {
continue;
}
$data->addCondition($param);
}
// apply grouping
foreach ($this->getGroups() as $group) {
$data->addGroupBy($group);
}
// apply sorting
foreach ($this->getOrders() as $order) {
$data->addOrder($order[0], $order[1], $order[2]);
}
$data->setDistinct($this->distinct);
return $data->fetch();
}
}
/**
* Check if the report data is available.
*
* @return bool
*/
public function hasResult()
{
return count($this->result) ? true : false;
}
/**
* Get report data.
*
* @return array
*/
public function getResult()
{
return $this->result;
}
/**
* Build report content.
*
* @see \NTLAB\Report\Report::generateFromObjects()
* @return string
*/
abstract protected function build();
/**
* Generate the report.
*
* @see \NTLAB\Report\Report::generateFromObjects()
* @return string|bool The generated content or false if a failure happened
*/
public function generate()
{
$this->result = null;
return $this->generateFromObjects($this->fetchResult());
}
/**
* Generate the report from supplied objects.
*
* @param array $objects The objects
* @return string|bool The generated content or false if a failure happened
*/
public function generateFromObjects($objects)
{
ReportCore::setReport($this);
$this->error = null;
$this->status = null;
$this->result = $objects;
if (count($this->result)) {
try {
if (null !== ($content = $this->build())) {
$this->status = static::STATUS_OK;
return $content;
}
}
catch (\Exception $e) {
$this->error = $e;
error_log($this->getExceptionMessage($e));
}
if (null === $this->status) {
$this->status = static::STATUS_ERR_INTERNAL;
}
} else {
$this->status = static::STATUS_ERR_NO_DATA;
}
return false;
}
protected function getExceptionMessage(\Exception $exception, $wrapper = '%s: [%s]')
{
$message = null;
while (null !== $exception) {
if ($msg = $exception->getMessage()) {
if (null == $message) {
$message = $msg;
} else {
$message = sprintf($wrapper, $message, $msg);
}
}
$exception = $exception->getPrevious();
}
return $message;
}
/**
* Check if current report is valid by executing the validators.
*
* @return bool
*/
public function isValid()
{
foreach ($this->validators as $validator) {
if (!$validator->isValid()) {
return false;
}
}
return true;
}
/**
* Populate report config values.
*
* @return \NTLAB\Report\Report
*/
public function populateConfigValues()
{
foreach ($this->configs as $config) {
$config->updateConfigValue();
}
return $this;
}
}
| mit |
flextry/books-coding-horror | Concurrency in C# - Cookbook/Functional-Friendly OOP/10. 3. Async Initialization Pattern/Imp/MyFundamentalType.cs | 971 | namespace AsyncInitializationPattern.Imp
{
using System;
using System.Threading.Tasks;
using AsyncInitializationPattern.Abstract;
internal class MyFundamentalType : IMyFundamentalType, IAsyncInitialization
{
private readonly ILogger logger;
public MyFundamentalType(ILogger logger)
{
this.logger = logger;
this.Initialization = this.InitializeAsync();
}
/// <summary>
/// The result of the asynchronous initialization of this instance.
/// </summary>
public Task Initialization { get; }
/// <summary>
/// Asynchronously initialize this instance.
/// </summary>
/// <returns></returns>
private async Task InitializeAsync()
{
await Task.Delay(TimeSpan.FromSeconds(1));
this.logger.WriteLine($"Object of type {this.GetType().FullName} was initialized successfully.");
}
}
} | mit |
sherxon/AlgoDS | src/problems/utils/Interval.java | 451 | package problems.utils;
/**
* Created by sherxon on 1/28/17.
*/
public class Interval {
public int start;
public int end;
public Interval() {
start = 0;
end = 0;
}
public Interval(int s, int e) {
start = s;
end = e;
}
@Override
public String toString() {
return "Interval{" +
"start=" + start +
", end=" + end +
'}';
}
}
| mit |
TravisWheelerLab/NINJA | docs/search/all_15.js | 241 | var searchData=
[
['which_303',['which',['../struct_heap_return.html#a92d5327a236a872dd1d0598fac7685ba',1,'HeapReturn']]],
['write_304',['write',['../class_distance_reader.html#ac6c565a94488665715dac977d32353a2',1,'DistanceReader']]]
];
| mit |
stivalet/PHP-Vulnerability-test-suite | Injection/CWE_90/unsafe/CWE_90__object-indexArray__func_FILTER-CLEANING-email_filter__name-sprintf_%s_simple_quote.php | 1811 | <?php
/*
Unsafe sample
input : get the field userData from the variable $_GET via an object, which store it in a array
Uses an email_filter via filter_var function
construction : use of sprintf via a %s with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
class Input{
private $input;
public function getInput(){
return $this->input['realOne'];
}
public function __construct(){
$this->input = array();
$this->input['test']= 'safe' ;
$this->input['realOne']= $_GET['UserData'] ;
$this->input['trap']= 'safe' ;
}
}
$temp = new Input();
$tainted = $temp->getInput();
$sanitized = filter_var($tainted, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized, FILTER_VALIDATE_EMAIL))
$tainted = $sanitized ;
else
$tainted = "" ;
$query = sprintf("name='%s'", $tainted);
//flaw
$ds=ldap_connect("localhost");
$r=ldap_bind($ds);
$sr=ldap_search($ds,"o=My Company, c=US", $query);
ldap_close($ds);
?> | mit |
emersonthis/fae | spec/dummy/config/initializers/fae.rb | 410 | Fae.setup do |config|
config.devise_secret_key = '79a3e96fecbdd893853495ff502cd387e22c9049fd30ff691115b8a0b074505be4edef6139e4be1a0a9ff407442224dbe99d94986e2abd64fd0aa01153f5be0d'
# models to exclude from dashboard list
config.dashboard_exclusions = %w( Aroma )
# language support
config.languages = {
en: 'English',
zh: 'Chinese',
ja: 'Japanese'
}
config.has_top_nav = true
end
| mit |
treytomes/ASCIIWorld2 | ASCIIWorld/ASCIIWorld/Data/Generation/Labyrinth/LabyrinthChunkGenerator.cs | 6091 | using CommonCore.Math;
using System;
using System.Collections.Generic;
using System.Linq;
namespace ASCIIWorld.Data.Generation.Labyrinth
{
public class LabyrinthChunkGenerator : BaseChunkGenerator
{
#region Fields
private int _doorId;
private int _floorId;
private int _wallId;
#endregion
#region Constructors
public LabyrinthChunkGenerator(Dictionary<int, string> blocks, int width, int height, string seed)
: base(width, height, seed)
{
_doorId = blocks.Single(x => x.Value == "WoodenDoor").Key;
_floorId = blocks.Single(x => x.Value == "Stone").Key;
_wallId = blocks.Single(x => x.Value == "Stone").Key;
}
#endregion
#region Properties
public override float AmbientLightLevel
{
get
{
return 8.0f;
}
}
#endregion
#region Methods
public override Chunk Generate(IProgress<string> progress, int chunkX, int chunkY)
{
Reseed(chunkX, chunkY);
var tileMap = new Chunk(Width, Height);
progress.Report("Generating dungeon...");
var generator = CreateDungeonGenerator(tileMap);
var dungeon = generator.Generate();
tileMap = ConvertToTileMap(tileMap, dungeon, progress);
return tileMap;
}
private Chunk ConvertToTileMap(Chunk chunk, LabyrinthDungeon dungeon, IProgress<string> progress)
{
progress.Report("Converting dungeon into chunk...");
progress.Report("Generating a rocky chunk...");
chunk = GenerateRockyChunk(chunk);
progress.Report("Excavating rooms...");
chunk = ExcavateRooms(chunk, dungeon, progress);
progress.Report("Excavating corridors...");
chunk = ExcavateCorridors(chunk, dungeon);
return chunk;
}
private Chunk GenerateRockyChunk(Chunk chunk)
{
// Initialize the tile array to rock.
for (var row = 0; row < chunk.Height; row++)
{
for (var column = 0; column < chunk.Width; column++)
{
chunk[ChunkLayer.Floor, column, row] = _floorId;
chunk[ChunkLayer.Blocking, column, row] = _wallId;
}
}
return chunk;
}
private Chunk ExcavateRooms(Chunk chunk, LabyrinthDungeon dungeon, IProgress<string> progress)
{
progress.Report("Excavating room...");
progress.Report($"Room count: {dungeon.Rooms.Count}");
// Fill tiles with corridor values for each room in dungeon.
foreach (var room in dungeon.Rooms)
{
// Get the room min and max location in tile coordinates.
var right = room.Bounds.X + room.Bounds.Width - 1;
var bottom = room.Bounds.Y + room.Bounds.Height - 1;
var minPoint = new Vector2I(room.Bounds.X * 2 + 1, room.Bounds.Y * 2 + 1);
var maxPoint = new Vector2I(right * 2, bottom * 2);
// Fill the room in tile space with an empty value.
for (var row = minPoint.Y; row <= maxPoint.Y; row++)
{
for (var column = minPoint.X; column <= maxPoint.X; column++)
{
ExcavateChunkPoint(chunk, new Vector2I(column, row));
}
}
}
progress.Report("Room complete!");
return chunk;
}
private Chunk ExcavateCorridors(Chunk chunk, LabyrinthDungeon dungeon)
{
// Loop for each corridor cell and expand it.
foreach (var cellLocation in dungeon.CorridorCellLocations)
{
var tileLocation = new Vector2I(cellLocation.X * 2 + 1, cellLocation.Y * 2 + 1);
ExcavateChunkPoint(chunk, new Vector2I(tileLocation.X, tileLocation.Y));
if (dungeon[cellLocation].NorthSide == SideType.Empty)
{
ExcavateChunkPoint(chunk, new Vector2I(tileLocation.X, tileLocation.Y - 1));
}
else if (dungeon[cellLocation].NorthSide == SideType.Door)
{
ExcavateChunkPoint(chunk, new Vector2I(tileLocation.X, tileLocation.Y - 1));
chunk[ChunkLayer.Blocking, tileLocation.X, tileLocation.Y - 1] = _doorId;
}
if (dungeon[cellLocation].SouthSide == SideType.Empty)
{
ExcavateChunkPoint(chunk, new Vector2I(tileLocation.X, tileLocation.Y + 1));
}
else if (dungeon[cellLocation].SouthSide == SideType.Door)
{
ExcavateChunkPoint(chunk, new Vector2I(tileLocation.X, tileLocation.Y + 1));
chunk[ChunkLayer.Blocking, tileLocation.X, tileLocation.Y + 1] = _doorId;
}
if (dungeon[cellLocation].WestSide == SideType.Empty)
{
ExcavateChunkPoint(chunk, new Vector2I(tileLocation.X - 1, tileLocation.Y));
}
else if (dungeon[cellLocation].WestSide == SideType.Door)
{
ExcavateChunkPoint(chunk, new Vector2I(tileLocation.X - 1, tileLocation.Y));
chunk[ChunkLayer.Blocking, tileLocation.X - 1, tileLocation.Y] = _doorId;
}
if (dungeon[cellLocation].EastSide == SideType.Empty)
{
ExcavateChunkPoint(chunk, new Vector2I(tileLocation.X + 1, tileLocation.Y));
}
else if (dungeon[cellLocation].EastSide == SideType.Door)
{
ExcavateChunkPoint(chunk, new Vector2I(tileLocation.X + 1, tileLocation.Y));
chunk[ChunkLayer.Blocking, tileLocation.X + 1, tileLocation.Y] = _doorId;
}
}
return chunk;
}
private void ExcavateChunkPoint(Chunk chunk, Vector2I chunkPoint)
{
chunk[ChunkLayer.Blocking, chunkPoint.X, chunkPoint.Y] = 0;
}
private bool IsDoorAdjacent(Chunk chunk, Vector2I chunkPoint)
{
var north = chunk[ChunkLayer.Blocking, chunkPoint.X, chunkPoint.Y - 1];
var south = chunk[ChunkLayer.Blocking, chunkPoint.X, chunkPoint.Y + 1];
var east = chunk[ChunkLayer.Blocking, chunkPoint.X + 1, chunkPoint.Y];
var west = chunk[ChunkLayer.Blocking, chunkPoint.X - 1, chunkPoint.Y];
return (north == _doorId) || (south == _doorId) || (east == _doorId) || (west == _doorId);
}
private LabyrinthGenerator CreateDungeonGenerator(Chunk chunk)
{
return new LabyrinthGenerator(Random, CreateRoomGenerator())
{
Rows = (chunk.Height - 1) / 2,
Columns = (chunk.Width - 1) / 2,
ChangeDirectionModifier = Random.NextDouble(),
SparsenessFactor = Random.NextDouble(),
DeadEndRemovalModifier = Random.NextDouble()
};
}
private RoomGenerator CreateRoomGenerator()
{
return new RoomGenerator(Random)
{
NumRooms = 5,
MinRoomRows = 2,
MaxRoomRows = 5,
MinRoomColumns = 2,
MaxRoomColumns = 5
};
}
#endregion
}
}
| mit |
tutelagesystems/billr | application/app/Http/Routes/Settings.php | 556 | <?php
Route::group(['prefix' => 'settings'], function(){
Route::get('/', array(
'as' => 'settings',
'uses' => 'SettingsController@index')
);
Route::post('/update', array(
'as' => 'settings.update',
'uses' => 'SettingsController@update')
);
Route::get('/testSMS', array(
'as' => 'settings.testSMS',
'uses' => 'SettingsController@testSMS')
);
Route::get('/testEmail', array(
'as' => 'settings.testEmail',
'uses' => 'SettingsController@testEmail')
);
}); | mit |
bhanuprasad143/refinerycms-authentication | spec/controllers/refinery/admin/users_controller_spec.rb | 2191 | require "spec_helper"
describe Refinery::Admin::UsersController do
login_refinery_superuser
shared_examples_for "new, create, update, edit and update actions" do
it "loads roles" do
Refinery::Role.should_receive(:all).once{ [] }
get :new
end
it "loads plugins" do
plugins = Refinery::Plugins.new
plugins.should_receive(:in_menu).once{ [] }
Refinery::Plugins.should_receive(:registered).at_least(1).times{ plugins }
get :new
end
end
describe "#new" do
it "renders the new template" do
get :new
response.should be_success
response.should render_template("refinery/admin/users/new")
end
it_should_behave_like "new, create, update, edit and update actions"
end
describe "#create" do
it "creates a new user with valid params" do
user = Refinery::User.new :username => "bob"
user.should_receive(:save).once{ true }
Refinery::User.should_receive(:new).once.with(instance_of(HashWithIndifferentAccess)){ user }
post :create, :user => {}
response.should be_redirect
end
it_should_behave_like "new, create, update, edit and update actions"
it "re-renders #new if there are errors" do
user = Refinery::User.new :username => "bob"
user.should_receive(:save).once{ false }
Refinery::User.should_receive(:new).once.with(instance_of(HashWithIndifferentAccess)){ user }
post :create, :user => {}
response.should be_success
response.should render_template("refinery/admin/users/new")
end
end
describe "#edit" do
it "renders the edit template" do
get :edit, :id => "1"
response.should be_success
response.should render_template("refinery/admin/users/edit")
end
it_should_behave_like "new, create, update, edit and update actions"
end
describe "#update" do
it "updates a user" do
user = FactoryGirl.create(:refinery_user)
Refinery::User.should_receive(:find).at_least(1).times{ user }
put "update", :id => user.id.to_s, :user => {}
response.should be_redirect
end
it_should_behave_like "new, create, update, edit and update actions"
end
end
| mit |
DevChampsBR/MeDaUmFilme | src/MeDaUmFilme.Language/Properties/AssemblyInfo.cs | 832 | 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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MeDaUmFilme.Language")]
[assembly: AssemblyTrademark("")]
// 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("079779c6-a689-4b73-a48c-30d522670f1f")]
| mit |
phpwaymx/phpwaymx.github.io | assets/js/init.js | 3541 | /**
* Init JS
*
* TABLE OF CONTENTS
* ---------------------------
* 1. Preloader
* 2. Ready Function
* a) Auto height for the home page
* b) Smooth Scroll
* c) 3d gallery
* d) Vimeo Video
* e) Schedule Accordian
* f) Speaker Slider
* g) Animation
* h) Registration Form
* i) Subscribe
* j) Nice Scroll
* h) Placeholder for ie9
*/
"use strict";
/* Preloader */
jQuery(window).load(function () {
// will first fade out the loading animation
jQuery(".status").fadeOut();
// will fade out the whole DIV that covers the website.
jQuery(".preloader").delay(100).fadeOut("slow");
jQuery("body").css('overflow-y', 'visible');
});
/* Ready Function */
jQuery(document).ready(function ($) {
$.noConflict();
/* Auto height function */
var setElementHeight = function () {
var height = $(window).height();
$('.autoheight').css('min-height', (height));
};
$(window).on("resize", function () {
setElementHeight();
}).resize();
/* Smooth scroll */
var height = $(".navbar.navbar-default").height();
var scroll = $(window).scrollTop();
if (scroll > height) {
$(".header-hide").addClass("scroll-header");
}
smoothScroll.init({
speed: 1000,
easing: 'easeInOutCubic',
offset: height,
updateURL: false,
callbackBefore: function (toggle, anchor) {
},
callbackAfter: function (toggle, anchor) {
}
});
$(window).scroll(function () {
var height = $(window).height();
var scroll = $(window).scrollTop();
if (scroll) {
$(".header-hide").addClass("scroll-header");
} else {
$(".header-hide").removeClass("scroll-header");
}
});
$('.nav_slide_button').click(function () {
$('.pull').slideToggle();
});
/* Overlay */
if (Modernizr.touch) {
// show the close overlay button
$(".close-overlay").removeClass("hidden");
// handle the adding of hover class when clicked
$(".img").click(function (e) {
if (!$(this).hasClass("hover")) {
$(this).addClass("hover");
}
});
// handle the closing of the overlay
$(".close-overlay").click(function (e) {
e.preventDefault();
e.stopPropagation();
if ($(this).closest(".img").hasClass("hover")) {
$(this).closest(".img").removeClass("hover");
}
});
} else {
// handle the mouseenter functionality
$(".img").mouseenter(function () {
$(this).addClass("hover");
})
// handle the mouseleave functionality
.mouseleave(function () {
$(this).removeClass("hover");
});
}
/* Animation */
var wow = new WOW({
boxClass: 'wow', // animated element css class (default is wow)
animateClass: 'animated', // animation css class (default is animated)
offset: 0, // distance to the element when triggering the animation (default is 0)
mobile: false, // trigger animations on mobile devices (default is true)
live: true // act on asynchronously loaded content (default is true)
});
wow.init();
/* Overlay close */
$('.md-overlay').click(function (e) {
$("#modal-10").removeClass("md-show");
$("#modal-11").removeClass("md-show");
});
/* Menu Close Logic */
$('.navbar-collapse.in').niceScroll({cursorcolor: "#c8bd9f"});
$('.nav li a').click(function () {
$('.navbar-collapse.collapse').toggleClass('in');
});
/* Nice Scroll */
$("html").niceScroll();
});
| mit |
manuelnelson/patient-pal | dist/api/curriculum-routes.js | 2435 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _express = require('express');
var _express2 = _interopRequireDefault(_express);
var _expressValidation = require('express-validation');
var _expressValidation2 = _interopRequireDefault(_expressValidation);
var _curriculumValidation = require('../config/curriculum-validation');
var _curriculumValidation2 = _interopRequireDefault(_curriculumValidation);
var _controllers = require('../controllers');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var router = _express2.default.Router(); // eslint-disable-line new-cap
router.route('/')
/** GET /api/curriculums - Get list of curriculums */
.get(_controllers.AuthCtrl.verifyToken, function (req, res, next) {
return _controllers.CurriculumCtrl.list(req, res, next).then(function (curriculums) {
return res.json(curriculums);
});
})
/** POST /api/curriculums - Create new curriculum */
.post(_controllers.AuthCtrl.verifyToken, (0, _expressValidation2.default)(_curriculumValidation2.default.createCurriculum), function (req, res, next) {
return _controllers.CurriculumCtrl.create(req, res, next).then(function (curriculum) {
return res.json(curriculum);
});
});
//.post(AuthCtrl.verifyToken,CurriculumCtrl.create);
// .post(validate(paramValidation.createUser), CurriculumCtrl.create);
router.route('/:id')
/** GET /api/curriculums/:id - Get curriculum */
.get(_controllers.AuthCtrl.verifyToken, function (req, res, next) {
return res.json(_controllers.CurriculumCtrl.get(req, res, next));
})
/** PUT /api/curriculums/:id - Update curriculum */
.put(_controllers.AuthCtrl.verifyToken, function (req, res, next) {
return _controllers.CurriculumCtrl.update(req, res, next).then(function (curriculum) {
return res.json(curriculum);
});
})
/** DELETE /api/curriculums/:id - Delete curriculum */
.delete(_controllers.AuthCtrl.verifyToken, function (req, res, next) {
return _controllers.CurriculumCtrl.remove(req, res, next).then(function (curriculum) {
return res.json(curriculum);
});
});
router.route('/search/:keyword')
/** GET /api/skills/search/:keyword - search skills */
.get(_controllers.CurriculumCtrl.search);
/** Load user when API with userId route parameter is hit */
router.param('id', _controllers.CurriculumCtrl.load);
exports.default = router;
//# sourceMappingURL=curriculum-routes.js.map | mit |
ahajri/AppWeb | backend/anonymous-routes.js | 4337 | var express = require('express');
var personService = require('./service/personService.js');
var countries = require('./countries');
var countryList = require('./countries.json');
var async = require('async');
var node_xj = require("xls-to-json");
var fs = require("fs");
var Converter = require("csvtojson").Converter;
var marklogic = require("marklogic");
var secConn = require("./config/secConfig.js").connection;
var db = marklogic.createDatabaseClient(secConn);
var qb = marklogic.queryBuilder;
var app = module.exports = express.Router();
function supportCrossOriginScript(req, res, next) {
res.status(200);
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods",
"POST, GET, OPTIONS, DELETE, PUT, HEAD");
next();
};
app.get('/api/random-quote', supportCrossOriginScript, function(req, res) {
res.status(200).send(countries.getRandomOne());
});
app.get('/api/csv2json', supportCrossOriginScript, function(req, res) {
var index = 0;
var convertedJson = JSON.stringify({});
async.series([
// Check and Load user
function(callback) {
// convert xls 2 json
var csvFileName = "../doc/csv/education_properties.csv";
// new converter instance
var converter = new Converter({});
// end_parsed will be emitted once parsing finished
converter.fromFile(csvFileName, function(err, result) {
if (err) {
callback(err);
}
if (result) {
convertedJson = JSON.stringify(result);
callback();
}
});
// end_parsed will be emitted once parsing finished
}, function(callback) {
console.log('data size: ' + convertedJson.length);
// save file in MarkLogic
db.documents.write({
uri : '/properties/education_properties.json',
contentType : 'application/json',
collections : [ 'ttp://localhost/StatCollection' ],
content : convertedJson
}).result(function(response, error) {
if (error) {
console.log(error);
callback(error);
} else {
index = 2;
callback()
}
});
} ], function(err) {
if (err) {
return res.status(500).send(err);
}
if (index === 2) {
return res.status(200).send("csv converted");
}
});
});
app.get('/api/search-countries/:cca3', supportCrossOriginScript, function(req,
res) {
var found = [];
if (req.params.cca3 === null) {
res.status(200).send(countryList);
}
for (var int = 0; int < countryList.length; int++) {
var json = JSON.stringify(countryList[int]);
if (countryList[int].name.common.toLowerCase().startsWith(
req.params.cca3.toLowerCase())) {
found.push(json);
}
}
res.status(200).send(found);
});
app.get('/api/educprop/', supportCrossOriginScript, function(req, res) {
db.documents.query(qb.where(qb.parsedFrom('SE.ENR.PRIM.FM.ZS'))
).result(function(results) {
return res.status(200).send(results);
});
})
app.get('/api/persons/:country', supportCrossOriginScript,
function(req, res) {
var country = req.params.country;
var SparqlClient = require('sparql-client');
var util = require('util');
var endpoint = 'http://localhost:8008/v1/graphs/sparql';
// Get the leaderName(s) of the given citys
// if you do not bind any city, it returns 10 random leaderNames
var query = "PREFIX dbb: <http://dbpedia.org/resource/> "
+ "PREFIX foaf: <http://xmlns.com/foaf/0.1/> "
+ "PREFIX onto: <http://dbpedia.org/ontology/> " +
"SELECT * "
+ "WHERE { ?person onto:birthPlace dbb:France } "
+ "SELECT * WHERE { ?person onto:birthPlace dbb:" + country
+ " } ";
var client = new SparqlClient(endpoint);
console.log("Query to " + endpoint);
console.log("Query: " + query);
client.query(query)
// .bind('city', 'db:Chicago')
// .bind('city', 'db:Tokyo')
// .bind('city', 'db:Casablanca')
.bind('birthPlace', '<http://dbpedia.org/resource/France>')
.execute(function(error, results) {
if (error) {
return res.status(500).send(error);
} else {
return res.status(200).send(results);
}
});
})
app.get('/api/find-profile', supportCrossOriginScript, function(req, res) {
res.status(200).send(JSON.stringify(personService.getRandomOne()));
});
app.get('/api/countries', supportCrossOriginScript, function(req, res) {
res.status(200).send(countries.getAllCountries());
}); | mit |
Loomie/KinoSim | finance/src/main/java/de/outstare/kinosim/finance/expenses/Expense.java | 321 | package de.outstare.kinosim.finance.expenses;
import de.outstare.kinosim.finance.Cents;
import de.outstare.kinosim.finance.NamedAmount;
/**
* An Expense is an amount of money we spent.
*/
public class Expense extends NamedAmount {
public Expense(final Cents amount, final String name) {
super(amount, name);
}
}
| mit |
tjtorres/SentiMap | static/js/jquery.eventsource.js | 6529 | /*!
* jQuery.EventSource (jQuery.eventsource)
*
* Copyright (c) 2011 Rick Waldron
* Dual licensed under the MIT and GPL licenses.
*/
(function( jQuery, global ) {
jQuery.extend( jQuery.ajaxSettings.accepts, {
stream: "text/event-stream"
});
var stream = {
defaults: {
// Stream identity
label: null,
url: null,
// Event Callbacks
open: jQuery.noop,
message: jQuery.noop
},
setup: {
stream: {},
lastEventId: 0,
isHostApi: false,
retry: 500,
history: {},
options: {}
},
cache: {}
},
pluginFns = {
public: {
close: function( label ) {
var tmp = {};
if ( !label || label === "*" ) {
for ( var prop in stream.cache ) {
if ( stream.cache[ prop ].isHostApi ) {
stream.cache[ prop ].stream.close();
}
}
stream.cache = {};
return stream.cache;
}
for ( var prop in stream.cache ) {
if ( label !== prop ) {
tmp[ prop ] = stream.cache[ prop ];
} else {
if ( stream.cache[ prop ].isHostApi ) {
stream.cache[ prop ].stream.close();
}
}
}
stream.cache = tmp;
return stream.cache;
},
streams: function( label ) {
if ( !label || label === "*" ) {
return stream.cache;
}
return stream.cache[ label ] || {};
}
},
_private: {
// Open a host api event source
openEventSource: function( options ) {
var label = options.label;
stream.cache[ label ].stream.addEventListener("open", function(event) {
if ( stream.cache[ label ] ) {
this.label = label;
stream.cache[ label ].options.open.call(this, event);
}
}, false);
stream.cache[label].stream.addEventListener("message", function(event) {
var streamData = [];
if ( stream.cache[ label ] ) {
streamData[ streamData.length ] = jQuery.parseJSON( event.data );
this.label = label;
stream.cache[ label ].lastEventId = +event.lastEventId;
stream.cache[ label ].history[stream.cache[ label ].lastEventId] = streamData;
stream.cache[ label ].options.message.call(this, streamData[0] ? streamData[0] : null, {
data: streamData,
lastEventId: stream.cache[ label ].lastEventId
}, event);
// TODO: Add custom event triggering
}
}, false);
return stream.cache[ label ].stream;
},
// open fallback event source
openPollingSource: function( options ) {
var label = options.label,
source;
if ( stream.cache[ label ] ) {
source = jQuery.ajax({
type: "GET",
url: options.url,
data: options.data,
beforeSend: function() {
if ( stream.cache[ label ] ) {
this.label = label;
stream.cache[ label ].options.open.call( this );
}
},
success: function( data ) {
var tempdata,
label = options.label,
parsedData = [],
streamData = jQuery.map( data.split("\n\n"), function(sdata, i) {
return !!sdata && sdata;
}),
idx = 0, length = streamData.length,
rretryprefix = /retry/,
retries;
if ( jQuery.isArray( streamData ) ) {
for ( ; idx < length; idx++ ) {
if ( streamData[ idx ] ) {
if ( rretryprefix.test( streamData[ idx ] ) &&
(retries = streamData[ idx ].split("retry: ")).length ) {
if ( retries.length === 2 && !retries[ 0 ] ) {
stream.cache[ label ].retry = stream.cache[ label ].options.retry = +retries[ 1 ];
}
} else {
tempdata = streamData[ idx ].split("data: ")[ 1 ];
// Convert `dataType` here
if ( options.dataType === "json" ) {
tempdata = jQuery.parseJSON( tempdata );
}
parsedData[ parsedData.length ] = tempdata;
}
}
}
}
if ( stream.cache[ label ] ) {
this.label = label;
stream.cache[ label ].lastEventId++;
stream.cache[ label ].history[ stream.cache[ label ].lastEventId ] = parsedData;
stream.cache[ label ].options.message.call(this, parsedData[0] ? parsedData[0] : null, {
data: parsedData,
lastEventId: stream.cache[ label ].lastEventId
});
setTimeout(
function() {
pluginFns._private.openPollingSource.call( this, options );
},
// Use server sent retry time if exists or default retry time if not
( stream.cache[ label ] && stream.cache[ label ].retry ) || 500
);
}
},
cache: false,
timeout: 50000
});
}
return source;
}
}
},
isHostApi = global.EventSource ? true : false;
jQuery.eventsource = function( options ) {
var streamType, opts;
// Plugin sub function
if ( options && !jQuery.isPlainObject( options ) && pluginFns.public[ options ] ) {
// If no label was passed, send message to all streams
return pluginFns.public[ options ](
arguments[1] ?
arguments[1] :
"*"
);
}
// If params were passed in as an object, normalize to a query string
options.data = options.data && jQuery.isPlainObject( options.data ) ?
jQuery.param( options.data ) :
options.data;
// Mimick the host api behavior?
if ( !options.url || typeof options.url !== "string" ) {
throw new SyntaxError("Not enough arguments: Must provide a url");
}
// If no explicit label, set internal label
options.label = !options.label ?
options.url + "?" + options.data :
options.label;
// Create new options object
opts = jQuery.extend({}, stream.defaults, options);
// Create empty object in `stream.cache`
stream.cache[ opts.label ] = {
options: opts
};
// Determine and declare `event stream` source,
// whether will be host api or XHR fallback
streamType = !isHostApi ?
// If not host api, open a polling fallback
pluginFns._private.openPollingSource(opts) :
new EventSource(opts.url + ( opts.data ? "?" + opts.data : "" ) );
// Add to event sources
stream.cache[ opts.label ] = jQuery.extend({}, stream.setup, {
stream: streamType,
isHostApi: isHostApi,
options: opts
});
if ( isHostApi ) {
pluginFns._private.openEventSource(opts);
}
return stream.cache;
};
jQuery.each( [ "close", "streams" ], function( idx, name ) {
jQuery.eventsource[ name ] = function( arg ) {
return jQuery.eventsource( name, arg || "*" );
};
});
})(jQuery, window); | mit |
karabeliov/Telerik-Academy | Courses/JavaScript Fundamentals/05.Arrays/04.MaximalIncreasingSequence/Properties/AssemblyInfo.cs | 1394 | 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.MaximalIncreasingSequence")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("_04.MaximalIncreasingSequence")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("f0e3e25d-1fdb-4444-955a-463206c8c6ad")]
// 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("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
jvasileff/aos-xp | src.java/org/anodyneos/xpImpl/tagext/TagLibraryRegistryImpl.java | 920 | package org.anodyneos.xpImpl.tagext;
import java.io.IOException;
import org.anodyneos.xp.tagext.TagLibraryInfo;
import org.anodyneos.xp.tagext.TagLibraryRegistry;
import org.anodyneos.xpImpl.tld.TLDParser;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class TagLibraryRegistryImpl extends TagLibraryRegistry {
private TLDParser tldParser = new TLDParser();
private EntityResolver resolver;
public TagLibraryRegistryImpl(EntityResolver resolver) {
this.resolver = resolver;
}
public void addTaglib(String uri, String location) throws SAXException, IOException {
InputSource is = resolver.resolveEntity(null, location);
if (is == null) {
is = new InputSource(location);
}
TagLibraryInfo tldInfo = tldParser.process(is, resolver);
tagLibraryInfos.put(uri, tldInfo);
}
}
| mit |
tamouse/kaprekar_kata | spec/spec_helper.rb | 1192 | # This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# Require this file using `require "spec_helper"` to ensure that it is only
# loaded once.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
config.treat_symbols_as_metadata_keys_with_true_values = true
config.run_all_when_everything_filtered = true
config.filter_run :focus
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
# config.order = 'random'
end
GOOD_KAPREKAR = [1, 9, 45, 55, 99, 297, 703, 999 , 2223, 2728, 4879,
4950, 5050, 5292, 7272, 7777, 9999 , 17344, 22222,
38962, 77778, 82656, 95121, 99999, 142857, 148149,
181819, 187110, 208495, 318682, 329967, 351352,
356643, 390313, 461539, 466830, 499500, 500500,
533170]
NOT_KAPREKAR = [-10, -9, -1, 0, 5, 7, 10, 100, 122, 1000, 1004, 10_000, 100_000, 1_000_000]
| mit |
zoubin/async-array-methods | example/chain.js | 1384 | var AsyncArray = require('..').Array
Promise.resolve()
.then(function () {
var origin = AsyncArray([1, 2, 3, 4, 5, 6])
var odd = origin.filter(isOdd)
var even = origin.filter(isEven)
return odd.then(function (res) {
// [1, 3, 5]
console.log(res)
return even
})
.then(function (res) {
// [2, 4, 6]
console.log(res)
})
.then(function () {
return even.reduce(flagMap, {})
})
.then(function (res) {
// { 2: true, 4: true, 6: true }
console.log(res)
})
.then(function () {
// chain
return origin.filter(isOdd).reduce(flagMap, {})
})
.then(function (res) {
// { 1: true, 3: true, 5: true }
console.log(res)
})
})
.then(function () {
// Modify the original array
var origin = [1, 3, 5]
var arr = AsyncArray(origin)
arr.forEach(function (v, i, arr) {
arr[i] = v + 2
})
.then(function (res) {
// [3, 5, 7]
console.log(res)
return arr
})
.then(function (res) {
// [3, 5, 7]
console.log(res)
})
.then(function () {
// [3, 5, 7]
console.log(origin)
})
})
function isOdd(n, i, arr, next) {
process.nextTick(function () {
next(null, n % 2)
})
}
function isEven(n, i, arr, next) {
return new Promise(function (resolve) {
process.nextTick(function () {
resolve((n + 1) % 2)
})
})
}
function flagMap(o, v) {
o[v] = true
return o
}
| mit |
lordjancso/LordjancsoDevelopmentBundle | src/LordjancsoDevelopmentBundle.php | 150 | <?php
namespace Lordjancso\DevelopmentBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class LordjancsoDevelopmentBundle extends Bundle
{
}
| mit |
brianmains/Nucleo.NET | src/Nucleo.Orm/Orm/UnitOfWorkManager.cs | 3613 | using System;
using System.Collections.Generic;
using System.Linq;
using Nucleo.Orm.Caching;
using Nucleo.Orm.Configuration;
using Nucleo.Orm.Creation;
using Nucleo.Orm.Discovery;
namespace Nucleo.Orm
{
/// <summary>
/// Represents the manager that can serve up unit of work implementations.
/// </summary>
/// <remarks>Instantiate using one of the available Create() methods.</remarks>
public class UnitOfWorkManager
{
private IUnitOfWorkCaching _caching = null;
private IUnitOfWorkCreator _creator = null;
private IUnitOfWorkDiscoveryStrategy _discoveryStrategy = null;
#region " Constructors "
private UnitOfWorkManager() { }
#endregion
#region " Methods "
/// <summary>
/// Creates a new instance of the unit of work manager, using the configuration section information from <see cref="UnitOfWorkSection"/>.
/// </summary>
/// <returns>The manager instance instantiated from the configuration file.</returns>
/// <exception cref="System.Configuration.ConfigurationErrorsException" />
public static UnitOfWorkManager Create()
{
UnitOfWorkSection section = UnitOfWorkSection.Instance;
if (section == null)
throw new System.Configuration.ConfigurationErrorsException("The unit of work configuration section has not yet been established.");
UnitOfWorkManager mgr = new UnitOfWorkManager();
mgr._caching = (IUnitOfWorkCaching)mgr.LoadType(() => section.CacheTypeName, "cache");
mgr._creator = (IUnitOfWorkCreator)mgr.LoadType(() => section.CreatorTypeName, "creator");
mgr._discoveryStrategy = (IUnitOfWorkDiscoveryStrategy)mgr.LoadType(() => section.DiscoveryStrategyTypeName, "discovery strategy");
return mgr;
}
/// <summary>
/// Creates a new instance of the unit of work manager using the specified discovery strategy, unit of work creator, and cacher.
/// </summary>
/// <param name="discoveryStrategy">The discovery strategy to use.</param>
/// <param name="creator">The creator instance.</param>
/// <param name="cacher">The cacher object.</param>
/// <returns>The manager instance instantiated.</returns>
public static UnitOfWorkManager Create(UnitOfWorkManagerOptions options)
{
if (options == null)
throw new ArgumentNullException("options");
return new UnitOfWorkManager
{
_discoveryStrategy = options.DiscoveryStrategy,
_creator = options.Creator,
_caching = options.Caching
};
}
private object LoadType(Func< string> selector, string entity)
{
string value = selector();
if (string.IsNullOrEmpty(value))
return null;
Type cacheType = Type.GetType(value);
if (cacheType == null)
throw new NullReferenceException("The " + entity + " type does not exist: " + value);
return Activator.CreateInstance(cacheType);
}
/// <summary>
/// Locates a unit of work.
/// </summary>
/// <param name="name">The name to use to find the unit of work.</param>
/// <returns>The unit of work instance.</returns>
/// <exception cref="ArgumentNullException">Thrown when name is null or empty.</exception>
public IUnitOfWork LocateUnitOfWork(string name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
if (_caching != null)
{
IUnitOfWork cachedWork = _caching.GetUnitOfWork(name);
if (cachedWork != null)
return cachedWork;
}
IUnitOfWork work = _discoveryStrategy.LocateUnitOfWork(new UnitOfWorkDiscoveryOptions
{
Name = name,
Creator = _creator
});
if (_caching != null && work != null)
_caching.SaveUnitOfWork(name, work);
return work;
}
#endregion
}
}
| mit |
KMK-ONLINE/xbt | src/Xbt/Template.php | 1928 | <?php // strict
namespace Xbt;
class Template extends TagNode
{
protected $extends;
protected $blocks;
protected $doctype;
public function __construct(TagAttributes $attributes, NodeList $children, $blocks = [])
{
if ($attributes->offsetExists(':extends') && !$attributes->offsetGet(':extends') instanceof StringNode) {
throw new SyntaxError("Extends attribute must be a StringNode");
}
$this->extends = $attributes->offsetGet(':extends');
if ($attributes->offsetExists(':doctype')) {
if (!$attributes->offsetGet(':doctype') instanceof StringNode) {
throw new SyntaxError("Doctype attribute must be a StringNode");
}
$doctype = $attributes->offsetGet(':doctype')->__toString();
if (!in_array($doctype, ['true', 'false'])) {
throw new SyntaxError("Doctype attribute must be true or false");
}
$this->doctype = $doctype === 'true';
}
parent::__construct('xbt:template', $attributes, $children);
$this->blocks = $blocks;
}
public function getBlocks()
{
return $this->blocks;
}
public function compile() //: string
{
$wrapper = 'x:frag';
if ($this->doctype) {
$wrapper = 'x:doctype';
}
$parent = $this->extends ? "app('xbt.compiler')->compileExtends('{$this->extends}')" : 'null';
return <<<RENDER
return new \\Xbt\TemplateRuntime(
{$parent},
function(\$__this, \$__params = []) {
return <{$wrapper}>{$this->renderChildren()}</{$wrapper}>;
},
[
{$this->compileBlocks()}
]
);
RENDER;
}
public function compileBlocks() //: string
{
$blocks = [];
foreach ($this->getBlocks() as $block) {
$blocks[] = $block->renderBody();
}
return implode("\n", $blocks);
}
}
| mit |
velidar/Telerik-Academy-ASP.NET-Web-Forms-Exam-September-2013 | LibrarySystem/ApsNetWebFormsExam/App_Start/Startup.Auth.cs | 1082 | using Owin;
namespace ApsNetWebFormsExam
{
public partial class Startup {
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301883
public void ConfigureAuth(IAppBuilder app)
{
// Enable the application to use a cookie to store information for the signed in user
// and also store information about a user logging in with a third party login provider.
// This is required if your application allows users to login
app.UseSignInCookies();
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication();
}
}
}
| mit |
bitovi-components/bit-graph | Gruntfile.js | 1035 | var path = require('path');
var docConfig = require('./documentjs.json');
var isCI = process.env.CI === 'true';
module.exports = function (grunt) {
grunt.loadNpmTasks('steal-tools');
grunt.loadNpmTasks('testee');
grunt.loadNpmTasks('grunt-serve');
grunt.loadNpmTasks('documentjs');
var config = {
documentjs: docConfig,
testee: {
options: {
reporter: 'Spec'
},
local: {
options: {
browsers: ['chrome']
},
src: ['test/test.html']
},
ci: {
options: {
browsers: ['firefox']
},
src: ['test/test.html']
}
},
serve: {
path: './'
},
'steal-export': {
dist: {
system: {
config: 'package.json!npm'
},
outputs: {
'+cjs': {},
'+amd': {},
'+global-js': {},
'+global-css': {}
}
}
}
};
grunt.initConfig(config);
grunt.registerTask('server',['serve']);
grunt.registerTask('build',['steal-export']);
grunt.registerTask('test', [ isCI ? 'testee:ci' : 'testee:local' ]);
grunt.registerTask('docs', ['documentjs'])
};
| mit |
ideaworld/FHIR_Tester | FHIR_Tester_statics/js/build/.module-cache/0cea89157bfa64f3fd553de7a685b92de1a0abdf.js | 10633 | var app = app || {};
(function(){
app.TestButton = React.createClass({displayName: "TestButton",
handleClick: function() {
this.props.submitTestTask(this.props.btnType);
},
render: function() {
return ( React.createElement("button", {onClick: this.handleClick,
className: "btn btn-test"}, " ", React.createElement("span", {className: "btn-test-text"}, " ", this.props.btn_name, " ")) );
}
});
app.CodeEditor = React.createClass({displayName: "CodeEditor",
handleType:function(){
this.props.updateCode(this.editor.session.getValue());
},
componentDidMount:function(){
this.editor = ace.edit("codeeditor");
this.editor.setTheme("ace/theme/clouds_midnight");
this.editor.setOptions({
fontSize: "1.2em"
});
this.editor.session.setMode("ace/mode/"+this.props.language);
},
render:function(){
return (
React.createElement("div", {id: "codeeditor", onKeyUp: this.handleType})
);
}
});
app.TokenEditor = React.createClass({displayName: "TokenEditor",
handleChange:function(){
var new_token = this.refs.tokenInput.value;
this.props.updateToken(new_token);
},
render: function(){
return (
React.createElement("input", {className: "input-url", onChange: this.handleChange, ref: "tokenInput", placeholder: "Input Server Access Token"})
);
}
});
app.UrlEditor = React.createClass({displayName: "UrlEditor",
getInitialState: function(){
return {
url_vaild:true
}
},
handleChange:function(){
//if url valid, update state, if not, warn
var url_str = this.refs.urlInput.value;
if (app.isUrl(url_str)){
this.setState({url_vaild:true});
//this.probs.updateUrl(url_str)
}else{
this.setState({url_vaild:false});
}
this.props.updateUrl(url_str);
},
classNames:function(){
return 'input-url ' + ((this.state.url_vaild) ? 'input-right':'input-error');
},
render: function(){
return (
React.createElement("input", {className: this.classNames(), onChange: this.handleChange, ref: "urlInput", placeholder: "Type Server or App URL"})
);
}
});
var ResultDisplay = app.ResultDisplay = React.createClass({displayName: "ResultDisplay",
getInitialState:function(){
return {'level':-1, test_type:0, 'steps':[]}
},
displayResult:function(res_dict){
console.log(res_dict);
var test_type = res_dict.test_type
this.setState({'test_type':test_type})
if (test_type == 0){
this.setState({'level':res_dict.level});
}
this.setState({'steps':res_dict['steps']});
},
render: function(){
return (
React.createElement("div", {className: "result-container"},
React.createElement("div", {className: "result-head"}, React.createElement("span", {className: "area-title area-title-black"}, "Test Type: "), " ", React.createElement("span", null, this.props.testType)),
React.createElement("div", {className: "detail-result"},
React.createElement("div", {className: "result-sum"},
this.state.test_type == 0 ? React.createElement("h3", null, "Level: ", this.state.level) : null
),
this.state.steps.map(function(step){
return React.createElement(StepDisplay, {stepInfo: step})
})
)
)
)
}
});
var StepDisplay = app.StepDisplay = React.createClass({displayName: "StepDisplay",
getInitialState: function(){
return {
is_img_hide:true,
is_modal_show:false,
is_has_image:false
}
},
componentDidMount:function(){
if(this.props.stepInfo.addi){
this.setState({is_has_image:true});
}
},
handleTextClick:function(){
if (this.state.is_has_image){
this.setState({is_img_hide:!this.state.is_img_hide});
}
},
handleShowFullImage:function(event){
event.stopPropagation();
this.setState({is_modal_show:true});
},
handleHideModal(){
this.setState({is_modal_show:false});
},
handleShowModal(){
this.setState({is_modal_show: true});
},
render:function(){
return (
React.createElement("div", {className: "step-brief step-brief-success", onClick: this.handleTextClick},
React.createElement("div", null, React.createElement("span", {className: "step-brief-text"}, this.props.stepInfo.desc)),
React.createElement("div", {hidden: this.state.is_img_hide && !this.state.is_has_image, className: "step-img-block"},
React.createElement("button", {onClick: this.handleShowFullImage, className: "btn btn-primary"}, "Full Image"),
React.createElement("img", {className: "img-responsive img-rounded step-img", src: this.props.stepInfo.addi})
),
this.state.is_modal_show && this.state.is_has_image ? React.createElement(Modal, {handleHideModal: this.handleHideModal, title: "Step Image", content: React.createElement(FullImageArea, {img_src: this.props.stepInfo.addi})}) : null
)
);
}
});
app.UserBtnArea = React.createClass({displayName: "UserBtnArea",
handleLogout:function(){
app.showMsg("Logout");
},
render:function(){
return (
React.createElement("div", {className: "user-op"},
React.createElement("button", {className: "btn btn-user", onClick: this.props.history_action}, "History"),
React.createElement("button", {className: "btn btn-user"}, "Search Task"),
React.createElement("button", {className: "btn btn-user"}, "Change Password"),
React.createElement("button", {className: "btn btn-user", onClick: this.handleLogout}, React.createElement("span", {className: "glyphicon glyphicon-off"}))
)
);
}
});
var FullImageArea = app.FullImageArea = React.createClass({displayName: "FullImageArea",
render:function(){
return(
React.createElement("img", {src: this.props.img_src, className: "img-responsive"})
);
}
});
var TaskItem = app.TaskItem = React.createClass({displayName: "TaskItem",
render:function(){
return (
React.createElement("div", {className: "list-item"},
React.createElement("span", null, "Task ID:"), this.props.task_id
)
);
}
});
var TaskList = app.TaskList = React.createClass({displayName: "TaskList",
render:function(){
return (
React.createElement("div", {className: "task-list"},
React.createElement("h2", null, "History Tasks"),
React.createElement("div", {className: "list-content"},
this.props.tasks.map(function(task_id){
return React.createElement(TaskItem, {task_id: task_id})
})
)
)
);
}
});
var HistoryViewer = app.HistoryViewer = React.createClass({displayName: "HistoryViewer",
getInitialState:function(){
return {tasks:[]};
},
componentDidMount:function(){
var postData = {
token:$.cookie('fhir_token')
};
var self = this;
console.log(postData);
$.ajax({
url:'http://localhost:8000/home/history',
type:'POST',
data:JSON.stringify(postData),
dataType:'json',
cache:false,
success:function(data){
if( data.isSuccessful ){
self.setState({tasks:data.tasks});
}
}
});
},
render:function(){
return (
React.createElement("div", {className: "history-area"},
React.createElement(TaskList, {tasks: this.state.tasks}),
React.createElement(ResultDisplay, null)
)
);
}
});
var Modal = app.Modal = React.createClass({displayName: "Modal",
componentDidMount(){
$(ReactDOM.findDOMNode(this)).modal('show');
$(ReactDOM.findDOMNode(this)).on('hidden.bs.modal', this.props.handleHideModal);
},
render:function(){
return (
React.createElement("div", {className: "modal modal-wide fade"},
React.createElement("div", {className: "modal-dialog"},
React.createElement("div", {className: "modal-content"},
React.createElement("div", {className: "modal-header"},
React.createElement("button", {type: "button", className: "close", "data-dismiss": "modal", "aria-label": "Close"}, React.createElement("span", {"aria-hidden": "true"}, "×")),
React.createElement("h4", {className: "modal-title"}, this.props.title)
),
React.createElement("div", {className: "modal-body"},
this.props.content
),
React.createElement("div", {className: "modal-footer text-center"},
React.createElement("button", {className: "btn btn-primary center-block", "data-dismiss": "modal"}, "Close")
)
)
)
)
);
}
});
})();
| mit |
GoZOo/Drupaloscopy | hashs-database/hashs/core___assets___vendor___ckeditor___plugins___a11yhelp___dialogs___lang___fo.js | 3211 | 8.0.0-beta16:b0059dc8606caba3ed932149b662b2be1bd6b7bf013b663a769ea5f99ca6830b
8.0.0-rc1:b0059dc8606caba3ed932149b662b2be1bd6b7bf013b663a769ea5f99ca6830b
8.0.0-rc2:b0059dc8606caba3ed932149b662b2be1bd6b7bf013b663a769ea5f99ca6830b
8.0.0-rc3:b0059dc8606caba3ed932149b662b2be1bd6b7bf013b663a769ea5f99ca6830b
8.0.0-rc4:b0059dc8606caba3ed932149b662b2be1bd6b7bf013b663a769ea5f99ca6830b
8.0.1:b0059dc8606caba3ed932149b662b2be1bd6b7bf013b663a769ea5f99ca6830b
8.0.2:b0059dc8606caba3ed932149b662b2be1bd6b7bf013b663a769ea5f99ca6830b
8.0.3:b0059dc8606caba3ed932149b662b2be1bd6b7bf013b663a769ea5f99ca6830b
8.0.4:b0059dc8606caba3ed932149b662b2be1bd6b7bf013b663a769ea5f99ca6830b
8.0.5:b0059dc8606caba3ed932149b662b2be1bd6b7bf013b663a769ea5f99ca6830b
8.0.6:b0059dc8606caba3ed932149b662b2be1bd6b7bf013b663a769ea5f99ca6830b
8.1.0-beta1:b0059dc8606caba3ed932149b662b2be1bd6b7bf013b663a769ea5f99ca6830b
8.1.0-beta2:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.1.0-rc1:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.1.1:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.1.2:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.1.3:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.1.4:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.1.5:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.1.6:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.1.7:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.1.8:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.1.9:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.1.10:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.2.0-beta1:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.2.0-beta2:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.2.0-beta3:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.2.0-rc1:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.2.0-rc2:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.2.1:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.2.2:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.2.3:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.2.4:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.2.5:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.2.6:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.3.0-alpha1:d4118a82bb1d1ff872add2b12fcbbfb71a95b288925ea4ddb60929ebaaac580c
8.3.0-beta1:be2b07337e9a2c422f7ce092a198339e40edf574298dc5990b2fd221378eebef
8.3.0-rc1:be2b07337e9a2c422f7ce092a198339e40edf574298dc5990b2fd221378eebef
8.2.7:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.3.0-rc2:be2b07337e9a2c422f7ce092a198339e40edf574298dc5990b2fd221378eebef
8.0.0:b0059dc8606caba3ed932149b662b2be1bd6b7bf013b663a769ea5f99ca6830b
8.1.0:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.2.0:005a23ed423d0cffedb903bf01dcd4d9a29f1f267f77837cfa0f522d728cba15
8.3.0:be2b07337e9a2c422f7ce092a198339e40edf574298dc5990b2fd221378eebef
| mit |
akrherz/iem | htdocs/plotting/auto/scripts100/p135.py | 7105 | """Accumuldated days"""
import datetime
from pandas.io.sql import read_sql
from pyiem.plot import figure_axes
from pyiem.util import get_autoplot_context, get_dbconn
from pyiem.exceptions import NoDataFound
PDICT = {
"high_above": "High Temperature At or Above",
"high_below": "High Temperature Below",
"low_above": "Low Temperature At or Above",
"low_below": "Low Temperature Below",
}
PDICT2 = {"jan1": "January 1", "jul1": "July 1"}
def get_description():
"""Return a dict describing how to call this plotter"""
desc = {}
desc["data"] = True
desc["cache"] = 86400
desc[
"description"
] = """This plot displays the accumulated number of days
that the high or low temperature was above or below some threshold.
"""
desc["arguments"] = [
dict(
type="station",
name="station",
default="IATDSM",
label="Select Station:",
network="IACLIMATE",
),
dict(
type="select",
name="var",
default="high_above",
label="Which Metric",
options=PDICT,
),
dict(type="int", name="threshold", default=32, label="Threshold (F)"),
dict(
type="select",
name="split",
default="jan1",
options=PDICT2,
label="Where to split the year?",
),
dict(
type="year",
name="year",
default=datetime.date.today().year,
label="Year to Highlight in Chart",
),
]
return desc
def highcharts(fdict):
"""Highcharts Output"""
ctx = get_autoplot_context(fdict, get_description())
station = ctx["station"]
varname = ctx["var"]
df = get_data(ctx)
j = {}
j["tooltip"] = {
"shared": True,
"headerFormat": (
'<span style="font-size: 10px">{point.key: %b %e}</span><br/>'
),
}
j["title"] = {
"text": "%s [%s] %s %sF"
% (
ctx["_nt"].sts[station]["name"],
station,
PDICT[varname],
int(fdict.get("threshold", 32)),
)
}
j["yAxis"] = {"title": {"text": "Accumulated Days"}, "startOnTick": False}
j["xAxis"] = {
"type": "datetime",
"dateTimeLabelFormats": { # don't display the dummy year
"month": "%e. %b",
"year": "%b",
},
"title": {"text": "Date"},
}
j["chart"] = {"zoomType": "xy", "type": "line"}
avgs = []
ranges = []
thisyear = []
for doy, row in df.iterrows():
ts = datetime.date(2001, 1, 1) + datetime.timedelta(days=(doy - 1))
ticks = (ts - datetime.date(1970, 1, 1)).total_seconds() * 1000.0
avgs.append([ticks, row["avg"]])
ranges.append([ticks, row["min"], row["max"]])
if row["thisyear"] >= 0:
thisyear.append([ticks, row["thisyear"]])
lbl = (
"%s" % (fdict.get("year", 2015),)
if fdict.get("split", "jan1") == "jan1"
else "%s - %s"
% (int(fdict.get("year", 2015)) - 1, int(fdict.get("year", 2015)))
)
j["series"] = [
{
"name": "Average",
"data": avgs,
"zIndex": 1,
"tooltip": {"valueDecimals": 2},
"marker": {
"fillColor": "white",
"lineWidth": 2,
"lineColor": "red",
},
},
{
"name": lbl,
"data": thisyear,
"zIndex": 1,
"marker": {
"fillColor": "blue",
"lineWidth": 2,
"lineColor": "green",
},
},
{
"name": "Range",
"data": ranges,
"type": "arearange",
"lineWidth": 0,
"linkedTo": ":previous",
"color": "tan",
"fillOpacity": 0.3,
"zIndex": 0,
},
]
return j
def get_data(ctx):
"""Get the data"""
pgconn = get_dbconn("coop")
station = ctx["station"]
threshold = ctx["threshold"]
varname = ctx["var"]
year = ctx["year"]
split = ctx["split"]
table = f"alldata_{station[:2]}"
days = 0 if split == "jan1" else 183
opp = " < " if varname.find("_below") > 0 else " >= "
col = "high" if varname.find("high") == 0 else "low"
# We need to do some magic to compute the start date, since we don't want
# an incomplete year mucking things up
sts = ctx["_nt"].sts[station]["archive_begin"]
if sts is None:
raise NoDataFound("Unknown station metadata.")
if sts.month > 1:
sts = sts + datetime.timedelta(days=365)
sts = sts.replace(month=1, day=1)
if split == "jul1":
sts = sts.replace(month=7, day=1)
df = read_sql(
f"""
with data as (
select extract(year from day + '%s days'::interval) as season,
extract(doy from day + '%s days'::interval) as doy,
(case when {col} {opp} %s then 1 else 0 end) as hit
from {table}
where station = %s and day >= %s),
agg1 as (
SELECT season, doy,
sum(hit) OVER (PARTITION by season ORDER by doy ASC) from data)
SELECT doy - %s as doy, min(sum), avg(sum), max(sum),
max(case when season = %s then sum else null end) as thisyear from agg1
WHERE doy < 365 GROUP by doy ORDER by doy ASC
""",
pgconn,
params=(days, days, threshold, station, sts, days, year),
index_col=None,
)
df["datestr"] = df["doy"].apply(
lambda x: (
datetime.date(2001, 1, 1) + datetime.timedelta(days=x)
).strftime("%-d %b")
)
df = df.set_index("doy")
return df
def plotter(fdict):
"""Go"""
ctx = get_autoplot_context(fdict, get_description())
station = ctx["station"]
threshold = ctx["threshold"]
varname = ctx["var"]
year = ctx["year"]
df = get_data(ctx)
if df.empty:
raise NoDataFound("Error, no results returned!")
title = ("%s [%s]\n" r"%s %.0f$^\circ$F") % (
ctx["_nt"].sts[station]["name"],
station,
PDICT[varname],
threshold,
)
(fig, ax) = figure_axes(title=title, apctx=ctx)
ax.plot(df.index.values, df["avg"], c="k", lw=2, label="Average")
ax.plot(df.index.values, df["thisyear"], c="g", lw=2, label=f"{year}")
ax.plot(df.index.values, df["max"], c="r", lw=2, label="Max")
ax.plot(df.index.values, df["min"], c="b", lw=2, label="Min")
ax.legend(ncol=1, loc=2)
xticks = []
xticklabels = []
for x in range(int(df.index.min()) - 1, int(df.index.max()) + 1):
ts = datetime.date(2000, 1, 1) + datetime.timedelta(days=x)
if ts.day == 1:
xticks.append(x)
xticklabels.append(ts.strftime("%b"))
ax.set_xticks(xticks)
ax.set_xticklabels(xticklabels)
ax.grid(True)
ax.set_xlim(int(df.index.min()) - 1, int(df.index.max()) + 1)
ax.set_ylabel("Accumulated Days")
return fig, df
if __name__ == "__main__":
plotter(dict())
| mit |
angularjs-tutorial/movie-trailer-app | app/services/CommentService.js | 407 | /**
* Created by avipokhrel on 6/22/17.
*/
'use strict';
angular.module('myApp')
.factory('CommentService', ['$http', function ($http) {
return {
getbyId: function (id) {
return $http.get('/api/comment/' + id);
},
save: function (commentObj) {
return $http.post('/api/comment/', commentObj);
}
}
}]); | mit |
BaranovNikita/Page-About-Me | src/frontend/components/NoMatchRoutePage/NoMatchRoutePage.js | 851 | import React from 'react';
import { browserHistory } from 'react-router';
import { RaisedButton } from 'material-ui';
import * as styles from './style.pcss';
class NoMatchRoutePage extends React.Component {
static propTypes = {
};
render() {
return (
<div className={`${styles.fof} ${styles.clear}`}>
<h1>404</h1>
<h2>Error ! <span>Page Not Found</span></h2>
<p>For Some Reason The Page You Requested Could Not Be Found On Our Server</p>
<div className={styles.buttons}>
<RaisedButton
onTouchTap={browserHistory.goBack}
className={styles.navButton}
primary
>« Go Back</RaisedButton>
<RaisedButton
onTouchTap={() => browserHistory.push('/')}
className={styles.navButton}
primary
>Go Home »</RaisedButton>
</div>
</div>);
}
}
export default NoMatchRoutePage;
| mit |
elafrikano/HelpDesk | scripts/scriptAddArea.php | 465 | <?php
require ("scriptValidaSession.php");
require ("../clases/area.class.php");
require ("../clases/baseDatos.class.php");
$conexion = new baseDatos();
if ($conexion->connect_errno) {
echo "Fallo la conexion: ".$conexion->connect_error;
}
$zona = new Area();
$zona->setCodigo($_POST['codigo']);
$zona->setNombre($_POST['nombre']);
$zona->addArea($conexion);
$conexion->close();
header("location: ../listArea.php?active=6");
?> | mit |
shogo82148/go-gracedown | gracedown.go | 1913 | // +build go1.8
package gracedown
import (
"context"
"net"
"net/http"
"sync"
"sync/atomic"
"time"
)
// Server provides a graceful equivalent of net/http.Server.
type Server struct {
*http.Server
KillTimeOut time.Duration
mu sync.Mutex
closed int32 // accessed atomically.
doneChan chan struct{}
}
// NewWithServer wraps an existing http.Server.
func NewWithServer(s *http.Server) *Server {
return &Server{
Server: s,
KillTimeOut: 10 * time.Second,
}
}
func (srv *Server) Serve(l net.Listener) error {
err := srv.Server.Serve(l)
// Wait for closing all connections.
if err == http.ErrServerClosed && atomic.LoadInt32(&srv.closed) != 0 {
ch := srv.getDoneChan()
<-ch
return nil
}
return err
}
func (srv *Server) getDoneChan() <-chan struct{} {
srv.mu.Lock()
defer srv.mu.Unlock()
return srv.getDoneChanLocked()
}
func (srv *Server) getDoneChanLocked() chan struct{} {
if srv.doneChan == nil {
srv.doneChan = make(chan struct{})
}
return srv.doneChan
}
func (srv *Server) closeDoneChanLocked() {
ch := srv.getDoneChanLocked()
select {
case <-ch:
// Already closed. Don't close again.
default:
// Safe to close here. We're the only closer, guarded
// by s.mu.
close(ch)
}
}
// Close shuts down the default server used by ListenAndServe, ListenAndServeTLS and
// Serve. It returns true if it's the first time Close is called.
func (srv *Server) Close() bool {
if !atomic.CompareAndSwapInt32(&srv.closed, 0, 1) {
return false
}
// immediately closes all connection.
if srv.KillTimeOut == 0 {
srv.Server.Close()
srv.mu.Lock()
defer srv.mu.Unlock()
srv.closeDoneChanLocked()
return true
}
// graceful shutdown
go func() {
ctx, cancel := context.WithTimeout(context.Background(), srv.KillTimeOut)
defer cancel()
srv.Shutdown(ctx)
srv.mu.Lock()
defer srv.mu.Unlock()
srv.closeDoneChanLocked()
}()
return true
}
| mit |
arkanox/MistShowdown | test/simulator/moves/quash.js | 1882 | 'use strict';
const assert = require('./../../assert');
let battle;
describe('Quash', function () {
afterEach(function () {
battle.destroy();
});
it('should cause the target to move last if it has not moved yet', function () {
battle = BattleEngine.Battle.construct('battle-quash-1', 'doublescustomgame');
battle.join('p1', 'Guest 1', 1, [
{species: "Sableye", ability: 'prankster', moves: ['quash']},
{species: "Aggron", ability: 'sturdy', moves: ['earthquake']},
]);
battle.join('p2', 'Guest 2', 1, [
{species: "Arceus", ability: 'multitype', moves: ['voltswitch']},
{species: "Aerodactyl", ability: 'unnerve', moves: ['swift']},
{species: "Rotom", ability: 'levitate', moves: ['thunderbolt']},
]);
battle.commitDecisions(); // Team Preview
battle.choose('p1', 'move 1 2, move 1');
battle.choose('p2', 'move 1 2, move 1');
battle.choose('p2', 'switch 3, pass'); // Volt Switch
assert.strictEqual(battle.log[battle.lastMoveLine].split('|')[3], 'Swift');
});
it('should not cause the target to move again if it has already moved', function () {
battle = BattleEngine.Battle.construct('battle-quash-2', 'doublescustomgame');
battle.join('p1', 'Guest 1', 1, [
{species: "Sableye", ability: 'prankster', moves: ['quash']},
{species: "Aggron", ability: 'sturdy', moves: ['earthquake']},
]);
battle.join('p2', 'Guest 2', 1, [
{species: "Arceus", ability: 'multitype', moves: ['voltswitch']},
{species: "Aerodactyl", ability: 'unnerve', moves: ['extremespeed']},
{species: "Rotom", ability: 'levitate', moves: ['thunderbolt']},
]);
battle.commitDecisions(); // Team Preview
battle.choose('p1', 'move 1 2, move 1');
battle.choose('p2', 'move 1 2, move 1 1');
battle.choose('p2', 'switch 3, pass'); // Volt Switch
assert.notStrictEqual(battle.log[battle.lastMoveLine].split('|')[3], 'Extremespeed');
});
});
| mit |
cytopia/devilbox | .devilbox/www/htdocs/vendor/phpmyadmin-5.0.4/libraries/classes/SysInfo.php | 1651 | <?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Library for extracting information about system memory and cpu.
* Currently supports all Windows and Linux platforms
*
* This code is based on the OS Classes from the phpsysinfo project
* (https://phpsysinfo.github.io/phpsysinfo/)
*
* @package PhpMyAdmin-sysinfo
*/
declare(strict_types=1);
namespace PhpMyAdmin;
use PhpMyAdmin\SysInfoBase;
/**
* PhpMyAdmin\SysInfo class
*
* @package PhpMyAdmin
*/
class SysInfo
{
public const MEMORY_REGEXP = '/^(MemTotal|MemFree|Cached|Buffers|SwapCached|SwapTotal|SwapFree):\s+(.*)\s*kB/im';
/**
* Returns OS type used for sysinfo class
*
* @param string $php_os PHP_OS constant
*
* @return string
*/
public static function getOs($php_os = PHP_OS)
{
// look for common UNIX-like systems
$unix_like = [
'FreeBSD',
'DragonFly',
];
if (in_array($php_os, $unix_like)) {
$php_os = 'Linux';
}
return ucfirst($php_os);
}
/**
* Gets sysinfo class mathing current OS
*
* @return SysInfoBase sysinfo class
*/
public static function get()
{
$php_os = self::getOs();
$supported = [
'Linux',
'WINNT',
'SunOS',
];
if (in_array($php_os, $supported)) {
$class_name = 'PhpMyAdmin\SysInfo' . $php_os;
/** @var SysInfoBase $ret */
$ret = new $class_name();
if ($ret->supported()) {
return $ret;
}
}
return new SysInfoBase();
}
}
| mit |
FilipPaluch/SimpleDataGenerator | Source/SimpleDataGenerator.Core/Mapping/Implementations/PropertyConfiguration.cs | 1347 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Ploeh.AutoFixture.Kernel;
using SimpleDataGenerator.Core.Customization.Specimens;
using SimpleDataGenerator.Core.Mapping.Interfaces;
namespace SimpleDataGenerator.Core.Mapping.Implementations
{
public class PropertyConfiguration<TProperty> : IPropertyConfiguration<TProperty>
{
protected PropertyInfo SelectedProperty { get; private set; }
private ISpecimenBuilder _customSpecimen;
public ISpecimenBuilder CustomSpecimen
{
get { return _customSpecimen; }
}
public PropertyConfiguration(PropertyInfo propertyInfo)
{
SelectedProperty = propertyInfo;
}
protected void AddCustomSpecimen(ISpecimenBuilder specimenBuilder)
{
_customSpecimen = specimenBuilder;
}
public IPropertyConfiguration<TProperty> WithConstValue(TProperty value)
{
AddCustomSpecimen(new ConstValueSpecimenBuilder(SelectedProperty, value));
return this;
}
public IPropertyConfiguration<TProperty> IsEmpty()
{
AddCustomSpecimen(new EmtpySpecimenBuilder(SelectedProperty));
return this;
}
}
}
| mit |
brightmarch/major-api | src/MajorApi/AppBundle/Tests/Controller/WebConnectionStripeControllerTest.php | 620 | <?php
namespace MajorApi\AppBundle\Tests\Controller;
use MajorApi\AppBundle\Tests\Controller\WebTestCase;
/**
* @group FunctionalTests
* @group WebTests
*/
class WebConnectionStripeControllerTest extends WebTestCase
{
public function testConnectingWithStripeRequiresCodeParameter()
{
$client = static::createClient();
$crawler = $client->request('GET', '/connect-with/stripe/connect');
$crawler = $client->followRedirect();
$message = "Sorry, the connection with Stripe could not be made successfully.";
$this->assertContains($message, $crawler->text());
}
}
| mit |
K-Phoen/Random-Stuff-Generator | app/config/config.php | 1341 | <?php
require_once __DIR__.'/../../vendor/autoload.php';
$app = new Silex\Application();
$app->register(new Silex\Provider\SerializerServiceProvider());
$app->register(new Silex\Provider\TwigServiceProvider(), array(
'twig.path' => __DIR__.'/../views',
));
$app->register(new Silex\Provider\ServiceControllerServiceProvider());
$app->register(new KPhoen\Provider\FakerServiceProvider('\RandomStuff\Faker\Factory'));
$app->register(new Silex\Provider\UrlGeneratorServiceProvider());
$app->register(new Knp\Provider\ConsoleServiceProvider(), array(
'console.name' => 'RandomStuffGenerator',
'console.version' => '1.0.0',
'console.project_directory' => __DIR__.'/..'
));
// Debug?
$app['debug'] = 'dev' === getenv('APPLICATION_ENV') || (!empty($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] === '10.0.2.2');
if ($app['debug']) {
$app->register(new Silex\Provider\WebProfilerServiceProvider(), array(
'profiler.cache_dir' => __DIR__.'/../cache/profiler',
'profiler.mount_prefix' => '/_profiler', // this is the default
));
}
// parameters
$app['flickr.api_key'] = 'your_api_key';
$app['flickr.api_secret'] = 'your_secret';
$app['avatar.directory'] = __DIR__ . '/../../web/avatars';
$app['avatar.thumb.directory'] = __DIR__ . '/../../web/avatars/thumbs';
return $app;
| mit |
wix/wix-style-react | packages/wix-style-react/src/AutoCompleteWithLabel/AutoCompleteWithLabel.js | 6071 | import React from 'react';
import PropTypes from 'prop-types';
import StatusAlertSmall from 'wix-ui-icons-common/StatusAlertSmall';
import Input from '../Input';
import LabelledElement from '../LabelledElement';
import Text from '../Text';
import InputWithOptions from '../InputWithOptions';
import { classes } from './AutoCompleteWithLabel.st.css';
import dataHooks from './dataHooks';
import { optionValidator } from '../DropdownLayout/DropdownLayout';
class AutoCompleteWithLabel extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
value: props.value || '',
isEditing: false,
};
}
static displayName = 'AutoCompleteWithLabel';
static propTypes = {
/** Applied as data-hook HTML attribute that can be used to create driver in testing */
dataHook: PropTypes.string,
/** label to appear in input */
label: PropTypes.string.isRequired,
/** options to appear in dropdown */
options: PropTypes.arrayOf(optionValidator).isRequired,
/** add suffix to input */
suffix: PropTypes.arrayOf(PropTypes.element),
/** input status - error, warning or loading */
status: PropTypes.oneOf(['error', 'warning', 'loading']),
/** JSX element that appears upon error */
statusMessage: PropTypes.node,
/** Standard input onFocus callback */
onFocus: PropTypes.func,
/** Standard input onBlur callback */
onBlur: PropTypes.func,
/** Standard input onChange callback */
onChange: PropTypes.func,
/** Used to reference element data when a form is submitted. */
name: PropTypes.string,
/** Specifies the type of <input> element to display.default is text. */
type: PropTypes.string,
/** Used to define a string that labels the current element in case where a text label is not visible on the screen. */
ariaLabel: PropTypes.string,
/** Standard React Input autoFocus (focus the element on mount) */
autoFocus: PropTypes.bool,
/** Sets value of autocomplete attribute (consult the [HTML spec](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-autocomplete) for possible values */
autocomplete: PropTypes.string,
/** when set to true this component is disabled */
disabled: PropTypes.bool,
/** A single CSS class name to be passed to the Input element. */
className: PropTypes.string,
/** Input max length */
maxLength: PropTypes.number,
/** Placeholder to display */
placeholder: PropTypes.string,
/** Callback function called whenever the user selects a different option in the list */
onSelect: PropTypes.func,
/** Indicates whether to render using the native select element */
native: PropTypes.bool,
/** Value of rendered child input */
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/** Set the max height of the dropdownLayout in pixels */
maxHeightPixels: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};
static defaultProps = {
...Input.defaultProps,
label: '',
options: [],
};
onSelect = option => {
const { value } = option;
this.setState({
value,
});
this.props.onSelect(option);
this.setState({ isEditing: false });
};
onChange = event => {
const { value } = event.target;
this.setState({ value, isEditing: true });
this.props.onChange && this.props.onChange(event);
};
_isInputControlled = () => typeof this.props.value !== 'undefined';
render() {
const {
label,
dataHook,
options,
status,
suffix,
statusMessage,
onFocus,
name,
type,
ariaLabel,
autoFocus,
autocomplete,
disabled,
className,
maxLength,
placeholder,
native,
onBlur,
maxHeightPixels,
} = this.props;
const { value } = this._isInputControlled() ? this.props : this.state;
const predicate = this.state.isEditing
? option => option.value.toLowerCase().includes(value.toLowerCase())
: () => true;
const filteredOptions = options.filter(predicate);
const suffixContainer = suffix
? suffix.map((item, index) => {
return <div className={classes.suffix} key={`${dataHook}-${index}`}>{item}</div>;
})
: [];
return (
<div data-hook={dataHook}>
<LabelledElement
label={label}
dataHook={dataHooks.labelledElement}
value={value}
>
<InputWithOptions
onChange={this.onChange}
onSelect={this.onSelect}
dataHook={dataHooks.inputWithOptions}
hideStatusSuffix
onFocus={onFocus}
onBlur={onBlur}
size={'large'}
inputElement={
<Input
name={name}
type={type}
ariaLabel={ariaLabel}
autoFocus={autoFocus}
autocomplete={autocomplete}
disabled={disabled}
maxLength={maxLength}
placeholder={placeholder}
dataHook={dataHooks.inputWithLabel}
value={value}
className={className}
suffix={suffixContainer}
status={status}
/>
}
options={filteredOptions}
native={native}
maxHeightPixels={maxHeightPixels}
/>
</LabelledElement>
{status === Input.StatusError && statusMessage && (
<Text
skin="error"
weight="normal"
size="small"
className={classes.statusMessage}
>
<span className={classes.statusMessageIcon}>
<StatusAlertSmall />
</span>
<span
data-hook={dataHooks.errorMessage}
className={classes.errorMessageContent}
>
{statusMessage}
</span>
</Text>
)}
</div>
);
}
}
export default AutoCompleteWithLabel;
| mit |
miter-framework/miter | src/decorators/orm/associations/belongs-to.decorator.ts | 1652 | import { StaticModelT, ModelT } from '../../../core/model';
import { ForeignModelSource } from '../../../metadata/orm/associations/association';
import { ModelBelongsToAssociationsSym, BelongsToMetadata, BelongsToMetadataSym } from '../../../metadata/orm/associations/belongs-to';
function isStaticModelT(test: any): test is StaticModelT<ModelT<any>> {
return test && !!(<any>test).db;
}
function isForeignModelSource(test: any): test is ForeignModelSource {
return test && (isStaticModelT(test) || !!(<any>test).modelName || !!(<any>test).tableName || typeof test === 'function');
}
export function BelongsTo(propMeta?: BelongsToMetadata | ForeignModelSource) {
let meta: BelongsToMetadata = {};
if (isForeignModelSource(propMeta)) meta = { foreignModel: propMeta };
else if (propMeta) meta = propMeta;
return function(model: any, propertyName: string) {
if (!isForeignModelSource(meta.foreignModel)) {
meta.foreignModel = Reflect.getMetadata('design:type', model, propertyName);
if (<any>meta.foreignModel === Object) meta.foreignModel = undefined;
else if (!isStaticModelT(meta.foreignModel)) throw new Error(`Cannot infer relation type for belongs-to association ${model.name || model}.${propertyName}.`);
}
meta.as = propertyName;
let props: string[] = Reflect.getOwnMetadata(ModelBelongsToAssociationsSym, model) || [];
props.push(propertyName);
Reflect.defineMetadata(ModelBelongsToAssociationsSym, props, model);
Reflect.defineMetadata(BelongsToMetadataSym, meta, model, propertyName);
}
}
| mit |
tomp2p/TomP2P.NET | TomP2P/TomP2P.Tests/Extensions/InteropRandomTest.cs | 1403 | using System;
using NUnit.Framework;
using TomP2P.Extensions;
namespace TomP2P.Tests.Extensions
{
[TestFixture]
public class InteropRandomTest
{
[Test]
public void TestSeed()
{
// create a random seed
var r = new Random();
var seed = (ulong)r.Next();
int tests = 20;
var randoms = new InteropRandom[tests];
var results = new int[tests];
for (int i = 0; i < tests; i++)
{
randoms[i] = new InteropRandom(seed);
results[i] = randoms[i].NextInt(1000);
if (i > 0)
{
Assert.AreEqual(results[i], results[i - 1]);
}
}
}
[Test]
public void TestInteropSeed()
{
// use the same seed as in Java
const int seed = 1234567890;
var random = new InteropRandom(seed);
var result1 = random.NextInt(1000);
var result2 = random.NextInt(500);
var result3 = random.NextInt(10);
// requires same results as in Java
// result1 is 677
// result2 is 242
// result3 is 1
Assert.AreEqual(result1, 677);
Assert.AreEqual(result2, 242);
Assert.AreEqual(result3, 1);
}
}
}
| mit |
dorayaki4369/CutImageFromVideo | CutImageFromVideo/Properties/Annotations1.cs | 41188 | /* MIT License
Copyright (c) 2016 JetBrains http://www.jetbrains.com
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. */
using System;
#pragma warning disable 1591
// ReSharper disable UnusedMember.Global
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable IntroduceOptionalParameters.Global
// ReSharper disable MemberCanBeProtected.Global
// ReSharper disable InconsistentNaming
namespace CutImageFromVideo.Annotations
{
/// <summary>
/// Indicates that the value of the marked element could be <c>null</c> sometimes,
/// so the check for <c>null</c> is necessary before its usage.
/// </summary>
/// <example><code>
/// [CanBeNull] object Test() => null;
///
/// void UseTest() {
/// var p = Test();
/// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException'
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event |
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)]
public sealed class CanBeNullAttribute : Attribute { }
/// <summary>
/// Indicates that the value of the marked element could never be <c>null</c>.
/// </summary>
/// <example><code>
/// [NotNull] object Foo() {
/// return null; // Warning: Possible 'null' assignment
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event |
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)]
public sealed class NotNullAttribute : Attribute { }
/// <summary>
/// Can be appplied to symbols of types derived from IEnumerable as well as to symbols of Task
/// and Lazy classes to indicate that the value of a collection item, of the Task.Result property
/// or of the Lazy.Value property can never be null.
/// </summary>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field)]
public sealed class ItemNotNullAttribute : Attribute { }
/// <summary>
/// Can be appplied to symbols of types derived from IEnumerable as well as to symbols of Task
/// and Lazy classes to indicate that the value of a collection item, of the Task.Result property
/// or of the Lazy.Value property can be null.
/// </summary>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field)]
public sealed class ItemCanBeNullAttribute : Attribute { }
/// <summary>
/// Indicates that the marked method builds string by format pattern and (optional) arguments.
/// Parameter, which contains format string, should be given in constructor. The format string
/// should be in <see cref="string.Format(IFormatProvider,string,object[])"/>-like form.
/// </summary>
/// <example><code>
/// [StringFormatMethod("message")]
/// void ShowError(string message, params object[] args) { /* do something */ }
///
/// void Foo() {
/// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Constructor | AttributeTargets.Method |
AttributeTargets.Property | AttributeTargets.Delegate)]
public sealed class StringFormatMethodAttribute : Attribute
{
/// <param name="formatParameterName">
/// Specifies which parameter of an annotated method should be treated as format-string
/// </param>
public StringFormatMethodAttribute([NotNull] string formatParameterName)
{
FormatParameterName = formatParameterName;
}
[NotNull] public string FormatParameterName { get; private set; }
}
/// <summary>
/// For a parameter that is expected to be one of the limited set of values.
/// Specify fields of which type should be used as values for this parameter.
/// </summary>
[AttributeUsage(
AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field,
AllowMultiple = true)]
public sealed class ValueProviderAttribute : Attribute
{
public ValueProviderAttribute([NotNull] string name)
{
Name = name;
}
[NotNull] public string Name { get; private set; }
}
/// <summary>
/// Indicates that the function argument should be string literal and match one
/// of the parameters of the caller function. For example, ReSharper annotates
/// the parameter of <see cref="System.ArgumentNullException"/>.
/// </summary>
/// <example><code>
/// void Foo(string param) {
/// if (param == null)
/// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class InvokerParameterNameAttribute : Attribute { }
/// <summary>
/// Indicates that the method is contained in a type that implements
/// <c>System.ComponentModel.INotifyPropertyChanged</c> interface and this method
/// is used to notify that some property value changed.
/// </summary>
/// <remarks>
/// The method should be non-static and conform to one of the supported signatures:
/// <list>
/// <item><c>NotifyChanged(string)</c></item>
/// <item><c>NotifyChanged(params string[])</c></item>
/// <item><c>NotifyChanged{T}(Expression{Func{T}})</c></item>
/// <item><c>NotifyChanged{T,U}(Expression{Func{T,U}})</c></item>
/// <item><c>SetProperty{T}(ref T, T, string)</c></item>
/// </list>
/// </remarks>
/// <example><code>
/// public class Foo : INotifyPropertyChanged {
/// public event PropertyChangedEventHandler PropertyChanged;
///
/// [NotifyPropertyChangedInvocator]
/// protected virtual void NotifyChanged(string propertyName) { ... }
///
/// string _name;
///
/// public string Name {
/// get { return _name; }
/// set { _name = value; NotifyChanged("LastName"); /* Warning */ }
/// }
/// }
/// </code>
/// Examples of generated notifications:
/// <list>
/// <item><c>NotifyChanged("Property")</c></item>
/// <item><c>NotifyChanged(() => Property)</c></item>
/// <item><c>NotifyChanged((VM x) => x.Property)</c></item>
/// <item><c>SetProperty(ref myField, value, "Property")</c></item>
/// </list>
/// </example>
[AttributeUsage(AttributeTargets.Method)]
public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute
{
public NotifyPropertyChangedInvocatorAttribute() { }
public NotifyPropertyChangedInvocatorAttribute([NotNull] string parameterName)
{
ParameterName = parameterName;
}
[CanBeNull] public string ParameterName { get; private set; }
}
/// <summary>
/// Describes dependency between method input and output.
/// </summary>
/// <syntax>
/// <p>Function Definition Table syntax:</p>
/// <list>
/// <item>FDT ::= FDTRow [;FDTRow]*</item>
/// <item>FDTRow ::= Input => Output | Output <= Input</item>
/// <item>Input ::= ParameterName: Value [, Input]*</item>
/// <item>Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value}</item>
/// <item>Value ::= true | false | null | notnull | canbenull</item>
/// </list>
/// If method has single input parameter, it's name could be omitted.<br/>
/// Using <c>halt</c> (or <c>void</c>/<c>nothing</c>, which is the same) for method output
/// means that the methos doesn't return normally (throws or terminates the process).<br/>
/// Value <c>canbenull</c> is only applicable for output parameters.<br/>
/// You can use multiple <c>[ContractAnnotation]</c> for each FDT row, or use single attribute
/// with rows separated by semicolon. There is no notion of order rows, all rows are checked
/// for applicability and applied per each program state tracked by R# analysis.<br/>
/// </syntax>
/// <examples><list>
/// <item><code>
/// [ContractAnnotation("=> halt")]
/// public void TerminationMethod()
/// </code></item>
/// <item><code>
/// [ContractAnnotation("halt <= condition: false")]
/// public void Assert(bool condition, string text) // regular assertion method
/// </code></item>
/// <item><code>
/// [ContractAnnotation("s:null => true")]
/// public bool IsNullOrEmpty(string s) // string.IsNullOrEmpty()
/// </code></item>
/// <item><code>
/// // A method that returns null if the parameter is null,
/// // and not null if the parameter is not null
/// [ContractAnnotation("null => null; notnull => notnull")]
/// public object Transform(object data)
/// </code></item>
/// <item><code>
/// [ContractAnnotation("=> true, result: notnull; => false, result: null")]
/// public bool TryParse(string s, out Person result)
/// </code></item>
/// </list></examples>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public sealed class ContractAnnotationAttribute : Attribute
{
public ContractAnnotationAttribute([NotNull] string contract)
: this(contract, false) { }
public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates)
{
Contract = contract;
ForceFullStates = forceFullStates;
}
[NotNull] public string Contract { get; private set; }
public bool ForceFullStates { get; private set; }
}
/// <summary>
/// Indicates that marked element should be localized or not.
/// </summary>
/// <example><code>
/// [LocalizationRequiredAttribute(true)]
/// class Foo {
/// string str = "my string"; // Warning: Localizable string
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.All)]
public sealed class LocalizationRequiredAttribute : Attribute
{
public LocalizationRequiredAttribute() : this(true) { }
public LocalizationRequiredAttribute(bool required)
{
Required = required;
}
public bool Required { get; private set; }
}
/// <summary>
/// Indicates that the value of the marked type (or its derivatives)
/// cannot be compared using '==' or '!=' operators and <c>Equals()</c>
/// should be used instead. However, using '==' or '!=' for comparison
/// with <c>null</c> is always permitted.
/// </summary>
/// <example><code>
/// [CannotApplyEqualityOperator]
/// class NoEquality { }
///
/// class UsesNoEquality {
/// void Test() {
/// var ca1 = new NoEquality();
/// var ca2 = new NoEquality();
/// if (ca1 != null) { // OK
/// bool condition = ca1 == ca2; // Warning
/// }
/// }
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct)]
public sealed class CannotApplyEqualityOperatorAttribute : Attribute { }
/// <summary>
/// When applied to a target attribute, specifies a requirement for any type marked
/// with the target attribute to implement or inherit specific type or types.
/// </summary>
/// <example><code>
/// [BaseTypeRequired(typeof(IComponent)] // Specify requirement
/// class ComponentAttribute : Attribute { }
///
/// [Component] // ComponentAttribute requires implementing IComponent interface
/// class MyComponent : IComponent { }
/// </code></example>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
[BaseTypeRequired(typeof(Attribute))]
public sealed class BaseTypeRequiredAttribute : Attribute
{
public BaseTypeRequiredAttribute([NotNull] Type baseType)
{
BaseType = baseType;
}
[NotNull] public Type BaseType { get; private set; }
}
/// <summary>
/// Indicates that the marked symbol is used implicitly (e.g. via reflection, in external library),
/// so this symbol will not be marked as unused (as well as by other usage inspections).
/// </summary>
[AttributeUsage(AttributeTargets.All)]
public sealed class UsedImplicitlyAttribute : Attribute
{
public UsedImplicitlyAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { }
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default) { }
public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags) { }
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
public ImplicitUseKindFlags UseKindFlags { get; private set; }
public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
/// <summary>
/// Should be used on attributes and causes ReSharper to not mark symbols marked with such attributes
/// as unused (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.GenericParameter)]
public sealed class MeansImplicitUseAttribute : Attribute
{
public MeansImplicitUseAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { }
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default) { }
public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags) { }
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
[UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; private set; }
[UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
[Flags]
public enum ImplicitUseKindFlags
{
Default = Access | Assign | InstantiatedWithFixedConstructorSignature,
/// <summary>Only entity marked with attribute considered used.</summary>
Access = 1,
/// <summary>Indicates implicit assignment to a member.</summary>
Assign = 2,
/// <summary>
/// Indicates implicit instantiation of a type with fixed constructor signature.
/// That means any unused constructor parameters won't be reported as such.
/// </summary>
InstantiatedWithFixedConstructorSignature = 4,
/// <summary>Indicates implicit instantiation of a type.</summary>
InstantiatedNoFixedConstructorSignature = 8,
}
/// <summary>
/// Specify what is considered used implicitly when marked
/// with <see cref="MeansImplicitUseAttribute"/> or <see cref="UsedImplicitlyAttribute"/>.
/// </summary>
[Flags]
public enum ImplicitUseTargetFlags
{
Default = Itself,
Itself = 1,
/// <summary>Members of entity marked with attribute are considered used.</summary>
Members = 2,
/// <summary>Entity marked with attribute and all its members considered used.</summary>
WithMembers = Itself | Members
}
/// <summary>
/// This attribute is intended to mark publicly available API
/// which should not be removed and so is treated as used.
/// </summary>
[MeansImplicitUse(ImplicitUseTargetFlags.WithMembers)]
public sealed class PublicAPIAttribute : Attribute
{
public PublicAPIAttribute() { }
public PublicAPIAttribute([NotNull] string comment)
{
Comment = comment;
}
[CanBeNull] public string Comment { get; private set; }
}
/// <summary>
/// Tells code analysis engine if the parameter is completely handled when the invoked method is on stack.
/// If the parameter is a delegate, indicates that delegate is executed while the method is executed.
/// If the parameter is an enumerable, indicates that it is enumerated while the method is executed.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class InstantHandleAttribute : Attribute { }
/// <summary>
/// Indicates that a method does not make any observable state changes.
/// The same as <c>System.Diagnostics.Contracts.PureAttribute</c>.
/// </summary>
/// <example><code>
/// [Pure] int Multiply(int x, int y) => x * y;
///
/// void M() {
/// Multiply(123, 42); // Waring: Return value of pure method is not used
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Method)]
public sealed class PureAttribute : Attribute { }
/// <summary>
/// Indicates that the return value of method invocation must be used.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class MustUseReturnValueAttribute : Attribute
{
public MustUseReturnValueAttribute() { }
public MustUseReturnValueAttribute([NotNull] string justification)
{
Justification = justification;
}
[CanBeNull] public string Justification { get; private set; }
}
/// <summary>
/// Indicates the type member or parameter of some type, that should be used instead of all other ways
/// to get the value that type. This annotation is useful when you have some "context" value evaluated
/// and stored somewhere, meaning that all other ways to get this value must be consolidated with existing one.
/// </summary>
/// <example><code>
/// class Foo {
/// [ProvidesContext] IBarService _barService = ...;
///
/// void ProcessNode(INode node) {
/// DoSomething(node, node.GetGlobalServices().Bar);
/// // ^ Warning: use value of '_barService' field
/// }
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.Method |
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.GenericParameter)]
public sealed class ProvidesContextAttribute : Attribute { }
/// <summary>
/// Indicates that a parameter is a path to a file or a folder within a web project.
/// Path can be relative or absolute, starting from web root (~).
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class PathReferenceAttribute : Attribute
{
public PathReferenceAttribute() { }
public PathReferenceAttribute([NotNull, PathReference] string basePath)
{
BasePath = basePath;
}
[CanBeNull] public string BasePath { get; private set; }
}
/// <summary>
/// An extension method marked with this attribute is processed by ReSharper code completion
/// as a 'Source Template'. When extension method is completed over some expression, it's source code
/// is automatically expanded like a template at call site.
/// </summary>
/// <remarks>
/// Template method body can contain valid source code and/or special comments starting with '$'.
/// Text inside these comments is added as source code when the template is applied. Template parameters
/// can be used either as additional method parameters or as identifiers wrapped in two '$' signs.
/// Use the <see cref="MacroAttribute"/> attribute to specify macros for parameters.
/// </remarks>
/// <example>
/// In this example, the 'forEach' method is a source template available over all values
/// of enumerable types, producing ordinary C# 'foreach' statement and placing caret inside block:
/// <code>
/// [SourceTemplate]
/// public static void forEach<T>(this IEnumerable<T> xs) {
/// foreach (var x in xs) {
/// //$ $END$
/// }
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Method)]
public sealed class SourceTemplateAttribute : Attribute { }
/// <summary>
/// Allows specifying a macro for a parameter of a <see cref="SourceTemplateAttribute">source template</see>.
/// </summary>
/// <remarks>
/// You can apply the attribute on the whole method or on any of its additional parameters. The macro expression
/// is defined in the <see cref="MacroAttribute.Expression"/> property. When applied on a method, the target
/// template parameter is defined in the <see cref="MacroAttribute.Target"/> property. To apply the macro silently
/// for the parameter, set the <see cref="MacroAttribute.Editable"/> property value = -1.
/// </remarks>
/// <example>
/// Applying the attribute on a source template method:
/// <code>
/// [SourceTemplate, Macro(Target = "item", Expression = "suggestVariableName()")]
/// public static void forEach<T>(this IEnumerable<T> collection) {
/// foreach (var item in collection) {
/// //$ $END$
/// }
/// }
/// </code>
/// Applying the attribute on a template method parameter:
/// <code>
/// [SourceTemplate]
/// public static void something(this Entity x, [Macro(Expression = "guid()", Editable = -1)] string newguid) {
/// /*$ var $x$Id = "$newguid$" + x.ToString();
/// x.DoSomething($x$Id); */
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method, AllowMultiple = true)]
public sealed class MacroAttribute : Attribute
{
/// <summary>
/// Allows specifying a macro that will be executed for a <see cref="SourceTemplateAttribute">source template</see>
/// parameter when the template is expanded.
/// </summary>
[CanBeNull] public string Expression { get; set; }
/// <summary>
/// Allows specifying which occurrence of the target parameter becomes editable when the template is deployed.
/// </summary>
/// <remarks>
/// If the target parameter is used several times in the template, only one occurrence becomes editable;
/// other occurrences are changed synchronously. To specify the zero-based index of the editable occurrence,
/// use values >= 0. To make the parameter non-editable when the template is expanded, use -1.
/// </remarks>>
public int Editable { get; set; }
/// <summary>
/// Identifies the target parameter of a <see cref="SourceTemplateAttribute">source template</see> if the
/// <see cref="MacroAttribute"/> is applied on a template method.
/// </summary>
[CanBeNull] public string Target { get; set; }
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
public sealed class AspMvcAreaMasterLocationFormatAttribute : Attribute
{
public AspMvcAreaMasterLocationFormatAttribute([NotNull] string format)
{
Format = format;
}
[NotNull] public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
public sealed class AspMvcAreaPartialViewLocationFormatAttribute : Attribute
{
public AspMvcAreaPartialViewLocationFormatAttribute([NotNull] string format)
{
Format = format;
}
[NotNull] public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
public sealed class AspMvcAreaViewLocationFormatAttribute : Attribute
{
public AspMvcAreaViewLocationFormatAttribute([NotNull] string format)
{
Format = format;
}
[NotNull] public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
public sealed class AspMvcMasterLocationFormatAttribute : Attribute
{
public AspMvcMasterLocationFormatAttribute([NotNull] string format)
{
Format = format;
}
[NotNull] public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
public sealed class AspMvcPartialViewLocationFormatAttribute : Attribute
{
public AspMvcPartialViewLocationFormatAttribute([NotNull] string format)
{
Format = format;
}
[NotNull] public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
public sealed class AspMvcViewLocationFormatAttribute : Attribute
{
public AspMvcViewLocationFormatAttribute([NotNull] string format)
{
Format = format;
}
[NotNull] public string Format { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC action. If applied to a method, the MVC action name is calculated
/// implicitly from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcActionAttribute : Attribute
{
public AspMvcActionAttribute() { }
public AspMvcActionAttribute([NotNull] string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
[CanBeNull] public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC area.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcAreaAttribute : Attribute
{
public AspMvcAreaAttribute() { }
public AspMvcAreaAttribute([NotNull] string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
[CanBeNull] public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is
/// an MVC controller. If applied to a method, the MVC controller name is calculated
/// implicitly from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcControllerAttribute : Attribute
{
public AspMvcControllerAttribute() { }
public AspMvcControllerAttribute([NotNull] string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
[CanBeNull] public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC Master. Use this attribute
/// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcMasterAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC model type. Use this attribute
/// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, Object)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcModelTypeAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is an MVC
/// partial view. If applied to a method, the MVC partial view name is calculated implicitly
/// from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcPartialViewAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Allows disabling inspections for MVC views within a class or a method.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class AspMvcSuppressViewErrorAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcDisplayTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC editor template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.EditorExtensions.EditorForModel(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcEditorTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC template.
/// Use this attribute for custom wrappers similar to
/// <c>System.ComponentModel.DataAnnotations.UIHintAttribute(System.String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC view component. If applied to a method, the MVC view name is calculated implicitly
/// from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Controller.View(Object)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcViewAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC view component name.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcViewComponentAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC view component view. If applied to a method, the MVC view component view name is default.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcViewComponentViewAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. When applied to a parameter of an attribute,
/// indicates that this parameter is an MVC action name.
/// </summary>
/// <example><code>
/// [ActionName("Foo")]
/// public ActionResult Login(string returnUrl) {
/// ViewBag.ReturnUrl = Url.Action("Foo"); // OK
/// return RedirectToAction("Bar"); // Error: Cannot resolve action
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)]
public sealed class AspMvcActionSelectorAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)]
public sealed class HtmlElementAttributesAttribute : Attribute
{
public HtmlElementAttributesAttribute() { }
public HtmlElementAttributesAttribute([NotNull] string name)
{
Name = name;
}
[CanBeNull] public string Name { get; private set; }
}
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)]
public sealed class HtmlAttributeValueAttribute : Attribute
{
public HtmlAttributeValueAttribute([NotNull] string name)
{
Name = name;
}
[NotNull] public string Name { get; private set; }
}
/// <summary>
/// Razor attribute. Indicates that a parameter or a method is a Razor section.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.WebPages.WebPageBase.RenderSection(String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class RazorSectionAttribute : Attribute { }
/// <summary>
/// Indicates how method, constructor invocation or property access
/// over collection type affects content of the collection.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)]
public sealed class CollectionAccessAttribute : Attribute
{
public CollectionAccessAttribute(CollectionAccessType collectionAccessType)
{
CollectionAccessType = collectionAccessType;
}
public CollectionAccessType CollectionAccessType { get; private set; }
}
[Flags]
public enum CollectionAccessType
{
/// <summary>Method does not use or modify content of the collection.</summary>
None = 0,
/// <summary>Method only reads content of the collection but does not modify it.</summary>
Read = 1,
/// <summary>Method can change content of the collection but does not add new elements.</summary>
ModifyExistingContent = 2,
/// <summary>Method can add new elements to the collection.</summary>
UpdatedContent = ModifyExistingContent | 4
}
/// <summary>
/// Indicates that the marked method is assertion method, i.e. it halts control flow if
/// one of the conditions is satisfied. To set the condition, mark one of the parameters with
/// <see cref="AssertionConditionAttribute"/> attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class AssertionMethodAttribute : Attribute { }
/// <summary>
/// Indicates the condition parameter of the assertion method. The method itself should be
/// marked by <see cref="AssertionMethodAttribute"/> attribute. The mandatory argument of
/// the attribute is the assertion type.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AssertionConditionAttribute : Attribute
{
public AssertionConditionAttribute(AssertionConditionType conditionType)
{
ConditionType = conditionType;
}
public AssertionConditionType ConditionType { get; private set; }
}
/// <summary>
/// Specifies assertion type. If the assertion method argument satisfies the condition,
/// then the execution continues. Otherwise, execution is assumed to be halted.
/// </summary>
public enum AssertionConditionType
{
/// <summary>Marked parameter should be evaluated to true.</summary>
IS_TRUE = 0,
/// <summary>Marked parameter should be evaluated to false.</summary>
IS_FALSE = 1,
/// <summary>Marked parameter should be evaluated to null value.</summary>
IS_NULL = 2,
/// <summary>Marked parameter should be evaluated to not null value.</summary>
IS_NOT_NULL = 3,
}
/// <summary>
/// Indicates that the marked method unconditionally terminates control flow execution.
/// For example, it could unconditionally throw exception.
/// </summary>
[Obsolete("Use [ContractAnnotation('=> halt')] instead")]
[AttributeUsage(AttributeTargets.Method)]
public sealed class TerminatesProgramAttribute : Attribute { }
/// <summary>
/// Indicates that method is pure LINQ method, with postponed enumeration (like Enumerable.Select,
/// .Where). This annotation allows inference of [InstantHandle] annotation for parameters
/// of delegate type by analyzing LINQ method chains.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class LinqTunnelAttribute : Attribute { }
/// <summary>
/// Indicates that IEnumerable, passed as parameter, is not enumerated.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class NoEnumerationAttribute : Attribute { }
/// <summary>
/// Indicates that parameter is regular expression pattern.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class RegexPatternAttribute : Attribute { }
/// <summary>
/// Prevents the Member Reordering feature from tossing members of the marked class.
/// </summary>
/// <remarks>
/// The attribute must be mentioned in your member reordering patterns
/// </remarks>
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.Enum)]
public sealed class NoReorderAttribute : Attribute { }
/// <summary>
/// XAML attribute. Indicates the type that has <c>ItemsSource</c> property and should be treated
/// as <c>ItemsControl</c>-derived type, to enable inner items <c>DataContext</c> type resolve.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public sealed class XamlItemsControlAttribute : Attribute { }
/// <summary>
/// XAML attribute. Indicates the property of some <c>BindingBase</c>-derived type, that
/// is used to bind some item of <c>ItemsControl</c>-derived type. This annotation will
/// enable the <c>DataContext</c> type resolve for XAML bindings for such properties.
/// </summary>
/// <remarks>
/// Property should have the tree ancestor of the <c>ItemsControl</c> type or
/// marked with the <see cref="XamlItemsControlAttribute"/> attribute.
/// </remarks>
[AttributeUsage(AttributeTargets.Property)]
public sealed class XamlItemBindingOfItemsControlAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class AspChildControlTypeAttribute : Attribute
{
public AspChildControlTypeAttribute([NotNull] string tagName, [NotNull] Type controlType)
{
TagName = tagName;
ControlType = controlType;
}
[NotNull] public string TagName { get; private set; }
[NotNull] public Type ControlType { get; private set; }
}
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)]
public sealed class AspDataFieldAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)]
public sealed class AspDataFieldsAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Property)]
public sealed class AspMethodPropertyAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class AspRequiredAttributeAttribute : Attribute
{
public AspRequiredAttributeAttribute([NotNull] string attribute)
{
Attribute = attribute;
}
[NotNull] public string Attribute { get; private set; }
}
[AttributeUsage(AttributeTargets.Property)]
public sealed class AspTypePropertyAttribute : Attribute
{
public bool CreateConstructorReferences { get; private set; }
public AspTypePropertyAttribute(bool createConstructorReferences)
{
CreateConstructorReferences = createConstructorReferences;
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class RazorImportNamespaceAttribute : Attribute
{
public RazorImportNamespaceAttribute([NotNull] string name)
{
Name = name;
}
[NotNull] public string Name { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class RazorInjectionAttribute : Attribute
{
public RazorInjectionAttribute([NotNull] string type, [NotNull] string fieldName)
{
Type = type;
FieldName = fieldName;
}
[NotNull] public string Type { get; private set; }
[NotNull] public string FieldName { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class RazorDirectiveAttribute : Attribute
{
public RazorDirectiveAttribute([NotNull] string directive)
{
Directive = directive;
}
[NotNull] public string Directive { get; private set; }
}
[AttributeUsage(AttributeTargets.Method)]
public sealed class RazorHelperCommonAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Property)]
public sealed class RazorLayoutAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Method)]
public sealed class RazorWriteLiteralMethodAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Method)]
public sealed class RazorWriteMethodAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class RazorWriteMethodParameterAttribute : Attribute { }
} | mit |
wknishio/variable-terminal | src/lanterna/com/googlecode/lanterna/TerminalTextUtils.java | 23537 | /*
* This file is part of lanterna (https://github.com/mabe02/lanterna).
*
* lanterna is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (C) 2010-2020 Martin Berglund
*/
package com.googlecode.lanterna;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import com.googlecode.lanterna.graphics.StyleSet;
import com.googlecode.lanterna.screen.TabBehaviour;
/**
* This class contains a number of utility methods for analyzing characters and strings in a terminal context. The main
* purpose is to make it easier to work with text that may or may not contain double-width text characters, such as CJK
* (Chinese, Japanese, Korean) and other special symbols. This class assumes those are all double-width and in case the
* terminal (-emulator) chooses to draw them (somehow) as single-column then all the calculations in this class will be
* wrong. It seems safe to assume what this class considers double-width really is taking up two columns though.
*
* @author Martin
*/
public class TerminalTextUtils {
private TerminalTextUtils() {
}
/**
* Given a string and an index in that string, returns the ANSI control sequence beginning on this index. If there
* is no control sequence starting there, the method will return null. The returned value is the complete escape
* sequence including the ESC prefix.
* @param string String to scan for control sequences
* @param index Index in the string where the control sequence begins
* @return {@code null} if there was no control sequence starting at the specified index, otherwise the entire
* control sequence
*/
public static String getANSIControlSequenceAt(String string, int index) {
int len = getANSIControlSequenceLength(string, index);
return len == 0 ? null : string.substring(index,index+len);
}
/**
* Given a string and an index in that string, returns the number of characters starting at index that make up
* a complete ANSI control sequence. If there is no control sequence starting there, the method will return 0.
* @param string String to scan for control sequences
* @param index Index in the string where the control sequence begins
* @return {@code 0} if there was no control sequence starting at the specified index, otherwise the length
* of the entire control sequence
*/
public static int getANSIControlSequenceLength(String string, int index) {
int len = 0, restlen = string.length() - index;
if (restlen >= 3) { // Control sequences require a minimum of three characters
char esc = string.charAt(index),
bracket = string.charAt(index+1);
if (esc == 0x1B && bracket == '[') { // escape & open bracket
len = 3; // esc,bracket and (later)terminator.
// digits or semicolons can still precede the terminator:
for (int i = 2; i < restlen; i++) {
char ch = string.charAt(i + index);
// only ascii-digits or semicolons allowed here:
if ( (ch >= '0' && ch <= '9') || ch == ';') {
len++;
} else {
break;
}
}
// if string ends in digits/semicolons, then it's not a sequence.
if (len > restlen) {
len = 0;
}
}
}
return len;
}
/**
* Given a character, is this character considered to be a CJK character?
* Shamelessly stolen from
* <a href="http://stackoverflow.com/questions/1499804/how-can-i-detect-japanese-text-in-a-java-string">StackOverflow</a>
* where it was contributed by user Rakesh N
* @param c Character to test
* @return {@code true} if the character is a CJK character
*
*/
public static boolean isCharCJK(final char c) {
Character.UnicodeBlock unicodeBlock = Character.UnicodeBlock.of(c);
return (unicodeBlock == Character.UnicodeBlock.HIRAGANA)
|| (unicodeBlock == Character.UnicodeBlock.KATAKANA)
|| (unicodeBlock == Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS)
|| (unicodeBlock == Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO)
|| (unicodeBlock == Character.UnicodeBlock.HANGUL_JAMO)
|| (unicodeBlock == Character.UnicodeBlock.HANGUL_SYLLABLES)
|| (unicodeBlock == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS)
|| (unicodeBlock == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A)
|| (unicodeBlock == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B)
|| (unicodeBlock == Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS)
|| (unicodeBlock == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS)
|| (unicodeBlock == Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT)
|| (unicodeBlock == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION)
|| (unicodeBlock == Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS)
|| (unicodeBlock == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS && c < 0xFF61); //The magic number here is the separating index between full-width and half-width
}
/**
* Checks if a character is expected to be taking up two columns if printed to a terminal. This will generally be
* {@code true} for CJK (Chinese, Japanese and Korean) characters.
* @param c Character to test if it's double-width when printed to a terminal
* @return {@code true} if this character is expected to be taking up two columns when printed to the terminal,
* otherwise {@code false}
*/
public static boolean isCharDoubleWidth(final char c) {
return isCharCJK(c);
}
/**
* Checks if a particular character is a control character, in Lanterna this currently means it's 0-31 or 127 in the
* ascii table.
* @param c character to test
* @return {@code true} if the character is a control character, {@code false} otherwise
*/
public static boolean isControlCharacter(char c) {
return c < 32 || c == 127;
}
/**
* Checks if a particular character is printable. This generally means that the code is not a control character that
* isn't able to be printed to the terminal properly. For example, NULL, ENQ, BELL and ESC and all control codes
* that has no proper character associated with it so the behaviour is undefined and depends completely on the
* terminal what happens if you try to print them. However, certain control characters have a particular meaning to
* the terminal and are as such considered printable. In Lanterna, we consider these control characters printable:
* <ul>
* <li>Backspace</li>
* <li>Horizontal Tab</li>
* <li>Line feed</li>
* </ul>
*
* @param c character to test
* @return {@code true} if the character is considered printable, {@code false} otherwise
*/
public static boolean isPrintableCharacter(char c) {
return !isControlCharacter(c) || c == '\t' || c == '\n' || c == '\b';
}
/**
* Given a string, returns how many columns this string would need to occupy in a terminal, taking into account that
* CJK characters takes up two columns.
* @param s String to check length
* @return Number of actual terminal columns the string would occupy
*/
public static int getColumnWidth(String s) {
return getColumnIndex(s, s.length());
}
/**
* Given a string and a character index inside that string, find out what the column index of that character would
* be if printed in a terminal. If the string only contains non-CJK characters then the returned value will be same
* as {@code stringCharacterIndex}, but if there are CJK characters the value will be different due to CJK
* characters taking up two columns in width. If the character at the index in the string is a CJK character itself,
* the returned value will be the index of the left-side of character. The tab character is counted as four spaces.
* @param s String to translate the index from
* @param stringCharacterIndex Index within the string to get the terminal column index of
* @return Index of the character inside the String at {@code stringCharacterIndex} when it has been writted to a
* terminal
* @throws StringIndexOutOfBoundsException if the index given is outside the String length or negative
*/
public static int getColumnIndex(String s, int stringCharacterIndex) throws StringIndexOutOfBoundsException {
return getColumnIndex(s, stringCharacterIndex, TabBehaviour.CONVERT_TO_ONE_SPACE, -1);
}
/**
* Given a string and a character index inside that string, find out what the column index of that character would
* be if printed in a terminal. If the string only contains non-CJK characters then the returned value will be same
* as {@code stringCharacterIndex}, but if there are CJK characters the value will be different due to CJK
* characters taking up two columns in width. If the character at the index in the string is a CJK character itself,
* the returned value will be the index of the left-side of character.
* @param s String to translate the index from
* @param stringCharacterIndex Index within the string to get the terminal column index of
* @param tabBehaviour The behavior to use when encountering the tab character
* @param firstCharacterColumnPosition Where on the screen the first character in the string would be printed, this
* applies only when you have an alignment-based {@link TabBehaviour}
* @return Index of the character inside the String at {@code stringCharacterIndex} when it has been writted to a
* terminal
* @throws StringIndexOutOfBoundsException if the index given is outside the String length or negative
*/
public static int getColumnIndex(String s, int stringCharacterIndex, TabBehaviour tabBehaviour, int firstCharacterColumnPosition) throws StringIndexOutOfBoundsException {
int index = 0;
for(int i = 0; i < stringCharacterIndex; i++) {
if(s.charAt(i) == '\t') {
index += tabBehaviour.getTabReplacement(firstCharacterColumnPosition).length();
}
else {
if (isCharCJK(s.charAt(i))) {
index++;
}
index++;
}
}
return index;
}
/**
* This method does the reverse of getColumnIndex, given a String and imagining it has been printed out to the
* top-left corner of a terminal, in the column specified by {@code columnIndex}, what is the index of that
* character in the string. If the string contains no CJK characters, this will always be the same as
* {@code columnIndex}. If the index specified is the right column of a CJK character, the index is the same as if
* the column was the left column. So calling {@code getStringCharacterIndex("英", 0)} and
* {@code getStringCharacterIndex("英", 1)} will both return 0.
* @param s String to translate the index to
* @param columnIndex Column index of the string written to a terminal
* @return The index in the string of the character in terminal column {@code columnIndex}
*/
public static int getStringCharacterIndex(String s, int columnIndex) {
int index = 0;
int counter = 0;
while(counter < columnIndex) {
if(isCharCJK(s.charAt(index++))) {
counter++;
if(counter == columnIndex) {
return index - 1;
}
}
counter++;
}
return index;
}
/**
* Given a string that may or may not contain CJK characters, returns the substring which will fit inside
* <code>availableColumnSpace</code> columns. This method does not handle special cases like tab or new-line.
* <p>
* Calling this method is the same as calling {@code fitString(string, 0, availableColumnSpace)}.
* @param string The string to fit inside the availableColumnSpace
* @param availableColumnSpace Number of columns to fit the string inside
* @return The whole or part of the input string which will fit inside the supplied availableColumnSpace
*/
public static String fitString(String string, int availableColumnSpace) {
return fitString(string, 0, availableColumnSpace);
}
/**
* Given a string that may or may not contain CJK characters, returns the substring which will fit inside
* <code>availableColumnSpace</code> columns. This method does not handle special cases like tab or new-line.
* <p>
* This overload has a {@code fromColumn} parameter that specified where inside the string to start fitting. Please
* notice that {@code fromColumn} is not a character index inside the string, but a column index as if the string
* has been printed from the left-most side of the terminal. So if the string is "日本語", fromColumn set to 1 will
* not starting counting from the second character ("本") in the string but from the CJK filler character belonging
* to "日". If you want to count from a particular character index inside the string, please pass in a substring
* and use fromColumn set to 0.
* @param string The string to fit inside the availableColumnSpace
* @param fromColumn From what column of the input string to start fitting (see description above!)
* @param availableColumnSpace Number of columns to fit the string inside
* @return The whole or part of the input string which will fit inside the supplied availableColumnSpace
*/
public static String fitString(String string, int fromColumn, int availableColumnSpace) {
if(availableColumnSpace <= 0) {
return "";
}
StringBuilder bob = new StringBuilder();
int column = 0;
int index = 0;
while(index < string.length() && column < fromColumn) {
char c = string.charAt(index++);
column += TerminalTextUtils.isCharCJK(c) ? 2 : 1;
}
if(column > fromColumn) {
bob.append(" ");
availableColumnSpace--;
}
while(availableColumnSpace > 0 && index < string.length()) {
char c = string.charAt(index++);
availableColumnSpace -= TerminalTextUtils.isCharCJK(c) ? 2 : 1;
if(availableColumnSpace < 0) {
bob.append(' ');
}
else {
bob.append(c);
}
}
return bob.toString();
}
/**
* This method will calculate word wrappings given a number of lines of text and how wide the text can be printed.
* The result is a list of new rows where word-wrapping was applied.
* @param maxWidth Maximum number of columns that can be used before word-wrapping is applied, if <= 0 then the
* lines will be returned unchanged
* @param lines Input text
* @return The input text word-wrapped at {@code maxWidth}; this may contain more rows than the input text
*/
public static List<String> getWordWrappedText(int maxWidth, String... lines) {
//Bounds checking
if(maxWidth <= 0) {
return Arrays.asList(lines);
}
List<String> result = new ArrayList<String>();
LinkedList<String> linesToBeWrapped = new LinkedList<String>(Arrays.asList(lines));
while(!linesToBeWrapped.isEmpty()) {
String row = linesToBeWrapped.removeFirst();
int rowWidth = getColumnWidth(row);
if(rowWidth <= maxWidth) {
result.add(row);
}
else {
//Now search in reverse and find the first possible line-break
final int characterIndexMax = getStringCharacterIndex(row, maxWidth);
int characterIndex = characterIndexMax;
while(characterIndex >= 0 &&
!Character.isSpaceChar(row.charAt(characterIndex)) &&
!isCharCJK(row.charAt(characterIndex))) {
characterIndex--;
}
// right *after* a CJK is also a "nice" spot to break the line!
if (characterIndex >= 0 && characterIndex < characterIndexMax &&
isCharCJK(row.charAt(characterIndex))) {
characterIndex++; // with these conditions it fits!
}
if(characterIndex < 0) {
//Failed! There was no 'nice' place to cut so just cut it at maxWidth
characterIndex = Math.max(characterIndexMax, 1); // at least 1 char
result.add(row.substring(0, characterIndex));
linesToBeWrapped.addFirst(row.substring(characterIndex));
}
else {
// characterIndex == 0 only happens, if either
// - first char is CJK and maxWidth==1 or
// - first char is whitespace
// either way: put it in row before break to prevent infinite loop.
characterIndex = Math.max( characterIndex, 1); // at least 1 char
//Ok, split the row, add it to the result and continue processing the second half on a new line
result.add(row.substring(0, characterIndex));
while(characterIndex < row.length() &&
Character.isSpaceChar(row.charAt(characterIndex))) {
characterIndex++;
}
if (characterIndex < row.length()) { // only if rest contains non-whitespace
linesToBeWrapped.addFirst(row.substring(characterIndex));
}
}
}
}
return result;
}
private static Integer[] mapCodesToIntegerArray(String[] codes) {
Integer[] result = new Integer[codes.length];
for (int i = 0; i < result.length; i++) {
if (codes[i].length() == 0) {
result[i] = 0;
} else {
try {
// An empty string is equivalent to 0.
// Warning: too large values could throw an Exception!
result[i] = Integer.parseInt(codes[i]);
} catch (NumberFormatException ignored) {
throw new IllegalArgumentException("Unknown CSI code " + codes[i]);
}
}
}
return result;
}
public static void updateModifiersFromCSICode(
String controlSequence,
StyleSet<?> target,
StyleSet<?> original) {
char controlCodeType = controlSequence.charAt(controlSequence.length() - 1);
controlSequence = controlSequence.substring(2, controlSequence.length() - 1);
Integer[] codes = mapCodesToIntegerArray(controlSequence.split(";"));
TextColor[] palette = TextColor.ANSI.values();
if(controlCodeType == 'm') { // SGRs
for (int i = 0; i < codes.length; i++) {
int code = codes[i];
switch (code) {
case 0:
target.setStyleFrom(original);
break;
case 1:
target.enableModifiers(SGR.BOLD);
break;
case 3:
target.enableModifiers(SGR.ITALIC);
break;
case 4:
target.enableModifiers(SGR.UNDERLINE);
break;
case 5:
target.enableModifiers(SGR.BLINK);
break;
case 7:
target.enableModifiers(SGR.REVERSE);
break;
case 21: // both do. 21 seems more straightforward.
case 22:
target.disableModifiers(SGR.BOLD);
break;
case 23:
target.disableModifiers(SGR.ITALIC);
break;
case 24:
target.disableModifiers(SGR.UNDERLINE);
break;
case 25:
target.disableModifiers(SGR.BLINK);
break;
case 27:
target.disableModifiers(SGR.REVERSE);
break;
case 38:
if (i + 2 < codes.length && codes[i + 1] == 5) {
target.setForegroundColor(new TextColor.Indexed(codes[i + 2]));
i += 2;
} else if (i + 4 < codes.length && codes[i + 1] == 2) {
target.setForegroundColor(new TextColor.RGB(codes[i + 2], codes[i + 3], codes[i + 4]));
i += 4;
}
break;
case 39:
target.setForegroundColor(original.getForegroundColor());
break;
case 48:
if (i + 2 < codes.length && codes[i + 1] == 5) {
target.setBackgroundColor(new TextColor.Indexed(codes[i + 2]));
i += 2;
} else if (i + 4 < codes.length && codes[i + 1] == 2) {
target.setBackgroundColor(new TextColor.RGB(codes[i + 2], codes[i + 3], codes[i + 4]));
i += 4;
}
break;
case 49:
target.setBackgroundColor(original.getBackgroundColor());
break;
default:
if (code >= 30 && code <= 37) {
target.setForegroundColor( palette[code - 30] );
}
else if (code >= 40 && code <= 47) {
target.setBackgroundColor( palette[code - 40] );
}
}
}
}
}
/**
* Given a character, is this character considered to be a Thai character?
* @param c Character to test
* @return {@code true} if the character is a Thai character
*/
public static boolean isCharThai(char c) {
Character.UnicodeBlock unicodeBlock = Character.UnicodeBlock.of(c);
return unicodeBlock == Character.UnicodeBlock.THAI;
}
}
| mit |
anotheri/cleverstack-visualCaptcha-demo | frontend/app/modules/users/module.js | 688 | define(['angular'], function (ng) {
'use strict';
ng.module('users.providers', []);
ng.module('users.controllers', []);
ng.module('users.services', []);
var module = ng.module('users', [
'cs_common',
'users.providers',
'users.controllers',
'users.services'
]);
module.config([
'$routeProvider',
'CSTemplateProvider',
function ($routeProvider, CSTemplateProvider) {
CSTemplateProvider.setPath('/modules/users/views');
$routeProvider
.when('/users', {
templateUrl: CSTemplateProvider.view('index'),
controller: 'UsersController',
public: false
});
}
]);
return module;
});
| mit |
dolimoni/ensa-Project | application/models/filiere_model.php | 1828 | <?php if(!defined ('BASEPATH')) exit ('No direct script access allowed');
class Filiere_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database('ensa_project');
$this->load->helper('url');
}
public function getListFiliere()
{
$this->db->select('id,titre,abreviation,signification,created_at');
$this->db->from('filiere');
$this->db->where("deleted",0);
$this->db->order_by('titre asc');
$query = $this->db->get();
$results = $query->result();
return $results;
}
public function getFiliereById($idFil)
{
$this->db->select('*');
$this->db->from('filiere');
$this->db->where(array('id'=> $idFil,'deleted'=>0));
$this->db->limit(1);
$query = $this->db->get();
$results = $query->result();
//$row = $query->row_array();
return $results;
}
// ça marche
public function deleteById($idFiliere)
{
$this->db->where('id', $idFiliere);
$this->db->update('filiere', array("deleted" => 1));
}
//modifier filiere
public function editFiliere($filiere)
{
$idFiliere=$filiere['id'];
$titre=$filiere['titre'];
$abreviation=$filiere['abreviation'];
$signification=$filiere['signification'];
//ajouter created_at
$this->db->where('id', $idFiliere);
$this->db->update('filiere', array('titre' => $titre,'abreviation'=>$abreviation,'signification' => $signification,'deleted'=>0));
}
//ajout
// ajouter une nouvelle filiere
public function addfiliere($filiere)
{
$titre=$filiere['titre'];
$abreviation=$filiere['abreviation'];
$signification=$filiere['signification'];
$this->db->set(array('titre' => $titre,'abreviation'=>$abreviation,'signification' => $signification,'deleted'=>0))
->set('created_at', 'NOW()', false)
->insert('filiere');
}
}
?> | mit |
veeseekay/wifi-streamer-v1 | src/main/java/com/guidestone/wifi/streamer/controllers/MediaController.java | 2564 | package com.guidestone.wifi.streamer.controllers;
import com.guidestone.wifi.streamer.entities.MediaEntity;
import com.guidestone.wifi.streamer.services.MediaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
//@EnableWebMvc
@RestController
@RequestMapping("/api/wifistreamer/v1/media")
@EnableAutoConfiguration
@ComponentScan
public class MediaController {
private static final Logger LOG = LoggerFactory.getLogger(MediaController.class);
@Autowired
MediaService mediaService;
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> getMedia(@RequestHeader HttpHeaders headers,
Pageable pageable, PagedResourcesAssembler assembler) throws Exception {
Page<MediaEntity> users = mediaService.getMedia(pageable);
return new ResponseEntity<>(assembler.toResource(users), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> addMedia(@RequestHeader HttpHeaders headers, @RequestBody List<MediaEntity> media) throws Exception {
LOG.debug("Media to add {}", media);
return new ResponseEntity<>(mediaService.addMedia(media), HttpStatus.OK);
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> getMedium(@RequestHeader HttpHeaders headers, @PathVariable String id) throws Exception {
return new ResponseEntity<>(mediaService.getMedium(id), HttpStatus.OK);
}
} | mit |
Uter1007/socialmscrm | uter.sociallistener.general/Twitter/Models/Mapping/TwitterHashTagMapper.cs | 1616 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Twitterizer.Entities;
using LinqToTwitter;
namespace uter.sociallistener.general.Twitter.Models.Mapping
{
public class TwitterHashTagMapper
{
public static TwitterHashTag Map(HashTagEntity hashtag)
{
AutoMapper.Mapper.CreateMap<HashTagEntity, TwitterHashTag>()
.ForMember(x => x.CRMID, opt => opt.Ignore())
.ForMember(x => x.Text, opt => opt.MapFrom(src => src.Tag));
AutoMapper.Mapper.AssertConfigurationIsValid();
return AutoMapper.Mapper.Map<HashTagEntity, TwitterHashTag>(hashtag);
}
public static TwitterHashTag Map(TwitterHashTagEntity hashtag)
{
AutoMapper.Mapper.CreateMap<TwitterHashTagEntity, TwitterHashTag>().ForMember(x => x.CRMID, opt => opt.Ignore());
AutoMapper.Mapper.AssertConfigurationIsValid();
return AutoMapper.Mapper.Map<TwitterHashTagEntity, TwitterHashTag>(hashtag);
}
public static Entity Map(TwitterHashTag hashtag, Guid configId)
{
var hash = new Entity("cott_twitterhashtag");
if (hashtag.CRMID != null)
{
hash.Id = hashtag.CRMID;
}
hash.Attributes.Add("cott_name", hashtag.Text);
hash.Attributes.Add("cott_createdbyconfig", new EntityReference("cott_twitterconfig", configId));
return hash;
}
}
}
| mit |
gustavomrs/app-almoxarifado | app/models/user.rb | 272 | class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable
validates :login, :password, presence: true
validates :login, uniqueness: true
end
| mit |
davidlibrera/scoped_associations | lib/scoped_associations/version.rb | 50 | module ScopedAssociations
VERSION = "0.1.4"
end
| mit |
eeveorg/GMSI | program/ui/ScriptChoosePanel.java | 2509 | /*
* Decompiled with CFR 0_119.
*/
package program.ui;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.JTextPane;
import javax.swing.JTree;
import program.ui.FileTree;
import program.ui.MyTreeListener;
public class ScriptChoosePanel
extends JPanel {
private static final long serialVersionUID = 1;
JSplitPane split1;
FileTree tree;
JPanel right;
JTextPane text;
JButton execute;
JButton viewSource;
public ScriptChoosePanel() {
GridBagLayout gridbag = new GridBagLayout();
this.setLayout(gridbag);
GridBagConstraints c = new GridBagConstraints();
c.fill = 1;
c.insets = new Insets(4, 4, 4, 4);
c.gridx = 0;
c.gridy = 0;
c.gridheight = 10;
c.gridwidth = 10;
c.weightx = 0.2;
c.weighty = 0.2;
this.tree = new FileTree(new File("."));
this.right = new JPanel();
this.split1 = new JSplitPane(1, this.tree, this.right);
this.add((Component)this.split1, c);
this.split1.setDividerLocation(250);
this.right.setLayout(new GridBagLayout());
this.text = new JTextPane();
this.right.add((Component)this.text, c);
this.text.setEditable(false);
this.text.setOpaque(false);
Font f = new Font("Verdana", 0, 12);
c.fill = 0;
c.gridx = 0;
c.gridy = -1;
c.gridheight = 4;
c.gridwidth = 3;
c.weightx = 0.0;
c.weighty = 0.0;
this.right.add(new JSeparator());
this.execute = new JButton("Execute Script");
this.right.add((Component)this.execute, c);
this.execute.setEnabled(false);
c.gridx = 3;
this.viewSource = new JButton("View Source");
this.right.add((Component)this.viewSource, c);
MyTreeListener listen = new MyTreeListener(this.tree.getTree(), this.text, this.execute, this.viewSource);
this.viewSource.setEnabled(false);
this.viewSource.addActionListener(listen);
this.execute.addActionListener(listen);
this.text.setFont(f);
this.tree.addListener(listen);
this.tree.getRefreshButton().addActionListener(listen);
}
}
| mit |
croxis/Panda-Core-Technology | NotAsOldPlanet/atmo_only.py | 3587 | from pandac.PandaModules import loadPrcFileData
loadPrcFileData('', 'frame-rate-meter-scale 0.035')
loadPrcFileData('', 'frame-rate-meter-side-margin 0.1')
loadPrcFileData('', 'show-frame-rate-meter 1')
loadPrcFileData('', 'window-title ' + "Planet Prototype")
loadPrcFileData('', "sync-video 0")
loadPrcFileData('', 'basic-shaders-only #f')
#loadPrcFileData('', 'dump-generated-shaders #t')
#loadPrcFileData('', 'pstats-tasks 1')
#loadPrcFileData('', 'want-pstats 1')
#loadPrcFileData('', 'threading-model Cull/Draw')
import direct.directbase.DirectStart
#base.setBackgroundColor(0.0, 0.0, 0.0)
from panda3d.core import PointLight
light = PointLight('light')
lightnp = render.attachNewNode(light)
lightnp.set_pos(0, -1000, 0)
render.set_light(lightnp)
from panda3d.core import CullFaceAttrib, Shader
import math
#atmo = surface_mesh.make_atmosphere()
#atmo = loader.loadModel("planet_sphere")
atmo = loader.loadModel("solar_sky_sphere")
#atmosphere.reparent_to(planet.node_path)
#import shapeGenerator
#atmo = shapeGenerator.Sphere(segements=64)
atmo.reparent_to(render)
#atmo.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
atmo.set_scale(1.025)
atmo.set_shader(
Shader.load(Shader.SLGLSL,
'atmoshaders/oneil_sky_from_space_vert.glsl',
'planet_atmosphere_frag.glsl'))
#atmo.node_path.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
outerRadius = abs(atmo.get_scale().getX())
scale = 1/(outerRadius - planet.get_scale().getX())
atmo.set_shader_input("fOuterRadius", outerRadius)
atmo.set_shader_input("fInnerRadius", planet.get_scale().getX())
atmo.set_shader_input("fOuterRadius2", outerRadius * outerRadius)
atmo.set_shader_input("fInnerRadius2", planet.get_scale().getX() * planet.get_scale().getX())
#atmo.set_shader_input("fKr4PI", 0.0025 * 4 * 3.14159)
#atmo.set_shader_input("fKm4PI", 0.0015 * 4 * 3.14159)
atmo.setShaderInput("fKr4PI", 0.000055 * 4 * 3.14159)
atmo.setShaderInput("fKm4PI", 0.000015 * 4 * 3.14159)
atmo.set_shader_input("fScale", scale)
atmo.set_shader_input("fScaleDepth", 0.25)
#atmo.setShaderInput("fScaleDepth", 0.5)
#atmo.set_shader_input("fScaleOverScaleDepth", scale/0.5)
atmo.set_shader_input("fScaleOverScaleDepth", scale/0.25)
# These do sunsets and sky colors
# Brightness of sun
ESun = 15
# Reyleight Scattering (Main sky colors)
atmo.set_shader_input("fKrESun", 0.0025 * ESun)
# Mie Scattering -- Haze and sun halos
atmo.set_shader_input("fKmESun", 0.0015 * ESun)
# Color of sun
atmo.set_shader_input("v3InvWavelength", 1.0 / math.pow(0.650, 4),
1.0 / math.pow(0.570, 4),
1.0 / math.pow(0.475, 4))
atmo.set_shader_input("g", 0.90)
atmo.set_shader_input("g2", 0.81)
atmo.set_shader_input("float", 2)
def shaderUpdate(task):
#TODO: Convert to relative positions, not world coords
atmo.set_shader_input("v3CameraPos", base.camera.getPos().getX(),
base.camera.getPos().getY(),
base.camera.getPos().getZ())
atmo.set_shader_input("fCameraHeight", base.camera.getPos().length())
atmo.set_shader_input("fCameraHeight2", base.camera.getPos().length()
*base.camera.getPos().length())
# Light vector from center of planet.
lightv = lightnp.getPos()
lightdir = lightv / lightv.length()
atmo.set_shader_input("v3LightPos", lightdir[0], lightdir[1], lightdir[2])
return task.cont
taskMgr.add(shaderUpdate, 'shaderUpdate')
def toggleWireframe():
base.toggleWireframe()
base.accept('w', toggleWireframe)
run()
| mit |
JayTeeGeezy/pyracing | pyracing/test/performances.py | 3692 | from .common import *
class GetPerformancesByHorseTest(EntityTest):
@classmethod
def setUpClass(cls):
cls.meet = pyracing.Meet.get_meets_by_date(historical_date)[0]
cls.race = cls.meet.races[0]
cls.runner = cls.race.runners[0]
cls.performances = pyracing.Performance.get_performances_by_horse(cls.runner.horse)
def test_types(self):
"""The get_performances_by_horse method should return a list of Performance objects"""
self.check_types(self.performances, list, pyracing.Performance)
def test_ids(self):
"""All Performance objects returned by get_performances_by_horse should have a database ID"""
self.check_ids(self.performances)
def test_scraped_at_dates(self):
"""All Performance objects returned by get_performances_by_horse should have a scraped_at date"""
self.check_scraped_at_dates(self.performances)
def test_no_rescrape(self):
"""Subsequent calls to get_performances_by_horse for the same horse should retrieve data from the database"""
self.check_no_rescrape(pyracing.Performance.get_performances_by_horse, self.runner.horse)
class GetPerformancesByJockeyTest(EntityTest):
@classmethod
def setUpClass(cls):
cls.meet = pyracing.Meet.get_meets_by_date(historical_date)[0]
cls.race = cls.meet.races[0]
cls.runner = cls.race.runners[0]
cls.performances = pyracing.Performance.get_performances_by_jockey(cls.runner.jockey)
def test_types(self):
"""The get_performances_by_jockey method should return a list of Performance objects"""
self.check_types(self.performances, list, pyracing.Performance)
def test_ids(self):
"""All Performance objects returned by get_performances_by_jockey should have a database ID"""
self.check_ids(self.performances)
def test_scraped_at_dates(self):
"""All Performance objects returned by get_performances_by_jockey should have a scraped_at date"""
self.check_scraped_at_dates(self.performances)
def test_no_rescrape(self):
"""Subsequent calls to get_performances_by_jockey for the same jockey should retrieve data from the database"""
self.check_no_rescrape(pyracing.Performance.get_performances_by_jockey, self.runner.jockey)
class PerformancePropertiesTest(EntityTest):
@classmethod
def setUpClass(cls):
for meet in pyracing.Meet.get_meets_by_date(historical_date):
if meet['track'] == 'Kilmore':
cls.meet = meet
for race in cls.meet.races:
if race['number'] == 5:
cls.race = race
for runner in cls.race.runners:
if runner['number'] == 1:
cls.runner = runner
cls.performance = cls.runner.horse.performances[0]
break
break
break
def test_actual_distance(self):
"""The actual_distance property should return the actual distance run by the horse in the winning time for this performance"""
self.assertEqual(self.performance['distance'] - (self.performance['lengths'] * self.performance.METRES_PER_LENGTH), self.performance.actual_distance)
def test_actual_weight(self):
"""The actual_weight property should return the weight carried by the horse plus the average weight of a racehorse"""
self.assertEqual(self.performance['carried'] + pyracing.Horse.AVERAGE_WEIGHT, self.performance.actual_weight)
def test_momentum(self):
"""The momentum property should return the average momentum achieved by the horse in this performance"""
self.assertEqual(self.performance.actual_weight * self.performance.speed, self.performance.momentum)
def test_speed(self):
"""The speed property should return the average speed achieved by the horse in this performance"""
self.assertEqual(self.performance.actual_distance / self.performance['winning_time'], self.performance.speed) | mit |
sehoone/seed | app/bower_components/jquery/src/traversing.js | 4322 | define( [
"./core",
"./traversing/var/dir",
"./traversing/var/siblings",
"./traversing/var/rneedsContext",
"./core/init",
"./traversing/findFilter",
"./selector"
], function( jQuery, dir, siblings, rneedsContext ) {
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend( {
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter( function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[ i ] ) ) {
return true;
}
}
} );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && ( pos ?
pos.index( cur ) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector( cur, selectors ) ) ) {
matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[ 0 ], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[ 0 ] : elem, this );
},
add: function( selector, context ) {
return this.pushStack(
jQuery.uniqueSort(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
}
} );
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each( {
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return siblings( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return siblings( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
ret = jQuery.uniqueSort( ret );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
ret = ret.reverse();
}
}
return this.pushStack( ret );
};
} );
return jQuery;
} );
| mit |
lucianot/dealbook-node-api | routes/index.js | 745 | /**
* Routes
*/
'use strict';
var express = require('express');
var router = express.Router();
var auth = require('./auth');
var companies = require('./companies');
// var user = require('./users.js');
/*
* Routes that can be accessed by anyone
*/
router.get('/', function(req, res) {
res.send('Hello! Welcome to the Dealbook API!');
});
router.post('/login', auth.login);
/*
* Routes that can be accessed only by autheticated users
*/
router.get('/api/v1/companies', companies.getAll);
router.get('/api/v1/company/:id', companies.getOne);
router.post('/api/v1/companies', companies.create);
router.put('/api/v1/company/:id', companies.update);
router.delete('/api/v1/company/:id', companies.deleteOne);
module.exports = router;
| mit |
beatrizjesus/my-first-blog | pasta/Scripts/django-admin.py | 165 | #!C:\Users\Beatriz\Desktop\django\pasta\Scripts\python.exe
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| mit |
isbasex/blog-engine | packages/server/middleware/pre-processing/normalization/index.ts | 321 | const normalization = (req, res, next) => {
const json = res.json
res.json = function(...args) {
const [obj] = args
if (obj && !('success' in obj)) {
args[0] = {
success: true,
...obj
}
}
res.json = json
res.json(...args)
}
next()
}
export default [normalization]
| mit |
chilimatic/chilimatic-framework | lib/database/sql/mysql/MySQL.php | 21245 | <?php
/**
* Mysql database abstraction class
* please feel free to add or modify this class as you like
* as long you don't spoil the old functionality
*
* @author j
* @version $id$
*
*/
namespace chilimatic\lib\database\sql\mysql;
use chilimatic\lib\database\AbstractDatabase;
use chilimatic\lib\config\Config;
use chilimatic\lib\database\connection\IDatabaseConnection;
use chilimatic\lib\database\sql\mysql\connection\MySQLConnection;
use chilimatic\lib\exception\DatabaseException;
/**
* Class Mysql
*
* @package chilimatic\lib\database
*/
class MySQL extends AbstractDatabase
{
/**
* only in cases of intense debug
* this can be activated
*
* @var int
*/
CONST SEVERITY_DEBUG = 0;
/**
* only log
*
* @var int
*/
CONST SEVERITY_LOG = 1;
/**
* mail it as well
*
* @var int
*/
CONST SEVERITY_MAIL = 2;
/**
* login error
*
* @var int
*/
CONST ERR_NO_CREDENTIALS = 1;
/**
* Connection error
*
* @var int
*/
CONST ERR_CONN = 2;
/**
* query error
*
* @var int
*/
CONST ERR_EXEC = 3;
/**
* no ressource given
*
* @var int
*/
CONST NO_RESSOURCE = 4;
/**
* to be pdo compatible -> i just copied the pdo variables
*
* Specifies that the fetch method shall return each row as an object with
* variable names that correspond to the column names returned in the result
* set. <b>PDO::FETCH_LAZY</b> creates the object variable names as they are accessed.
* Not valid inside <b>PDOStatement::fetchAll</b>.
*
* @link http://php.net/manual/en/pdo.constants.php
*/
const FETCH_LAZY = 1;
/**
* Specifies that the fetch method shall return each row as an array indexed
* by column name as returned in the corresponding result set. If the result
* set contains multiple columns with the same name,
* <b>PDO::FETCH_ASSOC</b> returns
* only a single value per column name.
*
* @link http://php.net/manual/en/pdo.constants.php
*/
const FETCH_ASSOC = 2;
/**
* Specifies that the fetch method shall return each row as an array indexed
* by column number as returned in the corresponding result set, starting at
* column 0.
*
* @link http://php.net/manual/en/pdo.constants.php
*/
const FETCH_NUM = 3;
/**
* Specifies that the fetch method shall return each row as an array indexed
* by both column name and number as returned in the corresponding result set,
* starting at column 0.
*
* @link http://php.net/manual/en/pdo.constants.php
*/
const FETCH_BOTH = 4;
/**
* Specifies that the fetch method shall return each row as an object with
* property names that correspond to the column names returned in the result
* set.
*
* @link http://php.net/manual/en/pdo.constants.php
*/
const FETCH_OBJ = 5;
/**
* Specifies that the fetch method shall return TRUE and assign the values of
* the columns in the result set to the PHP variables to which they were
* bound with the <b>PDOStatement::bindParam</b> or
* <b>PDOStatement::bindColumn</b> methods.
*
* @link http://php.net/manual/en/pdo.constants.php
*/
const FETCH_BOUND = 6;
/**
* Specifies that the fetch method shall return only a single requested
* column from the next row in the result set.
*
* @link http://php.net/manual/en/pdo.constants.php
*/
const FETCH_COLUMN = 7;
/**
* Specifies that the fetch method shall return a new instance of the
* requested class, mapping the columns to named properties in the class.
* The magic
* <b>__set</b>
* method is called if the property doesn't exist in the requested class
*
* @link http://php.net/manual/en/pdo.constants.php
*/
const FETCH_CLASS = 8;
/**
* Specifies that the fetch method shall update an existing instance of the
* requested class, mapping the columns to named properties in the class.
*
* @link http://php.net/manual/en/pdo.constants.php
*/
const FETCH_INTO = 9;
/**
* Allows completely customize the way data is treated on the fly (only
* valid inside <b>PDOStatement::fetchAll</b>).
*
* @link http://php.net/manual/en/pdo.constants.php
*/
const FETCH_FUNC = 10;
/**
* Group return by values. Usually combined with
* <b>PDO::FETCH_COLUMN</b> or
* <b>PDO::FETCH_KEY_PAIR</b>.
*
* @link http://php.net/manual/en/pdo.constants.php
*/
const FETCH_GROUP = 65536;
/**
* Fetch only the unique values.
*
* @link http://php.net/manual/en/pdo.constants.php
*/
const FETCH_UNIQUE = 196608;
/**
* Fetch a two-column result into an array where the first column is a key and the second column
* is the value. Available since PHP 5.2.3.
*
* @link http://php.net/manual/en/pdo.constants.php
*/
const FETCH_KEY_PAIR = 12;
/**
* Determine the class name from the value of first column.
*
* @link http://php.net/manual/en/pdo.constants.php
*/
const FETCH_CLASSTYPE = 262144;
/**
* As <b>PDO::FETCH_INTO</b> but object is provided as a serialized string.
* Available since PHP 5.1.0.
*
* @link http://php.net/manual/en/pdo.constants.php
*/
const FETCH_SERIALIZE = 524288;
/**
* Available since PHP 5.2.0
*
* @link http://php.net/manual/en/pdo.constants.php
*/
const FETCH_PROPS_LATE = 1048576;
/**
* Specifies that the fetch method shall return each row as an array indexed
* by column name as returned in the corresponding result set. If the result
* set contains multiple columns with the same name,
* <b>PDO::FETCH_NAMED</b> returns
* an array of values per column name.
*
* @link http://php.net/manual/en/pdo.constants.php
*/
const FETCH_NAMED = 11;
/**
* Database details object
* for the connected server
*
* @var object
*/
public $db_detail = null;
/**
* db resource
*
* @var MysqlConnection
*/
public $db = false;
/**
* amount of affected rows
*
* @var int
*/
public $affected_rows = 0;
/**
* error description
*
* @var string
*/
public $error = '';
/**
* error number
*
* @var int
*/
public $errorno = '';
/**
* mysql client encoding
*
* @var string
*/
public $mysqli_client_encoding = '';
/**
* the last query
*
* @var string
*/
public $lastSql = '';
/**
* new insert id
*
* @var int
*/
public $insert_id = 0;
/**
* enables the detail object for the databas object
*
* @var bool
*/
private $_get_detail = false;
/**
* @var MysqlConnection
*/
protected $masterConnection;
/**
* @var MysqlConnection
*/
protected $slaveConnection;
/**
* @param IDatabaseConnection $masterConnection
* @param IDatabaseConnection $slaveConnection
*
* @throws DatabaseException
* @throws \Exception
*/
public function __construct(IDatabaseConnection $masterConnection, IDatabaseConnection $slaveConnection = null)
{
if (!$masterConnection->connectionSettingsAreValid()) {
throw new \Exception('connection Data is not Valid');
}
$this->masterConnection = $masterConnection;
$this->connect($this->masterConnection);
if ($slaveConnection && $slaveConnection->connectionDataIsSet()) {
$this->slaveConnection = $slaveConnection;
$this->connect($this->slaveConnection);
}
}
/**
* create new database connection
*/
final public function __clone()
{
if (empty($this->_master_host)) return;
$this->connect($this->masterConnection);
if (empty($this->_slave_host)) return;
$this->connect($this->slaveConnection);
}
/**
* reconnect to db after serialisation
*/
final public function __wakeup()
{
if ($this->masterConnection) return;
$this->connect($this->masterConnection);
if ($this->slaveConnection) return;
$this->connect($this->slaveConnection);
}
/**
* commit the transaction
*
* @return bool
*/
public function commit()
{
return $this->query('commit');
}
/**
* connects to the db based on the mysql Connection
*
* @param MysqlConnection $connection
*
* @throws \chilimatic\lib\exception\DatabaseException|\Exception
*
* @return bool
*/
public function connect(MysqlConnection $connection)
{
try {
// if no connection to master and slave is possible
if (!$connection->isConnected()) {
throw new DatabaseException(__METHOD__ . "\nConnection failure no ressource given", self::NO_RESSOURCE, self::SEVERITY_LOG, __FILE__, __LINE__);
}
// get the mysql (only master) server details
if ($this->_get_detail === true) {
$this->db_detail = $this->getDatabaseDetail($this);
}
} catch (DatabaseException $ed) {
throw $ed;
}
if (!$this->db) {
$this->db = $connection;
}
return true;
}
/**
* fetches an array with only 1 dimension
* "SELECT <col_name> FROM <tablename>
*
* array($col_entry1,$col_entry2)
*
* @param \PDOStatement $res
* @param int $col
*
* @throws DatabaseException|\Exception
*
* @return array
*/
public function fetchSimpleList(\PDOStatement $res, $col = 0)
{
if (!$col) {
$col = 0;
}
$result = array();
try {
if (!$res) {
throw new DatabaseException(__METHOD__ . " No ressource has been given", self::NO_RESSOURCE, self::SEVERITY_LOG, __FILE__, __LINE__);
}
while ($row = $res->fetch(\PDO::FETCH_ASSOC)) {
$result[] = $row[$col];
}
} catch (DatabaseException $e) {
throw $e;
}
return $result;
}
/**
* fetches an associative array
*
* @param \PDOStatement $res
*
* @throws DatabaseException|\Exception
* @return bool array
*/
public function fetchAssoc(\PDOStatement $res)
{
return $res->fetchAll(\PDO::FETCH_ASSOC);
}
/**
* fetches an array list of associative arrays
* which can be assigned to a specific key from the row as well
*
* @param \PDOStatement $res
* @param $assign_by string
*
* @throws DatabaseException|\Exception
*
* @return array bool
*/
public function fetchAssocList(\PDOStatement $res, $assign_by = null)
{
$result = array();
try {
while ($row = $res->fetch(\PDO::FETCH_ASSOC)) {
if (!empty($assign_by) && !is_array($assign_by)) {
$result[$row[$assign_by]] = (array)$row;
} elseif (!empty($assign_by) && is_array($assign_by)) {
$key = array();
foreach ($assign_by as $key_w) {
if (isset($row[$key_w])) {
$key[] = $row[$key_w];
}
}
if (empty($key)) {
$result[] = (object)$row;
} else {
// removes the first '- '
$key = implode('-', $key);
$result[$key] = (object)$row;
}
} else {
$result[] = (array)$row;
}
}
} catch (DatabaseException $e) {
throw $e;
}
return $result;
}
/**
* fetches an array list of numeric arrays
*
* @param \PDOStatement $res
*
* @throws \chilimatic\lib\exception\DatabaseException
* @throws \Exception
*
* @return \SplFixedArray
*/
public function fetchNumericList(\PDOStatement $res)
{
$result = new \SplFixedArray($res->rowCount());
try {
while ($row = $res->fetch(\PDO::FETCH_NUM)) {
$result[] = (array)$row;
}
} catch (DatabaseException $e) {
throw $e;
}
return $result;
}
/**
* fetches an object of the current row
*
* @param \PDOStatement $res
*
* @throws DatabaseException|\Exception
* @return bool object
*/
public function fetchObject(\PDOStatement $res)
{
return $res->fetchAll(\PDO::FETCH_OBJ);
}
/**
* fetches an object list of associative arrays
* which can be assigned to a specific key from the row as well
*
*
* @param \PDOStatement $res
* @param string $assign_by
*
* @throws DatabaseException|\Exception
* @return array bool
*/
public function fetchObjectList(\PDOStatement $res, $assign_by = null)
{
try {
$result = [];
while ($row = $res->fetch(\PDO::FETCH_OBJ)) {
if (!empty($assign_by) && !is_array($assign_by)) {
$result[$row->$assign_by] = (object)$row;
} elseif (!empty($assign_by) && is_array($assign_by)) {
$key = array();
foreach ($assign_by as $key_w) {
if (property_exists($row, $key_w)) {
$key[] = $row->$key_w;
}
}
if (empty($key)) {
$result[] = (object)$row;
} else {
// removes the first '- '
$key = implode('-', $key);
$result[$key] = (object)$row;
}
} else {
$result[] = (object)$row;
}
}
} catch (DatabaseException $e) {
throw $e;
}
return $result;
}
/**
* fetches a string
*
* @param \PDOStatement $res
*
* @return string
*/
public function fetchString(\PDOStatement $res)
{
return (string)$res->fetch(\PDO::FETCH_NUM)[0];
}
/**
* free mysql resource
*
* @param \mysqli_result $res
*
* @throws \chilimatic\lib\exception\DatabaseException|\Exception
* @return bool
*/
public function free($res)
{
$res->free();
return true;
}
/**
*
* @param string $query
*
* @return \PDOStatement
* @throws \chilimatic\lib\exception\DatabaseException
* @throws \Exception
*/
public function prepare($query = '')
{
try {
if (empty($query)) return false;
if (empty($this->db)) {
throw new DatabaseException(__METHOD__ . " No Database Connection opened", self::NO_RESSOURCE, self::SEVERITY_DEBUG, __FILE__, __LINE__);
}
return $this->db->getDbAdapter()->prepare($query);
} catch (DatabaseException $e) {
throw $e;
}
}
/**
* @return mixed
*/
public function getLastInsertId() {
return $this->db->getDbAdapter()->getLastInsertId();
}
/**
* wrapper for the db_detail object the parameter should be a valid db
* object
*
* @param \chilimatic\lib\database\sql\mysql\mysql|object $db
*
* @return MysqlDetail
*/
public function getDatabaseDetail(MySQL $db = null)
{
if (empty($db) || empty($db->db)) {
$db = $this;
}
return new MysqlDetail($db);
}
/**
* @param string $query
*
* @return bool
*/
public function execute($query)
{
return (bool)$this->getDb()->getDb()->exec($query);
}
/**
* @return string
*/
public function lastQuery()
{
return (string)$this->lastSql;
}
/**
* @return bool
*/
public function isConnected()
{
return $this->db->isConnected();
}
/**
* @return resource
*/
public function getDb()
{
return $this->db->getDbAdapter()->getResource();
}
/**
* sends the query / update / insert statement to the database and returns
* a resource of the table
*
* @throws DatabaseException
*
* @param $query string
*
* @return resource
*/
public function query($query)
{
if (empty($query) || !$this->db) {
return false;
}
// if the resource type is not a mysql link it should try to reconnect
if (!$this->db->isConnected()) {
$this->db->ping();
}
// the last sql query
$this->lastSql = (string)$query;
// if the master is down a select may query the slave but it should not
// insert anything
if ($this->slaveConnection === $this->db && stripos(trim($query), 'SELECT') !== 0) {
throw new DatabaseException(__METHOD__ . ' no Select on slave, abort !!', self::ERR_CONN, self::SEVERITY_LOG, __FILE__, __LINE__);
}
// tries execute the query and fetches the result
$res = $this->db->getDbAdapter()->query($query);
try {
// in cases of errors
if (!$res) {
$this->error = $this->db->getDbAdapter()->getErrorInfo();
$this->errorno = $this->db->getDbAdapter()->getErrorCode();
throw new DatabaseException(__METHOD__ . "\nsql: $this->lastSql\nsql_error:$this->error\nsql_errorno:$this->errorno", self::ERR_EXEC, self::SEVERITY_LOG, __FILE__, __LINE__);
} else {
$this->insert_id = $this->db->getDbAdapter()->getLastInsertId();
}
} catch (DatabaseException $e) {
if (Config::get('use_exception') !== true) {
return false;
}
throw $e;
}
// reset old errors
$this->error = '';
$this->errorno = 0;
if ($res && $res instanceof \PDOStatement){
$this->affected_rows = $this->db->getDbAdapter()->getAffectedRows($res);
}
return $res;
}
/**
* rollback
*
* @return bool
*/
public function rollback()
{
return $this->query('rollback;');
}
/**
* selects a db
*
* @param \PDO $db
* @param string $dbname
*
* @throws DatabaseException
*
* @return bool
*/
public function selectDb($dbname, \PDO $db)
{
if (empty($db) || empty($dbname)) return false;
try {
if (!$db->query("USE `$dbname`")) {
$this->error = (string)$db->errorInfo();
$this->errorno = (int)$db->errorCode();
throw new DatabaseException(__METHOD__ . "\nsql_error: $this->error\nsql_errorno:$this->errorno", self::ERR_EXEC, self::SEVERITY_LOG, __FILE__, __LINE__);
}
} catch (DatabaseException $e) {
throw $e;
}
return true;
}
/**
* sets a different charset
*
* @param string $charset
* @param \PDO $db
*
* @throws DatabaseException|\Exception
* @return bool
*/
public function setCharset($charset = 'UTF8', \PDO $db)
{
try {
if (empty($charset) || !$db) {
throw new DatabaseException(__METHOD__ . "\ncharset:$charset\nressource:" . print_r($this->db, true), self::ERR_EXEC, self::SEVERITY_LOG, __FILE__, __LINE__);
}
$this->mysqli_client_encoding = (string)$charset;
if ($this->db_detail) {
$this->db_detail->character_set_client = (string)$charset;
}
} catch (DatabaseException $e) {
throw $e;
}
$db->exec("set names $charset");
return true;
}
/**
* if there should be transactions
*
* @return bool
*/
public function beginTransaction()
{
$this->getDb()->beginTransaction();
return true;
}
/**
* if there should be transactions
*
* @return bool
*/
public function endTransaction()
{
$this->getDb()->commit();
return true;
}
/**
* destructor
*
* @return void
*/
public function __destruct()
{
if (is_resource($this->masterConnection)) mysqli_close($this->masterConnection->getDb());
if (is_resource($this->slaveConnection)) mysqli_close($this->slaveConnection->getDb());
}
} | mit |
shipd/prow | lib/prow/paths.rb | 538 | module Prow
class Paths < Struct.new(:source_path, :compile_path)
def source
source_path || `pwd`.chomp
end
def compile
compile_path || source + "/public"
end
[:templates, :sass, :config].each do |path|
define_method(path) { composite_path(source, path) }
end
def pages_config
config + "/pages.json"
end
def stylesheets
composite_path(compile, "/stylesheets")
end
def composite_path(start_path, end_path)
"#{start_path}/#{end_path}"
end
end
end
| mit |
swiss-php-friends/Neo4jUserBundle | DependencyInjection/Neo4jUserExtension.php | 1352 | <?php
namespace Frne\Bundle\Neo4jUserBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Exception\BadMethodCallException;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class Neo4jUserExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
if(array_key_exists('entity_classname', $config)) {
$container->setParameter('neo4j_user.entity.class', $config['entity_classname']);
}
if(array_key_exists('entity_dehydrator', $config)) {
$container->setParameter('neo4j.user_dehydrator.class', $config['entity_dehydrator']);
}
}
}
| mit |
mateusjatenee/cms | public/js/app/admin/page-versions.js | 67 | devise.define(['jquery', 'pageData'], function ($, pageData)
{
}); | mit |
ahmednuaman/generator-radian | app/templates/assets/js/controller/app-controller.js | 1487 | define([
'config',
'angular',
'controller/radian-controller',
'partials',
'routes',
<% if (includeExample) { %>'controller/header/header-controller',
'controller/footer-controller',
'factory/page-loader-factory',
'factory/page-title-factory'
<% } %>], function(cfg, A, RC) {
RC('AppController', [
'$scope'<% if (includeExample) { %>,
'pageLoaderFactory',
'pageTitleFactory'
<% } %>], {
init: function() {
<% if (includeExample) { %>this.addListeners();
this.addPartials();
this.addScopeMethods();
},
addListeners: function() {
this.pageLoaderFactory.addListener(A.bind(this, this.handlePageLoaderChange));
this.pageTitleFactory.addListener(A.bind(this, this.handlePageTitleChange));
},
addPartials: function() {
this.$scope.ctaPartial = cfg.path.partial + 'cta-partial.html';
this.$scope.footerPartial = cfg.path.partial + 'footer-partial.html';
this.$scope.headerPartial = cfg.path.partial + 'header/header-partial.html';
},
addScopeMethods: function() {
this.$scope.handleViewLoaded = A.bind(this, this.handleViewLoaded);
},
handlePageTitleChange: function(event, title) {
this.$scope.pageTitle = 'Radian ~ A scalable AngularJS framework ~ ' + title;
},
handlePageLoaderChange: function(event, show) {
this.$scope.hideLoader = !show;
},
handleViewLoaded: function() {
this.pageLoaderFactory.hide();
<% } %>}
});
}); | mit |
samueljackson92/csa | db/migrate/20130903103221_create_broadcasts.rb | 356 | class CreateBroadcasts < ActiveRecord::Migration
def change
create_table :broadcasts do |t|
t.text :content, null: :no # Must have some text, empty broadcasts not allowed
t.references :user, null: :no, index: true # Must have been initiated by someone
t.timestamps # Created at will double up as broadcast date
end
end
end
| mit |
kouuki/CROWDRISEPIDEV | src/PIDEV/CrowdRiseBundle/Entity/Vote.php | 618 | <?php
namespace PIDEV\CrowdRiseBundle\Entity;
use DCS\RatingBundle\Entity\Vote as BaseVote;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\ChangeTrackingPolicy("DEFERRED_EXPLICIT")
*/
class Vote extends BaseVote
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="Rating", inversedBy="votes")
* @ORM\JoinColumn(name="rating_id", referencedColumnName="id")
*/
protected $rating;
/**
* @ORM\ManyToOne(targetEntity="Membre")
*/
protected $voter;
} | mit |
sosegon/sunshine | app/src/androidTest/java/com/keemsa/sunshine/data/TestUriMatcher.java | 3002 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.keemsa.sunshine.data;
import android.content.UriMatcher;
import android.net.Uri;
import android.test.AndroidTestCase;
/*
Uncomment this class when you are ready to test your UriMatcher. Note that this class utilizes
constants that are declared with package protection inside of the UriMatcher, which is why
the test must be in the same data package as the Android app code. Doing the test this way is
a nice compromise between data hiding and testability.
*/
public class TestUriMatcher extends AndroidTestCase {
private static final String LOCATION_QUERY = "London, UK";
private static final long TEST_DATE = 1419033600L; // December 20th, 2014
private static final long TEST_LOCATION_ID = 10L;
// content://com.keemsa.sunshine/weather"
private static final Uri TEST_WEATHER_DIR = WeatherContract.WeatherEntry.CONTENT_URI;
private static final Uri TEST_WEATHER_WITH_LOCATION_DIR = WeatherContract.WeatherEntry.buildWeatherLocation(LOCATION_QUERY);
private static final Uri TEST_WEATHER_WITH_LOCATION_AND_DATE_DIR = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(LOCATION_QUERY, TEST_DATE);
// content://com.keemsa.sunshine/location"
private static final Uri TEST_LOCATION_DIR = WeatherContract.LocationEntry.CONTENT_URI;
/*
Students: This function tests that your UriMatcher returns the correct integer value
for each of the Uri types that our ContentProvider can handle. Uncomment this when you are
ready to test your UriMatcher.
*/
public void testUriMatcher() {
UriMatcher testMatcher = WeatherProvider.buildUriMatcher();
assertEquals("Error: The WEATHER URI was matched incorrectly.",
testMatcher.match(TEST_WEATHER_DIR), WeatherProvider.WEATHER);
assertEquals("Error: The WEATHER WITH LOCATION URI was matched incorrectly.",
testMatcher.match(TEST_WEATHER_WITH_LOCATION_DIR), WeatherProvider.WEATHER_WITH_LOCATION);
assertEquals("Error: The WEATHER WITH LOCATION AND DATE URI was matched incorrectly.",
testMatcher.match(TEST_WEATHER_WITH_LOCATION_AND_DATE_DIR), WeatherProvider.WEATHER_WITH_LOCATION_AND_DATE);
assertEquals("Error: The LOCATION URI was matched incorrectly.",
testMatcher.match(TEST_LOCATION_DIR), WeatherProvider.LOCATION);
}
}
| mit |
Producenta/TelerikAcademy | C# 2/DomashnoMultiDimensionalArrays/05.SortArrayOfStrings/Properties/AssemblyInfo.cs | 1418 | 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("05.SortArrayOfStrings")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("05.SortArrayOfStrings")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("218f39f2-2230-4995-ab26-57e01d3802ca")]
// 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")]
| mit |
snags88/cafe-latency | db/migrate/20150721002739_create_stores.rb | 384 | class CreateStores < ActiveRecord::Migration
def change
create_table :stores do |t|
t.string :name
t.string :uid
t.string :url
t.float :rating
t.string :address
t.string :city
t.string :postal_code
t.string :neighborhood
t.string :state_code
t.string :display_address
t.timestamps null: false
end
end
end
| mit |
syonfox/PixelPlanetSandbox | haxe/export/linux64/cpp/obj/src/openfl/_legacy/net/SharedObject.cpp | 28312 | #include <hxcpp.h>
#ifndef INCLUDED_Reflect
#include <Reflect.h>
#endif
#ifndef INCLUDED_StringTools
#include <StringTools.h>
#endif
#ifndef INCLUDED_Sys
#include <Sys.h>
#endif
#ifndef INCLUDED_Type
#include <Type.h>
#endif
#ifndef INCLUDED_haxe_Log
#include <haxe/Log.h>
#endif
#ifndef INCLUDED_haxe_Serializer
#include <haxe/Serializer.h>
#endif
#ifndef INCLUDED_haxe_Unserializer
#include <haxe/Unserializer.h>
#endif
#ifndef INCLUDED_haxe_io_Output
#include <haxe/io/Output.h>
#endif
#ifndef INCLUDED_haxe_io_Path
#include <haxe/io/Path.h>
#endif
#ifndef INCLUDED_openfl__legacy_events_EventDispatcher
#include <openfl/_legacy/events/EventDispatcher.h>
#endif
#ifndef INCLUDED_openfl__legacy_events_IEventDispatcher
#include <openfl/_legacy/events/IEventDispatcher.h>
#endif
#ifndef INCLUDED_openfl__legacy_filesystem_File
#include <openfl/_legacy/filesystem/File.h>
#endif
#ifndef INCLUDED_openfl__legacy_net_SharedObject
#include <openfl/_legacy/net/SharedObject.h>
#endif
#ifndef INCLUDED_sys_FileSystem
#include <sys/FileSystem.h>
#endif
#ifndef INCLUDED_sys_io_File
#include <sys/io/File.h>
#endif
#ifndef INCLUDED_sys_io_FileOutput
#include <sys/io/FileOutput.h>
#endif
namespace openfl{
namespace _legacy{
namespace net{
Void SharedObject_obj::__construct(::String name,::String localPath,Dynamic data)
{
HX_STACK_FRAME("openfl._legacy.net.SharedObject","new",0xdcdfaf6b,"openfl._legacy.net.SharedObject.new","openfl/_legacy/net/SharedObject.hx",27,0xecec0fc2)
HX_STACK_THIS(this)
HX_STACK_ARG(name,"name")
HX_STACK_ARG(localPath,"localPath")
HX_STACK_ARG(data,"data")
{
HX_STACK_LINE(29)
super::__construct(null());
HX_STACK_LINE(31)
this->name = name;
HX_STACK_LINE(32)
this->localPath = localPath;
HX_STACK_LINE(33)
this->data = data;
}
;
return null();
}
//SharedObject_obj::~SharedObject_obj() { }
Dynamic SharedObject_obj::__CreateEmpty() { return new SharedObject_obj; }
hx::ObjectPtr< SharedObject_obj > SharedObject_obj::__new(::String name,::String localPath,Dynamic data)
{ hx::ObjectPtr< SharedObject_obj > _result_ = new SharedObject_obj();
_result_->__construct(name,localPath,data);
return _result_;}
Dynamic SharedObject_obj::__Create(hx::DynamicArray inArgs)
{ hx::ObjectPtr< SharedObject_obj > _result_ = new SharedObject_obj();
_result_->__construct(inArgs[0],inArgs[1],inArgs[2]);
return _result_;}
Void SharedObject_obj::clear( ){
{
HX_STACK_FRAME("openfl._legacy.net.SharedObject","clear",0x46e56958,"openfl._legacy.net.SharedObject.clear","openfl/_legacy/net/SharedObject.hx",38,0xecec0fc2)
HX_STACK_THIS(this)
HX_STACK_LINE(46)
::String tmp = this->name; HX_STACK_VAR(tmp,"tmp");
HX_STACK_LINE(46)
::String tmp1 = this->localPath; HX_STACK_VAR(tmp1,"tmp1");
HX_STACK_LINE(46)
::String tmp2 = ::openfl::_legacy::net::SharedObject_obj::getFilePath(tmp,tmp1); HX_STACK_VAR(tmp2,"tmp2");
HX_STACK_LINE(46)
::String filePath = tmp2; HX_STACK_VAR(filePath,"filePath");
HX_STACK_LINE(48)
::String tmp3 = filePath; HX_STACK_VAR(tmp3,"tmp3");
HX_STACK_LINE(48)
bool tmp4 = ::sys::FileSystem_obj::exists(tmp3); HX_STACK_VAR(tmp4,"tmp4");
HX_STACK_LINE(48)
if ((tmp4)){
HX_STACK_LINE(50)
::String tmp5 = filePath; HX_STACK_VAR(tmp5,"tmp5");
HX_STACK_LINE(50)
::sys::FileSystem_obj::deleteFile(tmp5);
}
}
return null();
}
HX_DEFINE_DYNAMIC_FUNC0(SharedObject_obj,clear,(void))
Void SharedObject_obj::close( ){
{
HX_STACK_FRAME("openfl._legacy.net.SharedObject","close",0x46ed0f83,"openfl._legacy.net.SharedObject.close","openfl/_legacy/net/SharedObject.hx",59,0xecec0fc2)
HX_STACK_THIS(this)
}
return null();
}
HX_DEFINE_DYNAMIC_FUNC0(SharedObject_obj,close,(void))
Dynamic SharedObject_obj::flush( hx::Null< int > __o_minDiskSpace){
int minDiskSpace = __o_minDiskSpace.Default(0);
HX_STACK_FRAME("openfl._legacy.net.SharedObject","flush",0x01255a8f,"openfl._legacy.net.SharedObject.flush","openfl/_legacy/net/SharedObject.hx",123,0xecec0fc2)
HX_STACK_THIS(this)
HX_STACK_ARG(minDiskSpace,"minDiskSpace")
{
HX_STACK_LINE(125)
Dynamic tmp = this->data; HX_STACK_VAR(tmp,"tmp");
HX_STACK_LINE(125)
::String tmp1 = ::haxe::Serializer_obj::run(tmp); HX_STACK_VAR(tmp1,"tmp1");
HX_STACK_LINE(125)
::String encodedData = tmp1; HX_STACK_VAR(encodedData,"encodedData");
HX_STACK_LINE(133)
::String tmp2 = this->name; HX_STACK_VAR(tmp2,"tmp2");
HX_STACK_LINE(133)
::String tmp3 = this->localPath; HX_STACK_VAR(tmp3,"tmp3");
HX_STACK_LINE(133)
::String tmp4 = ::openfl::_legacy::net::SharedObject_obj::getFilePath(tmp2,tmp3); HX_STACK_VAR(tmp4,"tmp4");
HX_STACK_LINE(133)
::String filePath = tmp4; HX_STACK_VAR(filePath,"filePath");
HX_STACK_LINE(134)
::String tmp5 = filePath; HX_STACK_VAR(tmp5,"tmp5");
HX_STACK_LINE(134)
::String tmp6 = ::haxe::io::Path_obj::directory(tmp5); HX_STACK_VAR(tmp6,"tmp6");
HX_STACK_LINE(134)
::String folderPath = tmp6; HX_STACK_VAR(folderPath,"folderPath");
HX_STACK_LINE(136)
::String tmp7 = folderPath; HX_STACK_VAR(tmp7,"tmp7");
HX_STACK_LINE(136)
bool tmp8 = ::sys::FileSystem_obj::exists(tmp7); HX_STACK_VAR(tmp8,"tmp8");
HX_STACK_LINE(136)
bool tmp9 = !(tmp8); HX_STACK_VAR(tmp9,"tmp9");
HX_STACK_LINE(136)
if ((tmp9)){
HX_STACK_LINE(138)
::String tmp10 = folderPath; HX_STACK_VAR(tmp10,"tmp10");
HX_STACK_LINE(138)
::openfl::_legacy::net::SharedObject_obj::mkdir(tmp10);
}
HX_STACK_LINE(142)
::String tmp10 = filePath; HX_STACK_VAR(tmp10,"tmp10");
HX_STACK_LINE(142)
::sys::io::FileOutput tmp11 = ::sys::io::File_obj::write(tmp10,false); HX_STACK_VAR(tmp11,"tmp11");
HX_STACK_LINE(142)
::sys::io::FileOutput output = tmp11; HX_STACK_VAR(output,"output");
HX_STACK_LINE(143)
::String tmp12 = encodedData; HX_STACK_VAR(tmp12,"tmp12");
HX_STACK_LINE(143)
output->writeString(tmp12);
HX_STACK_LINE(144)
output->close();
HX_STACK_LINE(148)
return ((Dynamic)((int)0));
}
}
HX_DEFINE_DYNAMIC_FUNC1(SharedObject_obj,flush,return )
Void SharedObject_obj::setProperty( ::String propertyName,Dynamic value){
{
HX_STACK_FRAME("openfl._legacy.net.SharedObject","setProperty",0x16fb7422,"openfl._legacy.net.SharedObject.setProperty","openfl/_legacy/net/SharedObject.hx",252,0xecec0fc2)
HX_STACK_THIS(this)
HX_STACK_ARG(propertyName,"propertyName")
HX_STACK_ARG(value,"value")
HX_STACK_LINE(254)
Dynamic tmp = this->data; HX_STACK_VAR(tmp,"tmp");
HX_STACK_LINE(254)
bool tmp1 = (tmp != null()); HX_STACK_VAR(tmp1,"tmp1");
HX_STACK_LINE(254)
if ((tmp1)){
HX_STACK_LINE(256)
Dynamic tmp2 = this->data; HX_STACK_VAR(tmp2,"tmp2");
HX_STACK_LINE(256)
::String tmp3 = propertyName; HX_STACK_VAR(tmp3,"tmp3");
HX_STACK_LINE(256)
Dynamic tmp4 = value; HX_STACK_VAR(tmp4,"tmp4");
HX_STACK_LINE(256)
::Reflect_obj::setField(tmp2,tmp3,tmp4);
}
}
return null();
}
HX_DEFINE_DYNAMIC_FUNC2(SharedObject_obj,setProperty,(void))
int SharedObject_obj::get_size( ){
HX_STACK_FRAME("openfl._legacy.net.SharedObject","get_size",0x9307155f,"openfl._legacy.net.SharedObject.get_size","openfl/_legacy/net/SharedObject.hx",272,0xecec0fc2)
HX_STACK_THIS(this)
HX_STACK_LINE(272)
return (int)0;
}
HX_DEFINE_DYNAMIC_FUNC0(SharedObject_obj,get_size,return )
Void SharedObject_obj::mkdir( ::String directory){
{
HX_STACK_FRAME("openfl._legacy.net.SharedObject","mkdir",0x083d447a,"openfl._legacy.net.SharedObject.mkdir","openfl/_legacy/net/SharedObject.hx",68,0xecec0fc2)
HX_STACK_ARG(directory,"directory")
HX_STACK_LINE(70)
::String tmp = directory; HX_STACK_VAR(tmp,"tmp");
HX_STACK_LINE(70)
::String tmp1 = ::StringTools_obj::replace(tmp,HX_HCSTRING("\\","\x5c","\x00","\x00","\x00"),HX_HCSTRING("/","\x2f","\x00","\x00","\x00")); HX_STACK_VAR(tmp1,"tmp1");
HX_STACK_LINE(70)
directory = tmp1;
HX_STACK_LINE(71)
::String total = HX_HCSTRING("","\x00","\x00","\x00","\x00"); HX_STACK_VAR(total,"total");
HX_STACK_LINE(73)
::String tmp2 = directory.substr((int)0,(int)1); HX_STACK_VAR(tmp2,"tmp2");
HX_STACK_LINE(73)
bool tmp3 = (tmp2 == HX_HCSTRING("/","\x2f","\x00","\x00","\x00")); HX_STACK_VAR(tmp3,"tmp3");
HX_STACK_LINE(73)
if ((tmp3)){
HX_STACK_LINE(75)
total = HX_HCSTRING("/","\x2f","\x00","\x00","\x00");
}
HX_STACK_LINE(79)
Array< ::String > parts = directory.split(HX_HCSTRING("/","\x2f","\x00","\x00","\x00")); HX_STACK_VAR(parts,"parts");
HX_STACK_LINE(80)
::String oldPath = HX_HCSTRING("","\x00","\x00","\x00","\x00"); HX_STACK_VAR(oldPath,"oldPath");
HX_STACK_LINE(82)
bool tmp4 = (parts->length > (int)0); HX_STACK_VAR(tmp4,"tmp4");
HX_STACK_LINE(82)
bool tmp5; HX_STACK_VAR(tmp5,"tmp5");
HX_STACK_LINE(82)
if ((tmp4)){
HX_STACK_LINE(82)
::String tmp6 = parts->__get((int)0); HX_STACK_VAR(tmp6,"tmp6");
HX_STACK_LINE(82)
::String tmp7 = tmp6; HX_STACK_VAR(tmp7,"tmp7");
HX_STACK_LINE(82)
int tmp8 = tmp7.indexOf(HX_HCSTRING(":","\x3a","\x00","\x00","\x00"),null()); HX_STACK_VAR(tmp8,"tmp8");
HX_STACK_LINE(82)
int tmp9 = tmp8; HX_STACK_VAR(tmp9,"tmp9");
HX_STACK_LINE(82)
tmp5 = (tmp9 > (int)-1);
}
else{
HX_STACK_LINE(82)
tmp5 = false;
}
HX_STACK_LINE(82)
if ((tmp5)){
HX_STACK_LINE(84)
::String tmp6 = ::Sys_obj::getCwd(); HX_STACK_VAR(tmp6,"tmp6");
HX_STACK_LINE(84)
oldPath = tmp6;
HX_STACK_LINE(85)
::String tmp7 = parts->__get((int)0); HX_STACK_VAR(tmp7,"tmp7");
HX_STACK_LINE(85)
::String tmp8 = (tmp7 + HX_HCSTRING("\\","\x5c","\x00","\x00","\x00")); HX_STACK_VAR(tmp8,"tmp8");
HX_STACK_LINE(85)
::Sys_obj::setCwd(tmp8);
HX_STACK_LINE(86)
parts->shift();
}
HX_STACK_LINE(90)
{
HX_STACK_LINE(90)
int _g = (int)0; HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(90)
while((true)){
HX_STACK_LINE(90)
bool tmp6 = (_g < parts->length); HX_STACK_VAR(tmp6,"tmp6");
HX_STACK_LINE(90)
bool tmp7 = !(tmp6); HX_STACK_VAR(tmp7,"tmp7");
HX_STACK_LINE(90)
if ((tmp7)){
HX_STACK_LINE(90)
break;
}
HX_STACK_LINE(90)
::String tmp8 = parts->__get(_g); HX_STACK_VAR(tmp8,"tmp8");
HX_STACK_LINE(90)
::String part = tmp8; HX_STACK_VAR(part,"part");
HX_STACK_LINE(90)
++(_g);
HX_STACK_LINE(92)
bool tmp9 = (part != HX_HCSTRING(".","\x2e","\x00","\x00","\x00")); HX_STACK_VAR(tmp9,"tmp9");
HX_STACK_LINE(92)
bool tmp10; HX_STACK_VAR(tmp10,"tmp10");
HX_STACK_LINE(92)
if ((tmp9)){
HX_STACK_LINE(92)
tmp10 = (part != HX_HCSTRING("","\x00","\x00","\x00","\x00"));
}
else{
HX_STACK_LINE(92)
tmp10 = false;
}
HX_STACK_LINE(92)
if ((tmp10)){
HX_STACK_LINE(94)
bool tmp11 = (total != HX_HCSTRING("","\x00","\x00","\x00","\x00")); HX_STACK_VAR(tmp11,"tmp11");
HX_STACK_LINE(94)
bool tmp12; HX_STACK_VAR(tmp12,"tmp12");
HX_STACK_LINE(94)
if ((tmp11)){
HX_STACK_LINE(94)
tmp12 = (total != HX_HCSTRING("/","\x2f","\x00","\x00","\x00"));
}
else{
HX_STACK_LINE(94)
tmp12 = false;
}
HX_STACK_LINE(94)
if ((tmp12)){
HX_STACK_LINE(96)
hx::AddEq(total,HX_HCSTRING("/","\x2f","\x00","\x00","\x00"));
}
HX_STACK_LINE(100)
hx::AddEq(total,part);
HX_STACK_LINE(102)
::String tmp13 = total; HX_STACK_VAR(tmp13,"tmp13");
HX_STACK_LINE(102)
bool tmp14 = ::sys::FileSystem_obj::exists(tmp13); HX_STACK_VAR(tmp14,"tmp14");
HX_STACK_LINE(102)
bool tmp15 = !(tmp14); HX_STACK_VAR(tmp15,"tmp15");
HX_STACK_LINE(102)
if ((tmp15)){
HX_STACK_LINE(104)
::String tmp16 = total; HX_STACK_VAR(tmp16,"tmp16");
HX_STACK_LINE(104)
::sys::FileSystem_obj::createDirectory(tmp16);
}
}
}
}
HX_STACK_LINE(112)
bool tmp6 = (oldPath != HX_HCSTRING("","\x00","\x00","\x00","\x00")); HX_STACK_VAR(tmp6,"tmp6");
HX_STACK_LINE(112)
if ((tmp6)){
HX_STACK_LINE(114)
::String tmp7 = oldPath; HX_STACK_VAR(tmp7,"tmp7");
HX_STACK_LINE(114)
::Sys_obj::setCwd(tmp7);
}
}
return null();
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(SharedObject_obj,mkdir,(void))
::String SharedObject_obj::getFilePath( ::String name,::String localPath){
HX_STACK_FRAME("openfl._legacy.net.SharedObject","getFilePath",0xc3ebf302,"openfl._legacy.net.SharedObject.getFilePath","openfl/_legacy/net/SharedObject.hx",153,0xecec0fc2)
HX_STACK_ARG(name,"name")
HX_STACK_ARG(localPath,"localPath")
HX_STACK_LINE(155)
::openfl::_legacy::filesystem::File tmp = ::openfl::_legacy::filesystem::File_obj::get_applicationStorageDirectory(); HX_STACK_VAR(tmp,"tmp");
HX_STACK_LINE(155)
::String path = tmp->nativePath; HX_STACK_VAR(path,"path");
HX_STACK_LINE(156)
::String tmp1 = (HX_HCSTRING("/","\x2f","\x00","\x00","\x00") + localPath); HX_STACK_VAR(tmp1,"tmp1");
HX_STACK_LINE(156)
::String tmp2 = (tmp1 + HX_HCSTRING("/","\x2f","\x00","\x00","\x00")); HX_STACK_VAR(tmp2,"tmp2");
HX_STACK_LINE(156)
::String tmp3 = name; HX_STACK_VAR(tmp3,"tmp3");
HX_STACK_LINE(156)
::String tmp4 = (tmp2 + tmp3); HX_STACK_VAR(tmp4,"tmp4");
HX_STACK_LINE(156)
::String tmp5 = (tmp4 + HX_HCSTRING(".sol","\xe2","\x74","\xbf","\x1e")); HX_STACK_VAR(tmp5,"tmp5");
HX_STACK_LINE(156)
hx::AddEq(path,tmp5);
HX_STACK_LINE(157)
::String tmp6 = path; HX_STACK_VAR(tmp6,"tmp6");
HX_STACK_LINE(157)
return tmp6;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(SharedObject_obj,getFilePath,return )
::openfl::_legacy::net::SharedObject SharedObject_obj::getLocal( ::String name,::String localPath,hx::Null< bool > __o_secure){
bool secure = __o_secure.Default(false);
HX_STACK_FRAME("openfl._legacy.net.SharedObject","getLocal",0x9fc0920a,"openfl._legacy.net.SharedObject.getLocal","openfl/_legacy/net/SharedObject.hx",162,0xecec0fc2)
HX_STACK_ARG(name,"name")
HX_STACK_ARG(localPath,"localPath")
HX_STACK_ARG(secure,"secure")
{
HX_STACK_LINE(164)
bool tmp = (localPath == null()); HX_STACK_VAR(tmp,"tmp");
HX_STACK_LINE(164)
if ((tmp)){
HX_STACK_LINE(166)
localPath = HX_HCSTRING("","\x00","\x00","\x00","\x00");
}
HX_STACK_LINE(176)
::String tmp1 = name; HX_STACK_VAR(tmp1,"tmp1");
HX_STACK_LINE(176)
::String tmp2 = localPath; HX_STACK_VAR(tmp2,"tmp2");
HX_STACK_LINE(176)
::String tmp3 = ::openfl::_legacy::net::SharedObject_obj::getFilePath(tmp1,tmp2); HX_STACK_VAR(tmp3,"tmp3");
HX_STACK_LINE(176)
::String filePath = tmp3; HX_STACK_VAR(filePath,"filePath");
HX_STACK_LINE(177)
::String rawData = HX_HCSTRING("","\x00","\x00","\x00","\x00"); HX_STACK_VAR(rawData,"rawData");
HX_STACK_LINE(179)
::String tmp4 = filePath; HX_STACK_VAR(tmp4,"tmp4");
HX_STACK_LINE(179)
bool tmp5 = ::sys::FileSystem_obj::exists(tmp4); HX_STACK_VAR(tmp5,"tmp5");
HX_STACK_LINE(179)
if ((tmp5)){
HX_STACK_LINE(181)
::String tmp6 = filePath; HX_STACK_VAR(tmp6,"tmp6");
HX_STACK_LINE(181)
::String tmp7 = ::sys::io::File_obj::getContent(tmp6); HX_STACK_VAR(tmp7,"tmp7");
HX_STACK_LINE(181)
rawData = tmp7;
}
struct _Function_1_1{
inline static Dynamic Block( ){
HX_STACK_FRAME("*","closure",0x5bdab937,"*.closure","openfl/_legacy/net/SharedObject.hx",187,0xecec0fc2)
{
hx::Anon __result = hx::Anon_obj::Create();
return __result;
}
return null();
}
};
HX_STACK_LINE(187)
Dynamic tmp6 = _Function_1_1::Block(); HX_STACK_VAR(tmp6,"tmp6");
HX_STACK_LINE(187)
Dynamic loadedData = tmp6; HX_STACK_VAR(loadedData,"loadedData");
HX_STACK_LINE(189)
bool tmp7 = (rawData != HX_HCSTRING("","\x00","\x00","\x00","\x00")); HX_STACK_VAR(tmp7,"tmp7");
HX_STACK_LINE(189)
bool tmp8; HX_STACK_VAR(tmp8,"tmp8");
HX_STACK_LINE(189)
if ((tmp7)){
HX_STACK_LINE(189)
tmp8 = (rawData != null());
}
else{
HX_STACK_LINE(189)
tmp8 = false;
}
HX_STACK_LINE(189)
if ((tmp8)){
HX_STACK_LINE(191)
try
{
HX_STACK_CATCHABLE(Dynamic, 0);
{
HX_STACK_LINE(193)
::haxe::Unserializer tmp9 = ::haxe::Unserializer_obj::__new(rawData); HX_STACK_VAR(tmp9,"tmp9");
HX_STACK_LINE(193)
::haxe::Unserializer unserializer = tmp9; HX_STACK_VAR(unserializer,"unserializer");
HX_STACK_LINE(194)
Dynamic tmp10 = ::Type_obj::resolveEnum_dyn(); HX_STACK_VAR(tmp10,"tmp10");
HX_STACK_LINE(194)
Dynamic tmp11 = ::openfl::_legacy::net::SharedObject_obj::resolveClass_dyn(); HX_STACK_VAR(tmp11,"tmp11");
struct _Function_3_1{
inline static Dynamic Block( Dynamic &tmp11,Dynamic &tmp10){
HX_STACK_FRAME("*","closure",0x5bdab937,"*.closure","openfl/_legacy/net/SharedObject.hx",194,0xecec0fc2)
{
hx::Anon __result = hx::Anon_obj::Create();
__result->Add(HX_HCSTRING("resolveEnum","\x0d","\x90","\x51","\xde") , tmp10,false);
__result->Add(HX_HCSTRING("resolveClass","\xac","\xbd","\xdd","\x80") , tmp11,false);
return __result;
}
return null();
}
};
HX_STACK_LINE(194)
Dynamic tmp12 = _Function_3_1::Block(tmp11,tmp10); HX_STACK_VAR(tmp12,"tmp12");
HX_STACK_LINE(194)
Dynamic tmp13 = tmp12; HX_STACK_VAR(tmp13,"tmp13");
HX_STACK_LINE(194)
unserializer->setResolver(tmp13);
HX_STACK_LINE(195)
Dynamic tmp14 = unserializer->unserialize(); HX_STACK_VAR(tmp14,"tmp14");
HX_STACK_LINE(195)
loadedData = tmp14;
}
}
catch(Dynamic __e){
{
HX_STACK_BEGIN_CATCH
Dynamic e = __e;{
HX_STACK_LINE(199)
::String tmp9 = (HX_HCSTRING("Could not unserialize SharedObject: ","\xef","\xee","\xc6","\xae") + name); HX_STACK_VAR(tmp9,"tmp9");
HX_STACK_LINE(199)
Dynamic tmp10 = hx::SourceInfo(HX_HCSTRING("SharedObject.hx","\xda","\x51","\x3d","\xf3"),199,HX_HCSTRING("openfl._legacy.net.SharedObject","\xf9","\x1d","\x0b","\xdf"),HX_HCSTRING("getLocal","\xf5","\xd8","\xc7","\xd8")); HX_STACK_VAR(tmp10,"tmp10");
HX_STACK_LINE(199)
::haxe::Log_obj::trace(tmp9,tmp10);
struct _Function_3_1{
inline static Dynamic Block( ){
HX_STACK_FRAME("*","closure",0x5bdab937,"*.closure","openfl/_legacy/net/SharedObject.hx",200,0xecec0fc2)
{
hx::Anon __result = hx::Anon_obj::Create();
return __result;
}
return null();
}
};
HX_STACK_LINE(200)
Dynamic tmp11 = _Function_3_1::Block(); HX_STACK_VAR(tmp11,"tmp11");
HX_STACK_LINE(200)
loadedData = tmp11;
}
}
}
}
HX_STACK_LINE(206)
::openfl::_legacy::net::SharedObject tmp9 = ::openfl::_legacy::net::SharedObject_obj::__new(name,localPath,loadedData); HX_STACK_VAR(tmp9,"tmp9");
HX_STACK_LINE(206)
::openfl::_legacy::net::SharedObject so = tmp9; HX_STACK_VAR(so,"so");
HX_STACK_LINE(207)
::openfl::_legacy::net::SharedObject tmp10 = so; HX_STACK_VAR(tmp10,"tmp10");
HX_STACK_LINE(207)
return tmp10;
}
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(SharedObject_obj,getLocal,return )
::hx::Class SharedObject_obj::resolveClass( ::String name){
HX_STACK_FRAME("openfl._legacy.net.SharedObject","resolveClass",0x5c912541,"openfl._legacy.net.SharedObject.resolveClass","openfl/_legacy/net/SharedObject.hx",212,0xecec0fc2)
HX_STACK_ARG(name,"name")
HX_STACK_LINE(214)
bool tmp = (name != null()); HX_STACK_VAR(tmp,"tmp");
HX_STACK_LINE(214)
if ((tmp)){
HX_STACK_LINE(216)
::String tmp1 = name; HX_STACK_VAR(tmp1,"tmp1");
HX_STACK_LINE(216)
bool tmp2 = ::StringTools_obj::startsWith(tmp1,HX_HCSTRING("neash.","\xef","\x97","\x2f","\x63")); HX_STACK_VAR(tmp2,"tmp2");
HX_STACK_LINE(216)
if ((tmp2)){
HX_STACK_LINE(218)
::String tmp3 = name; HX_STACK_VAR(tmp3,"tmp3");
HX_STACK_LINE(218)
::String tmp4 = ::StringTools_obj::replace(tmp3,HX_HCSTRING("neash.","\xef","\x97","\x2f","\x63"),HX_HCSTRING("openfl.","\x9e","\xba","\x42","\x40")); HX_STACK_VAR(tmp4,"tmp4");
HX_STACK_LINE(218)
name = tmp4;
}
HX_STACK_LINE(222)
::String tmp3 = name; HX_STACK_VAR(tmp3,"tmp3");
HX_STACK_LINE(222)
bool tmp4 = ::StringTools_obj::startsWith(tmp3,HX_HCSTRING("native.","\xb7","\x9a","\x13","\xb7")); HX_STACK_VAR(tmp4,"tmp4");
HX_STACK_LINE(222)
if ((tmp4)){
HX_STACK_LINE(224)
::String tmp5 = name; HX_STACK_VAR(tmp5,"tmp5");
HX_STACK_LINE(224)
::String tmp6 = ::StringTools_obj::replace(tmp5,HX_HCSTRING("native.","\xb7","\x9a","\x13","\xb7"),HX_HCSTRING("openfl.","\x9e","\xba","\x42","\x40")); HX_STACK_VAR(tmp6,"tmp6");
HX_STACK_LINE(224)
name = tmp6;
}
HX_STACK_LINE(228)
::String tmp5 = name; HX_STACK_VAR(tmp5,"tmp5");
HX_STACK_LINE(228)
bool tmp6 = ::StringTools_obj::startsWith(tmp5,HX_HCSTRING("flash.","\x7e","\xc4","\x22","\x38")); HX_STACK_VAR(tmp6,"tmp6");
HX_STACK_LINE(228)
if ((tmp6)){
HX_STACK_LINE(230)
::String tmp7 = name; HX_STACK_VAR(tmp7,"tmp7");
HX_STACK_LINE(230)
::String tmp8 = ::StringTools_obj::replace(tmp7,HX_HCSTRING("flash.","\x7e","\xc4","\x22","\x38"),HX_HCSTRING("openfl.","\x9e","\xba","\x42","\x40")); HX_STACK_VAR(tmp8,"tmp8");
HX_STACK_LINE(230)
name = tmp8;
}
HX_STACK_LINE(234)
::String tmp7 = name; HX_STACK_VAR(tmp7,"tmp7");
HX_STACK_LINE(234)
bool tmp8 = ::StringTools_obj::startsWith(tmp7,HX_HCSTRING("openfl._v2.","\x51","\x5c","\x9c","\x49")); HX_STACK_VAR(tmp8,"tmp8");
HX_STACK_LINE(234)
if ((tmp8)){
HX_STACK_LINE(236)
::String tmp9 = name; HX_STACK_VAR(tmp9,"tmp9");
HX_STACK_LINE(236)
::String tmp10 = ::StringTools_obj::replace(tmp9,HX_HCSTRING("openfl._v2.","\x51","\x5c","\x9c","\x49"),HX_HCSTRING("openfl._legacy.","\xe4","\x67","\x0c","\x9f")); HX_STACK_VAR(tmp10,"tmp10");
HX_STACK_LINE(236)
name = tmp10;
}
HX_STACK_LINE(240)
::String tmp9 = name; HX_STACK_VAR(tmp9,"tmp9");
HX_STACK_LINE(240)
::hx::Class tmp10 = ::Type_obj::resolveClass(tmp9); HX_STACK_VAR(tmp10,"tmp10");
HX_STACK_LINE(240)
::hx::Class value = tmp10; HX_STACK_VAR(value,"value");
HX_STACK_LINE(241)
bool tmp11 = (value == null()); HX_STACK_VAR(tmp11,"tmp11");
HX_STACK_LINE(241)
if ((tmp11)){
HX_STACK_LINE(241)
::String tmp12 = name; HX_STACK_VAR(tmp12,"tmp12");
HX_STACK_LINE(241)
::String tmp13 = ::StringTools_obj::replace(tmp12,HX_HCSTRING("openfl.","\x9e","\xba","\x42","\x40"),HX_HCSTRING("openfl._legacy.","\xe4","\x67","\x0c","\x9f")); HX_STACK_VAR(tmp13,"tmp13");
HX_STACK_LINE(241)
::hx::Class tmp14 = ::Type_obj::resolveClass(tmp13); HX_STACK_VAR(tmp14,"tmp14");
HX_STACK_LINE(241)
value = tmp14;
}
HX_STACK_LINE(243)
::hx::Class tmp12 = value; HX_STACK_VAR(tmp12,"tmp12");
HX_STACK_LINE(243)
return tmp12;
}
HX_STACK_LINE(247)
return null();
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(SharedObject_obj,resolveClass,return )
SharedObject_obj::SharedObject_obj()
{
}
void SharedObject_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(SharedObject);
HX_MARK_MEMBER_NAME(data,"data");
HX_MARK_MEMBER_NAME(size,"size");
HX_MARK_MEMBER_NAME(localPath,"localPath");
HX_MARK_MEMBER_NAME(name,"name");
::openfl::_legacy::events::EventDispatcher_obj::__Mark(HX_MARK_ARG);
HX_MARK_END_CLASS();
}
void SharedObject_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(data,"data");
HX_VISIT_MEMBER_NAME(size,"size");
HX_VISIT_MEMBER_NAME(localPath,"localPath");
HX_VISIT_MEMBER_NAME(name,"name");
::openfl::_legacy::events::EventDispatcher_obj::__Visit(HX_VISIT_ARG);
}
Dynamic SharedObject_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"data") ) { return data; }
if (HX_FIELD_EQ(inName,"size") ) { return inCallProp == hx::paccAlways ? get_size() : size; }
if (HX_FIELD_EQ(inName,"name") ) { return name; }
break;
case 5:
if (HX_FIELD_EQ(inName,"clear") ) { return clear_dyn(); }
if (HX_FIELD_EQ(inName,"close") ) { return close_dyn(); }
if (HX_FIELD_EQ(inName,"flush") ) { return flush_dyn(); }
break;
case 8:
if (HX_FIELD_EQ(inName,"get_size") ) { return get_size_dyn(); }
break;
case 9:
if (HX_FIELD_EQ(inName,"localPath") ) { return localPath; }
break;
case 11:
if (HX_FIELD_EQ(inName,"setProperty") ) { return setProperty_dyn(); }
}
return super::__Field(inName,inCallProp);
}
bool SharedObject_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 5:
if (HX_FIELD_EQ(inName,"mkdir") ) { outValue = mkdir_dyn(); return true; }
break;
case 8:
if (HX_FIELD_EQ(inName,"getLocal") ) { outValue = getLocal_dyn(); return true; }
break;
case 11:
if (HX_FIELD_EQ(inName,"getFilePath") ) { outValue = getFilePath_dyn(); return true; }
break;
case 12:
if (HX_FIELD_EQ(inName,"resolveClass") ) { outValue = resolveClass_dyn(); return true; }
}
return false;
}
Dynamic SharedObject_obj::__SetField(const ::String &inName,const Dynamic &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"data") ) { data=inValue.Cast< Dynamic >(); return inValue; }
if (HX_FIELD_EQ(inName,"size") ) { size=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"name") ) { name=inValue.Cast< ::String >(); return inValue; }
break;
case 9:
if (HX_FIELD_EQ(inName,"localPath") ) { localPath=inValue.Cast< ::String >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void SharedObject_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_HCSTRING("data","\x2a","\x56","\x63","\x42"));
outFields->push(HX_HCSTRING("size","\xc1","\xa0","\x53","\x4c"));
outFields->push(HX_HCSTRING("localPath","\xb0","\x6c","\x94","\x0c"));
outFields->push(HX_HCSTRING("name","\x4b","\x72","\xff","\x48"));
super::__GetFields(outFields);
};
#if HXCPP_SCRIPTABLE
static hx::StorageInfo sMemberStorageInfo[] = {
{hx::fsObject /*Dynamic*/ ,(int)offsetof(SharedObject_obj,data),HX_HCSTRING("data","\x2a","\x56","\x63","\x42")},
{hx::fsInt,(int)offsetof(SharedObject_obj,size),HX_HCSTRING("size","\xc1","\xa0","\x53","\x4c")},
{hx::fsString,(int)offsetof(SharedObject_obj,localPath),HX_HCSTRING("localPath","\xb0","\x6c","\x94","\x0c")},
{hx::fsString,(int)offsetof(SharedObject_obj,name),HX_HCSTRING("name","\x4b","\x72","\xff","\x48")},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo *sStaticStorageInfo = 0;
#endif
static ::String sMemberFields[] = {
HX_HCSTRING("data","\x2a","\x56","\x63","\x42"),
HX_HCSTRING("size","\xc1","\xa0","\x53","\x4c"),
HX_HCSTRING("localPath","\xb0","\x6c","\x94","\x0c"),
HX_HCSTRING("name","\x4b","\x72","\xff","\x48"),
HX_HCSTRING("clear","\x8d","\x71","\x5b","\x48"),
HX_HCSTRING("close","\xb8","\x17","\x63","\x48"),
HX_HCSTRING("flush","\xc4","\x62","\x9b","\x02"),
HX_HCSTRING("setProperty","\x17","\x12","\x99","\xdc"),
HX_HCSTRING("get_size","\x4a","\x5c","\x0e","\xcc"),
::String(null()) };
static void sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(SharedObject_obj::__mClass,"__mClass");
};
#ifdef HXCPP_VISIT_ALLOCS
static void sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(SharedObject_obj::__mClass,"__mClass");
};
#endif
hx::Class SharedObject_obj::__mClass;
static ::String sStaticFields[] = {
HX_HCSTRING("mkdir","\xaf","\x4c","\xb3","\x09"),
HX_HCSTRING("getFilePath","\xf7","\x90","\x89","\x89"),
HX_HCSTRING("getLocal","\xf5","\xd8","\xc7","\xd8"),
HX_HCSTRING("resolveClass","\xac","\xbd","\xdd","\x80"),
::String(null()) };
void SharedObject_obj::__register()
{
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_HCSTRING("openfl._legacy.net.SharedObject","\xf9","\x1d","\x0b","\xdf");
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &SharedObject_obj::__GetStatic;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mMarkFunc = sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(sStaticFields);
__mClass->mMembers = hx::Class_obj::dupFunctions(sMemberFields);
__mClass->mCanCast = hx::TCanCast< SharedObject_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = sStaticStorageInfo;
#endif
hx::RegisterClass(__mClass->mName, __mClass);
}
} // end namespace openfl
} // end namespace _legacy
} // end namespace net
| mit |
trabus/markdown-it-terminal | tests/test.js | 5951 | 'use strict';
var styles = require('ansi-styles');
var MarkdownIt = require('markdown-it');
var terminal = require('../');
var path = require('path');
var expect = require('chai').expect;
/*eslint-env mocha*/
describe('markdown-it-terminal', function () {
var md;
beforeEach(function () {
md = require('markdown-it')().use(terminal);
});
it('renders basic markdown', function() {
expect(md.render('# foo\n__bold__ **words**\n* un\n* ordered\n* list'))
.to.equal('\u001b[35m\u001b[4m\u001b[1m\nfoo\u001b[22m\u001b[24m\u001b[39m\n'+
'\u001b[0m\u001b[1mbold\u001b[22m \u001b[1mwords\u001b[22m\u001b[0m'+
'\n\n \u001b[0m* un\u001b[0m\n \u001b[0m* ordered\u001b[0m\n '+
'\u001b[0m* list\u001b[0m\n\n');
});
it('renders nested styles', function() {
expect(md.render('# foo __bold ~~del~~ and strong__'))
.to.equal('\u001b[35m\u001b[4m\u001b[1m\nfoo \u001b[1mbold \u001b[2m\u001b[90m'+
'\u001b[9mdel\u001b[29m\u001b[39m\u001b[22m and strong\u001b[22m'+
'\u001b[22m\u001b[24m\u001b[39m\n');
});
it('renders html', function() {
expect(md.render('<div>one</div>')).to.equal('\u001b[0m<div>one</div>\u001b[0m\n\n');
});
it('renders hr', function(){
expect(md.render('---'))
.to.have.string('\u001b[0m-----')
.to.have.string('-----\u001b[0m\n');
expect(md.render('***'))
.to.have.string('\u001b[0m-----')
.to.have.string('-----\u001b[0m\n');
expect(md.render('___'))
.to.have.string('\u001b[0m-----')
.to.have.string('-----\u001b[0m\n');
});
it('renders headers', function() {
expect(md.render('# h1\n## h2\n### h3\n#### h4\n##### h5\n###### h6'))
.to.equal('\u001b[35m\u001b[4m\u001b[1m\nh1\u001b[22m\u001b[24m\u001b[39m\n'+
'\u001b[32m\u001b[1m\nh2\u001b[22m\u001b[39m\n\u001b[32m\u001b[1m'+
'\nh3\u001b[22m\u001b[39m\n\u001b[32m\u001b[1m\nh4\u001b[22m'+
'\u001b[39m\n\u001b[32m\u001b[1m\nh5\u001b[22m\u001b[39m\n'+
'\u001b[32m\u001b[1m\nh6\u001b[22m\u001b[39m\n');
});
//TODO: nested list test
it('renders ordered list', function() {
expect(md.render('1. Item 1\n2. Item 2\n3. Item 3'))
.to.equal(' \u001b[0m1 Item 1\u001b[0m\n \u001b[0m2 Item 2\u001b[0m\n'+
' \u001b[0m3 Item 3\u001b[0m\n\u001b[0m\n');
});
it('renders links', function(){
expect(md.render('[test](http://www.test.com)')).to.equal('\u001b[0m\u001b[34mtest\u001b[39m\u001b[0m\n\n');
});
it('renders image links', function(){
expect(md.render(''))
.to.equal('\u001b[0m\u001b[34m \u001b[39m\n\u001b[0m\n\n');
});
it('renders strong', function(){
expect(md.render('**strong**')).to.equal('\u001b[0m\u001b[1mstrong\u001b[22m\u001b[0m\n\n');
expect(md.render('__strong__')).to.equal('\u001b[0m\u001b[1mstrong\u001b[22m\u001b[0m\n\n');
});
it('renders em', function(){
expect(md.render('*em*')).to.equal('\u001b[0m\u001b[3mem\u001b[23m\u001b[0m\n\n');
expect(md.render('_em_')).to.equal('\u001b[0m\u001b[3mem\u001b[23m\u001b[0m\n\n');
});
it('renders s (del)', function(){
expect(md.render('~~strike~~'))
.to.equal('\u001b[0m\u001b[2m\u001b[90m\u001b[9mstrike\u001b[29m\u001b[39m\u001b[22m\u001b[0m\n\n');
});
it('renders code inline', function(){
expect(md.render('`var foo = blah;`')).to.equal('\u001b[0m\u001b[33mvar foo = blah;\u001b[39m\u001b[0m\n\n');
});
it('renders code blocks', function(){
expect(md.render('```\nvar foo = blah;\nfunction bar() {\n return "bar";\n}\n```'))
.to.equal('\n\u001b[33mvar foo = blah;\nfunction bar() {\n return "bar";\n}\n\u001b[39m\n\n');
});
it('renders code highlighting', function(){
expect(md.render('```js\nvar foo = blah;\nfunction bar() {\n return "bar";\n}\n```'))
.to.equal('\n\u001b[33m\u001b[32mvar\u001b[39m \u001b[37mfoo\u001b[39m \u001b[93m=\u001b[39m'+
' \u001b[37mblah\u001b[39m\u001b[90m;\u001b[39m\n\u001b[94mfunction\u001b[39m \u001b[37m'+
'bar\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m\n \u001b[31m'+
'return\u001b[39m \u001b[92m"bar"\u001b[39m\u001b[90m;\u001b[39m\n\u001b[33m}\u001b[39m\n\u001b[39m\n\n');
});
it('allows overrides of basic styles', function() {
var markdown = new MarkdownIt().use(terminal,{styleOptions:{codespan:styles.green}});
expect(markdown.render('`code should be green`'))
.to.equal('\u001b[0m\u001b[32mcode should be green\u001b[39m\u001b[0m\n\n');
});
it('does not clobber default options', function() {
var markdown = new MarkdownIt().use(terminal,{styleOptions:{strong:styles.red}});
expect(markdown.render('**should be red**'))
.to.equal('\u001b[0m\u001b[31mshould be red\u001b[39m\u001b[0m\n\n');
var markdown2 = new MarkdownIt().use(terminal);
expect(markdown2.render('**should be default style**'))
.to.equal('\u001b[0m\u001b[1mshould be default style\u001b[22m\u001b[0m\n\n');
});
it('renders indents', function() {
var markdown = new MarkdownIt().use(terminal, { indent: ' ' });
expect(markdown.render('# h1\nfoo\n## h2\nbar\n#\nbaz'))
.to.equal('\u001b[35m\u001b[4m\u001b[1m\nh1\u001b[22m\u001b[24m\u001b[39m\n \u001b[0mfoo\u001b[0m\n\n' +
' \u001b[32m\u001b[1m\n h2\u001b[22m\u001b[39m\n \u001b[0mbar\u001b[0m\n\n \u001b[0mbaz\u001b[0m\n\n ');
});
it.skip('renders blue', function(){
console.log(md.render('<blue>content is blue and <red>this should be red</red> but this is blue</blue>'))
expect(md.render('<blue>blue</blue>'))
.to.equal('\u001b[0m\u001b[2m\u001b[90m\u001b[9mstrike\u001b[29m\u001b[39m\u001b[22m\u001b[0m\n\n');
});
}); | mit |
alf-tool/alf-sql | lib/alf/predicate/nodes/qualified_identifier.rb | 199 | module Alf
class Predicate
module QualifiedIdentifier
def to_sql(buffer = "")
buffer << qualifier.to_s << Sql::Expr::DOT << name.to_s
buffer
end
end
end
end
| mit |
ddieffen/YellowBrickV6Plotter | ZedGraph/LineObj.cs | 12970 | //============================================================================
//ZedGraph Class Library - A Flexible Line Graph/Bar Graph Library in C#
//Copyright © 2006 John Champion
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//=============================================================================
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace ZedGraph
{
/// <summary>
/// A class that represents a line segment object on the graph. A list of
/// GraphObj objects is maintained by the <see cref="GraphObjList"/> collection class.
/// </summary>
/// <remarks>
/// This should not be confused with the <see cref="LineItem" /> class, which represents
/// a set of points plotted together as a "curve". The <see cref="LineObj" /> class is
/// a single line segment, drawn as a "decoration" on the chart.</remarks>
///
/// <author> John Champion </author>
/// <version> $Revision: 3.4 $ $Date: 2007-01-25 07:56:09 $ </version>
[Serializable]
public class LineObj : GraphObj, ICloneable, ISerializable
{
#region Fields
/// <summary>
/// protected field that maintains the attributes of the line using an
/// instance of the <see cref="LineBase" /> class.
/// </summary>
protected LineBase _line;
#endregion
#region Properties
/// <summary>
/// A <see cref="LineBase" /> class that contains the attributes for drawing this
/// <see cref="LineObj" />.
/// </summary>
public LineBase Line
{
get { return _line; }
set { _line = value; }
}
#endregion
#region Constructors
/// <overloads>Constructors for the <see cref="LineObj"/> object</overloads>
/// <summary>
/// A constructor that allows the position, color, and size of the
/// <see cref="LineObj"/> to be pre-specified.
/// </summary>
/// <param name="color">An arbitrary <see cref="System.Drawing.Color"/> specification
/// for the arrow</param>
/// <param name="x1">The x position of the starting point that defines the
/// line. The units of this position are specified by the
/// <see cref="Location.CoordinateFrame"/> property.</param>
/// <param name="y1">The y position of the starting point that defines the
/// line. The units of this position are specified by the
/// <see cref="Location.CoordinateFrame"/> property.</param>
/// <param name="x2">The x position of the ending point that defines the
/// line. The units of this position are specified by the
/// <see cref="Location.CoordinateFrame"/> property.</param>
/// <param name="y2">The y position of the ending point that defines the
/// line. The units of this position are specified by the
/// <see cref="Location.CoordinateFrame"/> property.</param>
public LineObj( Color color, double x1, double y1, double x2, double y2 )
: base( x1, y1, x2 - x1, y2 - y1 )
{
_line = new LineBase( color );
this.Location.AlignH = AlignH.Left;
this.Location.AlignV = AlignV.Top;
}
/// <summary>
/// A constructor that allows only the position of the
/// line to be pre-specified. All other properties are set to
/// default values
/// </summary>
/// <param name="x1">The x position of the starting point that defines the
/// <see cref="LineObj"/>. The units of this position are specified by the
/// <see cref="Location.CoordinateFrame"/> property.</param>
/// <param name="y1">The y position of the starting point that defines the
/// <see cref="LineObj"/>. The units of this position are specified by the
/// <see cref="Location.CoordinateFrame"/> property.</param>
/// <param name="x2">The x position of the ending point that defines the
/// <see cref="LineObj"/>. The units of this position are specified by the
/// <see cref="Location.CoordinateFrame"/> property.</param>
/// <param name="y2">The y position of the ending point that defines the
/// <see cref="LineObj"/>. The units of this position are specified by the
/// <see cref="Location.CoordinateFrame"/> property.</param>
public LineObj( double x1, double y1, double x2, double y2 )
: this( LineBase.Default.Color, x1, y1, x2, y2 )
{
}
/// <summary>
/// Default constructor -- places the <see cref="LineObj"/> at location
/// (0,0) to (1,1). All other values are defaulted.
/// </summary>
public LineObj() : this( LineBase.Default.Color, 0, 0, 1, 1 )
{
}
/// <summary>
/// The Copy Constructor
/// </summary>
/// <param name="rhs">The <see cref="LineObj"/> object from which to copy</param>
public LineObj( LineObj rhs ) : base( rhs )
{
_line = new LineBase( rhs._line );
}
/// <summary>
/// Implement the <see cref="ICloneable" /> interface in a typesafe manner by just
/// calling the typed version of <see cref="Clone" />
/// </summary>
/// <returns>A deep copy of this object</returns>
object ICloneable.Clone()
{
return this.Clone();
}
/// <summary>
/// Typesafe, deep-copy clone method.
/// </summary>
/// <returns>A new, independent copy of this class</returns>
public LineObj Clone()
{
return new LineObj( this );
}
#endregion
#region Serialization
/// <summary>
/// Current schema value that defines the version of the serialized file
/// </summary>
// changed to 2 with addition of Style property
public const int schema2 = 11;
/// <summary>
/// Constructor for deserializing objects
/// </summary>
/// <param name="info">A <see cref="SerializationInfo"/> instance that defines the serialized data
/// </param>
/// <param name="context">A <see cref="StreamingContext"/> instance that contains the serialized data
/// </param>
protected LineObj( SerializationInfo info, StreamingContext context ) : base( info, context )
{
// The schema value is just a file version parameter. You can use it to make future versions
// backwards compatible as new member variables are added to classes
int sch = info.GetInt32( "schema2" );
_line = (LineBase)info.GetValue( "line", typeof( LineBase ) );
}
/// <summary>
/// Populates a <see cref="SerializationInfo"/> instance with the data needed to serialize the target object
/// </summary>
/// <param name="info">A <see cref="SerializationInfo"/> instance that defines the serialized data</param>
/// <param name="context">A <see cref="StreamingContext"/> instance that contains the serialized data</param>
[SecurityPermissionAttribute( SecurityAction.Demand, SerializationFormatter = true )]
public override void GetObjectData( SerializationInfo info, StreamingContext context )
{
base.GetObjectData( info, context );
info.AddValue( "schema2", schema2 );
info.AddValue( "line", _line );
}
#endregion
#region Rendering Methods
/// <summary>
/// Render this object to the specified <see cref="Graphics"/> device.
/// </summary>
/// <remarks>
/// This method is normally only called by the Draw method
/// of the parent <see cref="GraphObjList"/> collection object.
/// </remarks>
/// <param name="g">
/// A graphic device object to be drawn into. This is normally e.Graphics from the
/// PaintEventArgs argument to the Paint() method.
/// </param>
/// <param name="pane">
/// A reference to the <see cref="PaneBase"/> object that is the parent or
/// owner of this object.
/// </param>
/// <param name="scaleFactor">
/// The scaling factor to be used for rendering objects. This is calculated and
/// passed down by the parent <see cref="GraphPane"/> object using the
/// <see cref="PaneBase.CalcScaleFactor"/> method, and is used to proportionally adjust
/// font sizes, etc. according to the actual size of the graph.
/// </param>
override public void Draw( Graphics g, PaneBase pane, float scaleFactor )
{
// Convert the arrow coordinates from the user coordinate system
// to the screen coordinate system
PointF pix1 = this.Location.TransformTopLeft( pane );
PointF pix2 = this.Location.TransformBottomRight( pane );
if ( pix1.X > -10000 && pix1.X < 100000 && pix1.Y > -100000 && pix1.Y < 100000 &&
pix2.X > -10000 && pix2.X < 100000 && pix2.Y > -100000 && pix2.Y < 100000 )
{
// calculate the length and the angle of the arrow "vector"
double dy = pix2.Y - pix1.Y;
double dx = pix2.X - pix1.X;
float angle = (float)Math.Atan2( dy, dx ) * 180.0F / (float)Math.PI;
float length = (float)Math.Sqrt( dx * dx + dy * dy );
// Save the old transform matrix
Matrix transform = g.Transform;
// Move the coordinate system so it is located at the starting point
// of this arrow
g.TranslateTransform( pix1.X, pix1.Y );
// Rotate the coordinate system according to the angle of this arrow
// about the starting point
g.RotateTransform( angle );
// get a pen according to this arrow properties
using ( Pen pen = _line.GetPen( pane, scaleFactor ) )
//new Pen( _line._color, pane.ScaledPenWidth( _line._width, scaleFactor ) ) )
{
//pen.DashStyle = _style;
g.DrawLine( pen, 0, 0, length, 0 );
}
// Restore the transform matrix back to its original state
g.Transform = transform;
}
}
/// <summary>
/// Determine if the specified screen point lies inside the bounding box of this
/// <see cref="LineObj"/>.
/// </summary>
/// <remarks>The bounding box is calculated assuming a distance
/// of <see cref="GraphPane.Default.NearestTol"/> pixels around the arrow segment.
/// </remarks>
/// <param name="pt">The screen point, in pixels</param>
/// <param name="pane">
/// A reference to the <see cref="PaneBase"/> object that is the parent or
/// owner of this object.
/// </param>
/// <param name="g">
/// A graphic device object to be drawn into. This is normally e.Graphics from the
/// PaintEventArgs argument to the Paint() method.
/// </param>
/// <param name="scaleFactor">
/// The scaling factor to be used for rendering objects. This is calculated and
/// passed down by the parent <see cref="GraphPane"/> object using the
/// <see cref="PaneBase.CalcScaleFactor"/> method, and is used to proportionally adjust
/// font sizes, etc. according to the actual size of the graph.
/// </param>
/// <returns>true if the point lies in the bounding box, false otherwise</returns>
override public bool PointInBox( PointF pt, PaneBase pane, Graphics g, float scaleFactor )
{
if ( ! base.PointInBox(pt, pane, g, scaleFactor ) )
return false;
// transform the x,y location from the user-defined
// coordinate frame to the screen pixel location
PointF pix = _location.TransformTopLeft( pane );
PointF pix2 = _location.TransformBottomRight( pane );
using ( Pen pen = new Pen( Color.Black, (float)GraphPane.Default.NearestTol * 2.0F ) )
{
using ( GraphicsPath path = new GraphicsPath() )
{
path.AddLine( pix, pix2 );
return path.IsOutlineVisible( pt, pen );
}
}
}
/// <summary>
/// Determines the shape type and Coords values for this GraphObj
/// </summary>
override public void GetCoords( PaneBase pane, Graphics g, float scaleFactor,
out string shape, out string coords )
{
// transform the x,y location from the user-defined
// coordinate frame to the screen pixel location
RectangleF pixRect = _location.TransformRect( pane );
Matrix matrix = new Matrix();
if ( pixRect.Right == 0 )
pixRect.Width = 1;
float angle = (float) Math.Atan( ( pixRect.Top - pixRect.Bottom ) /
( pixRect.Left - pixRect.Right ) );
matrix.Rotate( angle, MatrixOrder.Prepend );
// Move the coordinate system to local coordinates
// of this text object (that is, at the specified
// x,y location)
matrix.Translate( -pixRect.Left, -pixRect.Top, MatrixOrder.Prepend );
PointF[] pts = new PointF[4];
pts[0] = new PointF( 0, 3 );
pts[1] = new PointF( pixRect.Width, 3 );
pts[2] = new PointF( pixRect.Width, -3 );
pts[3] = new PointF( 0, -3 );
matrix.TransformPoints( pts );
shape = "poly";
coords = String.Format( "{0:f0},{1:f0},{2:f0},{3:f0},{4:f0},{5:f0},{6:f0},{7:f0},",
pts[0].X, pts[0].Y, pts[1].X, pts[1].Y,
pts[2].X, pts[2].Y, pts[3].X, pts[3].Y );
}
#endregion
}
}
| mit |
albertboada/relativechange.js | test/relativechangeSpec.js | 5912 | describe("relativechange.js lib", function () {
var tests_data = [
{ ini: 100, fin: 400, chng: 3, pctg: 300, mltplr: 4 },
{ ini: 400, fin: 100, chng: -0.75, pctg: -75, mltplr: 0.25 },
{ ini: 100, fin: 100, chng: 0, pctg: 0, mltplr: 1 },
{ ini: 1, fin: 2, chng: 1, pctg: 100, mltplr: 2 },
{ ini: 5, fin: 2.5, chng: -0.5, pctg: -50, mltplr: 0.5 }
];
function _testloop(callback) {
for (var i=0; i<tests_data.length; i++) {
var t = tests_data[i];
callback(t);
}
}
describe("RawRelativeChange:", function () {
it("should not exist in global scope", function () {
expect(window.RawRelativeChange).toBeUndefined();
});
it("should exist in RelativeChange scope", function () {
expect(RelativeChange.Raw).toBeDefined();
});
it("initial & final values -> RelativeChange.Raw", function () {
_testloop(function (t) {
expect(RelativeChange.Raw.calculate(t.ini, t.fin).val()).toEqual(t.chng);
});
});
it("raw change value -> RelativeChange.Raw", function () {
var change = tests_data[0].change;
console.log(RelativeChange.Raw)
expect(RelativeChange.Raw.fromRaw(change).val()).toEqual(change);
});
it("percentage value -> RelativeChange.Raw", function () {
_testloop(function (t) {
expect(RelativeChange.Raw.fromPercentage(t.pctg).val()).toEqual(t.chng);
});
});
it("multiplier value -> RelativeChange.Raw", function () {
_testloop(function (t) {
expect(RelativeChange.Raw.fromMultiplier(t.mltplr).val()).toEqual(t.chng);
});
});
it("RelativeChange.Raw -> RelativeChange.Percentage", function () {
_testloop(function (t) {
expect(RelativeChange.Raw.calculate(t.ini, t.fin).percentage().val()).toEqual(t.pctg);
});
});
it("RelativeChange.Raw -> RelativeChange.Multiplier", function () {
_testloop(function (t) {
expect(RelativeChange.Raw.calculate(t.ini, t.fin).multiplier().val()).toEqual(t.mltplr);
});
});
});
describe("PercentageRelativeChange:", function () {
it("should not exist in global scope", function () {
expect(window.PercentageRelativeChange).toBeUndefined();
});
it("should exist in RelativeChange scope", function () {
expect(RelativeChange.Percentage).toBeDefined();
});
it("initial & final values -> RelativeChange.Percentage", function () {
_testloop(function (t) {
expect(RelativeChange.Percentage.calculate(t.ini, t.fin).val()).toEqual(t.pctg);
});
});
it("percentage value -> RelativeChange.Percentage", function () {
var percentage = tests_data[0].percentage;
expect(RelativeChange.Percentage.fromPercentage(percentage).val()).toEqual(percentage);
});
it("raw change value -> RelativeChange.Percentage", function () {
_testloop(function (t) {
expect(RelativeChange.Percentage.fromRaw(t.chng).val()).toEqual(t.pctg);
});
});
it("multiplier value -> RelativeChange.Percentage", function () {
_testloop(function (t) {
expect(RelativeChange.Percentage.fromMultiplier(t.mltplr).val()).toEqual(t.pctg);
});
});
it("RelativeChange.Percentage -> RelativeChange.Raw", function () {
_testloop(function (t) {
expect(RelativeChange.Percentage.calculate(t.ini, t.fin).raw().val()).toEqual(t.chng);
});
});
it("RelativeChange.Percentage -> RelativeChange.Multiplier", function () {
_testloop(function (t) {
expect(RelativeChange.Percentage.calculate(t.ini, t.fin).multiplier().val()).toEqual(t.mltplr);
});
});
});
describe("MultiplierRelativeChange:", function () {
it("should not exist in global scope", function () {
expect(window.MultiplierRelativeChange).toBeUndefined();
});
it("should exist in RelativeChange scope", function () {
expect(RelativeChange.Multiplier).toBeDefined();
});
it("initial & final values -> RelativeChange.Multiplier", function () {
_testloop(function (t) {
expect(RelativeChange.Multiplier.calculate(t.ini, t.fin).val()).toEqual(t.mltplr);
});
});
it("multiplier value -> RelativeChange.Multiplier", function () {
var multiplier = tests_data[0].multiplier;
expect(RelativeChange.Multiplier.fromMultiplier(multiplier).val()).toEqual(multiplier);
});
it("raw change value -> RelativeChange.Multiplier", function () {
_testloop(function (t) {
expect(RelativeChange.Multiplier.fromRaw(t.chng).val()).toEqual(t.mltplr);
});
});
it("percentage value -> RelativeChange.Multiplier", function () {
_testloop(function (t) {
expect(RelativeChange.Multiplier.fromPercentage(t.pctg).val()).toEqual(t.mltplr);
});
});
it("RelativeChange.Multiplier -> RelativeChange.Raw", function () {
_testloop(function (t) {
expect(RelativeChange.Multiplier.calculate(t.ini, t.fin).raw().val()).toEqual(t.chng);
});
});
it("RelativeChange.Multiplier -> RelativeChange.Percentage", function () {
_testloop(function (t) {
expect(RelativeChange.Multiplier.calculate(t.ini, t.fin).percentage().val()).toEqual(t.pctg);
});
});
});
}); | mit |
mjhapp/EWZSearchBundle | Tests/DependencyInjection/SearchExtensionTest.php | 817 | <?php
namespace EWZ\Bundle\SearchBundle\Tests\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use EWZ\Bundle\SearchBundle\DependencyInjection\EWZSearchExtension;
class SearchExtensionTest extends \PHPUnit_Framework_TestCase
{
/**
* @covers EWZ\Bundle\SearchBundle\DependencyInjection\EWZSearchExtension::load
*/
public function testConfigLoad()
{
$container = $this->getContainer();
$loader = new EWZSearchExtension();
$loader->load(array(), $container);
$this->assertEquals('Bundle\\SearchBundle\\Lucene\\LuceneSearch', $container->getParameter('ewz_search.lucene.search.class'), '->luceneLoad() loads the lucene.xml file if not already loaded');
}
}
| mit |
KatoTek/Gar | Gar.Business/Properties/AssemblyInfo.cs | 294 | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Gar.Business")]
[assembly: AssemblyDescription("")]
[assembly: Guid("ac77c187-ac2f-4c9a-af93-d9c5c7d42574")]
[assembly: AssemblyVersion("1.0.2016.308")]
[assembly: AssemblyFileVersion("1.0.2016.308")]
| mit |
Gunbard/ThreadWatch | theadwatch/src/main/java/honkhonk/threadwatch/retrievers/PostsRetriever.java | 7308 | package honkhonk.threadwatch.retrievers;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import org.json.JSONObject;
import java.util.ArrayList;
import honkhonk.threadwatch.ThreadWatch;
import honkhonk.threadwatch.helpers.Common;
import honkhonk.threadwatch.models.PostModel;
import honkhonk.threadwatch.models.PostsResponse;
import honkhonk.threadwatch.models.ThreadModel;
/**
* Retrieves all posts from a thread, and then tries to retrieve the first post thumbnail
* and the page the thread is on, in that order.
* TODO: Multithread these requests out
* Created by Gunbard on 10/11/2016.
*/
public class PostsRetriever implements ThumbnailRetriever.ThumbnailRetrieverListener,
PageDataRetriever.PageDataRetrieverListener {
/**
* List of listeners to notify about retrieval events
*/
private ArrayList<PostsRetrieverListener> listeners = new ArrayList<>();
/**
* Cached context
*/
private Context context;
/**
* Cached response
*/
private PostsResponse response;
/**
* The current thread this post retrieval is for
*/
private ThreadModel thread;
/**
* Retrieval events
*/
public interface PostsRetrieverListener {
/**
* Posts were retrieved successfully
* @param context Context of the retrieval
* @param thread The thread the posts were retrieved from
* @param posts The lists of posts that were retrieved
*/
void postsRetrieved(final Context context,
final ThreadModel thread,
final ArrayList<PostModel> posts);
/**
* Posts could not be retrieved. Site could be down, thread could have 404'd
* @param context Context of the retrieval
* @param thread The thread the posts were supposed to be retrieved from
*/
void postsRetrievalFailed(final Context context, final ThreadModel thread);
}
/**
* Adds to the list of listeners
* @param listener PostsRetrieverListener to notify about events
*/
public void addListener(final PostsRetrieverListener listener) {
listeners.add(listener);
}
/**
* Makes a request to get posts from a thread
* @param context Context for the retrieval
* @param thread The thread to retrieve posts from. Must have the board and id set.
*/
public void retrievePosts(final Context context, final ThreadModel thread) {
this.context = context;
this.thread = thread;
ConnectivityManager cm =
(ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
if (!isConnected) {
Log.i(this.getClass().getSimpleName(), "No network, so didn't refresh!");
for (final PostsRetrieverListener listener : listeners) {
listener.postsRetrievalFailed(context, thread);
}
return;
}
final String url =
"https://a.4cdn.org/"+ thread.board + "/thread/" + thread.id + ".json";
final JsonObjectRequest retrieveRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
PostsRetriever.this.thread.notFound = false;
PostsRetriever.this.response =
(new Gson()).fromJson(response.toString(), PostsResponse.class);
PostsRetriever.this.thread.attachmentId =
PostsRetriever.this.response.posts.get(0).attachmentId;
// Try to get OP thumbnail, too, if needed
final SharedPreferences appSettings =
PreferenceManager.getDefaultSharedPreferences(context);
final boolean shouldGetThumbnail =
appSettings.getBoolean("pref_view_thumbnails", true);
if (shouldGetThumbnail && PostsRetriever.this.thread.thumbnail == null) {
ThumbnailRetriever thumbnailRetriever = new ThumbnailRetriever();
thumbnailRetriever.addListener(PostsRetriever.this);
thumbnailRetriever.retrieveThumbnail(context, PostsRetriever.this.thread);
} else {
thumbnailRetrievalFinished(PostsRetriever.this.thread,
PostsRetriever.this.thread.thumbnail);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error != null &&
error.networkResponse != null &&
error.networkResponse.statusCode == 404) {
PostsRetriever.this.thread.notFound = true;
}
for (final PostsRetrieverListener listener : listeners) {
listener.postsRetrievalFailed(context, thread);
}
}
});
retrieveRequest.setShouldCache(false);
ThreadWatch.getInstance(context).addToRequestQueue(retrieveRequest);
}
/***********************************************
* ThumbnailRetriever.ThumbnailRetrieverListener
***********************************************/
@Override
public void thumbnailRetrievalFinished(final ThreadModel thread, final String encodedImage) {
this.thread.thumbnail = encodedImage;
PageDataRetriever pageDataRetriever = new PageDataRetriever();
pageDataRetriever.addListener(this);
pageDataRetriever.retrievePageData(context, this.thread);
}
/***********************************************
* PageDataRetriever.PageDataRetrieverListener
***********************************************/
@Override
public void pageDataRetrievalFinished(final ThreadModel thread, final int pageNumber) {
this.thread.isNowOnLastPage = (pageNumber >= Common.LAST_PAGE &&
this.thread.currentPage < Common.LAST_PAGE);
this.thread.currentPage = pageNumber;
for (final PostsRetrieverListener listener : listeners) {
if (response.posts != null) {
listener.postsRetrieved(context, this.thread, response.posts);
} else {
listener.postsRetrievalFailed(context, this.thread);
}
}
}
}
| mit |
Marcdnd/cryptoescudo | src/qt/locale/bitcoin_hi_IN.ts | 106583 | <?xml version="1.0" ?><!DOCTYPE TS><TS language="hi_IN" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Cryptoescudo</source>
<translation>बिटकोइन के संबंध में</translation>
</message>
<message>
<location line="+39"/>
<source><b>Cryptoescudo</b> version</source>
<translation>बिटकोइन वर्सन</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>कापीराइट</translation>
</message>
<message>
<location line="+0"/>
<source>The Cryptoescudo developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>पता पुस्तक</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>दो बार क्लिक करे पता या लेबल संपादन करने के लिए !</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>नया पता लिखिए !</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>चुनिन्दा पते को सिस्टम क्लिपबोर्ड पर कापी करे !</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&नया पता</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Cryptoescudo 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 filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&पता कॉपी करे</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Cryptoescudo address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Cryptoescudo address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&मिटाए !!</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Cryptoescudo addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>&लेबल कॉपी करे </translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&एडिट</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>पता पुस्तक का डेटा एक्सपोर्ट (निर्यात) करे !</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>ग़लतियाँ एक्सपोर्ट (निर्यात) करे!</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>फाइल में लिख नही सके %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>लेबल</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>पता</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(कोई लेबल नही !)</translation>
</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>पहचान शब्द/अक्षर डालिए !</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>नया पहचान शब्द/अक्षर डालिए !</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>दोबारा नया पहचान शब्द/अक्षर डालिए !</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>नया पहचान शब्द/अक्षर वॉलेट मे डालिए ! <br/> कृपा करके पहचान शब्द में <br> 10 से ज़्यादा अक्षॉरों का इस्तेमाल करे </b>,या <b>आठ या उससे से ज़्यादा शब्दो का इस्तेमाल करे</b> !</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>एनक्रिप्ट वॉलेट !</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>वॉलेट खोलने के आपका वॉलेट पहचान शब्द्/अक्षर चाईए !</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>वॉलेट खोलिए</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>वॉलेट डीक्रिप्ट( विकोड) करने के लिए आपका वॉलेट पहचान शब्द्/अक्षर चाईए !</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation> डीक्रिप्ट वॉलेट</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>पहचान शब्द/अक्षर बदलिये !</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>कृपा करके पुराना एवं नया पहचान शब्द/अक्षर वॉलेट में डालिए !</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>वॉलेट एनक्रिपशन को प्रमाणित कीजिए !</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR CRYPTOESCUDOS</b>!</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="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>वॉलेट एनक्रिप्ट हो गया !</translation>
</message>
<message>
<location line="-56"/>
<source>Cryptoescudo will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your cryptoescudos from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>वॉलेट एनक्रिप्ट नही हुआ!</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>वॉलेट एनक्रिपशन नाकाम हो गया इंटर्नल एरर की वजह से! आपका वॉलेट एनक्रीपत नही हुआ है!</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>आपके द्वारा डाले गये पहचान शब्द/अक्षर मिलते नही है !</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>वॉलेट का लॉक नही खुला !</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>वॉलेट डीक्रिप्ट करने के लिए जो पहचान शब्द/अक्षर डाले गये है वो सही नही है!</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>वॉलेट का डीक्रिप्ट-ष्ण असफल !</translation>
</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="+233"/>
<source>Sign &message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>नेटवर्क से समकालिक (मिल) रहा है ...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&विवरण</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>वॉलेट का सामानया विवरण दिखाए !</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>& लेन-देन
</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>देखिए पुराने लेन-देन के विवरण !</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>स्टोर किए हुए पते और लेबलओ को बदलिए !</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>पते की सूची दिखाए जिन्हे भुगतान करना है !</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>बाहर जायें</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>अप्लिकेशन से बाहर निकलना !</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Cryptoescudo</source>
<translation>बीटकोइन के बारे में जानकारी !</translation>
</message>
<message>
<location line="+2"/>
<source>About &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>&Options...</source>
<translation>&विकल्प</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&बैकप वॉलेट</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Cryptoescudo address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Cryptoescudo</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<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>पहचान शब्द/अक्षर जो वॉलेट एनक्रिपशन के लिए इस्तेमाल किया है उसे बदलिए!</translation>
</message>
<message>
<location line="+6"/>
<source>&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="-4"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Cryptoescudo</source>
<translation>बीटकोइन</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>वॉलेट</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About Cryptoescudo</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Cryptoescudo addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Cryptoescudo addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&फाइल</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&सेट्टिंग्स</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&मदद</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>टैबस टूलबार</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[टेस्टनेट]</translation>
</message>
<message>
<location line="+47"/>
<source>Cryptoescudo client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Cryptoescudo network</source>
<translation><numerusform>%n सक्रिया संपर्क बीटकोइन नेटवर्क से</numerusform><numerusform>%n सक्रिया संपर्क बीटकोइन नेटवर्क से</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n घंटा</numerusform><numerusform>%n घंटे</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n दिन</numerusform><numerusform>%n दिनो</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n हफ़्ता</numerusform><numerusform>%n हफ्ते</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>%1 पीछे</translation>
</message>
<message>
<location line="+14"/>
<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="+22"/>
<source>Error</source>
<translation>भूल</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>चेतावनी</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>जानकारी</translation>
</message>
<message>
<location line="+70"/>
<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="-140"/>
<source>Up to date</source>
<translation>नवीनतम</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>भेजी ट्रांजक्शन</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>प्राप्त हुई ट्रांजक्शन</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>तारीख: %1\n
राशि: %2\n
टाइप: %3\n
पता:%4\n</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Cryptoescudo address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड नहीं है</translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड है</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Cryptoescudo can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>पता एडिट करना</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&लेबल</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>इस एड्रेस बुक से जुड़ा एड्रेस</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&पता</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>इस एड्रेस बुक से जुड़ी प्रविष्टि केवल भेजने वाले addresses के लिए बदली जा सकती है|</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>नया स्वीकार्य पता</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>नया भेजने वाला पता</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>एडिट स्वीकार्य पता </translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>एडिट भेजने वाला पता</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>डाला गया पता "%1" एड्रेस बुक में पहले से ही मोजूद है|</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Cryptoescudo address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>वॉलेट को unlock नहीं किया जा सकता|</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>नयी कुंजी का निर्माण असफल रहा|</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Cryptoescudo-Qt</source>
<translation>बीटकोइन-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>संस्करण</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>खपत :</translation>
</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 "de_DE" (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>विकल्प</translation>
</message>
<message>
<location line="+16"/>
<source>&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.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start Cryptoescudo after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start Cryptoescudo on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Cryptoescudo 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 &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the Cryptoescudo network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &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>&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 &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>&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>&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&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &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 Cryptoescudo.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&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 Cryptoescudo addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&ओके</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&कैन्सल</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>चेतावनी</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Cryptoescudo.</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>फार्म</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Cryptoescudo network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>बाकी रकम :</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>अपुष्ट :</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>वॉलेट</translation>
</message>
<message>
<location line="+107"/>
<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="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>हाल का लेन-देन</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>आपका चालू बॅलेन्स</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>लेन देन की पुष्टि अभी नहीं हुई है, इसलिए इन्हें अभी मोजुदा बैलेंस में गिना नहीं गया है|</translation>
</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 cryptoescudo: 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>भुगतान का अनुरोध</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>राशि :</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>लेबल :</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&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"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>लागू नही
</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&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="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&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 Cryptoescudo-Qt help message to get a list with possible Cryptoescudo command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>Cryptoescudo - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Cryptoescudo Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the Cryptoescudo 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="-30"/>
<source>Welcome to the Cryptoescudo RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>सिक्के भेजें|</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>एक साथ कई प्राप्तकर्ताओं को भेजें</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>बाकी रकम :</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>भेजने की पुष्टि करें</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> से %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>सिक्के भेजने की पुष्टि करें</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>क्या आप %1 भेजना चाहते हैं?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>और</translation>
</message>
<message>
<location line="+23"/>
<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>भेजा गया अमाउंट शुन्य से अधिक होना चाहिए|</translation>
</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>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>फार्म</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>अमाउंट:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>प्राप्तकर्ता:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. CbLrmkaG65CM82MfU3sKDFMYwTNByZZR6h)</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>आपकी एड्रेस बुक में इस एड्रेस के लिए एक लेबल लिखें</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>लेबल:</translation>
</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>Alt-A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Clipboard से एड्रेस paste करें</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt-P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>प्राप्तकर्ता हटायें</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Cryptoescudo address (e.g. CbLrmkaG65CM82MfU3sKDFMYwTNByZZR6h)</source>
<translation>Cryptoescudo एड्रेस लिखें (उदाहरण: CbLrmkaG65CM82MfU3sKDFMYwTNByZZR6h)</translation>
</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"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<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. CbLrmkaG65CM82MfU3sKDFMYwTNByZZR6h)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt-A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Clipboard से एड्रेस paste करें</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt-P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>हस्ताक्षर</translation>
</message>
<message>
<location line="+27"/>
<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 Cryptoescudo address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<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. CbLrmkaG65CM82MfU3sKDFMYwTNByZZR6h)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Cryptoescudo address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Cryptoescudo address (e.g. CbLrmkaG65CM82MfU3sKDFMYwTNByZZR6h)</source>
<translation>Cryptoescudo एड्रेस लिखें (उदाहरण: CbLrmkaG65CM82MfU3sKDFMYwTNByZZR6h)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter Cryptoescudo 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>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Cryptoescudo developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>खुला है जबतक %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/अपुष्ट</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 पुष्टियाँ</translation>
</message>
<message>
<location line="+18"/>
<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><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>taareek</translation>
</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><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 120 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 "not accepted" and it won'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="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>राशि</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>सही</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>ग़लत</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, अभी तक सफलतापूर्वक प्रसारित नहीं किया गया है</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>अज्ञात</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>लेन-देन का विवरण</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation> ये खिड़की आपको लेन-देन का विस्तृत विवरण देगी !</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>taareek</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>टाइप</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>पता</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>राशि</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>खुला है जबतक %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>ऑफलाइन ( %1 पक्का करना)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>अपुष्ट ( %1 मे %2 पक्के )</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>पक्के ( %1 पक्का करना)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>यह ब्लॉक किसी भी और नोड को मिला नही है ! शायद यह ब्लॉक कोई भी नोड स्वीकारे गा नही !</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>जेनरेट किया गया किंतु स्वीकारा नही गया !</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>स्वीकारा गया</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>स्वीकार्य ओर से</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>भेजा गया</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>भेजा खुद को भुगतान</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>माइंड</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(लागू नहीं)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>ट्रांसेक्शन स्तिथि| पुष्टियों की संख्या जानने के लिए इस जगह पर माउस लायें|</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>तारीख तथा समय जब ये ट्रांसेक्शन प्राप्त हुई थी|</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>ट्रांसेक्शन का प्रकार|</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>ट्रांसेक्शन की मंजिल का पता|</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>अमाउंट बैलेंस से निकला या जमा किया गया |</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>सभी</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>आज</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>इस हफ्ते</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>इस महीने</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>पिछले महीने</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>इस साल</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>विस्तार...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>स्वीकार करना</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>भेजा गया</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>अपनेआप को</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>माइंड</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>अन्य</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>ढूँदने के लिए कृपा करके पता या लेबल टाइप करे !</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>लघुत्तम राशि</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>पता कॉपी करे</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>लेबल कॉपी करे </translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>कॉपी राशि</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>एडिट लेबल</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>लेन-देन का डेटा निर्यात करे !</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>पक्का</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>taareek</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>टाइप</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>लेबल</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>पता</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>राशि</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>ग़लतियाँ एक्सपोर्ट (निर्यात) करे!</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>फाइल में लिख नही सके %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>विस्तार:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>तक</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>बैकप वॉलेट</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>वॉलेट डेटा (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>बैकप असफल</translation>
</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>
<location line="+4"/>
<source>Backup Successful</source>
<translation>बैकप सफल</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Cryptoescudo version</source>
<translation>बीटकोइन संस्करण</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>खपत :</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or cryptoescudod</source>
<translation>-server या cryptoescudod को कमांड भेजें</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>commands की लिस्ट बनाएं</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>किसी command के लिए मदद लें</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>विकल्प:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: cryptoescudo.conf)</source>
<translation>configuraion की फाइल का विवरण दें (default: cryptoescudo.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: cryptoescudod.pid)</source>
<translation>pid फाइल का विवरण दें (default: cryptoescudo.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 61143 or testnet: 51143)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 61142 or testnet: 51142)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=cryptoescudorpc
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 "Cryptoescudo Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<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="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Cryptoescudo is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<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="+4"/>
<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>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>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<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="+5"/>
<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="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Cryptoescudo will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<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="+3"/>
<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="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>ब्लॉक्स जाँचे जा रहा है...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>वॉलेट जाँचा जा रहा है...</translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>जानकारी</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Cryptoescudo Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<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="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<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="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>चेतावनी</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-26"/>
<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="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>पता पुस्तक आ रही है...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Cryptoescudo</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Cryptoescudo to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>राशि ग़लत है</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>ब्लॉक इंडेक्स आ रहा है...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Cryptoescudo is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>वॉलेट आ रहा है...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>रि-स्केनी-इंग...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>लोड हो गया|</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>भूल</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> 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> | mit |
zerkms/symfony | src/Symfony/Component/Validator/Tests/Mapping/Factory/LazyLoadingMetadataFactoryTest.php | 8826 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Tests\Mapping\Factory;
use PHPUnit\Framework\TestCase;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Mapping\Cache\Psr6Cache;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory;
use Symfony\Component\Validator\Mapping\Loader\LoaderInterface;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;
use Symfony\Component\Validator\Tests\Fixtures\PropertyGetter;
use Symfony\Component\Validator\Tests\Fixtures\PropertyGetterInterface;
class LazyLoadingMetadataFactoryTest extends TestCase
{
private const CLASS_NAME = 'Symfony\Component\Validator\Tests\Fixtures\Entity';
private const PARENT_CLASS = 'Symfony\Component\Validator\Tests\Fixtures\EntityParent';
private const INTERFACE_A_CLASS = 'Symfony\Component\Validator\Tests\Fixtures\EntityInterfaceA';
public function testLoadClassMetadataWithInterface()
{
$factory = new LazyLoadingMetadataFactory(new TestLoader());
$metadata = $factory->getMetadataFor(self::PARENT_CLASS);
$constraints = [
new ConstraintA(['groups' => ['Default', 'EntityParent']]),
new ConstraintA(['groups' => ['Default', 'EntityInterfaceA', 'EntityParent']]),
];
$this->assertEquals($constraints, $metadata->getConstraints());
}
public function testMergeParentConstraints()
{
$factory = new LazyLoadingMetadataFactory(new TestLoader());
$metadata = $factory->getMetadataFor(self::CLASS_NAME);
$constraints = [
new ConstraintA(['groups' => [
'Default',
'Entity',
]]),
new ConstraintA(['groups' => [
'Default',
'EntityParent',
'Entity',
]]),
new ConstraintA(['groups' => [
'Default',
'EntityInterfaceA',
'EntityParent',
'Entity',
]]),
new ConstraintA(['groups' => [
'Default',
'EntityInterfaceB',
'Entity',
]]),
new ConstraintA(['groups' => [
'Default',
'EntityParentInterface',
'Entity',
]]),
];
$this->assertEquals($constraints, $metadata->getConstraints());
}
public function testCachedMetadata()
{
$cache = new ArrayAdapter();
$factory = new LazyLoadingMetadataFactory(new TestLoader(), $cache);
$expectedConstraints = [
new ConstraintA(['groups' => ['Default', 'EntityParent']]),
new ConstraintA(['groups' => ['Default', 'EntityInterfaceA', 'EntityParent']]),
];
$metadata = $factory->getMetadataFor(self::PARENT_CLASS);
$this->assertEquals(self::PARENT_CLASS, $metadata->getClassName());
$this->assertEquals($expectedConstraints, $metadata->getConstraints());
$loader = $this->createMock(LoaderInterface::class);
$loader->expects($this->never())->method('loadClassMetadata');
$factory = new LazyLoadingMetadataFactory($loader, $cache);
$metadata = $factory->getMetadataFor(self::PARENT_CLASS);
$this->assertEquals(self::PARENT_CLASS, $metadata->getClassName());
$this->assertEquals($expectedConstraints, $metadata->getConstraints());
}
/**
* @group legacy
*/
public function testWriteMetadataToLegacyCache()
{
$cache = new Psr6Cache(new ArrayAdapter());
$factory = new LazyLoadingMetadataFactory(new TestLoader(), $cache);
$parentClassConstraints = [
new ConstraintA(['groups' => ['Default', 'EntityParent']]),
new ConstraintA(['groups' => ['Default', 'EntityInterfaceA', 'EntityParent']]),
];
$metadata = $factory->getMetadataFor(self::PARENT_CLASS);
$this->assertEquals(self::PARENT_CLASS, $metadata->getClassName());
$this->assertEquals($parentClassConstraints, $metadata->getConstraints());
$this->assertInstanceOf(ClassMetadata::class, $cache->read(self::PARENT_CLASS));
$this->assertInstanceOf(ClassMetadata::class, $cache->read(self::INTERFACE_A_CLASS));
}
/**
* @group legacy
*/
public function testReadMetadataFromLegacyCache()
{
$loader = $this->getMockBuilder(LoaderInterface::class)->getMock();
$cache = $this->getMockBuilder(\Symfony\Component\Validator\Mapping\Cache\CacheInterface::class)->getMock();
$factory = new LazyLoadingMetadataFactory($loader, $cache);
$metadata = new ClassMetadata(self::PARENT_CLASS);
$metadata->addConstraint(new ConstraintA());
$parentClass = self::PARENT_CLASS;
$interfaceClass = self::INTERFACE_A_CLASS;
$loader->expects($this->never())
->method('loadClassMetadata');
$cache->expects($this->never())
->method('has');
$cache->expects($this->exactly(2))
->method('read')
->withConsecutive(
[self::PARENT_CLASS],
[self::INTERFACE_A_CLASS]
)
->willReturnCallback(function ($name) use ($metadata, $parentClass, $interfaceClass) {
if ($parentClass == $name) {
return $metadata;
}
return new ClassMetadata($interfaceClass);
});
$this->assertEquals($metadata, $factory->getMetadataFor(self::PARENT_CLASS));
}
public function testNonClassNameStringValues()
{
$this->expectException(\Symfony\Component\Validator\Exception\NoSuchMetadataException::class);
$testedValue = '[email protected]';
$loader = $this->getMockBuilder(LoaderInterface::class)->getMock();
$cache = $this->createMock(CacheItemPoolInterface::class);
$factory = new LazyLoadingMetadataFactory($loader, $cache);
$cache
->expects($this->never())
->method('getItem');
$factory->getMetadataFor($testedValue);
}
public function testMetadataCacheWithRuntimeConstraint()
{
$cache = new ArrayAdapter();
$factory = new LazyLoadingMetadataFactory(new TestLoader(), $cache);
$metadata = $factory->getMetadataFor(self::PARENT_CLASS);
$metadata->addConstraint(new Callback(function () {}));
$this->assertCount(3, $metadata->getConstraints());
$metadata = $factory->getMetadataFor(self::CLASS_NAME);
$this->assertCount(6, $metadata->getConstraints());
}
public function testGroupsFromParent()
{
$reader = new \Symfony\Component\Validator\Mapping\Loader\StaticMethodLoader();
$factory = new LazyLoadingMetadataFactory($reader);
$metadata = $factory->getMetadataFor('Symfony\Component\Validator\Tests\Fixtures\EntityStaticCarTurbo');
$groups = [];
foreach ($metadata->getPropertyMetadata('wheels') as $propertyMetadata) {
$constraints = $propertyMetadata->getConstraints();
$groups = array_replace($groups, $constraints[0]->groups);
}
$this->assertCount(4, $groups);
$this->assertContains('Default', $groups);
$this->assertContains('EntityStaticCarTurbo', $groups);
$this->assertContains('EntityStaticCar', $groups);
$this->assertContains('EntityStaticVehicle', $groups);
}
public function testMultipathInterfaceConstraint()
{
$factory = new LazyLoadingMetadataFactory(new PropertyGetterInterfaceConstraintLoader());
$metadata = $factory->getMetadataFor(PropertyGetter::class);
$constraints = $metadata->getPropertyMetadata('property');
$this->assertCount(1, $constraints);
}
}
class TestLoader implements LoaderInterface
{
public function loadClassMetadata(ClassMetadata $metadata): bool
{
$metadata->addConstraint(new ConstraintA());
return true;
}
}
class PropertyGetterInterfaceConstraintLoader implements LoaderInterface
{
public function loadClassMetadata(ClassMetadata $metadata)
{
if (PropertyGetterInterface::class === $metadata->getClassName()) {
$metadata->addGetterConstraint('property', new NotBlank());
}
return true;
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.