repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
peichhorn/tinyaudioplayer | src/main/java/de/fips/plugin/tinyaudioplayer/wizards/soundcloud/SearchPage.java | 2908 | /*
* Copyright © 2011-2012 Philipp Eichhorn.
*
* 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 de.fips.plugin.tinyaudioplayer.wizards.soundcloud;
import lombok.val;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
public class SearchPage extends WizardPage {
private Text searchText;
private Composite container;
public SearchPage() {
super("search.soundcloud");
setTitle("Search SoundCloud");
setDescription("Search SoundCloud...");
}
@Override
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible) {
searchText.setText("");
}
}
@Override
public void createControl(Composite parent) {
container = new Composite(parent, SWT.NULL);
val layout = new GridLayout();
container.setLayout(layout);
searchText = new Text(container, SWT.BORDER | SWT.SINGLE);
searchText.setData("org.eclipse.swtbot.widget.key", "searchText");
searchText.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (!getSearchText().isEmpty()) {
setPageComplete(true);
}
}
});
searchText.addVerifyListener(new VerifyListener() {
public void verifyText(VerifyEvent e) {
e.doit = e.text.matches("[a-zA-Z0-9 ]*");
}
});
val gd = new GridData(GridData.FILL_HORIZONTAL);
searchText.setLayoutData(gd);
setControl(container);
setPageComplete(false);
}
public String getSearchText() {
return searchText.getText();
}
} | mit |
glynnforrest/neptune | tests/Neptune/Tests/Swiftmailer/SwiftmailerFactoryTest.php | 5536 | <?php
namespace Neptune\Tests\Swiftmailer;
use Neptune\Swiftmailer\SwiftmailerFactory;
use Temping\Temping;
/**
* SwiftmailerFactoryTest
*
* @author Glynn Forrest <me@glynnforrest.com>
**/
class SwiftmailerFactoryTest extends \PHPUnit_Framework_TestCase
{
public function setup()
{
$this->factory = new SwiftmailerFactory(new \Swift_Events_SimpleEventDispatcher());
}
public function testInvalidTransport()
{
$this->setExpectedException('Neptune\Exceptions\DriverNotFoundException');
$this->factory->createTransport(['driver' => 'foo']);
}
public function testDefaultTransport()
{
$this->assertInstanceOf('\Swift_Transport_NullTransport', $this->factory->createTransport([]));
}
public function testNullTransport()
{
$config = [
'driver' => 'null',
];
$this->assertInstanceOf('\Swift_Transport_NullTransport', $this->factory->createTransport($config));
}
public function testDefaultSmtpTransport()
{
$config = [
'driver' => 'smtp',
];
$transport = $this->factory->createTransport($config);
$this->assertInstanceOf('\Swift_Transport_EsmtpTransport', $transport);
$this->assertSame('localhost', $transport->getHost());
$this->assertSame(25, $transport->getPort());
$this->assertSame('', $transport->getUsername());
$this->assertSame('', $transport->getPassword());
$this->assertSame(null, $transport->getEncryption());
$this->assertSame(null, $transport->getAuthMode());
}
public function testSmtpTransport()
{
$config = [
'driver' => 'smtp',
'host' => 'example.org',
'port' => 23,
'username' => 'user',
'password' => 'pass',
'encryption' => 'ssl',
'auth_mode' => 'login',
];
$transport = $this->factory->createTransport($config);
$this->assertInstanceOf('\Swift_Transport_EsmtpTransport', $transport);
$this->assertSame('example.org', $transport->getHost());
$this->assertSame(23, $transport->getPort());
$this->assertSame('user', $transport->getUsername());
$this->assertSame('pass', $transport->getPassword());
$this->assertSame('ssl', $transport->getEncryption());
$this->assertSame('login', $transport->getAuthMode());
}
public function testGmailTransport()
{
$config = [
'driver' => 'gmail',
'username' => 'example',
'password' => 'example',
];
$transport = $this->factory->createTransport($config);
$this->assertInstanceOf('\Swift_Transport_EsmtpTransport', $transport);
$this->assertSame('smtp.gmail.com', $transport->getHost());
$this->assertSame(465, $transport->getPort());
$this->assertSame('example', $transport->getUsername());
$this->assertSame('example', $transport->getPassword());
$this->assertSame('ssl', $transport->getEncryption());
$this->assertSame('login', $transport->getAuthMode());
}
public function testGmailTransportNoOverrideSettings()
{
$config = [
'driver' => 'gmail',
'username' => 'example',
'password' => 'example',
'host' => 'foo',
'port' => 42,
'auth_mode' => 'foo',
'encryption' => 'foo',
];
$transport = $this->factory->createTransport($config);
$this->assertInstanceOf('\Swift_Transport_EsmtpTransport', $transport);
$this->assertSame('smtp.gmail.com', $transport->getHost());
$this->assertSame(465, $transport->getPort());
$this->assertSame('example', $transport->getUsername());
$this->assertSame('example', $transport->getPassword());
$this->assertSame('ssl', $transport->getEncryption());
$this->assertSame('login', $transport->getAuthMode());
}
public function testInvalidSpool()
{
$this->setExpectedException('Neptune\Exceptions\DriverNotFoundException');
$this->factory->createSpool(['driver' => 'foo']);
}
public function testDefaultSpool()
{
$this->assertInstanceOf('\Swift_MemorySpool', $this->factory->createSpool([]));
}
public function testMemorySpool()
{
$config = ['driver' => 'memory'];
$this->assertInstanceOf('\Swift_MemorySpool', $this->factory->createSpool($config));
}
public function testFileSpoolNoPath()
{
$this->setExpectedException('Neptune\Config\Exception\ConfigKeyException');
$this->factory->createSpool(['driver' => 'file']);
}
public function testFileSpool()
{
//use a temporary directory so FileSpool can create the path it
//requires
$temping = new Temping();
$path = $temping->getPathname('foo/bar');
$config = [
'driver' => 'file',
'path' => $path,
];
$spool = $this->factory->createSpool($config);
//clean up the temporary directory before any assertions in case they
//fail
$temping->reset();
$this->assertInstanceOf('\Swift_FileSpool', $spool);
//FileSpool doesn't have a getPath() method
$r = new \ReflectionClass('\Swift_FileSpool');
$property = $r->getProperty('_path');
$property->setAccessible(true);
$this->assertSame($path, $property->getValue($spool));
}
}
| mit |
automenta/ensemble-clustering | ensemble-clustering/src/test/java/com/oculusinfo/math/linearalgebra/VectorTests.java | 2192 | /**
* Copyright (c) 2013 Oculus Info Inc.
* http://www.oculusinfo.com/
*
* Released under the MIT License.
*
* 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 com.oculusinfo.math.linearalgebra;
import junit.framework.Assert;
import org.junit.Test;
public class VectorTests {
@Test
public void testVectorEquality () {
Assert.assertFalse(new Vector(Double.NaN).equals(new Vector(0)));
Assert.assertFalse(new Vector(0).equals(new Vector(Double.NaN)));
Assert.assertTrue(new Vector(0).equals(new Vector(0)));
Assert.assertTrue(new Vector(Double.NaN).equals(new Vector(Double.NaN)));
}
@Test
public void testCrossProduct () {
Vector X = new Vector(1, 0, 0);
Vector Y = new Vector(0, 1, 0);
Vector Z = new Vector(0, 0, 1);
Assert.assertEquals(Z, X.cross(Y));
Assert.assertEquals(Y, Z.cross(X));
Assert.assertEquals(X, Y.cross(Z));
Assert.assertEquals(Z.scale(-1.0), Y.cross(X));
Assert.assertEquals(Y.scale(-1.0), X.cross(Z));
Assert.assertEquals(X.scale(-1.0), Z.cross(Y));
}
}
| mit |
Ac2zoom/giftgenie.io | src/com/amazonservices/mws/products/model/LowestOfferListingList.java | 4473 | /*******************************************************************************
* Copyright 2009-2015 Amazon Services. All Rights Reserved.
* 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://aws.amazon.com/apache2.0
* This file 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.
*******************************************************************************
* Lowest Offer Listing List
* API Version: 2011-10-01
* Library Version: 2015-02-13
* Generated: Tue Feb 10 14:34:49 PST 2015
*/
package com.amazonservices.mws.products.model;
import java.util.List;
import java.util.ArrayList;
import javax.xml.bind.annotation.*;
import com.amazonservices.mws.client.*;
/**
* LowestOfferListingList complex type.
*
* XML schema:
*
* <pre>
* <complexType name="LowestOfferListingList">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="LowestOfferListing" type="{http://mws.amazonservices.com/schema/Products/2011-10-01}LowestOfferListingType" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="LowestOfferListingList", propOrder={
"lowestOfferListing"
})
@XmlRootElement(name = "LowestOfferListingList")
public class LowestOfferListingList extends AbstractMwsObject {
@XmlElement(name="LowestOfferListing")
private List<LowestOfferListingType> lowestOfferListing;
/**
* Get the value of LowestOfferListing.
*
* @return The value of LowestOfferListing.
*/
public List<LowestOfferListingType> getLowestOfferListing() {
if (lowestOfferListing==null) {
lowestOfferListing = new ArrayList<LowestOfferListingType>();
}
return lowestOfferListing;
}
/**
* Set the value of LowestOfferListing.
*
* @param lowestOfferListing
* The new value to set.
*/
public void setLowestOfferListing(List<LowestOfferListingType> lowestOfferListing) {
this.lowestOfferListing = lowestOfferListing;
}
/**
* Clear LowestOfferListing.
*/
public void unsetLowestOfferListing() {
this.lowestOfferListing = null;
}
/**
* Check to see if LowestOfferListing is set.
*
* @return true if LowestOfferListing is set.
*/
public boolean isSetLowestOfferListing() {
return lowestOfferListing != null && !lowestOfferListing.isEmpty();
}
/**
* Add values for LowestOfferListing, return this.
*
* @param lowestOfferListing
* New values to add.
*
* @return This instance.
*/
public LowestOfferListingList withLowestOfferListing(LowestOfferListingType... values) {
List<LowestOfferListingType> list = getLowestOfferListing();
for (LowestOfferListingType value : values) {
list.add(value);
}
return this;
}
/**
* Read members from a MwsReader.
*
* @param r
* The reader to read from.
*/
@Override
public void readFragmentFrom(MwsReader r) {
lowestOfferListing = r.readList("LowestOfferListing", LowestOfferListingType.class);
}
/**
* Write members to a MwsWriter.
*
* @param w
* The writer to write to.
*/
@Override
public void writeFragmentTo(MwsWriter w) {
w.writeList("LowestOfferListing", lowestOfferListing);
}
/**
* Write tag, xmlns and members to a MwsWriter.
*
* @param w
* The Writer to write to.
*/
@Override
public void writeTo(MwsWriter w) {
w.write("http://mws.amazonservices.com/schema/Products/2011-10-01", "LowestOfferListingList",this);
}
/** Value constructor. */
public LowestOfferListingList(List<LowestOfferListingType> lowestOfferListing) {
this.lowestOfferListing = lowestOfferListing;
}
/** Default constructor. */
public LowestOfferListingList() {
super();
}
}
| mit |
wanjochan/cmp | app_root/webroot/_libs/cmp_bpm/LgcBPME.php | 6819 | <?php
class LgcBPME
{
//FOR ORM LEVEL
//public static function getDefaultDSN(){
// $dsn="db_app";
// return $dsn;
//}
const BPM_MODE_FUNC ='FUNC';//[SYNC]: Sync, Func
const BPM_MODE_DEFAULT ='DEFAULT';//[SYNC]: Sync, Local, Simple
//const BPM_MODE_LOCALIO ='LOCALIO';//[ASYNC] Sync + LocalFileIO
//const BPM_MODE_SESSION ='SESSION';//[ASYNC] Session Mode & Mode Sync
const BPM_MODE_ORM ='ORM';//[ASYNC] ORM Mode using Relative DB e.g. Mysql/Sqlite/MongoDB...
//const BPM_MODE_REDIS ='REDIS';//[ASYNC] Redis Mode//maybe give up
//const BPM_MODE_SWOOLE ='SWOOLE';//[ASYNC] using Swoole Server to do the object managerment
//For BPM_MODE_ORM:
const DEFAULT_BPME_TABLE='bpme';//引擎管理表 【WORKER THREAD】
const DEFAULT_BP_TABLE='bp';//bp实例管理表 【实例】
const DEFAULT_BP_FLOWOBJECT_TABLE='bpflowobject';//bp对象表 【实例】
//Flow Object Status Constants:
const FO_STATUS_NEW='NEW';
const FO_STATUS_LOCK='LOCK';
const FO_STATUS_DONE='DONE';
const FO_STATUS_JUMP='JUMP';
const ERRCODE_NOTFOUNDTASK=60404;
const DefaultHandleFatalError='defaultHandleFatalError';
const M_TYPE_PROGRAM = 'Program';
const M_TYPE_GATEWAY = 'Gateway';
const M_TYPE_EVENT = 'Event';
public function handleFuncMode($bpo, $_p){
$bpm_a=$bpo->bpm_a;
quicklog_must('BPM-DEBUG', 'LgcBPME.TODO{');
quicklog_must('BPM-DEBUG', 'bpo{');
quicklog_must('BPM-DEBUG', $bpo);
quicklog_must('BPM-DEBUG', 'bpo}');
quicklog_must('BPM-DEBUG', 'bpm_a{');
quicklog_must('BPM-DEBUG', $bpm_a);
quicklog_must('BPM-DEBUG', 'bpm_a}');
quicklog_must('BPM-DEBUG', 'LgcBPME.TODO}');
$output = array( 'STS'=>'TODO', 'errmsg'=>'handleFuncMode TODO' );
return $output;
}
//Design:
//https://www.processon.com/embed/570759a0e4b0dcddf98190f1
//for CMP, the param could have been put the _c/_m/lang/_s/etc/...
public function handle($_p, $timeout){
$rt=array('STS'=>'FATAL');
$_c=$_p['_c'];
BpmeTool::checkCond( !$_c, array("_c") );
BpmeTool::checkCond( strtolower(trim($_c))=='base', null, 'Not Allow Bpmn '.$_c );
$bpm_mode = $_p['bpm_mode'];
//if(!$bpm_mode){
// throw new Exception("bpm_mode is not config");
//}
$bpmn_c = 'Bp'.$_c;//safer, don't use $_c directly
if( class_exists( $bpmn_c ) ){
$bpo = new $bpmn_c( $bpmn_c );
}else{
throw new Exception("BPMN_NOT_FOUND $bpmn_c");
}
$bpm_a=$bpo->bpm_a;
if($bpm_mode==self::BPM_MODE_FUNC){
return $this->handleFuncMode($bpo, $_p);//Function Mode is Special
}
$properties=$bpm_a['properties'];
if(!$bpm_mode){
$bpm_mode = $properties['bpm_mode'];
if(!$bpm_mode) $bpm_mode= $properties['BpmMode'];
$bpm_mode = strtoupper($bpm_mode);
}
if(!$bpm_mode){
throw new Exception("bpm_mode is not config");
}
$bpm_flow_objects=$bpm_a['all'];
$_m=$_p['_m'];
if(!$_m){
$_m='start';
}
//get definition of the _m
$t=$bpm_flow_objects[$_m];
if(!$t){
throw new Exception("$_c.$_m undefined");
}
//bpm_entry_channel 是 bpm.php 给当前打上的.
$bpm_entry_channel=$_p['bpm_entry_channel'];//ref cmp
if($bpm_entry_channel=='WEB'){
$t_type=$t['type'];
$t_properties=$t['properties'];
$AllowWeb=$t_properties['AllowWeb'];
if ($AllowWeb===true || in_array(strtoupper($AllowWeb), array('YES','Y','TRUE'))){
//PASS if the _m.AllowWeb
}else{
if("UserTask"==$t_type){
//PASS IF UserTask (mostly for Web)...
}else{
$rt['errmsg']="$_c.$_m Not Allow Access From $bpm_entry_channel";
return $rt;
}
}
}
$bpm_timeout=$_p['bpm_timeout'];
//if(!$bpm_timeout) $bpm_timeout=getConf("bpm_timeout_default");//Seems no need
if($bpm_timeout>0){
set_time_limit($bpm_timeout);
#NOTES: In PHP-Safe-Mode, Fail to use ini_set() or set_time_limit() to change it. For that case, edit max_execution_time in the php.ini or not use safe-mode is the only solution.
}
/////////////////////// Basic check done... start to build FlowObject
$_p['bpm_mode'] = $bpm_mode;
$FlowObject = array(
'_c'=>$_c,
'_m'=>$_m,
'_p'=>$_p,
);
$system_code=$param['system_code'];
if(!$system_code){
$saas_conf=getConf("saas_conf");
if($saas_conf)
$system_code=$saas_conf['tenant_code'];
}
if($system_code){
$FlowObject['system_code']=$system_code;
}
if($bpm_timeout){
$FlowObject['bpm_timeout']=$bpm_timeout;
}
$env=array();
if($_SERVER) $env['SERVER']=$_SERVER;
if($_SESSION) $env['SESSION']=$_SESSION;
if($_REQUEST) $env['REQUEST']=$_REQUEST;
if($_GET) $env['GET']=$_GET;
if($_POST) $env['POST']=$_POST;
if($GLOBALS['HTTP_RAW_POST_DATA']) $env['HTTP_RAW_POST_DATA']=$GLOBALS['HTTP_RAW_POST_DATA'];
if ($env) $FlowObject['env']=$env;
//$flagAutoNotify=true;
//$BpmeInstance = self::getEngineInstance( $bpm_mode );
//$fo_id = $BpmeInstance->enqueueFlowObject(array(
// "fo"=>$FlowObject,
// "flagAutoNotify"=>$flagAutoNotify,//true will notify() automatically
//));
//if(!$flagAutoNotify) $BpmeInstance->notify("taskEnqueueed", array("fo_id"=>$fo_id));
$BpmeInstance = self::getEngineInstance( $bpm_mode );
$fo_id = $BpmeInstance->enqueueFlowObject(array(
"fo"=>$FlowObject,
));
//notify the engine there comes a task...
$BpmeInstance->notify("taskEnqueueed", array("fo_id"=>$fo_id));
//get the result when it stop, unless timeout:
//NOTES: the client may get the result to think whether to continue.
$query_rt_o = $BpmeInstance->queryLatestResultUntilTimeout(array(
'fo_id'=>$fo_id,
'bpm_timeout'=>$bpm_timeout,
));
$latest_result = $query_rt_o['result'];
if (is_string($latest_result)) {print $latest_result;return;}
$rt = array_merge( $rt, (array) $latest_result);
//TMP FOR DEBUG ONLY:
$rt['debug_rt']=$query_rt_o;
//$latest_fo = $query_rt_o['fo'];
//$rt['debug_fo']=$latest_fo;
return $rt;
}
protected static $cachedBpmeInstanceArray;
public static function getEngineInstance( $bpm_mode ){
if(!self::$cachedBpmeInstanceArray){
self::$cachedBpmeInstanceArray=array();
}
$cachedBpmeInstance = self::$cachedBpmeInstanceArray[ $bpm_mode ] ;
if( !$cachedBpmeInstance ){
switch( $bpm_mode ){
case self::BPM_MODE_DEFAULT:
$newBpmeIntance = new AppBpmeDefaultMode;
break;
case self::BPM_MODE_ORM:
$newBpmeIntance = new AppBpmeOrmMode;
break;
case self::BPM_MODE_FUNC:
$newBpmeIntance = new AppBpmeFuncMode;
break;
default:
throw new Exception("Unsupport bpm_mode $bpm_mode yet");
}
self::$cachedBpmeInstanceArray[ $bpm_mode ] = $newBpmeIntance;
return $newBpmeIntance;
}else{
return $cachedBpmeInstance;
}
}
}
| mit |
renstrom/oUF | elements/readycheck.lua | 3801 | --[[ Element: Ready Check Icon
Handles updating and visibility of `self.ReadyCheck` based upon the units
ready check status.
Widget
ReadyCheck - A Texture representing ready check status.
Notes
This element updates by changing the texture.
Options
.finishedTime - The number of seconds the icon should stick after a check has
completed. Defaults to 10 seconds.
.fadeTime - The number of seconds the icon should used to fade away after
the stick duration has completed. Defaults to 1.5 seconds.
Examples
-- Position and size
local ReadyCheck = self:CreateTexture(nil, 'OVERLAY')
ReadyCheck:SetSize(16, 16)
ReadyCheck:SetPoint('TOP')
-- Register with oUF
self.ReadyCheck = ReadyCheck
Hooks
Override(self) - Used to completely override the internal update function.
Removing the table key entry will make the element fall-back
to its internal function again.
]]
local parent, ns = ...
local oUF = ns.oUF
local _TIMERS = {}
local ReadyCheckFrame
local removeEntry = function(icon)
_TIMERS[icon] = nil
if(not next(_TIMERS)) then
return ReadyCheckFrame:Hide()
end
end
local Start = function(self)
removeEntry(self)
self:SetTexture(READY_CHECK_WAITING_TEXTURE)
self.state = 'waiting'
self:SetAlpha(1)
self:Show()
end
local Confirm = function(self, ready)
removeEntry(self)
if(ready) then
self:SetTexture(READY_CHECK_READY_TEXTURE)
self.state = 'ready'
else
self:SetTexture(READY_CHECK_NOT_READY_TEXTURE)
self.state = 'notready'
end
self:SetAlpha(1)
self:Show()
end
local Finish = function(self)
if(self.state == 'waiting') then
self:SetTexture(READY_CHECK_AFK_TEXTURE)
self.state = 'afk'
end
self.finishedTimer = self.finishedTime or 10
self.fadeTimer = self.fadeTime or 1.5
_TIMERS[self] = true
ReadyCheckFrame:Show()
end
local OnUpdate = function(self, elapsed)
for icon in next, _TIMERS do
if(icon.finishedTimer) then
icon.finishedTimer = icon.finishedTimer - elapsed
if(icon.finishedTimer <= 0) then
icon.finishedTimer = nil
end
elseif(icon.fadeTimer) then
icon.fadeTimer = icon.fadeTimer - elapsed
icon:SetAlpha(icon.fadeTimer / (icon.fadeTime or 1.5))
if(icon.fadeTimer <= 0) then
icon:Hide()
removeEntry(icon)
end
end
end
end
local Update = function(self, event)
local unit = self.unit
local readyCheck = self.ReadyCheck
if(event == 'READY_CHECK_FINISHED') then
Finish(readyCheck)
else
local status = GetReadyCheckStatus(unit)
if(UnitExists(unit) and status) then
if(status == 'ready') then
Confirm(readyCheck, 1)
elseif(status == 'notready') then
Confirm(readyCheck)
else
Start(readyCheck)
end
end
end
end
local Path = function(self, ...)
return (self.ReadyCheck.Override or Update) (self, ...)
end
local ForceUpdate = function(element)
return Path(element.__owner, 'ForceUpdate')
end
local Enable = function(self, unit)
local readyCheck = self.ReadyCheck
if(readyCheck and (unit and (unit:sub(1, 5) == 'party' or unit:sub(1,4) == 'raid'))) then
readyCheck.__owner = self
readyCheck.ForceUpdate = ForceUpdate
if(not ReadyCheckFrame) then
ReadyCheckFrame = CreateFrame'Frame'
ReadyCheckFrame:SetScript('OnUpdate', OnUpdate)
end
self:RegisterEvent('READY_CHECK', Path, true)
self:RegisterEvent('READY_CHECK_CONFIRM', Path, true)
self:RegisterEvent('READY_CHECK_FINISHED', Path, true)
return true
end
end
local Disable = function(self)
local readyCheck = self.ReadyCheck
if(readyCheck) then
readyCheck:Hide()
self:UnregisterEvent('READY_CHECK', Path)
self:UnregisterEvent('READY_CHECK_CONFIRM', Path)
self:UnregisterEvent('READY_CHECK_FINISHED', Path)
end
end
oUF:AddElement('ReadyCheck', Path, Enable, Disable)
| mit |
microsoftgraph/msgraph-sdk-java | src/main/java/com/microsoft/graph/requests/TimeOffReasonCollectionResponse.java | 766 | // Template Source: BaseEntityCollectionResponse.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.models.TimeOffReason;
import com.microsoft.graph.http.BaseCollectionResponse;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Time Off Reason Collection Response.
*/
public class TimeOffReasonCollectionResponse extends BaseCollectionResponse<TimeOffReason> {
}
| mit |
christopheschwyzer/StopheWebLab | chimp/js/chimp.js | 265 | $(document).ready(function () {
var frames = 8;
var chimp = $(".chimp");
var i = 0;
function animate() {
if(i < frames-1) {
i++;
} else {
i = 0;
}
chimp.css({"backgroundPosition": -i*chimp.width()});
}
window.setInterval(animate, 100);
});
| mit |
chaordic/node-restify | lib/response.js | 10504 | // Copyright 2012 Mark Cavage, Inc. All rights reserved.
var assert = require('assert');
var crypto = require('crypto');
var http = require('http');
var Stream = require('stream').Stream;
var util = require('util');
var mime = require('mime');
var errors = require('./errors');
var Request = require('./request');
///--- Globals
var Response = http.ServerResponse;
var sprintf = util.format;
var HttpError = errors.HttpError;
var RestError = errors.RestError;
var ALLOW_HEADERS = [
'Accept',
'Accept-Version',
'Content-Length',
'Content-MD5',
'Content-Type',
'Date',
'X-Api-Version'
].join(', ');
var EXPOSE_HEADERS = [
'X-Api-Version',
'X-Request-Id'
].join(', ');
var DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var MONTHS = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
];
///--- Helpers
function httpDate(now) {
if (!now)
now = new Date();
function pad(val) {
if (parseInt(val, 10) < 10)
val = '0' + val;
return val;
}
return DAYS[now.getUTCDay()] + ', ' +
pad(now.getUTCDate()) + ' ' +
MONTHS[now.getUTCMonth()] + ' ' +
now.getUTCFullYear() + ' ' +
pad(now.getUTCHours()) + ':' +
pad(now.getUTCMinutes()) + ':' +
pad(now.getUTCSeconds()) + ' GMT';
}
function setContentLength(res, length) {
if (res.getHeader('Content-Length') === undefined &&
res.contentLength === undefined) {
res.setHeader('Content-Length', length);
}
}
function formatBinary(req, res, body) {
if (!body) {
setContentLength(res, 0);
return null;
}
if (!Buffer.isBuffer(body))
body = new Buffer(body.toString());
setContentLength(res, body.length);
return body;
}
function formatText(req, res, body) {
if (!body) {
setContentLength(res, 0);
return null;
}
if (body instanceof Error) {
body = body.message;
} else if (typeof (body) === 'object') {
body = JSON.stringify(body);
} else {
body = body.toString();
}
setContentLength(res, Buffer.byteLength(body));
return body;
}
function formatJSON(req, res, body) {
if (!body) {
setContentLength(res, 0);
return null;
}
if (body instanceof Error) {
// snoop for RestError or HttpError, but don't rely on instanceof
if ((body.restCode || body.httpCode) && body.body) {
body = body.body;
} else {
body = {
message: body.message
};
}
}
if (Buffer.isBuffer(body))
body = body.toString('base64');
var data = JSON.stringify(body);
setContentLength(res, Buffer.byteLength(data));
return data;
}
function ensureDefaultFormatters(res) {
//
// We do this so that JSON formatters et al happen before custom ones,
// like HTML (i.e., if your client is curl, accept defaults to * / *, and
// v8 object keys are predictable, so we order them on the object such that
// JSON goes first
//
var save = res.formatters || {};
res.formatters = {};
if (!save['application/json'])
res.formatters['application/json'] = formatJSON;
if (!save['text/plain'])
res.formatters['text/plain'] = formatText;
if (!save['application/octet-stream'])
res.formatters['application/octet-stream'] = formatBinary;
Object.keys(save).forEach(function (k) {
if (!res.formatters[k])
res.formatters[k] = save[k];
});
return res;
}
function extendResponse(options) {
assert.ok(options instanceof Object);
var req = options.request;
var res = options.response;
res.charSet = false;
res.formatters = options.formatters;
res.id = req.id;
res.keepAlive = req.keepAlive;
res.log = options.log;
res._method = req.method;
res.methods = [];
res.responseTimeHeader = options.responseTimeHeader || 'X-Response-Time';
if (typeof (options.responseTimeFormatter) === 'function') {
res.responseTimeFormatter = options.responseTimeFormatter;
} else {
res.responseTimeFormatter = function defaultTimeFormatter(duration) {
return duration;
};
}
res.serverName = options.serverName || 'restify';
res.req = req;
ensureDefaultFormatters(res);
res.types = Object.keys(res.formatters);
return res;
}
///--- API
module.exports = {
extendResponse: extendResponse,
ACCEPTABLE: [
'application/json',
'text/plain',
'application/octet-stream'
]
};
if (!Response.prototype.hasOwnProperty('_writeHead')) {
Response.prototype._writeHead = Response.prototype.writeHead;
}
Response.prototype.writeHead = function restifyWriteHead() {
if (this.code !== undefined)
this.statusCode = this.code;
if (this.statusCode === 204 || this.statusCode === 304) {
this.removeHeader('Content-Length');
this.removeHeader('Content-MD5');
this.removeHeader('Content-Type');
}
this._writeHead.apply(this, arguments);
this.emit('header');
};
Response.prototype.header = function header(name, value) {
if (typeof (name) !== 'string')
throw new TypeError('name (String) required');
if (value === undefined)
return this.getHeader(name);
if (value instanceof Date)
value = httpDate(value);
// Support res.header('foo', 'bar %s', 'baz');
if (arguments.length > 2)
value = sprintf(value, Array.prototype.slice.call(arguments).slice(2));
this.setHeader(name, value);
return value;
};
Response.prototype.get = function get(name) {
return this.getHeader(name);
};
Response.prototype.set = function set(name, val) {
if (arguments.length === 2) {
if (typeof (name) !== 'string')
throw new TypeError('name (String) required');
this.header(name, val);
} else {
if (typeof (name) !== 'object')
throw new TypeError('Object required for argument 1');
var self = this;
Object.keys(name).forEach(function (k) {
self.header(k, name[k]);
});
}
return this;
};
Response.prototype.cache = function cache(type, options) {
if (typeof (type) !== 'string') {
options = type;
type = 'public';
}
if (options && options.maxAge) {
if (typeof (options.maxAge) !== 'number')
throw new TypeError('options.maxAge (Number) required');
type += ', max-age=' + (options.maxAge / 1000);
}
return this.setHeader('Cache-Control', type);
};
Response.prototype.link = function link(l, rel) {
if (typeof (l) !== 'string')
throw new TypeError('link (String) required');
if (typeof (rel) !== 'string')
throw new TypeError('rel (String) required');
var _link = sprintf('<%s>; rel="%s"', l, rel);
return this.setHeader('Link', _link);
};
Response.prototype.status = function status(code) {
this.statusCode = code;
return this;
};
Response.prototype.defaultResponseHeaders = function defaultHeaders(data) {
if (!this.getHeader('Connection'))
this.setHeader('Connection', this.keepAlive ? 'Keep-Alive' : 'close');
if (!this.getHeader('Content-Length')) {
if (this.contentLength !== undefined) {
this.setHeader('Content-Length', this.contentLength);
} else if (data) {
if (Buffer.isBuffer(data)) {
this.setHeader('Content-Length', data.length);
} else {
this.setHeader('Content-Length', Buffer.byteLength(data));
}
}
}
if (!this.getHeader('Content-MD5') && data) {
var hash = crypto.createHash('md5');
hash.update(data);
this.setHeader('Content-MD5', hash.digest('base64'));
}
if (this.header('Content-Type') || this.contentType) {
var type = this.header('Content-Type') || this.contentType;
if (this.charSet)
type += '; charset=' + this.charSet;
this.setHeader('Content-Type', type);
}
var now = new Date();
if (!this.getHeader('Date'))
this.setHeader('Date', httpDate(now));
if (this.etag && !this.getHeader('Etag'))
this.setHeader('Etag', this.etag);
this.setHeader('Server', this.serverName);
if (this.version)
this.setHeader('X-Api-Version', this.version);
this.setHeader('X-Request-Id', this.id);
if (!this.getHeader(this.responseTimeHeader))
this.setHeader(this.responseTimeHeader,
this.responseTimeFormatter(now.getTime() -
this.req.time.getTime()));
};
Response.prototype.send = function send(body) {
var head = (this._method === 'HEAD');
switch (arguments.length) {
case 0:
body = null;
break;
case 1:
if (typeof (body) === 'number') {
this.statusCode = body;
body = null;
} else if (body instanceof Error) {
this.statusCode = body.statusCode || 500;
}
break;
default:
this.statusCode = body;
body = arguments[1];
break;
}
// the formatter might tack in Content- headers, so fill in headers after
// serialization
var data = body ? this.format(body) : null;
this.emit('beforeSend', data);
this.defaultResponseHeaders(data);
this.writeHead(this.statusCode, this.headers);
if (data && !head && this.statusCode !== 204 && this.statusCode !== 304) {
this.write(data);
this._body = data;
}
this.end();
var self = this;
this.log.trace({res: self}, 'response sent');
return this;
};
Response.prototype.json = function json(obj) {
if (arguments.length === 2) {
this.statusCode = obj;
obj = arguments[1];
}
if (typeof (obj) !== 'object')
throw new TypeError('object (Object) required');
this.contentType = 'application/json';
return this.send(obj);
};
Response.prototype.format = function format(body) {
var log = this.log;
var type = this.contentType || this.getHeader('Content-Type');
log.trace('format entered(type=%s)', type);
if (!type) {
for (var i = 0; i < this.types.length; i++) {
if (this.req.accepts(this.types[i])) {
type = this.types[i];
break;
}
}
} else if (type.indexOf('/') === -1) {
type = mime.lookup(type);
}
if (this.types.indexOf(type) === -1) {
type = 'application/octet-stream';
log.trace('format content-type overriden: %s', type);
}
assert.ok(this.formatters[type]);
this.setHeader('Content-Type', type);
var data = this.formatters[type](this.req, this, body);
log.trace('format(%s) returning: %s', type, data);
return data;
};
Response.prototype.toString = function toString() {
var headers = '';
var self = this;
Object.keys(this.headers).forEach(function (k) {
headers += k + ': ' + self.headers[k] + '\n';
});
return 'HTTP/1.1 ' + this.statusCode + ' ' +
http.STATUS_CODES[this.statusCode] + '\n' + headers;
};
| mit |
scholtzm/wiki-parser | src/sk/scholtz/wikiparser/tests/XmlParserTest.java | 2141 | package sk.scholtz.wikiparser.tests;
import static org.junit.Assert.*;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import sk.scholtz.wikiparser.*;
/**
* Tests for our XmlParser
*
* @author Michael Scholtz
*
*/
public class XmlParserTest {
private static final String INPUTFILE = "res/sample_alts_skwiki-latest-pages-articles.xml";
private static final String VALIDOUTPUTFILE = "res/output_sample_alts_skwiki-latest-pages-articles.xml";
private static final String OUTPUTFILE = "output.xml";
private static XmlParser xmlParser;
@BeforeClass
public static void runBeforeAllTests() {
xmlParser = new XmlParser();
}
@Test
public void parsedStructureIsNotNull() {
ArrayList<Page> output = xmlParser.parseWiki(new File(INPUTFILE).getAbsolutePath());
assertNotNull("Parsed input file is not null.", output);
}
@Test
public void outputFileShouldExist() {
ArrayList<Page> wikiPages = xmlParser.parseWiki(new File(INPUTFILE).getAbsolutePath());
Processor processor = new Processor(wikiPages);
HashMap<String, Record> wikiRecords = processor.DoWork();
xmlParser.write(OUTPUTFILE, wikiRecords);
if (!new File(OUTPUTFILE).exists()) {
fail("Output file: \'" + OUTPUTFILE + "\' was not created.");
}
}
@Test
public void outputFileMatchesValidFile() {
outputFileShouldExist();
HashMap<String, Record> valid = xmlParser.parseDump(new File(VALIDOUTPUTFILE).getAbsolutePath());
HashMap<String, Record> generated = xmlParser.parseDump(new File(OUTPUTFILE).getAbsolutePath());
try {
assertEquals("Sample output file matches generated output file.", valid, generated);
} catch (Exception e) {
fail("Caught exception: " + e.getMessage());
}
}
@AfterClass
public static void cleanUp() {
File file = new File(OUTPUTFILE);
if (file.exists()) {
file.delete();
}
}
}
| mit |
valentin7/pianoHero | src/main/resources/static/js/highscores.js | 435 |
$(document).ready(function() {
console.log("PIANO HERO");
});
function getHighScores() {
$.get("/getsongs", function(responseJSON) {
var songs = JSON.parse(responseJSON);
for (i = 0; i < songs.length; i++) {
var song = {
songID: songs[i]._id,
songTitle: songs[i]._title,
songImage: songs[i]._imagePath
}
list.push(song);
}
curr = list[currInd];
setPageElements();
} | mit |
bghgary/glTF-Asset-Generator | Source/ModelGroups/Node_NegativeScale.cs | 8547 | using AssetGenerator.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
namespace AssetGenerator.ModelGroups
{
internal class Node_NegativeScale : ModelGroup
{
public override ModelGroupId Id => ModelGroupId.Node_NegativeScale;
public Node_NegativeScale(List<string> imageList)
{
var baseColorTexture = new Texture { Source = UseTexture(imageList, "BaseColor_Nodes") };
var normalTexture = new Texture { Source = UseTexture(imageList, "Normal_Nodes") };
var metallicRoughnessTexture = new Texture { Source = UseTexture(imageList, "MetallicRoughness_Nodes") };
// Track the common properties for use in the readme.
var translationValue = new Vector3(0, 2, 0);
Matrix4x4 matrixTranslationValue = Matrix4x4.CreateTranslation(translationValue);
CommonProperties.Add(new Property(PropertyName.Translation, translationValue.ToReadmeString()));
CommonProperties.Add(new Property(PropertyName.BaseColorTexture, baseColorTexture.Source.ToReadmeString()));
CommonProperties.Add(new Property(PropertyName.NormalTexture, normalTexture.Source.ToReadmeString()));
CommonProperties.Add(new Property(PropertyName.MetallicRoughnessTexture, metallicRoughnessTexture.Source.ToReadmeString()));
Model CreateModel(Action<List<Property>, Node, Node> setProperties)
{
var properties = new List<Property>();
List<Node> nodes = Nodes.CreateMultiNode();
// Apply the common properties to the gltf.
foreach (var node in nodes)
{
node.Mesh.MeshPrimitives.First().Material = new Runtime.Material
{
NormalTexture = new NormalTextureInfo { Texture = normalTexture },
PbrMetallicRoughness = new PbrMetallicRoughness
{
BaseColorTexture = new TextureInfo { Texture = baseColorTexture },
MetallicRoughnessTexture = new TextureInfo { Texture = metallicRoughnessTexture },
},
};
}
// Apply the properties that are specific to this gltf.
setProperties(properties, nodes[0], nodes[1]);
// Applies a translation to avoid clipping the other node.
// Models with a matrix applied have the translation applied in that matrix.
if (properties.Find(e => e.Name == PropertyName.Matrix) == null)
{
nodes[1].Translation = translationValue;
}
// Create the gltf object.
return new Model
{
Properties = properties,
GLTF = CreateGLTF(() => new Scene
{
Nodes = new[]
{
nodes[0]
}
})
};
}
void SetMatrixScaleX(List<Property> properties, Node node)
{
node.Matrix = Matrix4x4.Multiply(Matrix4x4.CreateScale(new Vector3(-1.0f, 1.0f, 1.0f)), matrixTranslationValue);
properties.Add(new Property(PropertyName.Matrix, node.Matrix.ToReadmeString()));
}
void SetMatrixScaleXY(List<Property> properties, Node node)
{
node.Matrix = Matrix4x4.Multiply(Matrix4x4.CreateScale(new Vector3(-1.0f, -1.0f, 1.0f)), matrixTranslationValue);
properties.Add(new Property(PropertyName.Matrix, node.Matrix.ToReadmeString()));
}
void SetMatrixScaleXYZ(List<Property> properties, Node node)
{
node.Matrix = Matrix4x4.Multiply(Matrix4x4.CreateScale(new Vector3(-1.0f, -1.0f, -1.0f)), matrixTranslationValue);
properties.Add(new Property(PropertyName.Matrix, node.Matrix.ToReadmeString()));
}
void SetScaleX(List<Property> properties, Node node)
{
node.Scale = new Vector3(-1.0f, 1.0f, 1.0f);
properties.Add(new Property(PropertyName.Scale, node.Scale.ToReadmeString()));
}
void SetScaleXY(List<Property> properties, Node node)
{
node.Scale = new Vector3(-1.0f, -1.0f, 1.0f);
properties.Add(new Property(PropertyName.Scale, node.Scale.ToReadmeString()));
}
void SetScaleXYZ(List<Property> properties, Node node)
{
node.Scale = new Vector3(-1.0f, -1.0f, -1.0f);
properties.Add(new Property(PropertyName.Scale, node.Scale.ToReadmeString()));
}
void SetVertexNormal(List<Property> properties, Node nodeZero, Node nodeOne)
{
var normals = Data.Create(Nodes.GetMultiNodeNormals());
nodeZero.Mesh.MeshPrimitives.First().Normals = normals;
nodeOne.Mesh.MeshPrimitives.First().Normals = normals;
properties.Add(new Property(PropertyName.VertexNormal, ":white_check_mark:"));
}
void SetVertexTangent(List<Property> properties, Node nodeZero, Node nodeOne)
{
var tangents = Data.Create(Nodes.GetMultiNodeTangents());
nodeZero.Mesh.MeshPrimitives.First().Tangents = tangents;
nodeOne.Mesh.MeshPrimitives.First().Tangents = tangents;
properties.Add(new Property(PropertyName.VertexTangent, ":white_check_mark:"));
}
Models = new List<Model>
{
CreateModel((properties, nodeZero, nodeOne) =>
{
// There are no properties set on this model.
}),
CreateModel((properties, nodeZero, nodeOne) =>
{
SetMatrixScaleX(properties, nodeOne);
}),
CreateModel((properties, nodeZero, nodeOne) =>
{
SetMatrixScaleXY(properties, nodeOne);
}),
CreateModel((properties, nodeZero, nodeOne) =>
{
SetMatrixScaleXYZ(properties, nodeOne);
}),
CreateModel((properties, nodeZero, nodeOne) =>
{
SetScaleX(properties, nodeOne);
}),
CreateModel((properties, nodeZero, nodeOne) =>
{
SetScaleXY(properties, nodeOne);
}),
CreateModel((properties, nodeZero, nodeOne) =>
{
SetScaleXYZ(properties, nodeOne);
}),
CreateModel((properties, nodeZero, nodeOne) =>
{
SetScaleX(properties, nodeOne);
SetVertexNormal(properties, nodeZero, nodeOne);
}),
CreateModel((properties, nodeZero, nodeOne) =>
{
SetScaleXY(properties, nodeOne);
SetVertexNormal(properties, nodeZero, nodeOne);
}),
CreateModel((properties, nodeZero, nodeOne) =>
{
SetScaleXYZ(properties, nodeOne);
SetVertexNormal(properties, nodeZero, nodeOne);
}),
CreateModel((properties, nodeZero, nodeOne) =>
{
SetScaleX(properties, nodeOne);
SetVertexNormal(properties, nodeZero, nodeOne);
SetVertexTangent(properties, nodeZero, nodeOne);
}),
CreateModel((properties, nodeZero, nodeOne) =>
{
SetScaleXY(properties, nodeOne);
SetVertexNormal(properties, nodeZero, nodeOne);
SetVertexTangent(properties, nodeZero, nodeOne);
}),
CreateModel((properties, nodeZero, nodeOne) =>
{
SetScaleXYZ(properties, nodeOne);
SetVertexNormal(properties, nodeZero, nodeOne);
SetVertexTangent(properties, nodeZero, nodeOne);
}),
};
GenerateUsedPropertiesList();
}
}
}
| mit |
tomcha/sinatras | lib/sinatras/command/options.rb | 2255 | # encoding: utf-8
require 'optparse'
module Sinatras
class Command
module Options
def self.parse!(argv)
options = {}
sub_command_parsers = create_sub_command_parsers(options)
command_parser = create_command_parser
begin
command_parser.order!(argv)
options[:command] = argv.shift
sub_command_parsers[options[:command]].parse!(argv)
if options[:command] == 'new'
raise ArgumentError, "#{options[:command]} Appname not found." if argv.empty?
options[:appname] = String(argv.first)
end
rescue OptionParser::MissingArgument, OptionParser::InvalidOption, ArgumentError => e
abort e.message
end
options
end
def self.create_sub_command_parsers(options)
sub_command_parsers = Hash.new do |k, v|
raise ArgumentError, "'#{v}' is not sinatras sub command"
end
sub_command_parsers['new'] = OptionParser.new do |opt|
opt.banner = 'Usage: new <args>'
opt.on_tail('-h', '--help', 'Show this message'){|v| help_sub_command(opt)}
end
sub_command_parsers
end
def self.help_sub_command(parser)
puts parser.help
exit
end
def self.create_command_parser
command_parser = OptionParser.new do |opt|
sub_command_help = [
{name: 'new Appname', summary: 'create new project scalton'},
]
opt.banner = "Usage: #{opt.program_name} [-h|--help][-v|--version] <command>[<args>]"
opt.separator ''
opt.separator "#{opt.program_name} Available Commands:"
sub_command_help.each do |command|
opt.separator [opt.summary_indent, command[:name].ljust(40), command[:summary]].join (' ')
end
opt.on_head('-h', '--help', ) do |v|
puts opt.help
exit
end
opt.on_head('-v', '--version', 'show program version') do |v|
opt.version = Sinatras::VERSION
puts opt.ver
exit
end
end
end
private_class_method :create_sub_command_parsers, :create_command_parser, :help_sub_command
end
end
end
| mit |
SweetDevil/blog | app/tplfunc/assertion.go | 249 | package tplfunc
import (
"strconv"
)
func Intval(v interface{}) int {
if r, ok := v.(string); ok {
res, err := strconv.Atoi(r)
if err != nil {
return 0
} else {
return res
}
}
if r, ok := v.(int); ok {
return r
}
return 0
}
| mit |
smich73/QnA-Maker-Uber-Search | qnamaker/QnAUtils.js | 3093 | const request = require('request');
const config = {
qnaMakerEndpoint: process.env.QNAMAKER_ENDPOINT,
qnaMakerKey: process.env.QNAMAKER_KEY
};
var headers = {
'Ocp-Apim-Subscription-Key': config.qnaMakerKey,
'Content-Type': 'application/json'
};
function createQnA(qnaForUpload) {
return new Promise((resolve, reject) => {
if (newQnA.qnaList.length > 0) {
// Configure the request
var options = {
url: qnaURL + 'create',
method: 'POST',
headers: headers,
json: qnaForUpload
};
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode === 201) {
resolve(body.kbId);
} else {
reject("Error:", body, "Status code:", response.statusCode);
}
});
}
else {
console.log("QnA has no data. QnAs left:", qnaCollection.length); //TODO: reject this?
return;
}
});
}
function getQnA(kbID) {
return new Promise((resolve, reject) => {
// Configure the request
var options = {
url: qnaURL + kbID,
method: 'GET',
headers: headers
};
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode === 200) {
resolve(body);
} else {
reject("Error:", body, "Status code:", response.statusCode);
}
});
});
}
function updateQnA(patch, kbID, callback) {
return new Promise((resolve, reject) => {
if (patch === 'No change') {
console.log("No change detected. QnAs left:", qnaCollection.length);
return;
}
// Configure the request
var options = {
url: qnaURL + kbID,
method: 'PATCH',
headers: headers,
json: patch
};
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode === 204) {
resolve(body);
} else {
reject("Error:", body, "Status code:", response.statusCode);
}
});
});
}
//TODO: Should this be fire and forget or should I wait for a response?
function deleteQnA(qna) {
// Configure the request
var options = {
url: qnaURL + kbID,
method: 'DELETE',
headers: headers
};
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode === 204) {
console.log("Success: QnA deleted. QnA:", qna.name, "QnAs left:", qnaCollection.length);
} else {
console.log("Error:", body, "Status code:", response.statusCode);
}
});
}
module.exports = {
createQnA: createQnA,
getQnA: getQnA,
updateQnA: updateQnA,
deleteQnA: deleteQnA
}; | mit |
102010cncger/antd-admin | src/components/index.js | 457 | import DataTable from './DataTable'
import DropOption from './DropOption'
import Iconfont from './Iconfont'
import Search from './Search'
import Editor from './Editor'
import FilterItem from './FilterItem'
import Loader from './Loader'
import * as Layout from './Layout/index.js'
import Page from './Page'
import layer from './layer'
export {
Layout,
DataTable,
DropOption,
Iconfont,
Search,
Editor,
FilterItem,
Loader,
layer,
Page,
}
| mit |
Aelith/SoundItAPI | server/src/app/repository/postgres/BaseRepository.ts | 4376 | /**
* Created by soundit on 17/01/2017.
*/
import "reflect-metadata";
import Read = require("./interfaces/Read");
import Write = require("./interfaces/Write");
import PostgresModel = require("./../../model/postgres/interfaces/PostgresModel");
import DataAccessPostgres = require("./../../dataAccess/postgres/DataAccessPostgres");
class BaseRepository<T extends PostgresModel> implements Read<T>, Write<T> {
private entity;
constructor(entity: new() => T) {
this.entity = entity;
}
/**
* Get one entity by his id
* @param id
* @param callback Callback : first param is error (null if succeeded), second is an entity (undefined if no result, or null if error)
*/
findById(id: number, callback: (error: any, result: any) => void) {
DataAccessPostgres.connect()
.getRepository(this.entity)
.findOneById(id)
.then((result) => {
callback(null, result);
})
.catch(e => {
callback(e, null);
});
}
/**
* Retrieve all entities from database
* @param callback Callback : first param is error (null if succeeded), second is an entity array (empty if no result, or null if error)
*/
retrieve (callback: (error: any, result: any) => void) : void {
DataAccessPostgres.connect()
.getRepository(this.entity)
.find()
.then((result) => {
callback(null, result);
})
.catch(e => {
callback(e, null);
});
}
/**
* Insert object into database
* @param item Object to save
* @param callback Callback : first param is error (null if succeeded), second is saved entity (or null if error)
*/
create (item: T, callback: (error: any, result: any) => void) : void {
DataAccessPostgres.connect()
.getRepository(this.entity)
.persist(item)
.then( (entity) => {
callback(null, entity);
})
.catch(e => {
callback(e, null);
});
}
/**
* Update object into database
* @param id Id of the object to update
* @param item Object to save
* @param callback Callback : first param is error (null if succeeded), second is saved entity (or null if error)
*/
update (item: T, callback: (error: any, result: any) => void) : void {
DataAccessPostgres.connect()
.getRepository(this.entity)
.persist(item)
.then( (entity) => {
callback(null, entity);
})
.catch(e => {
callback(e, null);
});
}
/**
* Delete object from database
* @param item Object to delete
* @param callback Callback : first param is error (null if succeeded), second is boolean (true if succeed, null if error)
*/
delete (item: T, callback: (error: any, result: any) => void) : void {
DataAccessPostgres.connect()
.getRepository(this.entity)
.remove(item)
.then( (entity) => {
callback(null, true);
})
.catch(e => {
callback(e, null);
});
}
/**
* Delete object from database
* @param id Id of the object to delete
* @param callback Callback : first param is error (null if succeeded), second is boolean (true if succeed, null if error)
*/
deleteById (id: number, callback: (error: any, result: any) => void) : void {
DataAccessPostgres.connect()
.getRepository(this.entity)
.findOneById(id)
.then(entityToDelete => {
DataAccessPostgres.connect()
.getRepository(this.entity)
.remove(entityToDelete)
.then( (entity) => {
callback(null, true);
})
.catch(e => {
callback(e, null);
});
})
.catch(e => {
callback(e, null);
});
}
}
export = BaseRepository; | mit |
NiurenZhu/ibas-framework-0.1.1 | bobas.businessobjectscommon/src/main/java/org/colorcoding/ibas/bobas/common/ISort.java | 452 | package org.colorcoding.ibas.bobas.common;
/**
* 查询排序
*
* @author Niuren.Zhu
*
*/
public interface ISort {
/**
* 获取-排序的字段(属性)名
*/
String getAlias();
/**
* 设置-排序的字段(属性)名
*
* @param value
*/
void setAlias(String value);
/**
* 获取-排序方式
*/
SortType getSortType();
/**
* 设置-排序方式
*
* @param value
*/
void setSortType(SortType value);
} | mit |
PassKitInc/pk-pass-display | src/pk-apple-pass/apple-pass-field-group/apple-pass-field-group.js | 788 | (function (angular) {
angular.module('pk-pass-display').component('pkApplePassFieldGroup', {
controller: [PKApplePassFieldGroupController],
templateUrl:"apple-pass-field-group.html",
bindings: {
fields: '<',
lang: '<',
type: '@'
}
});
function PKApplePassFieldGroupController() {
var ctrl = this;
ctrl.$onChanges = onChanges;
//Scope vars
ctrl.width = "100%";
function onChanges(changesObj) {
if (changesObj.hasOwnProperty("fields") && ctrl.fields != undefined) {
if(ctrl.fields != null) {
ctrl.width = Math.floor(100/ctrl.fields.length) + "%";
}
}
}
}
})(window.angular); | mit |
Michal-Fularz/ProgrammingCourse | ProgrammingCourse/VectorPassingTests/function_2.cpp | 3083 | #include "function_2.h"
#include <iostream>
#include <vector>
#include "Timer.h"
static double testFunction_passByValue(std::vector<double> data, int iteration)
{
double sum = 0.0;
double divison = (double)(1 + iteration);
for (auto value : data)
{
sum += value / divison;
}
return sum;
}
static double testFunction_passByReference(std::vector<double> &data, int iteration)
{
double sum = 0;
double divison = (double)(1 + iteration);
for (auto value : data)
{
sum += value / divison;
}
return sum;
}
static double testFunction_passByConstReference(const std::vector<double> &data, int iteration)
{
double sum = 0;
double divison = (double)(1 + iteration);
for (auto value : data)
{
sum += value / divison;
}
return sum;
}
static double testFunction_passByValue_move(std::vector<double>&& data, int iteration)
{
double sum = 0;
double divison = (double)(1 + iteration);
for (auto value : data)
{
sum += value / divison;
}
return sum;
}
void TEST_function_2(int numberOfIteration, int sizeOfVector)
{
std::vector<double> data;
for (int i = 0; i < sizeOfVector; ++i)
{
data.push_back((double)i);
}
Timer timer;
{
std::cout << "Without functions: " << std::endl;
timer.start();
double result = 0.0;
for (int i = 0; i < numberOfIteration; ++i)
{
double sum = 0.0;
double divison = (double)(1 + i);
for (auto value : data)
{
sum += value / divison;
}
result += sum;
}
timer.stop();
std::cout << "Result: " << result << std::endl;
std::cout << "Time: " << timer.getElapsedTimeInMilliSec() << std::endl << std::endl;
}
{
std::cout << "Pass by value: " << std::endl;
timer.start();
double result = 0.0;
for (int i = 0; i < numberOfIteration; ++i)
{
result += testFunction_passByValue(data, i);
}
timer.stop();
std::cout << "Result: " << result << std::endl;
std::cout << "Time: " << timer.getElapsedTimeInMilliSec() << std::endl << std::endl;
}
{
std::cout << "Pass by reference: " << std::endl;
timer.start();
double result = 0.0;
for (int i = 0; i < numberOfIteration; ++i)
{
result += testFunction_passByReference(data, i);
}
timer.stop();
std::cout << "Result: " << result << std::endl;
std::cout << "Time: " << timer.getElapsedTimeInMilliSec() << std::endl << std::endl;
}
{
std::cout << "Pass by const reference: " << std::endl;
timer.start();
double result = 0.0;
for (int i = 0; i < numberOfIteration; ++i)
{
result += testFunction_passByConstReference(data, i);
}
timer.stop();
std::cout << "Result: " << result << std::endl;
std::cout << "Time: " << timer.getElapsedTimeInMilliSec() << std::endl << std::endl;
}
{
std::cout << "Pass by value (move constuctor): " << std::endl;
timer.start();
double result = 0.0;
for (int i = 0; i < numberOfIteration; ++i)
{
result += testFunction_passByValue_move(std::move(data), i);
}
timer.stop();
std::cout << "Result: " << result << std::endl;
std::cout << "Time: " << timer.getElapsedTimeInMilliSec() << std::endl << std::endl;
}
}
| mit |
nfqakademija/illuminati | app/AppKernel.php | 2257 | <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new FOS\UserBundle\FOSUserBundle(),
new Illuminati\UserBundle\IlluminatiUserBundle(),
new Illuminati\OrderBundle\IlluminatiOrderBundle(),
new Knp\Bundle\MenuBundle\KnpMenuBundle(),
new Illuminati\ProductBundle\ProductBundle(),
new Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle(),
new Illuminati\CartBundle\CartBundle(),
new Ornicar\GravatarBundle\OrnicarGravatarBundle(),
new Illuminati\MainBundle\IlluminatiMainBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
$bundles[] = new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle();
}
return $bundles;
}
/**
* Changes symfony's default cache folder location.
*
* Used to solve permission problems and increase performance in vagrant
*
* @return string
*/
public function getCacheDir()
{
return '/tmp/cache';
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
}
}
| mit |
stefanliydov/SoftUniLab | Methods/ClassPractice/FirstProblem/Properties/AssemblyInfo.cs | 1400 | 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("FirstProblem")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FirstProblem")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("4dde6469-2fda-4f13-ae17-71ac241efcde")]
// 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 |
meltzow/supernovae | core/src/main/java/supernovae/world/terrain/heightmap/HeightMap.java | 3171 | package supernovae.world.terrain.heightmap;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import util.geometry.geom2d.Point2D;
import util.geometry.geom3d.Point3D;
import util.geometry.structure.grid.Grid;
public class HeightMap extends Grid<HeightMapNode> {
public HeightMap(int width, int height, Point2D coord) {
super(width, height, coord);
for(int i = 0; i < xSize*ySize; i++)
set(i, new HeightMapNode(i));
}
public HeightMap(@JsonProperty("width")int width,
@JsonProperty("height")int height,
@JsonProperty("flatData")String flatData,
@JsonProperty("coord")Point2D coord) {
super(width, height, coord);
int index = 0;
for (int i = 0; i < width * height; i++) {
if(flatData.charAt(index) == '-'){
int nbZero = getIntFromHexString(flatData.substring(index+1, index+9));
while(nbZero-- > 0){
set(i, new HeightMapNode(i, 0));
i++;
}
i--;
index += 10;
} else {
int f = getIntFromHexString(flatData.substring(index, index+8));
set(i, new HeightMapNode(i, Float.intBitsToFloat(f)));
index += 9;
}
}
// for(int i = 0; i < xSize*ySize; i++)
// set(i, new HeightMapNode(i, flatData[i]));
}
public Point3D getPos(HeightMapNode height){
return new Point3D(getCoord(height.getIndex()), height.getElevation());
}
public String getFlatData(){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < size(); i++){
float f = (float)(get(i).getElevation());
if(f == 0){
// grouping of zero values
int nbZero = 1;
while(i+nbZero < size() &&
nbZero < Integer.MAX_VALUE &&
(float)(get(i+nbZero)).getElevation() == 0){
nbZero++;
}
if(nbZero > 4){
sb.append("-"+String.format("%08X,", nbZero));
i = i+nbZero-1;
continue;
}
}
sb.append(String.format("%08X,", Float.floatToRawIntBits(f)));
}
return sb.toString();
}
public int getWidth(){
return xSize();
}
public int getHeight(){
return ySize;
}
@JsonIgnore
@Override
public List<HeightMapNode> getAll() {
return super.getAll();
}
public static float getFloatFromHexString(String s) {
return (Character.digit(s.charAt(0), 16) << 28) +
(Character.digit(s.charAt(1), 16) << 24) +
(Character.digit(s.charAt(2), 16) << 20) +
(Character.digit(s.charAt(3), 16) << 16) +
(Character.digit(s.charAt(4), 16) << 12) +
(Character.digit(s.charAt(5), 16) << 8) +
(Character.digit(s.charAt(6), 16) << 4) +
Character.digit(s.charAt(7), 16);
}
public static int getIntFromHexString(String s) {
return (Character.digit(s.charAt(0), 16) << 28) +
(Character.digit(s.charAt(1), 16) << 24) +
(Character.digit(s.charAt(2), 16) << 20) +
(Character.digit(s.charAt(3), 16) << 16) +
(Character.digit(s.charAt(4), 16) << 12) +
(Character.digit(s.charAt(5), 16) << 8) +
(Character.digit(s.charAt(6), 16) << 4) +
Character.digit(s.charAt(7), 16);
}
}
| mit |
Evenflow/MathDraw | MathDraw/NCalc.cs | 1630 | using NCalc;
using System;
using System.Threading;
using System.Windows.Forms;
namespace MathDraw
{
public sealed class NCalc
{
private static readonly object s_lock = new object();
private static NCalc instance = null;
private NCalc()
{
}
public static NCalc Instance
{
get
{
if (instance != null) return instance;
Monitor.Enter(s_lock);
var temp = new NCalc();
Interlocked.Exchange(ref instance, temp);
Monitor.Exit(s_lock);
return instance;
}
}
public double Formula_Parser(string formula, int x, int y, Thread thread = null)
{
formula = formula.Trim();
if (string.IsNullOrEmpty(formula))
{
MessageBox.Show("Formula cannot be empty!");
if (thread != null)
thread.Abort();
return 0;
}
formula = formula.Replace("i", x.ToString());
formula = formula.Replace("j", y.ToString());
return Evaluate(formula, thread);
}
private double Evaluate(string expression, Thread thread)
{
try
{
Expression e = new Expression(expression);
return double.Parse(e.Evaluate().ToString());
}
catch (Exception ex)
{
Utils.Instance.MessageBoxDebug("Evaluate: " + ex.ToString());
return 0;
}
}
}
}
| mit |
fastline32/TechModule | Dictionaries, Lambda and LINQ - Exercises/10.Сръбско Unleashed/Program.cs | 3626 | using System;
using System.Collections.Generic;
using System.Linq;
namespace Сръбско_Unleashed
{
class Program
{
static void Main()
{
Dictionary<string, Dictionary<string, long>> cityProfit = new Dictionary<string, Dictionary<string, long>>();
string[] singerInfo = ReadInfo();
while (!singerInfo[0].Equals("End"))
{
if (!singerInfo[0][singerInfo[0].Length - 1].Equals(' '))
{
singerInfo = ReadInfo();
}
else
{
string[] leftPart = singerInfo[0].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
string[] rightPart = singerInfo[1].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
string singer = string.Join(" ", leftPart);
if (rightPart.Length - 2 > 0)
{
string[] cityAsString = new string[rightPart.Length - 2];
for (int i = 0; i < cityAsString.Length; i++)
{
cityAsString[i] = rightPart[i];
}
int ticketPrice, ticketCount;
long profit;
if (int.TryParse(rightPart[rightPart.Length - 1], out ticketCount) &&
int.TryParse(rightPart[rightPart.Length - 2], out ticketPrice))
{
profit = ticketPrice * ticketCount;
string newCity = string.Join(" ", cityAsString);
InsertCity(cityProfit, newCity);
InsertProfit(cityProfit, newCity, singer, profit);
singerInfo = ReadInfo();
}
else
{
singerInfo = ReadInfo();
}
}
else
{
singerInfo = ReadInfo();
}
}
}
PrintProfit(cityProfit);
}
private static string[] ReadInfo()
{
string[] singerInfo = Console.ReadLine().Split('@').ToArray();
return singerInfo;
}
private static void PrintProfit(Dictionary<string, Dictionary<string, long>> cityProfit)
{
foreach (KeyValuePair<string, Dictionary<string, long>> cityEntry in cityProfit)
{
Console.WriteLine(cityEntry.Key);
foreach (KeyValuePair<string, long> singerProfit in cityEntry.Value.OrderByDescending(x => x.Value))
{
Console.WriteLine($"# {singerProfit.Key} -> {singerProfit.Value}");
}
}
}
private static void InsertProfit(Dictionary<string, Dictionary<string, long>> cityProfit, string newCity, string singer, long profit)
{
if (!cityProfit[newCity].ContainsKey(singer))
{
cityProfit[newCity].Add(singer, 0);
}
cityProfit[newCity][singer] += profit;
}
private static void InsertCity(Dictionary<string, Dictionary<string, long>> cityProfit, string newCity)
{
if (!cityProfit.ContainsKey(newCity))
{
cityProfit.Add(newCity, new Dictionary<string, long>());
}
}
}
} | mit |
TradeMe/tractor | plugins/mock-requests/src/tractor/server/init.spec.js | 1450 | // Test setup:
import { expect, Promise, sinon } from '@tractor/unit-test';
// Dependencies:
import { TractorError } from '@tractor/error-handler';
import * as tractorFileStructure from '@tractor/file-structure';
import * as tractorLogger from '@tractor/logger';
// Under test:
import { init } from './init';
describe('@tractor-plugins/mock-requests - init:', () => {
it.skip('should create the mock-requests directory', () => {
sinon.stub(tractorFileStructure, 'createDir').returns(Promise.resolve());
return init({
directory: './tractor'
})
.then(() => {
expect(tractorFileStructure.createDir).to.have.been.calledWith('/tractor/mock-requests');
})
.finally(() => {
tractorFileStructure.createDir.restore();
});
});
it.skip('should tell the user if the directory already exists', () => {
sinon.stub(tractorFileStructure, 'createDir').returns(Promise.reject(new TractorError('"/tractor/mock-requests" already exists.')));
sinon.stub(tractorLogger, 'warn');
return init({
directory: './tractor'
})
.then(() => {
expect(tractorLogger.warn).to.have.been.calledWith('"/tractor/mock-requests" already exists. Moving on...');
})
.finally(() => {
tractorFileStructure.createDir.restore();
tractorLogger.warn.restore();
});
});
});
| mit |
remomueller/slice | app/models/formatters/integer_formatter.rb | 625 | # frozen_string_literal: true
module Formatters
# Used to help format arrays of database responses for integer variables.
class IntegerFormatter < NumericFormatter
def raw_response(response, shared_responses = domain_options)
domain_option = shared_responses.find { |option| option.value == response }
if domain_option
domain_option.value
elsif response.blank?
response
else
response = response.gsub(/^([-+]?)(0*)/, "\\1") if response.is_a?(String) && response.strip != "0"
Integer(format("%d", response))
end
rescue
response
end
end
end
| mit |
AngleSharp/AngleSharp | src/AngleSharp.Core.Tests/Html/HtmlTokenization.cs | 15622 | namespace AngleSharp.Core.Tests.Html
{
using AngleSharp.Html;
using AngleSharp.Html.Parser;
using AngleSharp.Html.Parser.Tokens;
using AngleSharp.Text;
using NUnit.Framework;
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
[TestFixture]
public class HtmlTokenizationTests
{
private static HtmlTokenizer CreateTokenizer(TextSource source)
{
return new HtmlTokenizer(source, HtmlEntityProvider.Resolver);
}
[Test]
public void TokenizationCarriageReturnPureCharactersIssue_786()
{
var ms = new MemoryStream(Encoding.UTF8.GetBytes("\r\nThis is test 1\r\nThis is test 2"));
var s = new TextSource(ms);
var t = CreateTokenizer(s);
var token = t.Get();
Assert.AreEqual(HtmlTokenType.Character, token.Type);
Assert.AreEqual("\nThis is test 1\nThis is test 2", token.Data);
}
[Test]
public void TokenizationCarriageWithTextSourceIssue_786()
{
var ms = new MemoryStream(Encoding.UTF8.GetBytes("\r\nThis is test 1\r\nThis is test 2"));
var s = new TextSource(ms);
var t = CreateTokenizer(s);
var token = t.Get();
var start = token.Position.Index;
var text = s.Text.Substring(start, s.Index - start);
Assert.AreEqual("\r\nThis is test 1\r\nThis is test 2", text);
}
[Test]
public void TokenizationCarriageReturnNonLeadingIssue_786()
{
var ms = new MemoryStream(Encoding.UTF8.GetBytes("<html><body><p>\r\nThis is test 1<p> \r\nThis is test 2</body></html>"));
var s = new TextSource(ms);
var t = CreateTokenizer(s);
var tokenHtmlOpen = t.Get();
var tokenBodyOpen = t.Get();
var tokenP1 = t.Get();
var tokenP1data = t.Get();
var tokenP2 = t.Get();
var tokenP2data = t.Get();
var tokenBodyClose = t.Get();
var tokenHtmlClose = t.Get();
var eof = t.Get();
Assert.AreEqual(HtmlTokenType.EndTag, tokenHtmlClose.Type);
Assert.AreEqual(HtmlTokenType.StartTag, tokenHtmlOpen.Type);
Assert.AreEqual(HtmlTokenType.EndTag, tokenBodyClose.Type);
Assert.AreEqual(HtmlTokenType.StartTag, tokenBodyOpen.Type);
Assert.AreEqual(HtmlTokenType.StartTag, tokenP1.Type);
Assert.AreEqual(HtmlTokenType.StartTag, tokenP2.Type);
Assert.AreEqual(HtmlTokenType.Character, tokenP1data.Type);
Assert.AreEqual(HtmlTokenType.Character, tokenP2data.Type);
Assert.AreEqual(HtmlTokenType.EndOfFile, eof.Type);
Assert.AreEqual("\nThis is test 1", tokenP1data.Data);
Assert.AreEqual(" \nThis is test 2", tokenP2data.Data);
}
[Test]
public void TokenizationFinalEOF()
{
var s = new TextSource("");
var t = CreateTokenizer(s);
var token = t.Get();
Assert.AreEqual(HtmlTokenType.EndOfFile, token.Type);
}
[Test]
public void TokenizationLongerCharacterReference()
{
var content = "&abcdefghijklmnopqrstvwxyzABCDEFGHIJKLMNOPQRSTV;";
var s = new TextSource(content);
var t = CreateTokenizer(s);
var token = t.Get();
Assert.AreEqual(HtmlTokenType.Character, token.Type);
Assert.AreEqual(content, token.Data);
}
[Test]
public void TokenizationStartTagDetection()
{
var s = new TextSource("<p>");
var t = CreateTokenizer(s);
var token = t.Get();
Assert.AreEqual(HtmlTokenType.StartTag, token.Type);
Assert.AreEqual("p", ((HtmlTagToken)token).Name);
}
[Test]
public void TokenizationBogusCommentEmpty()
{
var s = new TextSource("<!>");
var t = CreateTokenizer(s);
var token = t.Get();
Assert.AreEqual(HtmlTokenType.Comment, token.Type);
Assert.AreEqual(String.Empty, token.Data);
}
[Test]
public void TokenizationBogusCommentQuestionMark()
{
var s = new TextSource("<?>");
var t = CreateTokenizer(s);
var token = t.Get();
Assert.AreEqual(HtmlTokenType.Comment, token.Type);
Assert.AreEqual("?", token.Data);
}
[Test]
public void TokenizationBogusCommentClosingTag()
{
var s = new TextSource("</ >");
var t = CreateTokenizer(s);
var token = t.Get();
Assert.AreEqual(HtmlTokenType.Comment, token.Type);
Assert.AreEqual(" ", token.Data);
}
[Test]
public void TokenizationTagNameDetection()
{
var s = new TextSource("<span>");
var t = CreateTokenizer(s);
var token = t.Get();
Assert.AreEqual("span", ((HtmlTagToken)token).Name);
}
[Test]
public void TokenizationTagSelfClosingDetected()
{
var s = new TextSource("<img />");
var t = CreateTokenizer(s);
var token = t.Get();
Assert.AreEqual(true, ((HtmlTagToken)token).IsSelfClosing);
}
[Test]
public void TokenizationAttributesDetected()
{
var s = new TextSource("<a target='_blank' href='http://whatever' title='ho'>");
var t = CreateTokenizer(s);
var token = t.Get();
Assert.AreEqual(3, ((HtmlTagToken)token).Attributes.Count);
}
[Test]
public void TokenizationAttributePositionsFoundSameLine()
{
var s = new TextSource("<a target='_blank' href='http://whatever' title='ho'>");
var t = CreateTokenizer(s);
var token = t.Get();
var attrs = ((HtmlTagToken)token).Attributes;
Assert.AreEqual(new TextPosition(1, 4, 4), attrs[0].Position);
Assert.AreEqual(new TextPosition(1, 20, 20), attrs[1].Position);
Assert.AreEqual(new TextPosition(1, 43, 43), attrs[2].Position);
}
[Test]
public void TokenizationAttributePositionsFoundOtherLine()
{
var s = new TextSource("<a target='_blank'\nhref='http://whatever'\n title='ho'>");
var t = CreateTokenizer(s);
var token = t.Get();
var attrs = ((HtmlTagToken)token).Attributes;
Assert.AreEqual(new TextPosition(1, 4, 4), attrs[0].Position);
Assert.AreEqual(new TextPosition(2, 1, 20), attrs[1].Position);
Assert.AreEqual(new TextPosition(3, 2, 44), attrs[2].Position);
}
[Test]
public void TokenizationAttributePositionsFoundAdditionalSpacesInOtherLine()
{
var s = new TextSource("<a target='_blank' \n href='http://whatever'\n title='ho'>");
var t = CreateTokenizer(s);
var token = t.Get();
var attrs = ((HtmlTagToken)token).Attributes;
Assert.AreEqual(new TextPosition(1, 4, 4), attrs[0].Position);
Assert.AreEqual(new TextPosition(2, 2, 24), attrs[1].Position);
Assert.AreEqual(new TextPosition(3, 5, 51), attrs[2].Position);
}
[Test]
public void TokenizationAttributeNameDetection()
{
var s = new TextSource("<input required>");
var t = CreateTokenizer(s);
var token = t.Get();
Assert.AreEqual("required", ((HtmlTagToken)token).Attributes[0].Name);
}
[Test]
public void TokenizationTagMixedCaseHandling()
{
var s = new TextSource("<InpUT>");
var t = CreateTokenizer(s);
var token = t.Get();
Assert.AreEqual("input", ((HtmlTagToken)token).Name);
}
[Test]
public void TokenizationTagSpacesBehind()
{
var s = new TextSource("<i >");
var t = CreateTokenizer(s);
var token = t.Get();
Assert.AreEqual("i", ((HtmlTagToken)token).Name);
}
[Test]
public void TokenizationCharacterReferenceNotin()
{
var str = string.Empty;
var src = "I'm ∉ I tell you";
var s = new TextSource(src);
var t = CreateTokenizer(s);
var token = default(HtmlToken);
do
{
token = t.Get();
if (token.Type == HtmlTokenType.Character)
{
str += token.Data;
}
}
while (token.Type != HtmlTokenType.EndOfFile);
Assert.AreEqual("I'm ∉ I tell you", str);
}
[Test]
public void TokenizationCharacterReferenceNotIt()
{
var str = string.Empty;
var src = "I'm ¬it; I tell you";
var s = new TextSource(src);
var t = CreateTokenizer(s);
var token = default(HtmlToken);
do
{
token = t.Get();
if (token.Type == HtmlTokenType.Character)
{
str += token.Data;
}
}
while (token.Type != HtmlTokenType.EndOfFile);
Assert.AreEqual("I'm ¬it; I tell you", str);
}
[Test]
public void TokenizationDoctypeDetected()
{
var s = new TextSource("<!doctype html>");
var t = CreateTokenizer(s);
var token = t.Get();
Assert.AreEqual(HtmlTokenType.Doctype, token.Type);
}
[Test]
public void TokenizationCommentDetected()
{
var s = new TextSource("<!-- hi my friend -->");
var t = CreateTokenizer(s);
var token = t.Get();
Assert.AreEqual(HtmlTokenType.Comment, token.Type);
}
[Test]
public void TokenizationCDataDetected()
{
var s = new TextSource("<![CDATA[hi mum how <!-- are you doing />]]>");
var t = CreateTokenizer(s);
t.IsAcceptingCharacterData = true;
var token = t.Get();
Assert.AreEqual(HtmlTokenType.Character, token.Type);
}
[Test]
public void TokenizationCDataCorrectCharacters()
{
StringBuilder sb = new StringBuilder();
var s = new TextSource("<![CDATA[hi mum how <!-- are you doing />]]>");
var t = CreateTokenizer(s);
var token = default(HtmlToken);
t.IsAcceptingCharacterData = true;
do
{
token = t.Get();
if (token.Type == HtmlTokenType.Character)
{
sb.Append(token.Data);
}
}
while (token.Type != HtmlTokenType.EndOfFile);
Assert.AreEqual("hi mum how <!-- are you doing />", sb.ToString());
}
[Test]
public void TokenizationUnusualDoctype()
{
var s = new TextSource("<!DOCTYPE root_element SYSTEM \"DTD_location\">");
var t = CreateTokenizer(s);
var e = t.Get();
Assert.AreEqual(HtmlTokenType.Doctype, e.Type);
var d = (HtmlDoctypeToken)e;
Assert.IsNotNull(d.Name);
Assert.AreEqual("root_element", d.Name);
Assert.IsFalse(d.IsSystemIdentifierMissing);
Assert.AreEqual("DTD_location", d.SystemIdentifier);
}
[Test]
public void TokenizationOnlyCarriageReturn()
{
var s = new TextSource("\r");
var t = CreateTokenizer(s);
var e = t.Get();
Assert.AreEqual(HtmlTokenType.Character, e.Type);
Assert.AreEqual("\n", e.Data);
}
[Test]
public void TokenizationOnlyLineFeed()
{
var s = new TextSource("\n");
var t = CreateTokenizer(s);
var e = t.Get();
Assert.AreEqual(HtmlTokenType.Character, e.Type);
Assert.AreEqual("\n", e.Data);
}
[Test]
public void TokenizationCarriageReturnLineFeed()
{
var s = new TextSource("\r\n");
var t = CreateTokenizer(s);
var e = t.Get();
Assert.AreEqual(HtmlTokenType.Character, e.Type);
Assert.AreEqual("\n", e.Data);
}
[Test]
public async Task TokenizationChangeEncodingWithMultibyteCharacter()
{
var phrase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 78 bytes
var content = String.Concat(Enumerable.Repeat(phrase, 53)); // x53 => 4134 bytes
var encoding = new UTF8Encoding(false);
using (var contentStm = new MemoryStream(encoding.GetBytes(content)))
{
var s = new TextSource(contentStm, encoding);
var t = CreateTokenizer(s);
// Read 4096 bytes to buffer
await s.PrefetchAsync(100, CancellationToken.None);
// Change encoding utf-8 to utf-8. (Same, but different instance)
s.CurrentEncoding = TextEncoding.Utf8;
var token = t.Get();
Assert.IsTrue(s.CurrentEncoding == TextEncoding.Utf8);
Assert.IsTrue(s.CurrentEncoding != encoding);
Assert.AreEqual(content, token.Data);
}
}
[Test]
public void TokenizationLongestLegalCharacterReference()
{
var content = "∳";
var s = new TextSource(content);
var t = CreateTokenizer(s);
var token = t.Get();
Assert.AreEqual(HtmlTokenType.Character, token.Type);
Assert.AreEqual("∳", token.Data);
}
[Test]
public void TokenizationLongestIllegalCharacterReference()
{
var content = "&CounterClockwiseContourIntegralWithWrongName;";
var s = new TextSource(content);
var t = CreateTokenizer(s);
var token = t.Get();
Assert.AreEqual(HtmlTokenType.Character, token.Type);
Assert.AreEqual("&CounterClockwiseContourIntegralWithWrongName;", token.Data);
}
[Test]
public void TokenizationWithReallyLongAttributeShouldNotBreak()
{
var content = Assets.GetManifestResourceString("Html.HtmlTokenization.TokenizationWithReallyLongAttributeShouldNotBreak.txt");
var s = new TextSource(content);
var t = CreateTokenizer(s);
var token = t.Get();
Assert.IsNotNull(token);
Assert.IsInstanceOf<HtmlTagToken>(token);
}
[Test]
public void TokenizationWithManyAttributesShouldNotBreak()
{
var content = Assets.GetManifestResourceString("Html.HtmlTokenization.TokenizationWithManyAttributesShouldNotBreak.txt");
var s = new TextSource(content);
var t = CreateTokenizer(s);
var token = t.Get();
Assert.IsNotNull(token);
Assert.IsInstanceOf<HtmlTagToken>(token);
}
}
}
| mit |
grammy3/rewards | src/util.cpp | 37873 | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "util.h"
#include "sync.h"
#include "strlcpy.h"
#include "version.h"
#include "ui_interface.h"
#include <boost/algorithm/string/join.hpp>
// Work around clang compilation problem in Boost 1.46:
// /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
// See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
// http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
namespace boost {
namespace program_options {
std::string to_internal(const std::string&);
}
}
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <stdarg.h>
#ifdef WIN32
#ifdef _MSC_VER
#pragma warning(disable:4786)
#pragma warning(disable:4804)
#pragma warning(disable:4805)
#pragma warning(disable:4717)
#endif
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <io.h> /* for _commit */
#include "shlobj.h"
#elif defined(__linux__)
# include <sys/prctl.h>
#endif
#ifndef WIN32
#include <execinfo.h>
#endif
using namespace std;
map<string, string> mapArgs;
map<string, vector<string> > mapMultiArgs;
bool fDebug = false;
bool fDebugNet = false;
bool fPrintToConsole = false;
bool fPrintToDebugger = false;
bool fRequestShutdown = false;
bool fShutdown = false;
bool fDaemon = false;
bool fServer = false;
bool fCommandLine = false;
string strMiscWarning;
bool fTestNet = false;
bool fNoListen = false;
bool fLogTimestamps = false;
CMedianFilter<int64_t> vTimeOffsets(200,0);
bool fReopenDebugLog = false;
// Init OpenSSL library multithreading support
static CCriticalSection** ppmutexOpenSSL;
void locking_callback(int mode, int i, const char* file, int line)
{
if (mode & CRYPTO_LOCK) {
ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
} else {
LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
}
}
LockedPageManager LockedPageManager::instance;
// Init
class CInit
{
public:
CInit()
{
// Init OpenSSL library multithreading support
ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
for (int i = 0; i < CRYPTO_num_locks(); i++)
ppmutexOpenSSL[i] = new CCriticalSection();
CRYPTO_set_locking_callback(locking_callback);
#ifdef WIN32
// Seed random number generator with screen scrape and other hardware sources
RAND_screen();
#endif
// Seed random number generator with performance counter
RandAddSeed();
}
~CInit()
{
// Shutdown OpenSSL library multithreading support
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks(); i++)
delete ppmutexOpenSSL[i];
OPENSSL_free(ppmutexOpenSSL);
}
}
instance_of_cinit;
void RandAddSeed()
{
// Seed with CPU performance counter
int64_t nCounter = GetPerformanceCounter();
RAND_add(&nCounter, sizeof(nCounter), 1.5);
memset(&nCounter, 0, sizeof(nCounter));
}
void RandAddSeedPerfmon()
{
RandAddSeed();
// This can take up to 2 seconds, so only do it every 10 minutes
static int64_t nLastPerfmon;
if (GetTime() < nLastPerfmon + 10 * 60)
return;
nLastPerfmon = GetTime();
#ifdef WIN32
// Don't need this on Linux, OpenSSL automatically uses /dev/urandom
// Seed with the entire set of perfmon data
unsigned char pdata[250000];
memset(pdata, 0, sizeof(pdata));
unsigned long nSize = sizeof(pdata);
long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
RegCloseKey(HKEY_PERFORMANCE_DATA);
if (ret == ERROR_SUCCESS)
{
RAND_add(pdata, nSize, nSize/100.0);
memset(pdata, 0, nSize);
printf("RandAddSeed() %lu bytes\n", nSize);
}
#endif
}
uint64_t GetRand(uint64_t nMax)
{
if (nMax == 0)
return 0;
// The range of the random source must be a multiple of the modulus
// to give every possible output value an equal possibility
uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
uint64_t nRand = 0;
do
RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
while (nRand >= nRange);
return (nRand % nMax);
}
int GetRandInt(int nMax)
{
return GetRand(nMax);
}
uint256 GetRandHash()
{
uint256 hash;
RAND_bytes((unsigned char*)&hash, sizeof(hash));
return hash;
}
static FILE* fileout = NULL;
inline int OutputDebugStringF(const char* pszFormat, ...)
{
int ret = 0;
if (fPrintToConsole)
{
// print to console
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret = vprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
}
else if (!fPrintToDebugger)
{
// print to debug.log
if (!fileout)
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
fileout = fopen(pathDebug.string().c_str(), "a");
if (fileout) setbuf(fileout, NULL); // unbuffered
}
if (fileout)
{
static bool fStartedNewLine = true;
// This routine may be called by global destructors during shutdown.
// Since the order of destruction of static/global objects is undefined,
// allocate mutexDebugLog on the heap the first time this routine
// is called to avoid crashes during shutdown.
static boost::mutex* mutexDebugLog = NULL;
if (mutexDebugLog == NULL) mutexDebugLog = new boost::mutex();
boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
// reopen the log file, if requested
if (fReopenDebugLog) {
fReopenDebugLog = false;
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
setbuf(fileout, NULL); // unbuffered
}
// Debug print useful for profiling
if (fLogTimestamps && fStartedNewLine)
fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
if (pszFormat[strlen(pszFormat) - 1] == '\n')
fStartedNewLine = true;
else
fStartedNewLine = false;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret = vfprintf(fileout, pszFormat, arg_ptr);
va_end(arg_ptr);
}
}
#ifdef WIN32
if (fPrintToDebugger)
{
static CCriticalSection cs_OutputDebugStringF;
// accumulate and output a line at a time
{
LOCK(cs_OutputDebugStringF);
static std::string buffer;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
buffer += vstrprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
int line_start = 0, line_end;
while((line_end = buffer.find('\n', line_start)) != -1)
{
OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
line_start = line_end + 1;
}
buffer.erase(0, line_start);
}
}
#endif
return ret;
}
string vstrprintf(const char *format, va_list ap)
{
char buffer[50000];
char* p = buffer;
int limit = sizeof(buffer);
int ret;
while (true)
{
va_list arg_ptr;
va_copy(arg_ptr, ap);
#ifdef WIN32
ret = _vsnprintf(p, limit, format, arg_ptr);
#else
ret = vsnprintf(p, limit, format, arg_ptr);
#endif
va_end(arg_ptr);
if (ret >= 0 && ret < limit)
break;
if (p != buffer)
delete[] p;
limit *= 2;
p = new char[limit];
if (p == NULL)
throw std::bad_alloc();
}
string str(p, p+ret);
if (p != buffer)
delete[] p;
return str;
}
string real_strprintf(const char *format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
return str;
}
string real_strprintf(const std::string &format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format.c_str(), arg_ptr);
va_end(arg_ptr);
return str;
}
bool error(const char *format, ...)
{
va_list arg_ptr;
va_start(arg_ptr, format);
std::string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
printf("ERROR: %s\n", str.c_str());
return false;
}
void ParseString(const string& str, char c, vector<string>& v)
{
if (str.empty())
return;
string::size_type i1 = 0;
string::size_type i2;
while (true)
{
i2 = str.find(c, i1);
if (i2 == str.npos)
{
v.push_back(str.substr(i1));
return;
}
v.push_back(str.substr(i1, i2-i1));
i1 = i2+1;
}
}
string FormatMoney(int64_t n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
int64_t n_abs = (n > 0 ? n : -n);
int64_t quotient = n_abs/COIN;
int64_t remainder = n_abs%COIN;
string str = strprintf("%"PRId64".%08"PRId64, quotient, remainder);
// Right-trim excess zeros before the decimal point:
int nTrim = 0;
for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
++nTrim;
if (nTrim)
str.erase(str.size()-nTrim, nTrim);
if (n < 0)
str.insert((unsigned int)0, 1, '-');
else if (fPlus && n > 0)
str.insert((unsigned int)0, 1, '+');
return str;
}
bool ParseMoney(const string& str, int64_t& nRet)
{
return ParseMoney(str.c_str(), nRet);
}
bool ParseMoney(const char* pszIn, int64_t& nRet)
{
string strWhole;
int64_t nUnits = 0;
const char* p = pszIn;
while (isspace(*p))
p++;
for (; *p; p++)
{
if (*p == '.')
{
p++;
int64_t nMult = CENT*10;
while (isdigit(*p) && (nMult > 0))
{
nUnits += nMult * (*p++ - '0');
nMult /= 10;
}
break;
}
if (isspace(*p))
break;
if (!isdigit(*p))
return false;
strWhole.insert(strWhole.end(), *p);
}
for (; *p; p++)
if (!isspace(*p))
return false;
if (strWhole.size() > 10) // guard against 63 bit overflow
return false;
if (nUnits < 0 || nUnits > COIN)
return false;
int64_t nWhole = atoi64(strWhole);
int64_t nValue = nWhole*COIN + nUnits;
nRet = nValue;
return true;
}
static const signed char phexdigit[256] =
{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
bool IsHex(const string& str)
{
BOOST_FOREACH(unsigned char c, str)
{
if (phexdigit[c] < 0)
return false;
}
return (str.size() > 0) && (str.size()%2 == 0);
}
vector<unsigned char> ParseHex(const char* psz)
{
// convert hex dump to vector
vector<unsigned char> vch;
while (true)
{
while (isspace(*psz))
psz++;
signed char c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
unsigned char n = (c << 4);
c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
n |= c;
vch.push_back(n);
}
return vch;
}
vector<unsigned char> ParseHex(const string& str)
{
return ParseHex(str.c_str());
}
static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
{
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
if (name.find("-no") == 0)
{
std::string positive("-");
positive.append(name.begin()+3, name.end());
if (mapSettingsRet.count(positive) == 0)
{
bool value = !GetBoolArg(name);
mapSettingsRet[positive] = (value ? "1" : "0");
}
}
}
void ParseParameters(int argc, const char* const argv[])
{
mapArgs.clear();
mapMultiArgs.clear();
for (int i = 1; i < argc; i++)
{
char psz[10000];
strlcpy(psz, argv[i], sizeof(psz));
char* pszValue = (char*)"";
if (strchr(psz, '='))
{
pszValue = strchr(psz, '=');
*pszValue++ = '\0';
}
#ifdef WIN32
_strlwr(psz);
if (psz[0] == '/')
psz[0] = '-';
#endif
if (psz[0] != '-')
break;
mapArgs[psz] = pszValue;
mapMultiArgs[psz].push_back(pszValue);
}
// New 0.6 features:
BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
{
string name = entry.first;
// interpret --foo as -foo (as long as both are not set)
if (name.find("--") == 0)
{
std::string singleDash(name.begin()+1, name.end());
if (mapArgs.count(singleDash) == 0)
mapArgs[singleDash] = entry.second;
name = singleDash;
}
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
InterpretNegativeSetting(name, mapArgs);
}
}
std::string GetArg(const std::string& strArg, const std::string& strDefault)
{
if (mapArgs.count(strArg))
return mapArgs[strArg];
return strDefault;
}
int64_t GetArg(const std::string& strArg, int64_t nDefault)
{
if (mapArgs.count(strArg))
return atoi64(mapArgs[strArg]);
return nDefault;
}
bool GetBoolArg(const std::string& strArg, bool fDefault)
{
if (mapArgs.count(strArg))
{
if (mapArgs[strArg].empty())
return true;
return (atoi(mapArgs[strArg]) != 0);
}
return fDefault;
}
bool SoftSetArg(const std::string& strArg, const std::string& strValue)
{
if (mapArgs.count(strArg))
return false;
mapArgs[strArg] = strValue;
return true;
}
bool SoftSetBoolArg(const std::string& strArg, bool fValue)
{
if (fValue)
return SoftSetArg(strArg, std::string("1"));
else
return SoftSetArg(strArg, std::string("0"));
}
string EncodeBase64(const unsigned char* pch, size_t len)
{
static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
string strRet="";
strRet.reserve((len+2)/3*4);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase64[enc >> 2];
left = (enc & 3) << 4;
mode = 1;
break;
case 1: // we have two bits
strRet += pbase64[left | (enc >> 4)];
left = (enc & 15) << 2;
mode = 2;
break;
case 2: // we have four bits
strRet += pbase64[left | (enc >> 6)];
strRet += pbase64[enc & 63];
mode = 0;
break;
}
}
if (mode)
{
strRet += pbase64[left];
strRet += '=';
if (mode == 1)
strRet += '=';
}
return strRet;
}
string EncodeBase64(const string& str)
{
return EncodeBase64((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
{
static const int decode64_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve(strlen(p)*3/4);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode64_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 6
left = dec;
mode = 1;
break;
case 1: // we have 6 bits and keep 4
vchRet.push_back((left<<2) | (dec>>4));
left = dec & 15;
mode = 2;
break;
case 2: // we have 4 bits and get 6, we keep 2
vchRet.push_back((left<<4) | (dec>>2));
left = dec & 3;
mode = 3;
break;
case 3: // we have 2 bits and get 6
vchRet.push_back((left<<6) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 4n base64 characters processed: ok
break;
case 1: // 4n+1 base64 character processed: impossible
*pfInvalid = true;
break;
case 2: // 4n+2 base64 characters processed: require '=='
if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
*pfInvalid = true;
break;
case 3: // 4n+3 base64 characters processed: require '='
if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase64(const string& str)
{
vector<unsigned char> vchRet = DecodeBase64(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
string EncodeBase32(const unsigned char* pch, size_t len)
{
static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
string strRet="";
strRet.reserve((len+4)/5*8);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase32[enc >> 3];
left = (enc & 7) << 2;
mode = 1;
break;
case 1: // we have three bits
strRet += pbase32[left | (enc >> 6)];
strRet += pbase32[(enc >> 1) & 31];
left = (enc & 1) << 4;
mode = 2;
break;
case 2: // we have one bit
strRet += pbase32[left | (enc >> 4)];
left = (enc & 15) << 1;
mode = 3;
break;
case 3: // we have four bits
strRet += pbase32[left | (enc >> 7)];
strRet += pbase32[(enc >> 2) & 31];
left = (enc & 3) << 3;
mode = 4;
break;
case 4: // we have two bits
strRet += pbase32[left | (enc >> 5)];
strRet += pbase32[enc & 31];
mode = 0;
}
}
static const int nPadding[5] = {0, 6, 4, 3, 1};
if (mode)
{
strRet += pbase32[left];
for (int n=0; n<nPadding[mode]; n++)
strRet += '=';
}
return strRet;
}
string EncodeBase32(const string& str)
{
return EncodeBase32((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
{
static const int decode32_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve((strlen(p))*5/8);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode32_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 5
left = dec;
mode = 1;
break;
case 1: // we have 5 bits and keep 2
vchRet.push_back((left<<3) | (dec>>2));
left = dec & 3;
mode = 2;
break;
case 2: // we have 2 bits and keep 7
left = left << 5 | dec;
mode = 3;
break;
case 3: // we have 7 bits and keep 4
vchRet.push_back((left<<1) | (dec>>4));
left = dec & 15;
mode = 4;
break;
case 4: // we have 4 bits, and keep 1
vchRet.push_back((left<<4) | (dec>>1));
left = dec & 1;
mode = 5;
break;
case 5: // we have 1 bit, and keep 6
left = left << 5 | dec;
mode = 6;
break;
case 6: // we have 6 bits, and keep 3
vchRet.push_back((left<<2) | (dec>>3));
left = dec & 7;
mode = 7;
break;
case 7: // we have 3 bits, and keep 0
vchRet.push_back((left<<5) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 8n base32 characters processed: ok
break;
case 1: // 8n+1 base32 characters processed: impossible
case 3: // +3
case 6: // +6
*pfInvalid = true;
break;
case 2: // 8n+2 base32 characters processed: require '======'
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
*pfInvalid = true;
break;
case 4: // 8n+4 base32 characters processed: require '===='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
*pfInvalid = true;
break;
case 5: // 8n+5 base32 characters processed: require '==='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
*pfInvalid = true;
break;
case 7: // 8n+7 base32 characters processed: require '='
if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase32(const string& str)
{
vector<unsigned char> vchRet = DecodeBase32(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
bool WildcardMatch(const char* psz, const char* mask)
{
while (true)
{
switch (*mask)
{
case '\0':
return (*psz == '\0');
case '*':
return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
case '?':
if (*psz == '\0')
return false;
break;
default:
if (*psz != *mask)
return false;
break;
}
psz++;
mask++;
}
}
bool WildcardMatch(const string& str, const string& mask)
{
return WildcardMatch(str.c_str(), mask.c_str());
}
static std::string FormatException(std::exception* pex, const char* pszThread)
{
#ifdef WIN32
char pszModule[MAX_PATH] = "";
GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
#else
const char* pszModule = "tenbillion";
#endif
if (pex)
return strprintf(
"EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
else
return strprintf(
"UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
}
void LogException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n%s", message.c_str());
}
void PrintException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
throw;
}
void LogStackTrace() {
printf("\n\n******* exception encountered *******\n");
if (fileout)
{
#ifndef WIN32
void* pszBuffer[32];
size_t size;
size = backtrace(pszBuffer, 32);
backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
#endif
}
}
void PrintExceptionContinue(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
}
boost::filesystem::path GetDefaultDataDir()
{
namespace fs = boost::filesystem;
// Windows < Vista: C:\Documents and Settings\Username\Application Data\tenbillion
// Windows >= Vista: C:\Users\Username\AppData\Roaming\tenbillion
// Mac: ~/Library/Application Support/tenbillion
// Unix: ~/.tenbillion
#ifdef WIN32
// Windows
return GetSpecialFolderPath(CSIDL_APPDATA) / "tenbillion";
#else
fs::path pathRet;
char* pszHome = getenv("HOME");
if (pszHome == NULL || strlen(pszHome) == 0)
pathRet = fs::path("/");
else
pathRet = fs::path(pszHome);
#ifdef MAC_OSX
// Mac
pathRet /= "Library/Application Support";
fs::create_directory(pathRet);
return pathRet / "tenbillion";
#else
// Unix
return pathRet / ".tenbillion";
#endif
#endif
}
const boost::filesystem::path &GetDataDir(bool fNetSpecific)
{
namespace fs = boost::filesystem;
static fs::path pathCached[2];
static CCriticalSection csPathCached;
static bool cachedPath[2] = {false, false};
fs::path &path = pathCached[fNetSpecific];
// This can be called during exceptions by printf, so we cache the
// value so we don't have to do memory allocations after that.
if (cachedPath[fNetSpecific])
return path;
LOCK(csPathCached);
if (mapArgs.count("-datadir")) {
path = fs::system_complete(mapArgs["-datadir"]);
if (!fs::is_directory(path)) {
path = "";
return path;
}
} else {
path = GetDefaultDataDir();
}
if (fNetSpecific && fTestNet)
path /= "testnet";
fs::create_directory(path);
cachedPath[fNetSpecific]=true;
return path;
}
boost::filesystem::path GetConfigFile()
{
boost::filesystem::path pathConfigFile(GetArg("-conf", "tenbillion.conf"));
if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
return pathConfigFile;
}
void ReadConfigFile(map<string, string>& mapSettingsRet,
map<string, vector<string> >& mapMultiSettingsRet)
{
boost::filesystem::ifstream streamConfig(GetConfigFile());
if (!streamConfig.good())
return; // No bitcoin.conf file is OK
set<string> setOptions;
setOptions.insert("*");
for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
{
// Don't overwrite existing settings so command line settings override bitcoin.conf
string strKey = string("-") + it->string_key;
if (mapSettingsRet.count(strKey) == 0)
{
mapSettingsRet[strKey] = it->value[0];
// interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
InterpretNegativeSetting(strKey, mapSettingsRet);
}
mapMultiSettingsRet[strKey].push_back(it->value[0]);
}
}
boost::filesystem::path GetPidFile()
{
boost::filesystem::path pathPidFile(GetArg("-pid", "tenbilliond.pid"));
if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
return pathPidFile;
}
#ifndef WIN32
void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
{
FILE* file = fopen(path.string().c_str(), "w");
if (file)
{
fprintf(file, "%d\n", pid);
fclose(file);
}
}
#endif
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
{
#ifdef WIN32
return MoveFileExA(src.string().c_str(), dest.string().c_str(),
MOVEFILE_REPLACE_EXISTING);
#else
int rc = std::rename(src.string().c_str(), dest.string().c_str());
return (rc == 0);
#endif /* WIN32 */
}
void FileCommit(FILE *fileout)
{
fflush(fileout); // harmless if redundantly called
#ifdef WIN32
_commit(_fileno(fileout));
#else
fsync(fileno(fileout));
#endif
}
void ShrinkDebugFile()
{
// Scroll debug.log if it's getting too big
boost::filesystem::path pathLog = GetDataDir() / "debug.log";
FILE* file = fopen(pathLog.string().c_str(), "r");
if (file && boost::filesystem::file_size(pathLog) > 10 * 1000000)
{
// Restart the file with some of the end
char pch[200000];
fseek(file, -sizeof(pch), SEEK_END);
int nBytes = fread(pch, 1, sizeof(pch), file);
fclose(file);
file = fopen(pathLog.string().c_str(), "w");
if (file)
{
fwrite(pch, 1, nBytes, file);
fclose(file);
}
}
}
//
// "Never go to sea with two chronometers; take one or three."
// Our three time sources are:
// - System clock
// - Median of other nodes clocks
// - The user (asking the user to fix the system clock if the first two disagree)
//
static int64_t nMockTime = 0; // For unit testing
int64_t GetTime()
{
if (nMockTime) return nMockTime;
return time(NULL);
}
void SetMockTime(int64_t nMockTimeIn)
{
nMockTime = nMockTimeIn;
}
static int64_t nTimeOffset = 0;
int64_t GetTimeOffset()
{
return nTimeOffset;
}
int64_t GetAdjustedTime()
{
return GetTime() + GetTimeOffset();
}
void AddTimeData(const CNetAddr& ip, int64_t nTime)
{
int64_t nOffsetSample = nTime - GetTime();
// Ignore duplicates
static set<CNetAddr> setKnown;
if (!setKnown.insert(ip).second)
return;
// Add data
vTimeOffsets.input(nOffsetSample);
printf("Added time data, samples %d, offset %+"PRId64" (%+"PRId64" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
{
int64_t nMedian = vTimeOffsets.median();
std::vector<int64_t> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
if (abs64(nMedian) < 70 * 60)
{
nTimeOffset = nMedian;
}
else
{
nTimeOffset = 0;
static bool fDone;
if (!fDone)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
BOOST_FOREACH(int64_t nOffset, vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;
if (!fMatch)
{
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong tenbillion will not work properly.");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage+" ", string("tenbillion"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
}
}
}
if (fDebug) {
BOOST_FOREACH(int64_t n, vSorted)
printf("%+"PRId64" ", n);
printf("| ");
}
printf("nTimeOffset = %+"PRId64" (%+"PRId64" minutes)\n", nTimeOffset, nTimeOffset/60);
}
}
string FormatVersion(int nVersion)
{
if (nVersion%100 == 0)
return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
else
return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
}
string FormatFullVersion()
{
return CLIENT_BUILD;
}
// Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
ss << "(" << boost::algorithm::join(comments, "; ") << ")";
ss << "/";
return ss.str();
}
#ifdef WIN32
boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
{
namespace fs = boost::filesystem;
char pszPath[MAX_PATH] = "";
if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
{
return fs::path(pszPath);
}
printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
return fs::path("");
}
#endif
void runCommand(std::string strCommand)
{
int nErr = ::system(strCommand.c_str());
if (nErr)
printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
}
void RenameThread(const char* name)
{
#if defined(PR_SET_NAME)
// Only the first 15 characters are used (16 - NUL terminator)
::prctl(PR_SET_NAME, name, 0, 0, 0);
#elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
// TODO: This is currently disabled because it needs to be verified to work
// on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
// removed.
pthread_set_name_np(pthread_self(), name);
// This is XCode 10.6-and-later; bring back if we drop 10.5 support:
// #elif defined(MAC_OSX)
// pthread_setname_np(name);
#else
// Prevent warnings for unused parameters...
(void)name;
#endif
}
bool NewThread(void(*pfn)(void*), void* parg)
{
try
{
boost::thread(pfn, parg); // thread detaches when out of scope
} catch(boost::thread_resource_error &e) {
printf("Error creating thread: %s\n", e.what());
return false;
}
return true;
}
| mit |
nicolasricci/SonataMediaBundle | Tests/Form/DataTransformer/ProviderDataTransformerTest.php | 5212 | <?php
/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\MediaBundle\Tests\Form\DataTransformer;
use Sonata\MediaBundle\Form\DataTransformer\ProviderDataTransformer;
use Sonata\MediaBundle\Model\MediaInterface;
use Sonata\MediaBundle\Provider\Pool;
use Sonata\MediaBundle\Tests\Helpers\PHPUnit_Framework_TestCase;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class ProviderDataTransformerTest extends PHPUnit_Framework_TestCase
{
public function testReverseTransformFakeValue()
{
$pool = $this->getMockBuilder('Sonata\MediaBundle\Provider\Pool')->disableOriginalConstructor()->getMock();
$transformer = new ProviderDataTransformer($pool, 'stdClass');
$this->assertSame('foo', $transformer->reverseTransform('foo'));
}
/**
* @expectedException \RuntimeException
*/
public function testReverseTransformUnknownProvider()
{
$pool = new Pool('default');
$media = $this->createMock('Sonata\MediaBundle\Model\MediaInterface');
$media->expects($this->exactly(3))->method('getProviderName')->will($this->returnValue('unknown'));
$media->expects($this->any())->method('getId')->will($this->returnValue(1));
$media->expects($this->any())->method('getBinaryContent')->will($this->returnValue('xcs'));
$transformer = new ProviderDataTransformer($pool, 'stdClass', array(
'new_on_update' => false,
));
$transformer->reverseTransform($media);
}
public function testReverseTransformValidProvider()
{
$provider = $this->createMock('Sonata\MediaBundle\Provider\MediaProviderInterface');
$provider->expects($this->once())->method('transform');
$pool = new Pool('default');
$pool->addProvider('default', $provider);
$media = $this->createMock('Sonata\MediaBundle\Model\MediaInterface');
$media->expects($this->exactly(3))->method('getProviderName')->will($this->returnValue('default'));
$media->expects($this->any())->method('getId')->will($this->returnValue(1));
$media->expects($this->any())->method('getBinaryContent')->will($this->returnValue('xcs'));
$transformer = new ProviderDataTransformer($pool, 'stdClass', array(
'new_on_update' => false,
));
$transformer->reverseTransform($media);
}
public function testReverseTransformWithNewMediaAndNoBinaryContent()
{
$provider = $this->createMock('Sonata\MediaBundle\Provider\MediaProviderInterface');
$pool = new Pool('default');
$pool->addProvider('default', $provider);
$media = $this->createMock('Sonata\MediaBundle\Model\MediaInterface');
$media->expects($this->any())->method('getId')->will($this->returnValue(null));
$media->expects($this->any())->method('getBinaryContent')->will($this->returnValue(null));
$media->expects($this->any())->method('getProviderName')->will($this->returnValue('default'));
$media->expects($this->once())->method('setProviderReference')->with(MediaInterface::MISSING_BINARY_REFERENCE);
$media->expects($this->once())->method('setProviderStatus')->with(MediaInterface::STATUS_PENDING);
$transformer = new ProviderDataTransformer($pool, 'stdClass', array(
'new_on_update' => false,
'empty_on_new' => false,
));
$this->assertSame($media, $transformer->reverseTransform($media));
}
public function testReverseTransformWithMediaAndNoBinaryContent()
{
$provider = $this->createMock('Sonata\MediaBundle\Provider\MediaProviderInterface');
$pool = new Pool('default');
$pool->addProvider('default', $provider);
$media = $this->createMock('Sonata\MediaBundle\Model\MediaInterface');
$media->expects($this->any())->method('getId')->will($this->returnValue(1));
$media->expects($this->any())->method('getBinaryContent')->will($this->returnValue(null));
$transformer = new ProviderDataTransformer($pool, 'stdClass');
$this->assertSame($media, $transformer->reverseTransform($media));
}
public function testReverseTransformWithMediaAndUploadFileInstance()
{
$provider = $this->createMock('Sonata\MediaBundle\Provider\MediaProviderInterface');
$pool = new Pool('default');
$pool->addProvider('default', $provider);
$media = $this->createMock('Sonata\MediaBundle\Model\MediaInterface');
$media->expects($this->exactly(3))->method('getProviderName')->will($this->returnValue('default'));
$media->expects($this->any())->method('getId')->will($this->returnValue(1));
$media->expects($this->any())->method('getBinaryContent')->will($this->returnValue(new UploadedFile(__FILE__, 'ProviderDataTransformerTest')));
$transformer = new ProviderDataTransformer($pool, 'stdClass', array(
'new_on_update' => false,
));
$transformer->reverseTransform($media);
}
}
| mit |
asoltys/gc-openid | vendor/plugins/rails_upgrade/lib/routes_upgrader.rb | 9160 | # -*- encoding : utf-8 -*-
# TODO: Fix formatting on member/collection methods
module Rails
module Upgrading
module FakeRouter
module ActionController
module Routing
class Routes
def self.setup
@redrawer = Rails::Upgrading::RouteRedrawer.new
end
def self.redrawer
@redrawer
end
def self.draw
yield @redrawer
end
end
end
end
end
class RoutesUpgrader
def generate_new_routes
if has_routes_file?
upgrade_routes
else
raise FileNotFoundError, "Can't find your routes file [config/routes.rb]!"
end
end
def has_routes_file?
File.exists?("config/routes.rb")
end
def routes_code
File.read("config/routes.rb")
end
def upgrade_routes
FakeRouter::ActionController::Routing::Routes.setup
# Read and eval the file; our fake route mapper will capture
# the calls to draw routes and generate new route code
FakeRouter.module_eval(routes_code)
# Give the route set to the code generator and get its output
generator = RouteGenerator.new(FakeRouter::ActionController::Routing::Routes.redrawer.routes)
generator.generate
end
end
class RouteRedrawer
attr_accessor :routes
def self.stack
@stack
end
def self.stack=(val)
@stack = val
end
def initialize
@routes = []
# The old default route was actually two routes; we generate the new style
# one only if we haven't generated it for the first old default route.
@default_route_generated = false
# Setup the stack for parents; used use proper indentation
self.class.stack = [@routes]
end
def root(options)
debug "mapping root"
@routes << FakeRoute.new("/", options)
end
def connect(path, options={})
debug "connecting #{path}"
if (path == ":controller/:action/:id.:format" || path == ":controller/:action/:id")
if !@default_route_generated
current_parent << FakeRoute.new("/:controller(/:action(/:id))", {:default_route => true})
@default_route_generated = true
end
else
current_parent << FakeRoute.new(path, options)
end
end
def resources(*args)
if block_given?
parent = FakeResourceRoute.new(args.shift)
debug "mapping resources #{parent.name} with block"
parent = stack(parent) do
yield(self)
end
current_parent << parent
else
if args.last.is_a?(Hash)
current_parent << FakeResourceRoute.new(args.shift, args.pop)
debug "mapping resources #{current_parent.last.name} w/o block with args"
else
args.each do |a|
current_parent << FakeResourceRoute.new(a)
debug "mapping resources #{current_parent.last.name}"
end
end
end
end
def resource(*args)
if block_given?
parent = FakeSingletonResourceRoute.new(args.shift)
debug "mapping resource #{parent.name} with block"
parent = stack(parent) do
yield(self)
end
current_parent << parent
else
if args.last.is_a?(Hash)
current_parent << FakeSingletonResourceRoute.new(args.shift, args.pop)
debug "mapping resources #{current_parent.last.name} w/o block with args"
else
args.each do |a|
current_parent << FakeSingletonResourceRoute.new(a)
debug "mapping resources #{current_parent.last.name}"
end
end
end
end
def namespace(name)
debug "mapping namespace #{name}"
namespace = FakeNamespace.new(name)
namespace = stack(namespace) do
yield(self)
end
current_parent << namespace
end
def method_missing(m, *args)
debug "named route: #{m}"
current_parent << FakeRoute.new(args.shift, args.pop, m.to_s)
end
def self.indent
' ' * ((stack.length) * 2)
end
private
def debug(txt)
puts txt if ENV['DEBUG']
end
def stack(obj)
self.class.stack << obj
yield
self.class.stack.pop
end
def current_parent
self.class.stack.last
end
end
class RouteObject
def indent_lines(code_lines)
if code_lines.length > 1
code_lines.flatten.map {|l| "#{@indent}#{l.chomp}"}.join("\n") + "\n"
else
"#{@indent}#{code_lines.shift}"
end
end
def opts_to_string(opts)
opts.is_a?(Hash) ? opts.map {|k, v|
":#{k} => " + (v.is_a?(Hash) ? ('{ ' + opts_to_string(v) + ' }') : "#{value_to_string(v)}")
}.join(", ") : opts.to_s
end
def value_to_string(value)
case value
when Regexp then value.inspect
when String then "'" + value.to_s + "'"
else value.to_s
end
end
end
class FakeNamespace < RouteObject
attr_accessor :routes, :name
def initialize(name)
@routes = []
@name = name
@indent = RouteRedrawer.indent
end
def to_route_code
lines = ["namespace :#{@name} do", @routes.map {|r| r.to_route_code}, "end"]
indent_lines(lines)
end
def <<(val)
@routes << val
end
def last
@routes.last
end
end
class FakeRoute < RouteObject
attr_accessor :name, :path, :options
def initialize(path, options, name = "")
@path = path
@options = options || {}
@name = name
@indent = RouteRedrawer.indent
end
def to_route_code
if @options[:default_route]
indent_lines ["match '#{@path}'"]
else
base = "match '%s' => '%s#%s'"
extra_options = []
if not name.empty?
extra_options << ":as => :#{name}"
end
if @options[:requirements]
@options[:constraints] = @options.delete(:requirements)
end
if @options[:conditions]
@options[:via] = @options.delete(:conditions).delete(:method)
end
@options ||= {}
base = (base % [@path, @options.delete(:controller), (@options.delete(:action) || "index")])
opts = opts_to_string(@options)
route_pieces = ([base] + extra_options + [opts])
route_pieces.delete("")
indent_lines [route_pieces.join(", ")]
end
end
end
class FakeResourceRoute < RouteObject
attr_accessor :name, :children
def initialize(name, options = {})
@name = name
@children = []
@options = options
@indent = RouteRedrawer.indent
end
def to_route_code
if !@children.empty? || @options.has_key?(:collection) || @options.has_key?(:member)
prefix = ["#{route_method} :#{@name} do"]
lines = prefix + custom_methods + [@children.map {|r| r.to_route_code}.join("\n"), "end"]
indent_lines(lines)
else
base = "#{route_method} :%s"
indent_lines [base % [@name]]
end
end
def custom_methods
collection_code = generate_custom_methods_for(:collection)
member_code = generate_custom_methods_for(:member)
[collection_code, member_code]
end
def generate_custom_methods_for(group)
return "" unless @options[group]
method_code = []
RouteRedrawer.stack << self
@options[group].each do |k, v|
method_code << "#{v} :#{k}"
end
RouteRedrawer.stack.pop
indent_lines ["#{group} do", method_code, "end"].flatten
end
def route_method
"resources"
end
def <<(val)
@children << val
end
def last
@children.last
end
end
class FakeSingletonResourceRoute < FakeResourceRoute
def route_method
"resource"
end
end
class RouteGenerator
def initialize(routes)
@routes = routes
@new_code = ""
end
def generate
@new_code = @routes.map do |r|
r.to_route_code
end.join("\n")
"#{app_name.underscore.classify}::Application.routes.draw do\n#{@new_code}\nend\n"
end
private
def app_name
File.basename(Dir.pwd)
end
end
end
end
| mit |
niello/deusexmachina | Tools/DialogEditor/DialogLogic/DialogInfo.cs | 8077 | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Xml.Linq;
namespace DialogLogic
{
public class DialogInfo:ICharacterContainer
{
public event EventHandler DialogInfoChanged;
private readonly Dialogs _dialogs;
public Dialogs Dialogs{get { return _dialogs; }}
public ObservableCollection<DialogCharacter> DialogCharacters { get; private set; }
private string _name;
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
OnDialogInfoChanged();
}
}
}
private readonly DialogGraph _graph=new DialogGraph();
public DialogGraph Graph { get { return _graph;}}
private readonly CharacterAttributeCollection _attributeCollection;
public CharacterAttributeCollection AttributeCollection
{
get { return _attributeCollection; }
}
public ICharacterContainer ParentContainer
{
get { return _dialogs; }
}
public string ScriptFile { get; set; }
public DialogInfo(Dialogs dialogs)
{
_dialogs = dialogs;
DialogCharacters = new ObservableCollection<DialogCharacter>();
DialogCharacters.CollectionChanged += CharactersCollectionChanged;
_graph.GraphChanged += OnGraphChanged;
_attributeCollection = new CharacterAttributeCollection(this);
_attributeCollection.AddProperty("IsPlayer", typeof (bool));
}
internal void ReadXml(XElement xDialog, Func<int,DialogCharacter> characterSelector)
{
string name;
if(xDialog.TryGetAttribute("name",out name))
Name = name;
XElement characterProperties = xDialog.Element("characterProperties"),
graph = xDialog.Element("graph"), chatactersNode = xDialog.Element("characters");
Dictionary<int, string> propertyMap;
if (characterProperties != null)
propertyMap = _attributeCollection.ReadXml(characterProperties, new List<string> { "IsPlayer" });
else
propertyMap = new Dictionary<int, string>();
var tmpCharacters = new Dictionary<int, DialogCharacter>();
if(chatactersNode!=null)
{
foreach(var ch in chatactersNode.Elements("character"))
{
int id;
if(!ch.TryGetAttribute("id",out id))
continue;
var baseChar = characterSelector(id);
var character = new DialogCharacter(baseChar, this);
character.ReadProperties(ch, propId => propertyMap[propId]);
tmpCharacters.Add(character.Id, character);
DialogCharacters.Add(character);
}
}
if (graph != null)
{
XElement xNodes = graph.Element("nodes"), xLinks = graph.Element("links");
var nodeDefaultLinks = new Dictionary<int, int>();
if (xNodes != null)
{
foreach (var xNode in xNodes.Elements())
{
int id;
if (!xNode.TryGetAttribute("id", out id))
continue;
int defaultLink;
if (xNode.TryGetAttribute("defaultLink", out defaultLink))
nodeDefaultLinks.Add(id, defaultLink);
DialogGraphNodeBase node = null;
switch (xNode.Name.LocalName)
{
case "node":
var n = new PhraseDialogGraphNode();
int charId;
if (xNode.TryGetAttribute("characterId", out charId))
n.Character = tmpCharacters[charId].Name;
n.Phrase = xNode.Value;
node = n;
break;
case "empty":
node = new EmptyDialogGraphNode();
break;
case "answer":
node = new AnswerCollectionDialogGraphNode();
break;
}
if (node != null)
{
node.Id = id;
_graph.ForceInsertNode(node);
}
}
}
if(xLinks!=null)
{
foreach(var xLink in xLinks.Elements("link"))
{
int from, to;
if (!xLink.TryGetAttribute("from", out from) || !xLink.TryGetAttribute("to", out to))
continue;
var link = Graph.Link(from, to);
int fromNodeDefault;
if(nodeDefaultLinks.TryGetValue(to,out fromNodeDefault) && fromNodeDefault==from)
{
var node = _graph.GetNode(to);
node.DefaultLinkHere = link;
}
}
}
}
}
public List<DialogCharacter> GetCharacters()
{
return new List<DialogCharacter>(DialogCharacters);
}
public bool TryGetCharacter(string name, out DialogCharacter character)
{
character = DialogCharacters.FirstOrDefault(c => c.Name == name);
return character != null;
}
public bool ContainsCharacter(string name)
{
return DialogCharacters.Any(c => c.Name == name);
}
public DialogCharacter AddCharacter(string name)
{
DialogCharacter baseCh;
if (!ParentContainer.TryGetCharacter(name, out baseCh))
baseCh = ParentContainer.AddCharacter(name);
var ch = new DialogCharacter(baseCh, this);
DialogCharacters.Add(ch);
return ch;
}
public bool IsActiveCharacter(DialogCharacter ch)
{
return Graph.AnyNode<PhraseDialogGraphNode>(node => node.Character == ch.Name);
}
public void LoadFromFile(string fPath, IDialogUserProperties mdReader)
{
_graph.LoadFromFile(fPath, mdReader);
}
public void SaveToFile(string filePath, IDialogUserProperties pref)
{
_graph.SaveToFile(filePath, pref);
}
private void OnDialogInfoChanged()
{
var eh = DialogInfoChanged;
if (eh != null)
eh(this, EventArgs.Empty);
}
private void CharactersCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (DialogCharacter item in e.NewItems)
item.PropertyChanged += OnCharacterPropertyChanged;
}
if (e.OldItems != null)
{
foreach (DialogCharacter item in e.OldItems)
item.PropertyChanged -= OnCharacterPropertyChanged;
}
OnDialogInfoChanged();
}
private void OnCharacterPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnDialogInfoChanged();
}
private void OnGraphChanged(object sender, EventArgs e)
{
OnDialogInfoChanged();
}
}
}
| mit |
cristianomg10/beach | src/Optimizers/Genetic/Operators/CrossOvers/TwoPointCrossOver.php | 1889 | <?php
/**
* Created by PhpStorm.
* User: cristiano
* Date: 11/11/16
* Time: 2:36 PM
*/
namespace App\Optimizers\Genetic\Operators\CrossOvers;
use App\Optimizers\Genetic\Operators\Elements\BinaryChromosome;
use App\Utils\Exceptions\IllegalArgumentException;
class TwoPointCrossOver implements ICrossOver
{
private $point1;
private $point2;
function __construct($point1 = 0, $point2 = 0)
{
$this->point1 = $point1;
$this->point2 = $point2;
}
public function crossOver($individual1, $individual2)
{
if (!is_a($individual1, BinaryChromosome::class) || !is_a($individual2, BinaryChromosome::class)){
throw new IllegalArgumentException("Individuals are not Chromosomes.");
}
if (
($this->point2 <= $this->point1 and $this->point1 != 0) ||
($this->point1 > $individual1->getLength() - 1 || $this->point2 > $individual1->getLength() - 1)
){
throw new IllegalArgumentException("Second point bigger than the First point of cut.");
}
if (!$this->point1)
$point1 = rand(1, round($individual1->getLength() / 2));
if (!$this->point2)
$point2 = rand($point1 + 1, $individual1->getLength() - 1);
$newIndividual1 = new BinaryChromosome();
$newIndividual2 = new BinaryChromosome();
for ($i = 0; $i < $individual1->getLength(); ++$i){
if ($i < $point1 || $i >= $point2){
$newIndividual1->updateGenes($i, $individual1->getGene($i));
$newIndividual2->updateGenes($i, $individual2->getGene($i));
} else {
$newIndividual1->updateGenes($i, $individual2->getGene($i));
$newIndividual2->updateGenes($i, $individual1->getGene($i));;
}
}
return [$newIndividual1, $newIndividual2];
}
} | mit |
dimkk/l2broker | site/server/api/items/index.js | 268 | 'use strict';
var express = require('express');
var controller = require('./items.controller');
var router = express.Router();
router.get('/', controller.index);
router.get('/:id', controller.show);
//router.post('/:id', controller.sort);
module.exports = router;
| mit |
tsiry95/openshift-strongloop-cartridge | strongloop/node_modules/strong-debugger/src/debugger.cc | 3596 | #include <nan.h> // Must be included as the first file
#include <limits>
#include <memory>
#include "controller.h"
#include "compat.h"
namespace strongloop {
namespace debugger {
using v8::Function;
using v8::FunctionTemplate;
using v8::Handle;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;
static const uint16_t MAX_PORT = -1;
static void StartCallback(const char* err, uint16_t port, void* data) {
Nan::HandleScope scope;
Nan::Callback* js_callback = static_cast<Nan::Callback*>(data);
Local<Value> args[] = {
err ? Nan::Error(err) : static_cast<Local<Value> >(Nan::Null()),
Nan::New<Number>(port)
};
js_callback->Call(ArraySize(args), args);
delete js_callback;
}
static void StopCallback(void* data) {
Nan::HandleScope scope;
Nan::Callback* js_callback = static_cast<Nan::Callback*>(data);
js_callback->Call(0, NULL);
delete js_callback;
}
NAN_METHOD(Start) {
if (!info[0]->IsObject()) {
return Nan::ThrowTypeError(
"Internal error: the first arg must be an \"options\" object");
}
Local<Object> options = info[0].As<Object>();
Local<Value> key = Nan::New("port").ToLocalChecked();
Local<Value> port_handle = Nan::Get(options, key).ToLocalChecked();
if (!port_handle->IsUint32()) {
return Nan::ThrowTypeError(
"The \"port\" option must be an unsigned integer.");
}
const uint32_t port = port_handle->Uint32Value();
if (port > MAX_PORT) {
return Nan::ThrowRangeError(
"The \"port\" option must be a number between 0 - 65535.");
}
key = Nan::New("scriptRoot").ToLocalChecked();
Local<Value> val = Nan::Get(options, key).ToLocalChecked();
if (!val->IsString()) {
return Nan::ThrowTypeError("options.scriptRoot must be a string");
}
Nan::Utf8String script_root(val);
key = Nan::New("debuglogEnabled").ToLocalChecked();
val = Nan::Get(options, key).ToLocalChecked();
if (!val->IsBoolean()) {
return Nan::ThrowTypeError("options.debuglogEnabled must be a boolean");
}
bool debuglog_enabled = val->BooleanValue();
if (!info[1]->IsFunction()) {
return Nan::ThrowError("You must supply a callback argument.");
}
Local<Function> callback = info[1].As<Function>();
Controller* controller = Controller::GetInstance(info.GetIsolate());
if (!controller) {
controller = new Controller(info.GetIsolate(),
uv_default_loop(),
*script_root,
debuglog_enabled);
}
if (!controller) {
Local<Value> err = Nan::New<String>(
"Cannot create a new Controller object, out of memory?").ToLocalChecked();
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), callback, 1, &err);
}
Nan::Callback* js_callback = new Nan::Callback(callback);
controller->Start(port, StartCallback, js_callback);
}
NAN_METHOD(Stop) {
if (!info[0]->IsFunction()) {
return Nan::ThrowError("You must supply a callback argument.");
}
Local<Function> callback = info[0].As<Function>();
Nan::Callback* js_callback = new Nan::Callback(callback);
Controller* controller = Controller::GetInstance(info.GetIsolate());
controller->Stop(StopCallback, js_callback);
}
void InitModule(Handle<Object> exports) {
exports->Set(Nan::New("start").ToLocalChecked(),
Nan::New<FunctionTemplate>(Start)->GetFunction());
exports->Set(Nan::New("stop").ToLocalChecked(),
Nan::New<FunctionTemplate>(Stop)->GetFunction());
}
NODE_MODULE(debugger, InitModule)
} // namespace debugger
} // namespace strongloop
| mit |
warmsea/warmsea.net | warmsea/urls.py | 924 | import os
from flask import send_from_directory
from warmsea import app, admin, api, blog, models, srm, views
# Weibo verifications
app.add_url_rule('/wb_5ba2b446644528f2.txt', 'weibo_verification',
lambda: send_from_directory(
os.path.join(app.config['ROOT_DIR'],
'third_part_verifications'),
'wb_5ba2b446644528f2.txt'))
# Home page
app.add_url_rule('/', 'index', view_func=views.index)
# About page and guest book
app.add_url_rule('/about/', 'about', views.about)
app.add_url_rule('/guestbook/', 'guestbook', views.guestbook)
app.register_blueprint(admin.blueprint, url_prefix='/admin')
app.register_blueprint(api.blueprint, url_prefix='/api')
app.register_blueprint(blog.blueprint, url_prefix='/blog')
app.register_blueprint(models.blueprint, url_prefix='/models')
app.register_blueprint(srm.blueprint, url_prefix='/srm')
| mit |
alexthe21/e-boxoffice | src/At21/EBoxOfficeBundle/DependencyInjection/Configuration.php | 879 | <?php
namespace At21\EBoxOfficeBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('acme_user');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
| mit |
uppsaladatavetare/foobar-kiosk | @types/global/index.d.ts | 646 | declare const __DEV__: boolean;
declare const Thunder: {
connect: (host: string, apikey: string, channels: string[], options?: object) => void;
listen: (
handler: (data: { channel: string, payload: string }) => void
) => void;
};
declare const config: {
API: {
host: string;
key: string;
};
THUNDER: {
host: string;
key: string;
secret: string;
};
SENTRY?: string;
SCREEN: "primary" | "secondary";
};
declare module "*.scss" {
interface IClassNames {
[className: string]: string;
}
const classNames: IClassNames;
export = classNames;
}
| mit |
trytocatch/MapSearcher | src/com/github/trytocatch/mapsearcher/SearchInfo.java | 2231 | package com.github.trytocatch.mapsearcher;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Phaser;
class SearchInfo<N, R> implements Cloneable {
ArrayList<N> steps;
R result;
int depth;
int weight;
Task<N, R> task;
int startIndex;
BitSet nodeBitSet;
List<N> unmodifiableSteps;
ArrayList<Integer> stepIndexes;
ConcurrentLinkedQueue<R> resultQueue;
Phaser phaser;
SearchInfo(ArrayList<N> steps, R result, int depth, int weight, Task<N, R> task, int startIndex,
BitSet nodeBitSet, ArrayList<Integer> stepIndexes, ConcurrentLinkedQueue<R> resultQueue, Phaser phaser) {
this.steps = steps;
this.result = result;
this.depth = depth;
this.weight = weight;
this.startIndex = startIndex;
this.nodeBitSet = nodeBitSet;
this.stepIndexes = stepIndexes;
this.task = task;
this.resultQueue = resultQueue;
this.phaser = phaser;
unmodifiableSteps = Collections.unmodifiableList(steps);
}
@SuppressWarnings("unchecked")
SearchInfo<N, R> fork(int startIndex, int curWeight) {
SearchInfo<N, R> newObj;
try {
newObj = (SearchInfo<N, R>) super.clone();
newObj.startIndex = startIndex;
newObj.steps = (ArrayList<N>) steps.clone();
newObj.unmodifiableSteps = Collections.unmodifiableList(newObj.steps);
if (nodeBitSet != null)
newObj.nodeBitSet = (BitSet) nodeBitSet.clone();
if (stepIndexes != null)
newObj.stepIndexes = (ArrayList<Integer>) stepIndexes.clone();
newObj.depth++;
newObj.weight += curWeight;
newObj.result = task.getForkResultHandler().fork(result);
return newObj;
} catch (CloneNotSupportedException e) {
return null;// won't happen
}
}
void mergeResult() {
// for (R r, newResult = result;;) {
// r = joinResult.get();
// if (r == null) {
// if (joinResult.compareAndSet(null, newResult))
// break;
// } else if (joinResult.compareAndSet(r, null)) {
// newResult = task.getForkResultHandler().merge(r, newResult);
// }
// }
resultQueue.add(result);
}
} | mit |
Tallisado/webtools_old | webtools/dom_audit/dom_audit_webdriver.rb | 2985 | require File.join(File.dirname(__FILE__), "../../webrobot/lib/helper")
url = ENV['WR_URL']
username = ENV['WR_USERNAME']
userpass = ENV['WR_USERPASS']
puts "Arguments passed to webdriver testcode"
puts "url: " + url
puts "username: " + username
puts "userpass: " + userpass
login_url = String.new
if url.split('/')[0] == "http:"
login_url = url.split('/')[0..2].join('/')
else
login_url = 'http://' + url.split('/')[0]
end
puts 'login url: ' + login_url
# describe "Fetch all the scripts arguments", :local => true do
# it "should have a valid url" do
# ENV['WR_URL'].should_not == nil
# end
# it "should know what it will be logged in as" do
# ENV['WR_login'].should_not == nil
# end
# end
describe "Inspect the webpage to scrape the DOM object", :local => true do
it "should find the dom object for the html node" do
wr_p "Logging in"
wr_d "Opening webpage"
@selenium.navigate.to login_url
#@selenium.navigate.to "http://10.10.9.129"
#@selenium.navigate.to "http://www.google.ca"
wr_d "Finding login element"
@selenium.find_element(:id, "loginnameid-inputEl").send_keys username
wr_d "Finding password element"
@selenium.find_element(:id, "loginpasswordid-inputEl").send_keys userpass
wr_d "Finding submit element"
@selenium.find_element(:id, "loginbuttonid-btnIconEl").click
sleep 5
begin
@selenium.navigate.to url
rescue
wr_p "-----> MAKE SURE URL IS CORRECT. Eg: http://10.10.9.129/LocalAdmin/index.php"
end
begin
wr_p "Requesting DOM object"
wait_for_it = Selenium::WebDriver::Wait.new(:timeout => 120 )
wait_for_it.until { @selenium.find_element(:id, "logout_btn-btnIconEl") }
rescue
wr_p "-----> MAKE SURE YOUR USER/PASSWORD IS CORRECT"
end
wr_d "Finding html element"
html_element = @selenium.find_element(:tag_name, "html")
# wr_p "forcing window.stop() javascript call"
# @selenium.execute_script("window.stop();")
wr_d "Dumping DOM object to STDOUT"
html_object = @selenium.execute_script("return arguments[0].innerHTML;", html_element)
#wr_p html_object
wr_p "Parsing the DOM structure for each ID"
element_array = html_element.find_elements(:xpath, ".//*");
wr_p "Found the fllowing dynamic IDs"
#collected_attributes = element_array.collect {|e| e.attribute("id") }
# collected_attributes.each do |e|
# if e.match("[0-9]{4,4}")
# wr_tag(e,"STATIC")
# end
# end
element_array.each do |e|
begin
if e.attribute("id").match("[0-9]{4,4}")
wr_tag(e.attribute("id"),"STATIC")
end
rescue Timeout::Error, Selenium::WebDriver::Error::StaleElementReferenceError
wr_p "ERROR: Retrieval of attribute object timed out."
wr_p "The reason could be that the js is looping unexpectedly behind the scene (JS bug), or that the page changed during the search"
break
end
end
end
end | mit |
hyrise/hyrise | src/lib/optimizer/strategy/index_scan_rule.hpp | 1434 | #pragma once
#include <memory>
#include <string>
#include <vector>
#include "abstract_rule.hpp"
#include "storage/index/index_statistics.hpp"
#include "types.hpp"
namespace opossum {
class AbstractLQPNode;
class PredicateNode;
/**
* This optimizer rule finds PredicateNodes whose inputs are StoredTableNodes. These PredicateNodes are candidates
* for being executed by IndexScans. If the expected selectivity of the predicate falls below a certain threshold, the
* ScanType of the PredicateNode is set to IndexScan.
*
* Note:
* For now this rule is only applicable to single-column indexes. Multi-column predicates (i.e. WHERE a < b) are also
* not supported. We also assume that if chunks have an index, all of them are of the same type, we do not mix GroupKey
* and ART indexes. In addition, chains of IndexScans are not possible since an IndexScan's input must be a GetTable.
* Currently, only GroupKeyIndexes are supported.
*/
class IndexScanRule : public AbstractRule {
public:
std::string name() const override;
protected:
void _apply_to_plan_without_subqueries(const std::shared_ptr<AbstractLQPNode>& lqp_root) const override;
bool _is_index_scan_applicable(const IndexStatistics& index_statistics,
const std::shared_ptr<PredicateNode>& predicate_node) const;
static bool _is_single_segment_index(const IndexStatistics& index_statistics);
};
} // namespace opossum
| mit |
hanami/assets | spec/support/tmp.rb | 162 | # frozen_string_literal: true
require "pathname"
# TMP = Pathname.new(__dir__).join("..", "tmp")
TMP = Pathname.new(__dir__).join("..", "..", "tmp")
TMP.mkpath
| mit |
ro8inb/baivi | src/AppBundle/Services/Shop/ShopActions.php | 582 | <?php
namespace AppBundle\Services\Shop;
class ShopActions {
private $collection;
public function getCollectionName($products){
foreach ($products as $product){
if($product->getCollection()->getId() === 1){
$this->collection = 'Wax';
}
if($product->getCollection()->getId() === 2){
$this->collection = 'Uni';
}
if($product->getCollection()->getId() === 3){
$this->collection = 'Motifs';
}
}
return $this->collection;
}
} | mit |
kmcphillips/rails | activesupport/lib/active_support/ruby_features.rb | 260 | # frozen_string_literal: true
module ActiveSupport
module RubyFeatures # :nodoc:
CLASS_DESCENDANTS = Class.method_defined?(:descendants) # RUBY_VERSION >= "3.1"
CLASS_SUBCLASSES = Class.method_defined?(:subclasses) # RUBY_VERSION >= "3.1"
end
end
| mit |
levfurtado/scoops | library/Proxy/__CG__NewscoopEntityComment.php | 15668 | <?php
namespace Proxy\__CG__\Newscoop\Entity;
/**
* DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE'S PROXY GENERATOR
*/
class Comment extends \Newscoop\Entity\Comment implements \Doctrine\ORM\Proxy\Proxy
{
/**
* @var \Closure the callback responsible for loading properties in the proxy object. This callback is called with
* three parameters, being respectively the proxy object to be initialized, the method that triggered the
* initialization process and an array of ordered parameters that were passed to that method.
*
* @see \Doctrine\Common\Persistence\Proxy::__setInitializer
*/
public $__initializer__;
/**
* @var \Closure the callback responsible of loading properties that need to be copied in the cloned object
*
* @see \Doctrine\Common\Persistence\Proxy::__setCloner
*/
public $__cloner__;
/**
* @var boolean flag indicating if this object was already initialized
*
* @see \Doctrine\Common\Persistence\Proxy::__isInitialized
*/
public $__isInitialized__ = false;
/**
* @var array properties to be lazy loaded, with keys being the property
* names and values being their default values
*
* @see \Doctrine\Common\Persistence\Proxy::__getLazyProperties
*/
public static $lazyPropertiesDefaults = array();
/**
* @param \Closure $initializer
* @param \Closure $cloner
*/
public function __construct($initializer = null, $cloner = null)
{
$this->__initializer__ = $initializer;
$this->__cloner__ = $cloner;
}
/**
*
* @return array
*/
public function __sleep()
{
if ($this->__isInitialized__) {
return array('__isInitialized__', 'allowedEmpty', 'allowedTags', 'status_enum', 'id', 'commenter', 'forum', 'parent', 'thread', 'language', 'subject', 'message', 'thread_level', 'thread_order', 'status', 'ip', 'time_created', 'time_updated', 'likes', 'dislikes', 'recommended', 'indexed', 'source');
}
return array('__isInitialized__', 'allowedEmpty', 'allowedTags', 'status_enum', 'id', 'commenter', 'forum', 'parent', 'thread', 'language', 'subject', 'message', 'thread_level', 'thread_order', 'status', 'ip', 'time_created', 'time_updated', 'likes', 'dislikes', 'recommended', 'indexed', 'source');
}
/**
*
*/
public function __wakeup()
{
if ( ! $this->__isInitialized__) {
$this->__initializer__ = function (Comment $proxy) {
$proxy->__setInitializer(null);
$proxy->__setCloner(null);
$existingProperties = get_object_vars($proxy);
foreach ($proxy->__getLazyProperties() as $property => $defaultValue) {
if ( ! array_key_exists($property, $existingProperties)) {
$proxy->$property = $defaultValue;
}
}
};
}
}
/**
*
*/
public function __clone()
{
$this->__cloner__ && $this->__cloner__->__invoke($this, '__clone', array());
}
/**
* Forces initialization of the proxy
*/
public function __load()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, '__load', array());
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __isInitialized()
{
return $this->__isInitialized__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setInitialized($initialized)
{
$this->__isInitialized__ = $initialized;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setInitializer(\Closure $initializer = null)
{
$this->__initializer__ = $initializer;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __getInitializer()
{
return $this->__initializer__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setCloner(\Closure $cloner = null)
{
$this->__cloner__ = $cloner;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific cloning logic
*/
public function __getCloner()
{
return $this->__cloner__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
* @static
*/
public function __getLazyProperties()
{
return self::$lazyPropertiesDefaults;
}
/**
* {@inheritDoc}
*/
public function setId($id)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setId', array($id));
return parent::setId($id);
}
/**
* {@inheritDoc}
*/
public function getId()
{
if ($this->__isInitialized__ === false) {
return (int) parent::getId();
}
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getId', array());
return parent::getId();
}
/**
* {@inheritDoc}
*/
public function setTimeCreated(\DateTime $datetime)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setTimeCreated', array($datetime));
return parent::setTimeCreated($datetime);
}
/**
* {@inheritDoc}
*/
public function getTimeCreated()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getTimeCreated', array());
return parent::getTimeCreated();
}
/**
* {@inheritDoc}
*/
public function setTimeUpdated(\DateTime $datetime)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setTimeUpdated', array($datetime));
return parent::setTimeUpdated($datetime);
}
/**
* {@inheritDoc}
*/
public function getTimeUpdated()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getTimeUpdated', array());
return parent::getTimeUpdated();
}
/**
* {@inheritDoc}
*/
public function setSubject($subject)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setSubject', array($subject));
return parent::setSubject($subject);
}
/**
* {@inheritDoc}
*/
public function getSubject()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getSubject', array());
return parent::getSubject();
}
/**
* {@inheritDoc}
*/
public function setMessage($message)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setMessage', array($message));
return parent::setMessage($message);
}
/**
* {@inheritDoc}
*/
public function getMessage()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getMessage', array());
return parent::getMessage();
}
/**
* {@inheritDoc}
*/
public function setIp($ip)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setIp', array($ip));
return parent::setIp($ip);
}
/**
* {@inheritDoc}
*/
public function getIp()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getIp', array());
return parent::getIp();
}
/**
* {@inheritDoc}
*/
public function setRecommended($recommended)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setRecommended', array($recommended));
return parent::setRecommended($recommended);
}
/**
* {@inheritDoc}
*/
public function getRecommended()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getRecommended', array());
return parent::getRecommended();
}
/**
* {@inheritDoc}
*/
public function setCommenter(\Newscoop\Entity\Comment\Commenter $commenter)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setCommenter', array($commenter));
return parent::setCommenter($commenter);
}
/**
* {@inheritDoc}
*/
public function getCommenter()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getCommenter', array());
return parent::getCommenter();
}
/**
* {@inheritDoc}
*/
public function getName()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getName', array());
return parent::getName();
}
/**
* {@inheritDoc}
*/
public function getCommenterName()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getCommenterName', array());
return parent::getCommenterName();
}
/**
* {@inheritDoc}
*/
public function getEmail()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getEmail', array());
return parent::getEmail();
}
/**
* {@inheritDoc}
*/
public function getCommenterEmail()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getCommenterEmail', array());
return parent::getCommenterEmail();
}
/**
* {@inheritDoc}
*/
public function setStatus($status)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setStatus', array($status));
return parent::setStatus($status);
}
/**
* {@inheritDoc}
*/
public function getStatus()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getStatus', array());
return parent::getStatus();
}
/**
* {@inheritDoc}
*/
public function setForum(\Newscoop\Entity\Publication $forum)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setForum', array($forum));
return parent::setForum($forum);
}
/**
* {@inheritDoc}
*/
public function getForum()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getForum', array());
return parent::getForum();
}
/**
* {@inheritDoc}
*/
public function setThread($thread)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setThread', array($thread));
return parent::setThread($thread);
}
/**
* {@inheritDoc}
*/
public function getThread()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getThread', array());
return parent::getThread();
}
/**
* {@inheritDoc}
*/
public function setThreadLevel($level)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setThreadLevel', array($level));
return parent::setThreadLevel($level);
}
/**
* {@inheritDoc}
*/
public function getThreadLevel()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getThreadLevel', array());
return parent::getThreadLevel();
}
/**
* {@inheritDoc}
*/
public function setThreadOrder($order)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setThreadOrder', array($order));
return parent::setThreadOrder($order);
}
/**
* {@inheritDoc}
*/
public function getThreadOrder()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getThreadOrder', array());
return parent::getThreadOrder();
}
/**
* {@inheritDoc}
*/
public function setLanguage(\Newscoop\Entity\Language $language)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setLanguage', array($language));
return parent::setLanguage($language);
}
/**
* {@inheritDoc}
*/
public function getLanguage()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getLanguage', array());
return parent::getLanguage();
}
/**
* {@inheritDoc}
*/
public function setParent(\Newscoop\Entity\Comment $parent = NULL)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setParent', array($parent));
return parent::setParent($parent);
}
/**
* {@inheritDoc}
*/
public function getParent()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getParent', array());
return parent::getParent();
}
/**
* {@inheritDoc}
*/
public function getParentId()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getParentId', array());
return parent::getParentId();
}
/**
* {@inheritDoc}
*/
public function getLikes()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getLikes', array());
return parent::getLikes();
}
/**
* {@inheritDoc}
*/
public function getDislikes()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getDislikes', array());
return parent::getDislikes();
}
/**
* {@inheritDoc}
*/
public function getRealName()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getRealName', array());
return parent::getRealName();
}
/**
* {@inheritDoc}
*/
public function SameAs($comment)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'SameAs', array($comment));
return parent::SameAs($comment);
}
/**
* {@inheritDoc}
*/
public function exists()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'exists', array());
return parent::exists();
}
/**
* {@inheritDoc}
*/
public function getProperty($key)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getProperty', array($key));
return parent::getProperty($key);
}
/**
* {@inheritDoc}
*/
public function setIndexed(\DateTime $indexed = NULL)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setIndexed', array($indexed));
return parent::setIndexed($indexed);
}
/**
* {@inheritDoc}
*/
public function getIndexed()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getIndexed', array());
return parent::getIndexed();
}
/**
* {@inheritDoc}
*/
public function getSource()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getSource', array());
return parent::getSource();
}
/**
* {@inheritDoc}
*/
public function setSource($source)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setSource', array($source));
return parent::setSource($source);
}
}
| mit |
alaingilbert/ttdashboard | server/ttdashboard/website/views.py | 66767 | from django.views.decorators.cache import cache_page
from django.shortcuts import get_object_or_404, render_to_response
from website.models import *
from website.forms import *
from django.db import connection, transaction
from django.core.context_processors import csrf
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.core.mail import send_mail
from django.utils.html import escape
from django.core.cache import cache
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.template import RequestContext
from website.crypto import rc4EncryptStr, rc4DecryptStr
from datetime import datetime
from settings import SECRET_KEY, SCRIPTS_PATH
import urllib, urllib2
import re, json, hashlib, random
import subprocess
def authkey(req):
ctx = {}
return render_to_response('authkey.html', ctx, context_instance=RequestContext(req))
@login_required
def playlists_export(req, playlist_id):
ctx = {}
cursor = connection.cursor()
user = req.user
profile = user.get_profile()
uid = profile.ttuid
auth = rc4DecryptStr(profile.auth_key, SECRET_KEY)
if not uid: raise Http404
if not auth:
ctx.update({'error':'You must set your auth key to communicate with turntable.fm'})
return render_to_response('authkey.html', ctx, context_instance=RequestContext(req))
cursor.execute("SELECT \
p.id, \
p.name, \
p.comment \
FROM playlists AS p \
WHERE id = %s AND uid = %s \
LIMIT 1 \
", [playlist_id, req.user.id])
if cursor.rowcount != 1:
raise Http404
if req.GET.get('confirm', None) is None:
return render_to_response('ttaction.html', ctx, context_instance=RequestContext(req))
cursor.execute("SELECT userid FROM users WHERE id=%s LIMIT 1", [uid])
auth = rc4DecryptStr(profile.auth_key, SECRET_KEY)
ttuid = dict_cursor(cursor)[0].get('userid')
# Get the playlist
params = ['python', '%s/export.py' % SCRIPTS_PATH, auth, ttuid]
playlist = dict_cursor(cursor)[0]
cursor.execute("SELECT \
s.id, \
s.songid, \
s.album, \
s.artist, \
s.coverart, \
s.song \
FROM playlists_songs AS ps \
LEFT JOIN songs AS s \
ON s.id = ps.song_id \
WHERE playlist_id = %s \
", [playlist_id])
songs = dict_cursor(cursor)
for song in songs:
params.append(song['songid']);
p = subprocess.Popen(params, shell=False, stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
data = json.loads(stdout)
ctx.update({'songs':list})
return HttpResponseRedirect('/profile/playlists/%s/' % playlist_id)
@csrf_exempt
@login_required
def playlists_import_save(req):
if req.method != 'POST':
raise Http404
cursor = connection.cursor()
playlist = []
for p in req.POST:
if p[:5] == 'song_':
if req.POST[p] not in playlist:
playlist.append(req.POST[p])
print playlist
name = 'import from tt.fm : %s' % (datetime.now().strftime('%d/%m/%Y %H:%M:%S'))
comment = '...'
cursor.execute("INSERT INTO playlists \
(uid, created, name, comment) \
VALUES \
(%s, NOW(), %s, %s) \
", [req.user.id, name, comment])
playlist_id = cursor.lastrowid
insert = ''
for song_id in playlist:
print "%s - %s" % (song_id, playlist_id)
insert += "('%s', '%s', NOW(), ''),\n" % (str(song_id), int(playlist_id))
insert = insert[:-2]
print insert
sql = "INSERT INTO playlists_songs \
(song_id, playlist_id, created, comment) \
VALUES \
%s \
" % insert
cursor.execute(sql)
transaction.commit_unless_managed()
return HttpResponseRedirect('/profile/playlists/%s/' % playlist_id)
@login_required
def playlists_import(req):
ctx = {}
cursor = connection.cursor()
user = req.user
profile = user.get_profile()
uid = profile.ttuid
auth = profile.auth_key
if not uid: raise Http404
if not auth:
ctx.update({'error':'You must set your auth key to communicate with turntable.fm'})
return render_to_response('authkey.html', ctx, context_instance=RequestContext(req))
if req.GET.get('confirm', None) is None:
return render_to_response('ttaction.html', ctx, context_instance=RequestContext(req))
cursor.execute("SELECT userid FROM users WHERE id=%s LIMIT 1", [uid])
ttuid = dict_cursor(cursor)[0].get('userid')
# Get the playlist
auth = rc4DecryptStr(profile.auth_key, SECRET_KEY)
p = subprocess.Popen(['python', '%s/import.py' % SCRIPTS_PATH, auth, ttuid], shell=False, stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
data = json.loads(stdout)
list = data.get('list')
params = []
for song in list:
song['songid'] = song.get('_id')
songid = song.get('_id')
album = song['metadata'].get('album', '')
artist = song['metadata'].get('artist', '')
coverart = song['metadata'].get('coverart', '')
song_name = song['metadata'].get('song', '')
length = song['metadata'].get('length', 0)
mnid = song['metadata'].get('mnid', 0)
genre = song['metadata'].get('genre', '')
filepath = song['metadata'].get('filepath', '')
bitrate = song['metadata'].get('bitrate', 0)
nb_play = 0
params = [songid, album, artist, coverart, song_name, length, mnid, genre, filepath, bitrate, nb_play]
print params
sql = "INSERT INTO songs \
(songid, album, artist, coverart, song, length, mnid, genre, filepath, bitrate, nb_play) \
VALUES \
(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) \
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id) \
"
cursor.execute(sql, params)
song['id'] = cursor.lastrowid
transaction.commit_unless_managed()
ctx.update({'songs':list})
return render_to_response('playlists_import.html', ctx, context_instance=RequestContext(req))
@login_required
def playlist_remove_song(req, playlist_id, song_id):
ctx = {}
cursor = connection.cursor()
cursor.execute("SELECT id, comment, name \
FROM playlists \
WHERE id = %s AND uid = %s \
LIMIT 1 \
", [playlist_id, req.user.id])
if cursor.rowcount != 1:
raise Http404
cursor.execute("DELETE FROM playlists_songs \
WHERE playlist_id = %s AND song_id = %s \
", [playlist_id, song_id])
transaction.commit_unless_managed()
return HttpResponseRedirect('/profile/playlists/%s/' % playlist_id)
@login_required
def playlist(req, playlist_id):
ctx = {}
cursor = connection.cursor()
cursor.execute("SELECT \
p.id, \
p.name, \
p.comment \
FROM playlists AS p \
WHERE id = %s AND uid = %s \
LIMIT 1 \
", [playlist_id, req.user.id])
if cursor.rowcount != 1:
raise Http404
playlist = dict_cursor(cursor)[0]
cursor.execute("SELECT \
s.id, \
s.album, \
s.artist, \
s.coverart, \
s.song \
FROM playlists_songs AS ps \
LEFT JOIN songs AS s \
ON s.id = ps.song_id \
WHERE playlist_id = %s \
", [playlist_id])
songs = dict_cursor(cursor)
ctx.update({'playlist':playlist})
ctx.update({'songs':songs})
return render_to_response('playlist.html', ctx, context_instance=RequestContext(req))
@login_required
def playlists_add_song(req, song_id):
ctx = {}
cursor = connection.cursor()
if req.method == 'POST':
playlists_ids = []
for p in req.POST:
if p[:8] == 'playlist':
playlists_ids.append(req.POST[p])
insert = ''
for id in playlists_ids:
insert += "('%s', '%s', NOW(), '')," % (int(song_id), int(id))
insert = insert[:-1]
sql = "INSERT INTO playlists_songs \
(song_id, playlist_id, created, comment) \
VALUES \
%s \
" % insert
cursor.execute(sql)
transaction.commit_unless_managed()
return HttpResponseRedirect('/profile/playlists/')
cursor = connection.cursor()
cursor.execute("SELECT \
p.id, \
p.uid, \
p.created, \
p.comment, \
p.name, \
ps.song_id, \
ps.playlist_id, \
ps.created, \
ps.comment AS song_comment \
FROM playlists AS p \
LEFT JOIN playlists_songs AS ps \
ON ps.playlist_id = p.id AND ps.song_id = %s \
WHERE p.uid = %s \
GROUP BY p.id, p.uid, p.created, p.comment, p.name, ps.song_id, ps.playlist_id, ps.created, ps.comment \
", [song_id, req.user.id])
if cursor.rowcount <= 0:
raise Http404
playlists = dict_cursor(cursor)
ctx.update({'playlists':playlists})
return render_to_response('playlists_add_song.html', ctx, context_instance=RequestContext(req))
@login_required
def add_playlists(req):
ctx = {}
cursor = connection.cursor()
if req.method == 'POST':
form = PlaylistForm(req.POST)
if form.is_valid():
name = req.POST['name']
comment = req.POST['comment']
cursor.execute("INSERT INTO playlists \
(uid, created, name, comment) \
VALUES \
(%s, %s, %s, %s) \
", [req.user.id, datetime.now(), name, comment])
transaction.commit_unless_managed()
return HttpResponseRedirect('/profile/playlists/')
else:
form = PlaylistForm()
ctx.update(csrf(req))
ctx.update({'form':form})
return render_to_response('add_playlists.html', ctx, context_instance=RequestContext(req))
@login_required
def playlists(req):
ctx = {}
cursor = connection.cursor()
cursor.execute("SELECT \
p.id, p.name, p.comment, \
COUNT(ps.playlist_id) AS nb_songs \
FROM playlists AS p \
LEFT JOIN playlists_songs AS ps \
ON ps.playlist_id = p.id \
WHERE p.uid = %s \
GROUP BY p.id, p.name, p.comment \
", [req.user.id])
playlists = dict_cursor(cursor)
ctx.update({'playlists':playlists})
return render_to_response('playlists.html', ctx, context_instance=RequestContext(req))
@login_required
def edit_playlists(req, playlist_id):
ctx = {}
cursor = connection.cursor()
cursor.execute("SELECT id, comment, name \
FROM playlists \
WHERE id = %s AND uid = %s \
LIMIT 1 \
", [playlist_id, req.user.id])
if cursor.rowcount != 1:
raise Http404
playlist = dict_cursor(cursor)[0]
if req.method == 'POST':
form = PlaylistForm(req.POST)
if form.is_valid():
name = req.POST.getlist('name')[0] if len(req.POST.getlist('name')) > 0 else ''
comment = req.POST.getlist('comment')[0] if len(req.POST.getlist('comment')) > 0 else ''
cursor.execute("UPDATE playlists \
SET name = %s, \
comment = %s \
WHERE id = %s AND uid = %s \
", [name, comment, playlist_id, req.user.id])
transaction.commit_unless_managed()
return HttpResponseRedirect('/profile/playlists/')
else:
form = PlaylistForm(playlist)
ctx.update(csrf(req))
ctx.update({'form':form})
return render_to_response('edit_playlists.html', ctx, context_instance=RequestContext(req))
@login_required
def delete_playlists(req, playlist_id):
ctx = {}
cursor = connection.cursor()
cursor.execute("SELECT id, comment, name \
FROM playlists \
WHERE id = %s AND uid = %s \
LIMIT 1 \
", [playlist_id, req.user.id])
if cursor.rowcount != 1:
raise Http404
cursor.execute("DELETE FROM playlists \
WHERE id = %s AND uid = %s \
", [playlist_id, req.user.id])
transaction.commit_unless_managed()
return HttpResponseRedirect('/profile/playlists/')
@login_required
def edit_profile(req):
ctx = {}
user = get_object_or_404(User, pk=req.user.id)
profile = user.get_profile()
if req.method == 'POST':
form = ProfileForm(req.POST)
auth_key = req.POST.getlist('auth_key')[0] if len(req.POST.getlist('auth_key')) > 0 else ''
if len(auth_key) != 0 and len(auth_key) != 50:
ctx.update(csrf(req))
ctx.update({'form':form})
ctx.update({'error':'Your auth key may have 50 chars.'})
return render_to_response('edit_profile.html', ctx, context_instance=RequestContext(req))
if len(auth_key) != 0 and auth_key[:10] != 'auth+live+':
ctx.update(csrf(req))
ctx.update({'form':form})
ctx.update({'error':'Your auth key is invalid.'})
return render_to_response('edit_profile.html', ctx, context_instance=RequestContext(req))
if form.is_valid():
first_name = req.POST.getlist('first_name')[0] if len(req.POST.getlist('first_name')) > 0 else ''
last_name = req.POST.getlist('last_name')[0] if len(req.POST.getlist('last_name')) > 0 else ''
auth_key = rc4EncryptStr(auth_key, SECRET_KEY)
user.first_name = first_name
user.last_name = last_name
user.save()
profile.auth_key = auth_key
profile.save()
return HttpResponseRedirect('/profile/')
else:
dict = user.__dict__
dict.update(profile.__dict__)
if dict['auth_key']:
dict['auth_key'] = rc4DecryptStr(dict['auth_key'], SECRET_KEY)
form = ProfileForm(dict)
ctx.update(csrf(req))
ctx.update({'form':form})
return render_to_response('edit_profile.html', ctx, context_instance=RequestContext(req))
@login_required
def profile(req):
ctx = {}
cursor = connection.cursor()
auth_user = req.user
auth_profile = auth_user.get_profile()
cursor.execute("SELECT \
* \
FROM users AS u \
WHERE u.id = %s \
LIMIT 1", [auth_profile.ttuid])
user = None
if cursor.rowcount == 1:
user = dict_cursor(cursor)[0]
#if not cache.get('profile_%s_newsongs' % auth_profile.ttuid):
# # Select my 10 favs songs.
# cursor.execute("SELECT \
# song_id, \
# nb, \
# user_id \
# FROM users_songs_liked \
# WHERE user_id=%s \
# ORDER BY nb DESC \
# LIMIT 100", [auth_profile.ttuid])
# songs_like = dict_cursor(cursor)
# l = []
# for s in songs_like:
# l.append(s['song_id'])
# if len(l) > 0:
# ctx.update({'songs_like':songs_like})
# # Who love those songs
# cursor.execute("SELECT \
# song_id, \
# nb, \
# user_id \
# FROM users_songs_liked \
# WHERE song_id IN %s \
# ORDER BY nb DESC \
# LIMIT 15", [l[:5]])
# users_like = dict_cursor(cursor)
# ctx.update({'users_like':users_like})
# l2 = []
# for u in users_like:
# l2.append(u['user_id'])
# # Get common loved songs.
# cursor.execute("SELECT \
# SUM(nb) AS test, \
# s.id AS song_id, \
# s.song AS song_name, \
# s.artist AS song_artist, \
# s.genre AS song_genre, \
# s.coverart AS song_coverart, \
# s.previewurl, \
# s.collectionviewurl, \
# s.album AS song_album \
# FROM users_songs_liked AS usl \
# LEFT JOIN songs AS s \
# ON s.id = song_id \
# WHERE user_id IN %s AND usl.song_id NOT IN %s \
# GROUP BY usl.song_id \
# ORDER BY test DESC \
# LIMIT 20", [l2, l])
# songs_like2 = dict_cursor(cursor)
# for s in songs_like2:
# if not s['previewurl']:
# print "CALISS"
# print s['previewurl']
# data = json.loads(urllib2.urlopen('http://itunes.apple.com/search?' + urllib.urlencode({'term':'%s %s' % (s['song_artist'], s['song_name']), 'entity':'song', 'limit':'25'})).read())
# if len(data['results']):
# previewurl = data['results'][0].get('previewUrl')
# collectionviewurl = data['results'][0].get('collectionViewUrl')
# cursor.execute("UPDATE songs SET previewurl=%s, collectionviewurl=%s WHERE id = %s", [previewurl, collectionviewurl, s['song_id']])
# s['previewurl'] = data['results'][0].get('previewUrl')
# else:
# cursor.execute("UPDATE songs SET previewurl='NOTHING', collectionviewurl='NOTHING' WHERE id = %s", [s['song_id']])
# s['previewurl'] = ''
# transaction.commit_unless_managed()
# ctx.update({'discover_songs':songs_like2})
# cache.set('profile_%s_newsongs' % auth_profile.ttuid, songs_like2, 60*15)
#else:
# songs_like2 = cache.get('profile_%s_newsongs' % auth_profile.ttuid)
# ctx.update({'discover_songs':songs_like2})
ctx.update({'tuser':user})
return render_to_response('profile.html', ctx, context_instance=RequestContext(req))
@login_required
def link_profile(req, uid):
cursor = connection.cursor()
cursor.execute("SELECT * FROM users WHERE id = %s LIMIT 1", [uid])
count = cursor.rowcount
if count != 1:
raise Http404
profile = req.user.get_profile()
profile.ttuid = uid
profile.save()
return HttpResponseRedirect('/profile/')
@login_required
def change_email(req):
if req.method == 'POST':
pass
@login_required
def user_logout(req):
logout(req)
return HttpResponseRedirect('/')
def generate_password():
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
psw = ""
for i in range(0, 10):
c = random.randint(0, len(chars)-1)
psw += chars[c]
return psw
@csrf_exempt
def password_recovery(req):
if req.method == 'POST':
form = RecoveryForm(req.POST)
if form.is_valid():
email = req.POST['email']
try:
tmp = User.objects.get(email=email)
except:
ctx = {'err':'This email does not exists.'}
return render_to_response('recovery.html', ctx, context_instance=RequestContext(req))
hash = hashlib.sha1(str(datetime.now())).hexdigest()
PasswordRecovery.objects.create(hash=hash, email=email)
send_mail('ttDashboard password recovery', 'http://ttdashboard.com/recovery/%s/' % hash, 'no-reply@ttdashboard.com', [email], fail_silently=False)
return HttpResponseRedirect('/')
else:
return render_to_response('recovery.html', {}, context_instance=RequestContext(req))
def password_recovery2(req, key):
recovery = get_object_or_404(PasswordRecovery, hash=key)
email = recovery.email
recovery.delete()
password = generate_password()
user = User.objects.get(email=email)
username = user.username
user.set_password(password)
user.save()
send_mail('ttDashboard password recovery', 'Username: %s, New password: %s' % (username, password), 'no-reply@ttdashboard.com', [email], fail_silently=False)
return HttpResponseRedirect('/')
@csrf_exempt
def change_password(req):
if req.method == 'POST':
form = ChangePasswordForm(req.POST)
if form.is_valid():
password = req.POST['password']
if len(password) < 5:
ctx = {'err':'Your password must have at least 5 characters.'}
return render_to_response('change_password.html', ctx, context_instance=RequestContext(req))
user = req.user
user.set_password(password)
user.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('change_password.html', {}, context_instance=RequestContext(req))
@csrf_exempt
def user_login(req):
if req.method == 'POST': # If the form has been submitted...
form = LoginForm(req.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
user = authenticate(username=req.POST['username'], password=req.POST['password'])
if user is not None:
login(req, user)
return HttpResponseRedirect('/profile/')
return render_to_response('login.html', {'err':'Bad username/password'}, context_instance=RequestContext(req))
else:
raise Http404
@csrf_exempt
def user_register(req):
if req.method == 'POST':
form = RegisterForm(req.POST)
if form.is_valid():
username = req.POST['username']
email = req.POST['email']
password = req.POST['password']
try:
tmp = User.objects.get(email=email)
return render_to_response('register.html', {'err':'Email already taken'}, context_instance=RequestContext(req))
except:
pass
try:
tmp = User.objects.get(username=username)
return render_to_response('register.html', {'err':'Username already taken'}, context_instance=RequestContext(req))
except:
pass
key = hashlib.sha1(str(datetime.now())).hexdigest()
api_key = hashlib.sha1(str(datetime.now()) + str(random.randint(0, 100000))).hexdigest()
user = User.objects.create_user(username, email, password)
user.is_active = False
user.save()
profile = user.get_profile()
profile.activation_key = key
profile.api_key = api_key
profile.save()
send_mail('ttDashboard confirmation', 'http://ttdashboard.com/activate/%s/' % key, 'no-reply@ttdashboard.com', [email], fail_silently=False)
user = authenticate(username=username, password=password)
if user is not None:
login(req, user)
return HttpResponseRedirect('/profile/')
return render_to_response('register.html', {'err':'Invalid form'}, context_instance=RequestContext(req))
else:
raise Http404
def user_activate(req, key):
profile = get_object_or_404(UserProfile, activation_key=key)
user = profile.user
if user.is_active:
raise Http404
profile.activation_key = None
profile.save()
user.is_active = True
user.save()
return HttpResponseRedirect('/')
def dict_cursor(cursor):
description = [x[0] for x in cursor.description]
rows = []
for row in cursor:
rows.append(dict(zip(description, row)))
return rows
@cache_page(10)
def ajax_home(req):
if req.is_ajax():
cursor = connection.cursor()
cursor.execute("SELECT \
r.roomid AS roomid, \
r.name AS room_name, \
r.shortcut AS room_shortcut, \
r.listeners AS room_listeners, \
u.id AS current_dj_id, \
u.name AS current_dj, \
s.nb_play AS room_nb_play, \
s.song AS song_name, \
s.coverart AS song_coverart, \
r.downvotes, \
r.upvotes \
FROM rooms AS r \
LEFT JOIN songs AS s \
ON s.id = r.current_song \
LEFT JOIN users AS u \
ON u.id = r.current_dj \
ORDER BY r.listeners DESC \
LIMIT 6")
rooms = dict_cursor(cursor)
return render_to_response('ajax_home.html', {'rooms':rooms}, context_instance=RequestContext(req))
def top_users_points(req):
cursor = connection.cursor()
cursor.execute("SELECT * FROM users \
WHERE id NOT IN (11717, 139, 13248, 532, 580) \
ORDER BY points DESC LIMIT 12")
users_points = dict_cursor(cursor)
return users_points
def top_users_fans(req):
cursor = connection.cursor()
cursor.execute("SELECT * FROM users \
WHERE id NOT IN (6902) \
ORDER BY fans DESC LIMIT 12")
users_fans = dict_cursor(cursor)
return users_fans
def top_songs(req):
cursor = connection.cursor()
cursor.execute("SELECT * FROM songs ORDER BY nb_play DESC LIMIT 12")
pop_songs = dict_cursor(cursor)
return pop_songs
def v2_0(req):
pass
ctx = {}
return render_to_response('v2_0.html', ctx, context_instance=RequestContext(req))
def home(req):
if req.is_ajax():
raise Http404
cursor = connection.cursor()
cursor.execute("SELECT \
r.roomid AS roomid, \
r.name AS room_name, \
r.shortcut AS room_shortcut, \
r.listeners AS room_listeners, \
u.id AS current_dj_id, \
u.name AS current_dj, \
s.nb_play AS room_nb_play, \
s.song AS song_name, \
s.coverart AS song_coverart, \
r.downvotes, \
r.upvotes \
FROM rooms AS r \
LEFT JOIN songs AS s \
ON s.id = r.current_song \
LEFT JOIN users AS u \
ON u.id = r.current_dj \
ORDER BY r.listeners DESC \
LIMIT 6")
rooms = dict_cursor(cursor)
if not cache.get('top_users_points'):
users_points = top_users_points(req)
cache.set('top_users_points', users_points, 60*15)
else:
users_points = cache.get('top_users_points')
if not cache.get('top_users_fans'):
users_fans = top_users_fans(req)
cache.set('top_users_fans', users_fans, 60*15)
else:
users_fans = cache.get('top_users_fans')
if not cache.get('top_songs'):
pop_songs = top_songs(req)
cache.set('top_songs', pop_songs, 60*15)
else:
pop_songs = cache.get('top_songs')
return render_to_response('home.html', {'onglet':'home', 'users_points':users_points, 'users_fans':users_fans, 'pop_songs':pop_songs, 'rooms':rooms}, context_instance=RequestContext(req))
def songs(req):
cursor = connection.cursor()
if not cache.get('songs_ups'):
cursor.execute("SELECT \
SUM(sl.upvotes) AS upvotes, \
s.coverart, s.id, s.song \
FROM songs AS s \
LEFT JOIN song_log AS sl \
ON sl.song_id = s.id \
WHERE \
sl.created > CURRENT_DATE - INTERVAL '1' DAY \
GROUP BY sl.song_id, s.id, s.song, s.coverart \
ORDER BY upvotes DESC \
LIMIT 10")
ups = dict_cursor(cursor)
cache.set('songs_ups', ups, 60*15)
else:
ups = cache.get('songs_ups')
if not cache.get('songs_downs'):
cursor.execute("SELECT \
SUM(sl.downvotes) AS downvotes, \
s.coverart, s.id, s.song \
FROM songs AS s \
LEFT JOIN song_log AS sl \
ON sl.song_id = s.id \
WHERE \
sl.created > CURRENT_DATE - INTERVAL '1' DAY \
GROUP BY sl.song_id, s.id, s.song, s.coverart \
ORDER BY downvotes DESC \
LIMIT 10")
downs = dict_cursor(cursor)
cache.set('songs_downs', downs, 60*15)
else:
downs = cache.get('songs_downs')
if not cache.get('songs_combined'):
cursor.execute("SELECT \
SUM(sl.upvotes) - SUM(sl.downvotes) AS votes, \
s.coverart, s.id, s.song \
FROM songs AS s \
LEFT JOIN song_log AS sl \
ON sl.song_id = s.id \
WHERE \
sl.created > CURRENT_DATE - INTERVAL '1' DAY \
GROUP BY sl.song_id, s.id, s.song, s.coverart \
ORDER BY votes DESC \
LIMIT 10")
combined = dict_cursor(cursor)
cache.set('songs_combined', combined, 60*15)
else:
combined = cache.get('songs_combined')
if not cache.get('songs_pop_songs'):
cursor.execute("SELECT \
COUNT(sl.song_id) AS nb_play, \
s.coverart, s.id, s.song \
FROM songs AS s \
LEFT JOIN song_log AS sl \
ON sl.song_id = s.id \
WHERE \
sl.created > CURRENT_DATE - INTERVAL '1' DAY \
GROUP BY sl.song_id, s.id, s.song, s.coverart \
ORDER BY nb_play DESC \
LIMIT 10")
pop_songs = dict_cursor(cursor)
cache.set('songs_pop_songs', pop_songs, 60*15)
else:
pop_songs = cache.get('songs_pop_songs')
return render_to_response('songs.html', {'onglet':'songs', 'ups':ups, 'downs':downs, 'combined':combined, 'pop_songs':pop_songs}, context_instance=RequestContext(req))
#@cache_page(60 * 15)
def songs_played(req):
cursor = connection.cursor()
cursor.execute("SELECT * FROM songs ORDER BY nb_play DESC LIMIT 100")
pop_songs = dict_cursor(cursor)
return render_to_response('songs_played.html', {'onglet':'songs', 'pop_songs':pop_songs}, context_instance=RequestContext(req))
def song_ttid(req, song_id):
cursor = connection.cursor()
cursor.execute("SELECT s.id, s.song, s.album, s.artist, s.length, s.genre, s.nb_play, s.coverart \
FROM songs AS s \
WHERE s.songid=%s \
LIMIT 1", [song_id])
song = dict_cursor(cursor)[0]
song['length'] = format_length(song['length'])
try:
data = json.loads(urllib2.urlopen('http://itunes.apple.com/search?' + urllib.urlencode({'term':'%s %s' % (song['artist'], song['song']), 'entity':'song', 'limit':'1'})).read())
if data['results']:
song['previewUrl'] = data['results'][0].get('previewUrl')
song['collectionViewUrl'] = data['results'][0].get('collectionViewUrl')
except:
pass
cursor.execute("SELECT SUM(sl.upvotes) AS upvotes, \
SUM(sl.downvotes) AS downvotes \
FROM songlog AS sl \
WHERE sl.songid=%s \
LIMIT 1", [song['id']])
votes = dict_cursor(cursor)[0]
song['upvotes'] = votes['upvotes']
song['downvotes'] = votes['downvotes']
cursor.execute("SELECT sl.upvotes AS upvotes, \
sl.downvotes AS downvotes, \
sl.starttime, \
sl.current_dj AS current_dj_id, \
u.name AS current_dj, \
r.name AS room_name, \
r.roomid AS roomid, \
r.shortcut AS room_shortcut \
FROM songlog AS sl \
LEFT JOIN users AS u \
ON u.id = sl.current_dj \
LEFT JOIN rooms AS r \
ON r.id = sl.roomid \
WHERE sl.songid=%s \
ORDER BY sl.starttime DESC \
LIMIT 20", [song['id']])
appreciation_log = dict_cursor(cursor)
return render_to_response('song.html', {'onglet':'songs', 'song':song, 'appreciation_log':appreciation_log}, context_instance=RequestContext(req))
def song(req, song_id):
cursor = connection.cursor()
cursor.execute("SELECT s.id, s.song, s.album, s.artist, s.length, s.genre, s.nb_play, s.coverart \
FROM songs AS s \
WHERE s.id=%s \
LIMIT 1" % int(song_id))
song = dict_cursor(cursor)[0]
song['length'] = format_length(song['length'])
try:
data = json.loads(urllib2.urlopen('http://itunes.apple.com/search?' + urllib.urlencode({'term':'%s %s' % (song['artist'], song['song']), 'entity':'song', 'limit':'1'})).read())
if data['results']:
song['previewUrl'] = data['results'][0].get('previewUrl')
song['collectionViewUrl'] = data['results'][0].get('collectionViewUrl')
except:
pass
cursor.execute("SELECT SUM(sl.upvotes) AS upvotes, \
SUM(sl.downvotes) AS downvotes \
FROM song_log AS sl \
WHERE sl.song_id=%s \
LIMIT 1" % (int(song_id)))
votes = dict_cursor(cursor)[0]
song['upvotes'] = votes['upvotes']
song['downvotes'] = votes['downvotes']
cursor.execute("SELECT sl.upvotes AS upvotes, \
sl.downvotes AS downvotes, \
sl.dj AS current_dj_id, \
sl.created, \
u.name AS current_dj, \
r.name AS room_name, \
r.roomid AS roomid, \
r.shortcut AS room_shortcut \
FROM song_log AS sl \
LEFT JOIN users AS u \
ON u.id = sl.dj \
LEFT JOIN rooms AS r \
ON r.id = sl.room_id \
WHERE sl.song_id=%s \
ORDER BY sl.created DESC \
LIMIT 20" % (int(song_id)))
appreciation_log = dict_cursor(cursor)
return render_to_response('song.html', {'onglet':'songs', 'song':song, 'appreciation_log':appreciation_log}, context_instance=RequestContext(req))
def format_length(length):
if length != None:
minutes = length / 60
secondes = length - minutes * 60
return "%sm %s" % (minutes, secondes)
else:
return ""
@cache_page(10)
def ajax_room_infos(req, shortcut):
if not req.is_ajax():
raise Http404
if re.match('^\w{24}$', shortcut):
where = 'r.roomid'
else:
where = 'r.shortcut'
cursor = connection.cursor()
cursor.execute("SELECT \
r.id AS room_id, \
r.name AS room_name, \
r.description AS room_description, \
r.shortcut AS room_shortcut, \
r.listeners AS room_listeners, \
r.roomid AS roomid, \
r.downvotes, \
r.upvotes, \
r.current_dj AS current_dj_id, \
s.id AS song_id, \
s.nb_play AS room_nb_play, \
s.length AS song_length, \
s.song AS song_name, \
s.album AS song_album, \
s.artist AS song_artist, \
s.coverart AS song_coverart, \
u.name AS current_dj \
FROM rooms AS r \
LEFT JOIN songs AS s \
ON s.id = r.current_song \
LEFT JOIN users AS u \
ON u.id = r.current_dj \
WHERE %s='%s' \
LIMIT 1" % (where, str(shortcut)))
# Raise 404 if no entry has been found.
count = cursor.rowcount
if count != 1:
raise Http404
room = dict_cursor(cursor)[0]
room['song_length'] = format_length(room['song_length'])
# itunes infos...
data = json.loads(urllib2.urlopen('http://itunes.apple.com/search?' + urllib.urlencode({'term':'%s %s' % (room['song_artist'], room['song_name']), 'entity':'song', 'limit':'1'})).read())
if data['results']:
room['previewUrl'] = data['results'][0].get('previewUrl')
room['collectionViewUrl'] = data['results'][0].get('collectionViewUrl')
return render_to_response('ajax_room_infos.html', {'room':room}, context_instance=RequestContext(req))
#def ajax_room_day_bests(req, limit):
# cursor.execute("SELECT s.coverart, \
# s.id AS song_id, \
# s.song, \
# s.artist, \
# sl.upvotes, sl.downvotes, \
# sl.starttime, \
# sl.current_dj AS current_dj_id, \
# u.name AS current_dj \
# FROM songlog AS sl \
# LEFT JOIN songs AS s \
# ON s.id = sl.songid \
# LEFT JOIN users AS u \
# ON u.id = sl.current_dj \
# WHERE roomid=%s \
# ORDER BY starttime DESC \
# LIMIT %s, 20", [int(room['room_id']), limit])
# songs = dict_cursor(cursor)
# return songs
def ajax_room_day_appreciated(req):
pass
def room(req, shortcut):
if re.match('^\w{24}$', shortcut):
where = 'r.roomid'
else:
where = 'r.shortcut'
cursor = connection.cursor()
cursor.execute("SELECT \
r.id AS room_id, \
r.name AS room_name, \
r.description AS room_description, \
r.shortcut AS room_shortcut, \
r.listeners AS room_listeners, \
r.roomid AS roomid, \
r.downvotes, \
r.upvotes, \
r.current_dj AS current_dj_id, \
r.current_dj_name AS current_dj, \
r.current_song AS CALISS, \
s.id AS song_id, \
s.nb_play AS room_nb_play, \
s.length AS song_length, \
s.song AS song_name, \
s.album AS song_album, \
s.artist AS song_artist, \
s.coverart AS song_coverart \
FROM rooms AS r \
LEFT JOIN songs AS s \
ON s.id = r.current_song \
WHERE %s='%s' \
LIMIT 1" % (where, str(shortcut)))
# Raise 404 if no entry has been found.
count = cursor.rowcount
if count != 1:
raise Http404
room = dict_cursor(cursor)[0]
room['song_length'] = format_length(room['song_length'])
# itunes infos...
try:
data = json.loads(urllib2.urlopen('http://itunes.apple.com/search?' + urllib.urlencode({'term':'%s %s' % (room['song_artist'], room['song_name']), 'entity':'song', 'limit':'1'})).read())
if data['results']:
room['previewUrl'] = data['results'][0].get('previewUrl')
room['collectionViewUrl'] = data['results'][0].get('collectionViewUrl')
except:
pass
if req.is_ajax():
last = int(req.GET.get('last', 0))
limit = last+1
else:
limit = 0
cursor.execute("SELECT \
sl.song_coverart AS coverart, \
sl.song_id AS song_id, \
sl.song_name AS song, \
sl.song_artist AS artist, \
sl.created, \
sl.upvotes, sl.downvotes, \
sl.dj AS current_dj_id, \
sl.dj_name AS current_dj \
FROM song_log AS sl \
WHERE sl.room_id=%s \
ORDER BY sl.created DESC \
LIMIT 20 OFFSET %s", [room['room_id'], limit])
songs_log = dict_cursor(cursor)
content = {'room':room, 'songs_log':songs_log}
if not req.is_ajax():
cursor.execute("SELECT sl.listeners, sl.created \
FROM song_log AS sl \
WHERE sl.room_id=%s \
AND sl.created::date = CURRENT_DATE \
ORDER BY sl.created", [room['room_id']])
room_stats = dict_cursor(cursor)
print room_stats;
content.update({'room_stats': room_stats})
if req.is_ajax():
content.update({'last':last})
return render_to_response('ajax_room.html', content, context_instance=RequestContext(req))
else:
content.update({'onglet':'rooms'})
return render_to_response('room.html', content, context_instance=RequestContext(req))
def rooms(req):
cursor = connection.cursor()
if not cache.get('rooms_ups'):
cursor.execute("SELECT \
SUM(sl.upvotes) AS upvotes, \
r.id AS room_id, \
r.roomid AS roomid, \
r.name AS room_name, \
r.listeners AS room_listeners, \
r.shortcut AS room_shortcut, \
r.upvotes AS song_upvotes, \
r.downvotes AS song_downvotes \
FROM rooms AS r \
LEFT JOIN song_log AS sl \
ON sl.room_id = r.id \
WHERE \
sl.created > CURRENT_DATE - INTERVAL '1' DAY \
GROUP BY r.id, r.roomid, r.name, r.listeners, r.shortcut, \
r.upvotes, r.downvotes \
ORDER BY upvotes DESC \
LIMIT 10")
ups = dict_cursor(cursor)
cache.set('rooms_ups', ups, 60*15)
else:
ups = cache.get('rooms_ups')
if not cache.get('rooms_downs'):
cursor.execute("SELECT \
SUM(sl.downvotes) AS downvotes, \
r.id AS room_id, \
r.roomid AS roomid, \
r.name AS room_name, \
r.listeners AS room_listeners, \
r.shortcut AS room_shortcut, \
r.upvotes AS song_upvotes, \
r.downvotes AS song_downvotes \
FROM rooms AS r \
LEFT JOIN song_log AS sl \
ON sl.room_id = r.id \
WHERE \
sl.created > CURRENT_DATE - INTERVAL '1' DAY \
GROUP BY r.id, r.roomid, r.name, r.listeners, r.shortcut, \
r.upvotes, r.downvotes \
ORDER BY downvotes DESC \
LIMIT 10")
downs = dict_cursor(cursor)
cache.set('rooms_downs', downs, 60*15)
else:
downs = cache.get('rooms_downs')
if not cache.get('rooms_combined'):
cursor.execute("SELECT \
SUM(sl.upvotes) - SUM(sl.downvotes) AS votes, \
r.id AS room_id, \
r.roomid AS roomid, \
r.name AS room_name, \
r.listeners AS room_listeners, \
r.shortcut AS room_shortcut, \
r.upvotes AS song_upvotes, \
r.downvotes AS song_downvotes \
FROM rooms AS r \
LEFT JOIN song_log AS sl \
ON sl.room_id = r.id \
WHERE \
sl.created > CURRENT_DATE - INTERVAL '1' DAY \
GROUP BY r.id, r.roomid, r.name, r.listeners, r.shortcut, \
r.upvotes, r.downvotes \
ORDER BY votes DESC \
LIMIT 10")
combined = dict_cursor(cursor)
cache.set('rooms_combined', combined, 60*15)
else:
combined = cache.get('rooms_combined')
if not cache.get('rooms_active'):
cursor.execute("SELECT \
AVG(sl.upvotes + sl.downvotes) AS moyenne, \
r.id AS room_id, \
r.roomid AS roomid, \
r.name AS room_name, \
r.listeners AS room_listeners, \
r.shortcut AS room_shortcut \
FROM rooms AS r \
LEFT JOIN song_log AS sl \
ON sl.room_id = r.id \
WHERE \
sl.dj IS NOT NULL AND \
sl.created > CURRENT_DATE - INTERVAL '1' DAY \
GROUP BY r.id, r.roomid, r.name, r.listeners, r.shortcut, \
r.upvotes, r.downvotes \
ORDER BY moyenne DESC \
LIMIT 10")
active = dict_cursor(cursor)
cache.set('rooms_active', active, 60*15)
else:
active = cache.get('rooms_active')
return render_to_response('rooms.html', {'onglet':'rooms', 'ups':ups, 'downs':downs, 'combined':combined, 'active':active}, context_instance=RequestContext(req))
def user_fbid(req, fbid):
cursor = connection.cursor()
# Get infos about the user.
cursor.execute("SELECT id \
FROM users AS u \
WHERE u.fbid=%s \
LIMIT 1", [int(fbid)])
user_id = dict_cursor(cursor)[0]['id']
return user(req, user_id)
def user_uid(req, uid):
cursor = connection.cursor()
# Get infos about the user.
cursor.execute("SELECT id \
FROM users AS u \
WHERE u.userid=%s \
LIMIT 1", [uid])
user_id = dict_cursor(cursor)[0]['id']
return user(req, user_id)
def user(req, user_id):
cursor = connection.cursor()
# Get infos about the user.
cursor.execute("SELECT * \
FROM users AS u \
WHERE u.id=%s \
LIMIT 1" % (int(user_id)))
user = dict_cursor(cursor)[0]
# Get how many up and down he got as a DJ.
cursor.execute("SELECT SUM(sl.upvotes) AS upvotes, \
SUM(sl.downvotes) AS downvotes \
FROM song_log AS sl \
WHERE sl.dj=%s \
LIMIT 1" % (int(user_id)))
votes = dict_cursor(cursor)[0]
user['upvotes'] = votes['upvotes']
user['downvotes'] = votes['downvotes']
# Songs that the user has played.
cursor.execute("SELECT \
sl.created, \
sl.upvotes, \
sl.downvotes, \
r.name AS room_name, \
r.roomid AS roomid, \
r.shortcut AS room_shortcut, \
sl.song_id AS song_id, \
sl.song_name AS song_name, \
sl.song_artist AS song_artist, \
sl.song_coverart AS song_coverart, \
sl.song_album AS song_album \
FROM song_log AS sl \
LEFT JOIN rooms AS r \
ON r.id = sl.room_id \
WHERE sl.dj=%s \
ORDER BY sl.created DESC \
LIMIT 30" % (int(user_id)))
songs_log = dict_cursor(cursor)
# Songs that the user like.
cursor.execute("SELECT \
sl.song_id, \
sl.nb_awesomes AS nb, \
s.id AS song_id, \
s.song AS song_name, \
s.artist AS song_artist, \
s.genre AS song_genre, \
s.coverart AS song_coverart, \
s.album AS song_album \
FROM users_songs_liked AS sl \
LEFT JOIN songs AS s \
ON s.id = sl.song_id \
WHERE sl.user_id='%s' \
AND sl.nb_awesomes > 0 \
ORDER BY nb_awesomes DESC, sl.modified DESC \
LIMIT 30" % int(user_id))
songs_like = dict_cursor(cursor)
# Songs that the user dislike.
cursor.execute("SELECT \
sl.song_id, \
sl.nb_lames AS nb, \
s.id AS song_id, \
s.song AS song_name, \
s.artist AS song_artist, \
s.genre AS song_genre, \
s.coverart AS song_coverart, \
s.album AS song_album \
FROM users_songs_liked AS sl \
LEFT JOIN songs AS s \
ON s.id = sl.song_id \
WHERE sl.user_id='%s' \
AND sl.nb_lames > 0 \
ORDER BY nb_lames DESC, sl.modified DESC \
LIMIT 30" % int(user_id))
songs_dislike = dict_cursor(cursor)
cursor.execute("SELECT \
COUNT(*) AS rank \
FROM users AS u \
WHERE u.id NOT IN (11717, 139, 13248, 532, 580) AND u.points > %s", [user['points']])
rank_points = dict_cursor(cursor)[0]['rank']+1
cursor.execute("SELECT \
COUNT(*) AS rank \
FROM users AS u \
WHERE u.id NOT IN (6902) AND u.fans > %s", [user['fans']])
rank_fans = dict_cursor(cursor)[0]['rank']+1
return render_to_response('user.html', { 'onglet':'users', 'tuser':user, 'songs_log':songs_log, 'songs_like':songs_like, 'songs_dislike':songs_dislike, 'rank_points':rank_points, 'rank_fans':rank_fans }, context_instance=RequestContext(req))
def ajax_uid_brag(req, uid):
cursor = connection.cursor()
cursor.execute("SELECT \
id, \
name, \
laptop AS platform, \
userid, \
acl, \
fans, \
points, \
avatarid \
FROM users \
WHERE id = %s \
LIMIT 1", [uid])
count = cursor.rowcount
if count == 1:
user = dict_cursor(cursor)[0]
cursor.execute("SELECT \
COUNT(*) AS rank \
FROM users AS u \
WHERE u.id NOT IN (11717, 139, 13248, 532, 580) AND u.points > %s", [user['points']])
rank_points = dict_cursor(cursor)[0]['rank']+1
cursor.execute("SELECT \
COUNT(*) AS rank \
FROM users AS u \
WHERE u.id NOT IN (6902) AND u.fans > %s", [user['fans']])
rank_fans = dict_cursor(cursor)[0]['rank']+1
user['rank_points'] = rank_points
user['rank_fans'] = rank_fans
else:
return render_to_response('ajax_brag.html', {'find':False}, context_instance=RequestContext(req))
return render_to_response('ajax_brag.html', {'find':True, 'tuser':user}, context_instance=RequestContext(req))
def ajax_find_account(req, username):
cursor = connection.cursor()
cursor.execute("SELECT \
id, \
name, \
laptop AS platform, \
userid, \
acl, \
fans, \
points, \
avatarid \
FROM users \
WHERE LOWER(name) LIKE %s \
LIMIT 30", ['%'+username.lower()+'%'])
users = dict_cursor(cursor)
return render_to_response('ajax_find_account.html', {'find':True, 'users':users}, context_instance=RequestContext(req))
def ajax_brag(req, username):
cursor = connection.cursor()
cursor.execute("SELECT \
id, \
name, \
laptop AS platform, \
userid, \
acl, \
fans, \
points, \
avatarid \
FROM users \
WHERE name LIKE %s \
LIMIT 1", ['%'+username+'%'])
count = cursor.rowcount
if count == 1:
user = dict_cursor(cursor)[0]
cursor.execute("SELECT \
COUNT(*) AS rank \
FROM users AS u \
WHERE u.id NOT IN (11717, 139, 13248, 532, 580) AND u.points > %s", [user['points']])
rank_points = dict_cursor(cursor)[0]['rank']+1
cursor.execute("SELECT \
COUNT(*) AS rank \
FROM users AS u \
WHERE u.id NOT IN (6902) AND u.fans > %s", [user['fans']])
rank_fans = dict_cursor(cursor)[0]['rank']+1
user['rank_points'] = rank_points
user['rank_fans'] = rank_fans
else:
return render_to_response('ajax_brag.html', {'find':False}, context_instance=RequestContext(req))
return render_to_response('ajax_brag.html', {'find':True, 'tuser':user}, context_instance=RequestContext(req))
def chat(req, chatlog_id):
cursor = connection.cursor()
cursor.execute("SELECT \
cl.id, \
cl.room_id AS log_roomid, \
cl.created, \
cl.user_id, \
u.id AS user_id, \
u.avatarid AS user_avatar, \
u.name AS user_name, \
u.laptop AS user_laptop, \
u.points AS user_points, \
u.fans AS user_fans, \
r.roomid AS roomid, \
r.shortcut AS room_shortcut, \
r.name AS room_name \
FROM chat_log AS cl \
LEFT JOIN users AS u \
ON u.id = cl.user_id \
LEFT JOIN rooms AS r \
ON r.id = cl.room_id \
WHERE cl.id=%s \
LIMIT 1", [chatlog_id])
chatlog = dict_cursor(cursor)[0]
cursor.execute("SELECT \
cl.id, \
cl.name, \
cl.created, \
cl.room_id, \
cl.user_id, \
cl.text \
FROM chat_log AS cl \
WHERE cl.room_id=%s \
AND cl.created > %s - INTERVAL '5' MINUTE \
AND cl.created < %s + INTERVAL '5' MINUTE \
", [chatlog['log_roomid'], chatlog['created'], chatlog['created']])
history = dict_cursor(cursor)
return render_to_response('chat.html', {'chatlog':chatlog, 'history':history}, context_instance=RequestContext(req))
def thanks(req):
return render_to_response('thanks.html', {}, context_instance=RequestContext(req))
def comments_and_suggestions(req):
if req.method == 'POST': # If the form has been submitted...
form = ContactForm(req.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
message = str(req.POST['message']+' --> '+req.POST['sender'])
send_mail('FEEDBACK FROM TTDASHBOARD', message, str(req.POST['sender']), ['alain.gilbert.15@gmail.com'], fail_silently=False)
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
ctx = {}
ctx.update(csrf(req))
ctx.update({'form':form})
return render_to_response('comments.html', ctx, context_instance=RequestContext(req))
def users(req):
cursor = connection.cursor()
if not cache.get('users_ups'):
cursor.execute("SELECT \
SUM(sl.upvotes) AS upvotes, \
u.name, u.id, u.avatarid \
FROM users AS u \
LEFT JOIN song_log AS sl \
ON sl.dj = u.id \
WHERE \
sl.created > CURRENT_DATE - INTERVAL '1' DAY \
GROUP BY sl.dj, u.name, u.id, u.avatarid \
ORDER BY upvotes DESC \
LIMIT 10")
ups = dict_cursor(cursor)
cache.set('users_ups', ups, 60*15)
else:
ups = cache.get('users_ups')
if not cache.get('users_downs'):
cursor.execute("SELECT \
SUM(sl.downvotes) AS downvotes, \
u.name, u.id, u.avatarid \
FROM users AS u \
LEFT JOIN song_log AS sl \
ON sl.dj = u.id \
WHERE \
sl.created > CURRENT_DATE - INTERVAL '1' DAY \
GROUP BY sl.dj, u.name, u.id, u.avatarid \
ORDER BY downvotes DESC \
LIMIT 10")
downs = dict_cursor(cursor)
cache.set('users_downs', downs, 60*15)
else:
downs = cache.get('users_downs')
if not cache.get('users_combined'):
cursor.execute("SELECT \
SUM(sl.upvotes) - SUM(sl.downvotes) AS votes, \
u.name, u.id, u.avatarid \
FROM users AS u \
LEFT JOIN song_log AS sl \
ON sl.dj = u.id \
WHERE \
sl.created > CURRENT_DATE - INTERVAL '1' DAY \
GROUP BY sl.dj, u.name, u.id, u.avatarid \
ORDER BY votes DESC \
LIMIT 10")
combined = dict_cursor(cursor)
cache.set('users_combined', combined, 60*15)
else:
combined = cache.get('users_combined')
return render_to_response('users.html', {'onglet':'users', 'ups':ups, 'downs':downs, 'combined':combined}, context_instance=RequestContext(req))
def users_appreciated(req):
cursor = connection.cursor()
if not cache.get('users_appreciated'):
cursor.execute("SELECT * FROM users \
WHERE id NOT IN (11717, 139, 13248, 532, 580) \
ORDER BY points DESC LIMIT 100")
appreciated = dict_cursor(cursor)
cache.set('users_appreciated', appreciated, 60*15)
else:
appreciated = cache.get('users_appreciated')
return render_to_response('users_appreciated.html', {'onglet':'users', 'appreciated':appreciated}, context_instance=RequestContext(req))
def users_popular(req):
if not cache.get('users_popular'):
cursor = connection.cursor()
cursor.execute("SELECT * FROM users \
WHERE id NOT IN (6902) \
ORDER BY fans DESC LIMIT 100")
popular = dict_cursor(cursor)
cache.set('users_popular', popular, 60*15)
else:
popular = cache.get('users_popular')
return render_to_response('users_popular.html', {'onglet':'users', 'popular':popular}, context_instance=RequestContext(req))
def hackaround(req):
return render_to_response('hackaround.html', {})
def bookmarklet(req):
return render_to_response('bookmarklet.html', {}, context_instance=RequestContext(req))
def terms(req):
return render_to_response('terms.html', {}, context_instance=RequestContext(req))
def sidespeech(req):
return render_to_response('sidespeech.html', {}, context_instance=RequestContext(req))
def itunes(req, artist, song_name):
data = json.loads(urllib2.urlopen('http://itunes.apple.com/search?' + urllib.urlencode({'term':'%s %s' % (artist, song_name), 'entity':'song', 'limit':'25'})).read())
return render_to_response('itunes.html', {'data':data}, context_instance=RequestContext(req))
def search(req):
cursor = connection.cursor()
search = req.GET.get('search', None)
what = req.GET.get('what', None)
if search == None or what == None:
return render_to_response('search.html', {'results':[], 'what':what, 'search':search}, context_instance=RequestContext(req))
db_search = "%%%s%%" % search.lower()
if what == 'user':
db_select = "*"
db_from = "users"
db_where = ['name']
elif what == 'song':
db_select = "*"
db_from = "songs"
db_where = ['album', 'artist', 'song', 'genre']
elif what == 'chat':
db_select = "cl.id, cl.user_id, cl.room_id, cl.name, cl.text, cl.created, r.id AS room_id, r.name AS room_name, r.shortcut AS room_shortcut"
db_from = "chat_log AS cl LEFT JOIN rooms AS r ON r.id = cl.room_id"
db_where = ['text']
elif what == 'room':
db_select = "*"
db_from = "rooms"
db_where = ['name', 'description']
else:
return render_to_response('search.html', {'results':[], 'what':what, 'search':search}, context_instance=RequestContext(req))
# Generate sql where statement
if what == 'chat':
params = []
params.append(db_search)
db_where_gen = "text_tsv @@ to_tsquery(%s)"
else:
params = []
db_where_gen = ''
for w in db_where:
params.append(db_search)
db_where_gen += "LOWER(%s) LIKE %%s OR " % w
db_where_gen = db_where_gen[:-4]
# Our full querie
rq = "SELECT "+db_select+" FROM "+db_from+" WHERE "+db_where_gen
if what == 'chat':
rq += ' ORDER BY created DESC'
elif what == 'room':
rq += ' ORDER BY listeners DESC'
if req.is_ajax():
last = int(req.GET.get('last', 0))
rq += ' LIMIT 30 OFFSET %s' % last
else:
rq += ' LIMIT 30 OFFSET 0'
cursor.execute(rq, params)
results = dict_cursor(cursor)
for result in results:
for field in db_where:
result['%s_highlight' % field] = escape(result[field])
result['%s_highlight' % field] = re.sub(r"(?i)(%s)" % re.escape(search.lower()), lambda m: '<span class="highlight">%s</span>' % m.group(1), result['%s_highlight' % field], re.IGNORECASE)
content = {'results':results, 'what':what, 'search':search}
if req.is_ajax():
content.update({'last':last})
return render_to_response('ajax_search.html', content, context_instance=RequestContext(req))
else:
return render_to_response('search.html', content, context_instance=RequestContext(req))
def get_battle_infos():
cursor = connection.cursor()
roomid = '4e2a48c114169c27bb3e63cd'
content = {}
cursor.execute("SELECT r.id AS room_id, r.name AS room_name, \
r.description AS room_description, \
r.shortcut AS room_shortcut, \
r.listeners AS room_listeners, \
r.roomid AS roomid, \
r.downvotes, \
r.upvotes, \
r.current_dj AS current_dj_id, \
s.id AS song_id, \
s.nb_play AS room_nb_play, \
s.length AS song_length, \
s.song AS song_name, \
s.album AS song_album, \
s.artist AS song_artist, \
s.coverart AS song_coverart, \
u.name AS current_dj \
FROM rooms AS r \
LEFT JOIN songs AS s \
ON s.id = r.current_song \
LEFT JOIN users AS u \
ON u.id = r.current_dj \
WHERE r.roomid=%s \
LIMIT 1", [roomid])
room = dict_cursor(cursor)[0]
room['song_length'] = format_length(room['song_length'])
content.update({'room':room})
cursor.execute("SELECT s.coverart, \
s.id AS song_id, \
s.song, \
s.artist, \
sl.upvotes, sl.downvotes, \
sl.starttime, \
sl.current_dj AS current_dj_id, \
u.name AS current_dj \
FROM songlog AS sl \
LEFT JOIN songs AS s \
ON s.id = sl.songid \
LEFT JOIN users AS u \
ON u.id = sl.current_dj \
WHERE roomid=%s \
ORDER BY starttime DESC \
LIMIT 0, 20", [int(room['room_id'])])
songs_log = dict_cursor(cursor)
content.update({'songs_log':songs_log})
cursor.execute("SELECT \
u.name, \
u.id, \
u.laptop, \
u.fans, \
u.points, \
u.avatarid, \
SUM(sl.upvotes) AS dj_upvotes, \
SUM(sl.downvotes) AS dj_downvotes \
FROM users AS u \
LEFT JOIN songlog AS sl \
ON starttime BETWEEN '2011-07-29 05:20:00' AND '2011-07-29 08:00:00' AND sl.current_dj = u.id AND roomid = %s \
WHERE id IN (7, 5, 108434, 1011, 35232) \
GROUP BY u.id \
LIMIT 5 \
", [room['room_id']])
djs = dict_cursor(cursor)
for dj in djs:
dj['dj_upvotes'] = dj['dj_upvotes'] if dj['dj_upvotes'] else 0
dj['dj_downvotes'] = dj['dj_downvotes'] if dj['dj_downvotes'] else 0
content.update({'djs':djs})
return content
def ajax_battle(req):
if not req.is_ajax():
raise Http404
content = {}
if not cache.get('battle'):
battle_infos = get_battle_infos()
cache.set('battle', battle_infos, 10)
else:
battle_infos = cache.get('battle')
content.update(battle_infos)
return render_to_response('ajax_battle.html', content, context_instance=RequestContext(req))
def battle(req):
content = {}
if not cache.get('battle'):
battle_infos = get_battle_infos()
cache.set('battle', battle_infos, 10)
else:
battle_infos = cache.get('battle')
content.update(battle_infos)
return render_to_response('battle.html', content, context_instance=RequestContext(req))
| mit |
enchev-93/Telerik-Academy | 02.C Sharp part 2/06.StringAndTextProcessing/DatesFromTextInCanada/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("DatesFromTextInCanada")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DatesFromTextInCanada")]
[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("51e24c08-7a99-44d6-b0ed-6ed2b2e67eae")]
// 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 |
zinserjan/mocha-webpack | test/unit/cli/parseConfig.test.js | 1635 | /* eslint-env node, mocha */
/* eslint-disable func-names, prefer-arrow-callback */
import path from 'path';
import fs from 'fs-extra';
import { assert } from 'chai';
import parseConfig from '../../../src/cli/parseConfig';
const optsTestCasesPath = path.join(__dirname, 'fixture', 'config', 'optsTestCases');
const optsTestCases = fs.readdirSync(optsTestCasesPath);
describe('parseConfig', function () {
it('returns empty object when default config file is missing', function () {
assert.deepEqual(parseConfig(), {});
});
it('throws an error when explicitly-specified default config file is missing', function () {
const fn = () => {
parseConfig('mocha-webpack.opts');
};
// then
assert.throws(fn, /Options file 'mocha-webpack.opts' not found/);
});
it('throws an error when specified config file is missing', function () {
const fn = () => {
parseConfig('missing-config.opts');
};
// then
assert.throws(fn, /Options file 'missing-config.opts' not found/);
});
optsTestCases.forEach((testDirName) => {
const testDirPath = path.join(optsTestCasesPath, testDirName);
const optsFilePath = path.join(testDirPath, 'mocha-webpack.opts');
const expectedResultsPath = path.join(testDirPath, 'expected.json');
it(`parses '${testDirName}/mocha-webpack.opts' and returns options`, function () {
// eslint-disable-next-line global-require, import/no-dynamic-require
const expectedResult = require(expectedResultsPath);
const parsedOptions = parseConfig(optsFilePath);
assert.deepEqual(parsedOptions, expectedResult);
});
});
});
| mit |
levfurtado/scoops | cache/1c8f3cfcc366ccb235a2e5d8cdd607f2c51a6da5.file.footer.tpl.php | 5354 | <?php /* Smarty version Smarty-3.1.21, created on 2016-02-24 10:37:04
compiled from "/var/www/newscoop/themes/publication_1/theme_1/_tpl/footer.tpl" */ ?>
<?php /*%%SmartyHeaderCode:19707396156cdce203f5118-09030744%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'1c8f3cfcc366ccb235a2e5d8cdd607f2c51a6da5' =>
array (
0 => '/var/www/newscoop/themes/publication_1/theme_1/_tpl/footer.tpl',
1 => 1455831505,
2 => 'file',
),
),
'nocache_hash' => '19707396156cdce203f5118-09030744',
'function' =>
array (
),
'variables' =>
array (
'gimme' => 0,
),
'has_nocache_code' => false,
'version' => 'Smarty-3.1.21',
'unifunc' => 'content_56cdce204559a2_70529969',
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_56cdce204559a2_70529969')) {function content_56cdce204559a2_70529969($_smarty_tpl) {?><?php if (!is_callable('smarty_block_local')) include '/var/www/newscoop/application/../include/smarty/campsite_plugins/block.local.php';
if (!is_callable('smarty_function_set_current_issue')) include '/var/www/newscoop/application/../include/smarty/campsite_plugins/function.set_current_issue.php';
if (!is_callable('smarty_block_list_sections')) include '/var/www/newscoop/application/../include/smarty/campsite_plugins/block.list_sections.php';
if (!is_callable('smarty_function_url')) include '/var/www/newscoop/application/../include/smarty/campsite_plugins/function.url.php';
if (!is_callable('smarty_block_list_articles')) include '/var/www/newscoop/application/../include/smarty/campsite_plugins/block.list_articles.php';
?><footer class="footer-alpha clearfix" role="contentinfo">
<div class="footer-main">
<div>
<h4><?php echo $_smarty_tpl->getConfigVariable('sections');?>
</h4>
<ul>
<?php $_smarty_tpl->smarty->_tag_stack[] = array('local', array()); $_block_repeat=true; echo smarty_block_local(array(), null, $_smarty_tpl, $_block_repeat);while ($_block_repeat) { ob_start();?>
<?php echo smarty_function_set_current_issue(array(),$_smarty_tpl);?>
<?php $_smarty_tpl->smarty->_tag_stack[] = array('list_sections', array()); $_block_repeat=true; echo smarty_block_list_sections(array(), null, $_smarty_tpl, $_block_repeat);while ($_block_repeat) { ob_start();?>
<li><a href="<?php echo smarty_function_url(array('options'=>'section'),$_smarty_tpl);?>
" title="<?php echo $_smarty_tpl->tpl_vars['gimme']->value->section->name;?>
"> <?php echo $_smarty_tpl->tpl_vars['gimme']->value->section->name;?>
</a></li>
<?php $_block_content = ob_get_clean(); $_block_repeat=false; echo smarty_block_list_sections(array(), $_block_content, $_smarty_tpl, $_block_repeat); } array_pop($_smarty_tpl->smarty->_tag_stack);?>
<?php $_block_content = ob_get_clean(); $_block_repeat=false; echo smarty_block_local(array(), $_block_content, $_smarty_tpl, $_block_repeat); } array_pop($_smarty_tpl->smarty->_tag_stack);?>
</ul>
</div>
<div>
<h4><?php echo $_smarty_tpl->getConfigVariable('moreLinks');?>
</h4>
<ul>
<?php $_smarty_tpl->smarty->_tag_stack[] = array('list_articles', array('ignore_issue'=>"true",'ignore_section'=>"true",'constraints'=>"type is page")); $_block_repeat=true; echo smarty_block_list_articles(array('ignore_issue'=>"true",'ignore_section'=>"true",'constraints'=>"type is page"), null, $_smarty_tpl, $_block_repeat);while ($_block_repeat) { ob_start();?>
<li><a href="<?php echo smarty_function_url(array('options'=>"article"),$_smarty_tpl);?>
"><?php echo $_smarty_tpl->tpl_vars['gimme']->value->article->name;?>
</a></li>
<?php $_block_content = ob_get_clean(); $_block_repeat=false; echo smarty_block_list_articles(array('ignore_issue'=>"true",'ignore_section'=>"true",'constraints'=>"type is page"), $_block_content, $_smarty_tpl, $_block_repeat); } array_pop($_smarty_tpl->smarty->_tag_stack);?>
<li><a title="<?php echo $_smarty_tpl->getConfigVariable('opensNewWindow');?>
" target="_blank" href="http://twitter.com/sourcefabric "><span aria-hidden="true" class="icon-twitter"></span> Twitter</a></li>
<li><a title="<?php echo $_smarty_tpl->getConfigVariable('opensNewWindow');?>
" target="_blank" href="http://facebook.com/sourcefabric "><span aria-hidden="true" class="icon-facebook"></span> Facebook</a></li>
<li><a title="<?php echo $_smarty_tpl->getConfigVariable('opensNewWindow');?>
" target="_blank" href="/en/static/rss"><span aria-hidden="true" class="icon-feed"></span> RSS</a></li>
<li><a href="/?tpl=6"><span aria-hidden="true" class="icon-list"></span> <?php echo $_smarty_tpl->getConfigVariable('archive');?>
</a></li>
</ul>
</div>
<div>
<h4><?php echo $_smarty_tpl->getConfigVariable('aboutUs');?>
</h4>
<p>squad squad</p>
</div>
<div class="copyright">
<p>SquAAAAAAAAD </p>
<p>Newscoop Tommy Theme</p>
</div>
<a class="link-to-top" href="#top"><?php echo $_smarty_tpl->getConfigVariable('backToTop');?>
</a>
</div>
</footer>
<?php }} ?>
| mit |
AgostonSzepessy/battle-of-oxshan | BlueThing.cpp | 2551 | #include "BlueThing.hpp"
BlueThing::BlueThing(int x, int y)
{
this->x = x;
this->y = y;
dx = 0;
dy = 0;
speed = 3;
height = 52;
width = 52;
currentAnimation = STANDING;
health = maxHealth;
damage = 5;
delay = 400;
reloading = false;
startReload = false;
reloadAccumulator = 1000;
if (!texture->loadFromFile("res/sprites/enemy/bluething-spritesheet.png"))
{
std::cout << "not able to load BlueThing texture" << std::endl;
}
sprite->setTexture(*texture);
for (int i = 0; i < 10; ++i)
{
dying->addFrame(sf::IntRect(i * 52, 52, 52, 52));
}
dying->setDelay(10 / 100);
standing->addFrame(sf::IntRect(0, 0, 52, 52));
sprite->setFrames(*standing);
sprite->setOrigin(sprite->getGlobalBounds().width / 2, sprite->getGlobalBounds().height / 2);
healthBar->update(x - sprite->getGlobalBounds().width / 2, y - sprite->getGlobalBounds().height);
}
void BlueThing::update(const Entity &e, const BoundingBox &box)
{
if (dead)
return;
sprite->update();
if (isDying)
{
// if the animation isn't dying, set it to dying
if (currentAnimation != DYING)
{
currentAnimation = DYING;
sprite->setFrames(*dying);
// don't let player move
dx = 0;
dy = 0;
}
// if death animation has played, signal that player is dead
if (sprite->hasPlayedOnce() && currentAnimation == DYING && health == 0)
{
dead = true;
}
// don't let other animations play
return;
}
if (numTimesFired > 5)
{
reloading = true;
startReload = true;
numTimesFired = 0;
}
moveTowardsPlayer(e);
checkBrickCollision(box);
checkBounds();
// set x and y equal to the new values
x = tempx + dx;
y = tempy + dy;
setPosition(x, y);
healthBar->update(x - sprite->getGlobalBounds().width / 2, y - sprite->getGlobalBounds().height / 2);
}
void BlueThing::draw(sf::RenderWindow *window)
{
window->draw(*sprite);
healthBar->draw(window);
}
bool BlueThing::isReloading()
{
static int reloadTime = 600;
static int reloadCurrentTime;
static int reloadPrevTime = c->getElapsedTime().asMilliseconds();
if (startReload)
{
reloadAccumulator = 0;
startReload = false;
}
reloadCurrentTime = c->getElapsedTime().asMicroseconds() / 1000;
reloadAccumulator += reloadCurrentTime - reloadPrevTime;
reloadPrevTime = reloadCurrentTime;
if (reloadAccumulator < reloadTime)
{
if (reloading)
{
reloading = false;
return true;
}
}
return false;
}
std::unique_ptr<BlueThing> BlueThing::create(int x, int y)
{
std::unique_ptr<BlueThing> b(new BlueThing(x, y));
return b;
}
BlueThing::~BlueThing()
{
}
| mit |
arapaka/algorithms-datastructures | algorithms/src/main/java/datastrutures/strings/PrintListOfItemsContainingAllChars.java | 1487 | package datastrutures.strings;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by archithrapaka on 3/5/17.
*/
public class PrintListOfItemsContainingAllChars {
static void printList(String pattern, ArrayList<String> dict) {
// for each sorted string in the list check if the pattern and the word match
for (String word : dict) {
int[] charcount = StringUtils.getCharCount(pattern);
if (matchChars(word, charcount, pattern.length())) {
System.out.print(word + " ");
}
}
}
private static boolean matchChars(String word, int[] charcount, int patternLength) {
int length = 0;
for (int i = 0; i < word.length(); i++) {
if (length == patternLength) {
return true;
}
char c = word.charAt(i);
if (charcount[c] <= 0) {
continue;
}
length++;
charcount[c]--;
}
return false;
}
public static void main(String[] args) {
String s = "suns";
String[] words = new String[]{"sunday", "utensil", "sansui", "samsung"};
ArrayList<String> dict = new ArrayList<>(Arrays.asList(words));
//printList(s,dict);
String s2 = "geeks quiz practice code";
String s3 = "getting good at coding needs a lot of practice";
System.out.print(StringUtils.reverseWords(s3));
}
}
| mit |
Babarix/RSI-Crawler | RSI Crawler/Program.cs | 484 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace RSI_Crawler
{
static class Program
{
/// <summary>
/// Der Haupteinstiegspunkt für die Anwendung.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| mit |
ellipse-js/ellipse | lib/context.js | 3451 | 'use strict'
// expose
module.exports = Context
// includes
const Cookies = require('cookies'),
httpError = require('http-errors'),
httpAssert = require('http-assert'),
alias = require('./utils/alias')
// constructor
function Context(req, res) {
this._req = req
this._res = res
req._ctx =
res._ctx = this
}
// instance members
Context.prototype = {
respond: false,
get res() {
return this._res
},
get response() {
return this._res
},
get req() {
return this._req
},
get request() {
return this._req
},
get cookies() {
if (this._cookies)
return this._cookies
else
return this._cookies = new Cookies(this._req, this._res, this.app.keys)
},
get state() {
return this._state || (this._state = {})
},
set state(value) {
this._state = value
},
get type() {
return this._res.get('content-type') || 'text/html; charset=utf-8'
},
set type(value) {
this._res.type(value)
},
get body () {
return this._res._body
},
set body(value) {
this._res._body = value
},
get text() {
return this._res._body || (this.text = '')
},
set text(value) {
this._res.type('text/plain')
this._res._body = value
},
get html() {
return this._res._body || (this.html = '')
},
set html(value) {
this._res.type('text/html')
this._res._body = value
},
get json() {
return this._res._body || (this.json = {})
},
set json(value) {
this._res.type('application/json')
this._res._body = value
},
assert: function () {
httpAssert.apply(this, arguments)
return this // allow chaining
},
throw: function () {
throw httpError.apply(this, arguments)
},
'catch': function (err) {
this.router.onerror(this, err)
return this // allow chaining
},
toJSON: function toJSON() {
return {
request: this._req.toJSON(),
response: this._res.toJSON(),
app: this.app.toJSON(),
originalUrl: this.originalUrl
}
},
inspect: function inspect() {
return this.toJSON()
}
}
// aliases
const descriptor = {}
// request
alias('_req', descriptor)
('headers')
('header', 'headers')
('method', true)
('url', true)
('originalUrl')
('href')
('ip')
('ips')
('path', true)
('query', true)
('querystring', true)
('search', true)
('params')
('param', 'params')
('host')
('hostname')
('fresh')
('stale')
('xhr')
('socket')
('protocol')
('secure')
('subdomains')
('get')
('accept')
('accepts')
('acceptsEncodings')
('acceptsEncoding', 'acceptsEncodings')
('acceptsCharsets')
('acceptsCharset', 'acceptsCharsets')
('acceptsLanguages')
('acceptsLanguage', 'acceptsLanguages')
('is')
('typeIs', 'is')
// response
alias('_res', descriptor)
('next')
('app')
('application')
('append')
('router')
('statusCode', true)
('status', 'statusCode', true)
('message', true)
('length', true)
('headersSent')
('headerSent', 'headersSent')
('finished')
('redirect')
('set')
('remove')
('lastModified', true)
('etag', true)
('ETag', 'etag', true)
('attachment')
('download')
('sendFile')
('send')
// extend Context proto
Object.defineProperties(Context.prototype, descriptor)
| mit |
dukegod/node-basic | demos/libs/node-version.js | 310 | /**
* Created by hui on 16/12/18.
*/
// module.exports = function(){
// var obj = this;
// console.log(this);
// console.log(obj.process.versions);
// }()
module.exports = (() => {
// let obj = e;
// console.log(obj);
// console.log(obj.process.versions);
console.log(process.versions);
})()
| mit |
Programming-Systems-Lab/knarr | Phosphor/src/edu/columbia/cs/psl/phosphor/org/objectweb/asm/util/Textifier.java | 48837 | /***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2011 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of the copyright holders 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.
*/
package edu.columbia.cs.psl.phosphor.org.objectweb.asm.util;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import edu.columbia.cs.psl.phosphor.org.objectweb.asm.Attribute;
import edu.columbia.cs.psl.phosphor.org.objectweb.asm.ClassReader;
import edu.columbia.cs.psl.phosphor.org.objectweb.asm.Handle;
import edu.columbia.cs.psl.phosphor.org.objectweb.asm.Label;
import edu.columbia.cs.psl.phosphor.org.objectweb.asm.Opcodes;
import edu.columbia.cs.psl.phosphor.org.objectweb.asm.Type;
import edu.columbia.cs.psl.phosphor.org.objectweb.asm.TypePath;
import edu.columbia.cs.psl.phosphor.org.objectweb.asm.TypeReference;
import edu.columbia.cs.psl.phosphor.org.objectweb.asm.signature.SignatureReader;
/**
* A {@link Printer} that prints a disassembled view of the classes it visits.
*
* @author Eric Bruneton
*/
public class Textifier extends Printer {
/**
* Constant used in {@link #appendDescriptor appendDescriptor} for internal
* type names in bytecode notation.
*/
public static final int INTERNAL_NAME = 0;
/**
* Constant used in {@link #appendDescriptor appendDescriptor} for field
* descriptors, formatted in bytecode notation
*/
public static final int FIELD_DESCRIPTOR = 1;
/**
* Constant used in {@link #appendDescriptor appendDescriptor} for field
* signatures, formatted in bytecode notation
*/
public static final int FIELD_SIGNATURE = 2;
/**
* Constant used in {@link #appendDescriptor appendDescriptor} for method
* descriptors, formatted in bytecode notation
*/
public static final int METHOD_DESCRIPTOR = 3;
/**
* Constant used in {@link #appendDescriptor appendDescriptor} for method
* signatures, formatted in bytecode notation
*/
public static final int METHOD_SIGNATURE = 4;
/**
* Constant used in {@link #appendDescriptor appendDescriptor} for class
* signatures, formatted in bytecode notation
*/
public static final int CLASS_SIGNATURE = 5;
/**
* Constant used in {@link #appendDescriptor appendDescriptor} for field or
* method return value signatures, formatted in default Java notation
* (non-bytecode)
*/
public static final int TYPE_DECLARATION = 6;
/**
* Constant used in {@link #appendDescriptor appendDescriptor} for class
* signatures, formatted in default Java notation (non-bytecode)
*/
public static final int CLASS_DECLARATION = 7;
/**
* Constant used in {@link #appendDescriptor appendDescriptor} for method
* parameter signatures, formatted in default Java notation (non-bytecode)
*/
public static final int PARAMETERS_DECLARATION = 8;
/**
* Constant used in {@link #appendDescriptor appendDescriptor} for handle
* descriptors, formatted in bytecode notation
*/
public static final int HANDLE_DESCRIPTOR = 9;
/**
* Tab for class members.
*/
protected String tab = " ";
/**
* Tab for bytecode instructions.
*/
protected String tab2 = " ";
/**
* Tab for table and lookup switch instructions.
*/
protected String tab3 = " ";
/**
* Tab for labels.
*/
protected String ltab = " ";
/**
* The label names. This map associate String values to Label keys.
*/
protected Map<Label, String> labelNames;
/**
* Class access flags
*/
private int access;
private int valueNumber = 0;
/**
* Constructs a new {@link Textifier}. <i>Subclasses must not use this
* constructor</i>. Instead, they must use the {@link #Textifier(int)}
* version.
*
* @throws IllegalStateException
* If a subclass calls this constructor.
*/
public Textifier() {
this(Opcodes.ASM5);
if (getClass() != Textifier.class) {
throw new IllegalStateException();
}
}
/**
* Constructs a new {@link Textifier}.
*
* @param api
* the ASM API version implemented by this visitor. Must be one
* of {@link Opcodes#ASM4} or {@link Opcodes#ASM5}.
*/
protected Textifier(final int api) {
super(api);
}
/**
* Prints a disassembled view of the given class to the standard output.
* <p>
* Usage: Textifier [-debug] <binary class name or class file name >
*
* @param args
* the command line arguments.
*
* @throws Exception
* if the class cannot be found, or if an IO exception occurs.
*/
public static void main(final String[] args) throws Exception {
int i = 0;
int flags = ClassReader.SKIP_DEBUG;
boolean ok = true;
if (args.length < 1 || args.length > 2) {
ok = false;
}
if (ok && "-debug".equals(args[0])) {
i = 1;
flags = 0;
if (args.length != 2) {
ok = false;
}
}
if (!ok) {
System.err
.println("Prints a disassembled view of the given class.");
System.err.println("Usage: Textifier [-debug] "
+ "<fully qualified class name or class file name>");
return;
}
ClassReader cr;
if (args[i].endsWith(".class") || args[i].indexOf('\\') > -1
|| args[i].indexOf('/') > -1) {
cr = new ClassReader(new FileInputStream(args[i]));
} else {
cr = new ClassReader(args[i]);
}
cr.accept(new TraceClassVisitor(new PrintWriter(System.out)), flags);
}
// ------------------------------------------------------------------------
// Classes
// ------------------------------------------------------------------------
@Override
public void visit(final int version, final int access, final String name,
final String signature, final String superName,
final String[] interfaces) {
this.access = access;
int major = version & 0xFFFF;
int minor = version >>> 16;
buf.setLength(0);
buf.append("// class version ").append(major).append('.').append(minor)
.append(" (").append(version).append(")\n");
if ((access & Opcodes.ACC_DEPRECATED) != 0) {
buf.append("// DEPRECATED\n");
}
buf.append("// access flags 0x")
.append(Integer.toHexString(access).toUpperCase()).append('\n');
appendDescriptor(CLASS_SIGNATURE, signature);
if (signature != null) {
TraceSignatureVisitor sv = new TraceSignatureVisitor(access);
SignatureReader r = new SignatureReader(signature);
r.accept(sv);
buf.append("// declaration: ").append(name)
.append(sv.getDeclaration()).append('\n');
}
appendAccess(access & ~Opcodes.ACC_SUPER);
if ((access & Opcodes.ACC_ANNOTATION) != 0) {
buf.append("@interface ");
} else if ((access & Opcodes.ACC_INTERFACE) != 0) {
buf.append("interface ");
} else if ((access & Opcodes.ACC_ENUM) == 0) {
buf.append("class ");
}
appendDescriptor(INTERNAL_NAME, name);
if (superName != null && !"java/lang/Object".equals(superName)) {
buf.append(" extends ");
appendDescriptor(INTERNAL_NAME, superName);
buf.append(' ');
}
if (interfaces != null && interfaces.length > 0) {
buf.append(" implements ");
for (int i = 0; i < interfaces.length; ++i) {
appendDescriptor(INTERNAL_NAME, interfaces[i]);
buf.append(' ');
}
}
buf.append(" {\n\n");
text.add(buf.toString());
}
@Override
public void visitSource(final String file, final String debug) {
buf.setLength(0);
if (file != null) {
buf.append(tab).append("// compiled from: ").append(file)
.append('\n');
}
if (debug != null) {
buf.append(tab).append("// debug info: ").append(debug)
.append('\n');
}
if (buf.length() > 0) {
text.add(buf.toString());
}
}
@Override
public void visitOuterClass(final String owner, final String name,
final String desc) {
buf.setLength(0);
buf.append(tab).append("OUTERCLASS ");
appendDescriptor(INTERNAL_NAME, owner);
buf.append(' ');
if (name != null) {
buf.append(name).append(' ');
}
appendDescriptor(METHOD_DESCRIPTOR, desc);
buf.append('\n');
text.add(buf.toString());
}
@Override
public Textifier visitClassAnnotation(final String desc,
final boolean visible) {
text.add("\n");
return visitAnnotation(desc, visible);
}
@Override
public Printer visitClassTypeAnnotation(int typeRef, TypePath typePath,
String desc, boolean visible) {
text.add("\n");
return visitTypeAnnotation(typeRef, typePath, desc, visible);
}
@Override
public void visitClassAttribute(final Attribute attr) {
text.add("\n");
visitAttribute(attr);
}
@Override
public void visitInnerClass(final String name, final String outerName,
final String innerName, final int access) {
buf.setLength(0);
buf.append(tab).append("// access flags 0x");
buf.append(
Integer.toHexString(access & ~Opcodes.ACC_SUPER).toUpperCase())
.append('\n');
buf.append(tab);
appendAccess(access);
buf.append("INNERCLASS ");
appendDescriptor(INTERNAL_NAME, name);
buf.append(' ');
appendDescriptor(INTERNAL_NAME, outerName);
buf.append(' ');
appendDescriptor(INTERNAL_NAME, innerName);
buf.append('\n');
text.add(buf.toString());
}
@Override
public Textifier visitField(final int access, final String name,
final String desc, final String signature, final Object value) {
buf.setLength(0);
buf.append('\n');
if ((access & Opcodes.ACC_DEPRECATED) != 0) {
buf.append(tab).append("// DEPRECATED\n");
}
buf.append(tab).append("// access flags 0x")
.append(Integer.toHexString(access).toUpperCase()).append('\n');
if (signature != null) {
buf.append(tab);
appendDescriptor(FIELD_SIGNATURE, signature);
TraceSignatureVisitor sv = new TraceSignatureVisitor(0);
SignatureReader r = new SignatureReader(signature);
r.acceptType(sv);
buf.append(tab).append("// declaration: ")
.append(sv.getDeclaration()).append('\n');
}
buf.append(tab);
appendAccess(access);
appendDescriptor(FIELD_DESCRIPTOR, desc);
buf.append(' ').append(name);
if (value != null) {
buf.append(" = ");
if (value instanceof String) {
buf.append('\"').append(value).append('\"');
} else {
buf.append(value);
}
}
buf.append('\n');
text.add(buf.toString());
Textifier t = createTextifier();
text.add(t.getText());
return t;
}
@Override
public Textifier visitMethod(final int access, final String name,
final String desc, final String signature, final String[] exceptions) {
buf.setLength(0);
buf.append('\n');
if ((access & Opcodes.ACC_DEPRECATED) != 0) {
buf.append(tab).append("// DEPRECATED\n");
}
buf.append(tab).append("// access flags 0x")
.append(Integer.toHexString(access).toUpperCase()).append('\n');
if (signature != null) {
buf.append(tab);
appendDescriptor(METHOD_SIGNATURE, signature);
TraceSignatureVisitor v = new TraceSignatureVisitor(0);
SignatureReader r = new SignatureReader(signature);
r.accept(v);
String genericDecl = v.getDeclaration();
String genericReturn = v.getReturnType();
String genericExceptions = v.getExceptions();
buf.append(tab).append("// declaration: ").append(genericReturn)
.append(' ').append(name).append(genericDecl);
if (genericExceptions != null) {
buf.append(" throws ").append(genericExceptions);
}
buf.append('\n');
}
buf.append(tab);
appendAccess(access & ~Opcodes.ACC_VOLATILE);
if ((access & Opcodes.ACC_NATIVE) != 0) {
buf.append("native ");
}
if ((access & Opcodes.ACC_VARARGS) != 0) {
buf.append("varargs ");
}
if ((access & Opcodes.ACC_BRIDGE) != 0) {
buf.append("bridge ");
}
if ((this.access & Opcodes.ACC_INTERFACE) != 0
&& (access & Opcodes.ACC_ABSTRACT) == 0
&& (access & Opcodes.ACC_STATIC) == 0) {
buf.append("default ");
}
buf.append(name);
appendDescriptor(METHOD_DESCRIPTOR, desc);
if (exceptions != null && exceptions.length > 0) {
buf.append(" throws ");
for (int i = 0; i < exceptions.length; ++i) {
appendDescriptor(INTERNAL_NAME, exceptions[i]);
buf.append(' ');
}
}
buf.append('\n');
text.add(buf.toString());
Textifier t = createTextifier();
text.add(t.getText());
return t;
}
@Override
public void visitClassEnd() {
text.add("}\n");
}
// ------------------------------------------------------------------------
// Annotations
// ------------------------------------------------------------------------
@Override
public void visit(final String name, final Object value) {
buf.setLength(0);
appendComa(valueNumber++);
if (name != null) {
buf.append(name).append('=');
}
if (value instanceof String) {
visitString((String) value);
} else if (value instanceof Type) {
visitType((Type) value);
} else if (value instanceof Byte) {
visitByte(((Byte) value).byteValue());
} else if (value instanceof Boolean) {
visitBoolean(((Boolean) value).booleanValue());
} else if (value instanceof Short) {
visitShort(((Short) value).shortValue());
} else if (value instanceof Character) {
visitChar(((Character) value).charValue());
} else if (value instanceof Integer) {
visitInt(((Integer) value).intValue());
} else if (value instanceof Float) {
visitFloat(((Float) value).floatValue());
} else if (value instanceof Long) {
visitLong(((Long) value).longValue());
} else if (value instanceof Double) {
visitDouble(((Double) value).doubleValue());
} else if (value.getClass().isArray()) {
buf.append('{');
if (value instanceof byte[]) {
byte[] v = (byte[]) value;
for (int i = 0; i < v.length; i++) {
appendComa(i);
visitByte(v[i]);
}
} else if (value instanceof boolean[]) {
boolean[] v = (boolean[]) value;
for (int i = 0; i < v.length; i++) {
appendComa(i);
visitBoolean(v[i]);
}
} else if (value instanceof short[]) {
short[] v = (short[]) value;
for (int i = 0; i < v.length; i++) {
appendComa(i);
visitShort(v[i]);
}
} else if (value instanceof char[]) {
char[] v = (char[]) value;
for (int i = 0; i < v.length; i++) {
appendComa(i);
visitChar(v[i]);
}
} else if (value instanceof int[]) {
int[] v = (int[]) value;
for (int i = 0; i < v.length; i++) {
appendComa(i);
visitInt(v[i]);
}
} else if (value instanceof long[]) {
long[] v = (long[]) value;
for (int i = 0; i < v.length; i++) {
appendComa(i);
visitLong(v[i]);
}
} else if (value instanceof float[]) {
float[] v = (float[]) value;
for (int i = 0; i < v.length; i++) {
appendComa(i);
visitFloat(v[i]);
}
} else if (value instanceof double[]) {
double[] v = (double[]) value;
for (int i = 0; i < v.length; i++) {
appendComa(i);
visitDouble(v[i]);
}
}
buf.append('}');
}
text.add(buf.toString());
}
private void visitInt(final int value) {
buf.append(value);
}
private void visitLong(final long value) {
buf.append(value).append('L');
}
private void visitFloat(final float value) {
buf.append(value).append('F');
}
private void visitDouble(final double value) {
buf.append(value).append('D');
}
private void visitChar(final char value) {
buf.append("(char)").append((int) value);
}
private void visitShort(final short value) {
buf.append("(short)").append(value);
}
private void visitByte(final byte value) {
buf.append("(byte)").append(value);
}
private void visitBoolean(final boolean value) {
buf.append(value);
}
private void visitString(final String value) {
appendString(buf, value);
}
private void visitType(final Type value) {
buf.append(value.getClassName()).append(".class");
}
@Override
public void visitEnum(final String name, final String desc,
final String value) {
buf.setLength(0);
appendComa(valueNumber++);
if (name != null) {
buf.append(name).append('=');
}
appendDescriptor(FIELD_DESCRIPTOR, desc);
buf.append('.').append(value);
text.add(buf.toString());
}
@Override
public Textifier visitAnnotation(final String name, final String desc) {
buf.setLength(0);
appendComa(valueNumber++);
if (name != null) {
buf.append(name).append('=');
}
buf.append('@');
appendDescriptor(FIELD_DESCRIPTOR, desc);
buf.append('(');
text.add(buf.toString());
Textifier t = createTextifier();
text.add(t.getText());
text.add(")");
return t;
}
@Override
public Textifier visitArray(final String name) {
buf.setLength(0);
appendComa(valueNumber++);
if (name != null) {
buf.append(name).append('=');
}
buf.append('{');
text.add(buf.toString());
Textifier t = createTextifier();
text.add(t.getText());
text.add("}");
return t;
}
@Override
public void visitAnnotationEnd() {
}
// ------------------------------------------------------------------------
// Fields
// ------------------------------------------------------------------------
@Override
public Textifier visitFieldAnnotation(final String desc,
final boolean visible) {
return visitAnnotation(desc, visible);
}
@Override
public Printer visitFieldTypeAnnotation(int typeRef, TypePath typePath,
String desc, boolean visible) {
return visitTypeAnnotation(typeRef, typePath, desc, visible);
}
@Override
public void visitFieldAttribute(final Attribute attr) {
visitAttribute(attr);
}
@Override
public void visitFieldEnd() {
}
// ------------------------------------------------------------------------
// Methods
// ------------------------------------------------------------------------
@Override
public void visitParameter(final String name, final int access) {
buf.setLength(0);
buf.append(tab2).append("// parameter ");
appendAccess(access);
buf.append(' ').append((name == null) ? "<no name>" : name)
.append('\n');
text.add(buf.toString());
}
@Override
public Textifier visitAnnotationDefault() {
text.add(tab2 + "default=");
Textifier t = createTextifier();
text.add(t.getText());
text.add("\n");
return t;
}
@Override
public Textifier visitMethodAnnotation(final String desc,
final boolean visible) {
return visitAnnotation(desc, visible);
}
@Override
public Printer visitMethodTypeAnnotation(int typeRef, TypePath typePath,
String desc, boolean visible) {
return visitTypeAnnotation(typeRef, typePath, desc, visible);
}
@Override
public Textifier visitParameterAnnotation(final int parameter,
final String desc, final boolean visible) {
buf.setLength(0);
buf.append(tab2).append('@');
appendDescriptor(FIELD_DESCRIPTOR, desc);
buf.append('(');
text.add(buf.toString());
Textifier t = createTextifier();
text.add(t.getText());
text.add(visible ? ") // parameter " : ") // invisible, parameter ");
text.add(new Integer(parameter));
text.add("\n");
return t;
}
@Override
public void visitMethodAttribute(final Attribute attr) {
buf.setLength(0);
buf.append(tab).append("ATTRIBUTE ");
appendDescriptor(-1, attr.type);
if (attr instanceof Textifiable) {
((Textifiable) attr).textify(buf, labelNames);
} else {
buf.append(" : unknown\n");
}
text.add(buf.toString());
}
@Override
public void visitCode() {
}
@Override
public void visitFrame(final int type, final int nLocal,
final Object[] local, final int nStack, final Object[] stack) {
buf.setLength(0);
buf.append(ltab);
buf.append("FRAME ");
switch (type) {
case Opcodes.F_NEW:
case Opcodes.F_FULL:
buf.append("FULL [");
appendFrameTypes(nLocal, local);
buf.append("] [");
appendFrameTypes(nStack, stack);
buf.append(']');
break;
case Opcodes.F_APPEND:
buf.append("APPEND [");
appendFrameTypes(nLocal, local);
buf.append(']');
break;
case Opcodes.F_CHOP:
buf.append("CHOP ").append(nLocal);
break;
case Opcodes.F_SAME:
buf.append("SAME");
break;
case Opcodes.F_SAME1:
buf.append("SAME1 ");
appendFrameTypes(1, stack);
break;
}
buf.append('\n');
text.add(buf.toString());
}
@Override
public void visitInsn(final int opcode) {
buf.setLength(0);
buf.append(tab2).append(OPCODES[opcode]).append('\n');
text.add(buf.toString());
}
@Override
public void visitIntInsn(final int opcode, final int operand) {
buf.setLength(0);
buf.append(tab2)
.append(OPCODES[opcode])
.append(' ')
.append(opcode == Opcodes.NEWARRAY ? TYPES[operand] : Integer
.toString(operand)).append('\n');
text.add(buf.toString());
}
@Override
public void visitVarInsn(final int opcode, final int var) {
buf.setLength(0);
buf.append(tab2).append(OPCODES[opcode]).append(' ').append(var)
.append('\n');
text.add(buf.toString());
}
@Override
public void visitTypeInsn(final int opcode, final String type) {
buf.setLength(0);
buf.append(tab2).append(OPCODES[opcode]).append(' ');
appendDescriptor(INTERNAL_NAME, type);
buf.append('\n');
text.add(buf.toString());
}
@Override
public void visitFieldInsn(final int opcode, final String owner,
final String name, final String desc) {
buf.setLength(0);
buf.append(tab2).append(OPCODES[opcode]).append(' ');
appendDescriptor(INTERNAL_NAME, owner);
buf.append('.').append(name).append(" : ");
appendDescriptor(FIELD_DESCRIPTOR, desc);
buf.append('\n');
text.add(buf.toString());
}
@Deprecated
@Override
public void visitMethodInsn(final int opcode, final String owner,
final String name, final String desc) {
if (api >= Opcodes.ASM5) {
super.visitMethodInsn(opcode, owner, name, desc);
return;
}
doVisitMethodInsn(opcode, owner, name, desc,
opcode == Opcodes.INVOKEINTERFACE);
}
@Override
public void visitMethodInsn(final int opcode, final String owner,
final String name, final String desc, final boolean itf) {
if (api < Opcodes.ASM5) {
super.visitMethodInsn(opcode, owner, name, desc, itf);
return;
}
doVisitMethodInsn(opcode, owner, name, desc, itf);
}
private void doVisitMethodInsn(final int opcode, final String owner,
final String name, final String desc, final boolean itf) {
buf.setLength(0);
buf.append(tab2).append(OPCODES[opcode]).append(' ');
appendDescriptor(INTERNAL_NAME, owner);
buf.append('.').append(name).append(' ');
appendDescriptor(METHOD_DESCRIPTOR, desc);
buf.append('\n');
text.add(buf.toString());
}
@Override
public void visitInvokeDynamicInsn(String name, String desc, Handle bsm,
Object... bsmArgs) {
buf.setLength(0);
buf.append(tab2).append("INVOKEDYNAMIC").append(' ');
buf.append(name);
appendDescriptor(METHOD_DESCRIPTOR, desc);
buf.append(" [");
buf.append('\n');
buf.append(tab3);
appendHandle(bsm);
buf.append('\n');
buf.append(tab3).append("// arguments:");
if (bsmArgs.length == 0) {
buf.append(" none");
} else {
buf.append('\n');
for (int i = 0; i < bsmArgs.length; i++) {
buf.append(tab3);
Object cst = bsmArgs[i];
if (cst instanceof String) {
Printer.appendString(buf, (String) cst);
} else if (cst instanceof Type) {
Type type = (Type) cst;
if(type.getSort() == Type.METHOD){
appendDescriptor(METHOD_DESCRIPTOR, type.getDescriptor());
} else {
buf.append(type.getDescriptor()).append(".class");
}
} else if (cst instanceof Handle) {
appendHandle((Handle) cst);
} else {
buf.append(cst);
}
buf.append(", \n");
}
buf.setLength(buf.length() - 3);
}
buf.append('\n');
buf.append(tab2).append("]\n");
text.add(buf.toString());
}
@Override
public void visitJumpInsn(final int opcode, final Label label) {
buf.setLength(0);
buf.append(tab2).append(OPCODES[opcode]).append(' ');
appendLabel(label);
buf.append('\n');
text.add(buf.toString());
}
@Override
public void visitLabel(final Label label) {
buf.setLength(0);
buf.append(ltab);
appendLabel(label);
buf.append('\n');
text.add(buf.toString());
}
@Override
public void visitLdcInsn(final Object cst) {
buf.setLength(0);
buf.append(tab2).append("LDC ");
if (cst instanceof String) {
Printer.appendString(buf, (String) cst);
} else if (cst instanceof Type) {
buf.append(((Type) cst).getDescriptor()).append(".class");
} else {
buf.append(cst);
}
buf.append('\n');
text.add(buf.toString());
}
@Override
public void visitIincInsn(final int var, final int increment) {
buf.setLength(0);
buf.append(tab2).append("IINC ").append(var).append(' ')
.append(increment).append('\n');
text.add(buf.toString());
}
@Override
public void visitTableSwitchInsn(final int min, final int max,
final Label dflt, final Label... labels) {
buf.setLength(0);
buf.append(tab2).append("TABLESWITCH\n");
for (int i = 0; i < labels.length; ++i) {
buf.append(tab3).append(min + i).append(": ");
appendLabel(labels[i]);
buf.append('\n');
}
buf.append(tab3).append("default: ");
appendLabel(dflt);
buf.append('\n');
text.add(buf.toString());
}
@Override
public void visitLookupSwitchInsn(final Label dflt, final int[] keys,
final Label[] labels) {
buf.setLength(0);
buf.append(tab2).append("LOOKUPSWITCH\n");
for (int i = 0; i < labels.length; ++i) {
buf.append(tab3).append(keys[i]).append(": ");
appendLabel(labels[i]);
buf.append('\n');
}
buf.append(tab3).append("default: ");
appendLabel(dflt);
buf.append('\n');
text.add(buf.toString());
}
@Override
public void visitMultiANewArrayInsn(final String desc, final int dims) {
buf.setLength(0);
buf.append(tab2).append("MULTIANEWARRAY ");
appendDescriptor(FIELD_DESCRIPTOR, desc);
buf.append(' ').append(dims).append('\n');
text.add(buf.toString());
}
@Override
public Printer visitInsnAnnotation(int typeRef, TypePath typePath,
String desc, boolean visible) {
return visitTypeAnnotation(typeRef, typePath, desc, visible);
}
@Override
public void visitTryCatchBlock(final Label start, final Label end,
final Label handler, final String type) {
buf.setLength(0);
buf.append(tab2).append("TRYCATCHBLOCK ");
appendLabel(start);
buf.append(' ');
appendLabel(end);
buf.append(' ');
appendLabel(handler);
buf.append(' ');
appendDescriptor(INTERNAL_NAME, type);
buf.append('\n');
text.add(buf.toString());
}
@Override
public Printer visitTryCatchAnnotation(int typeRef, TypePath typePath,
String desc, boolean visible) {
buf.setLength(0);
buf.append(tab2).append("TRYCATCHBLOCK @");
appendDescriptor(FIELD_DESCRIPTOR, desc);
buf.append('(');
text.add(buf.toString());
Textifier t = createTextifier();
text.add(t.getText());
buf.setLength(0);
buf.append(") : ");
appendTypeReference(typeRef);
buf.append(", ").append(typePath);
buf.append(visible ? "\n" : " // invisible\n");
text.add(buf.toString());
return t;
}
@Override
public void visitLocalVariable(final String name, final String desc,
final String signature, final Label start, final Label end,
final int index) {
buf.setLength(0);
buf.append(tab2).append("LOCALVARIABLE ").append(name).append(' ');
appendDescriptor(FIELD_DESCRIPTOR, desc);
buf.append(' ');
appendLabel(start);
buf.append(' ');
appendLabel(end);
buf.append(' ').append(index).append('\n');
if (signature != null) {
buf.append(tab2);
appendDescriptor(FIELD_SIGNATURE, signature);
TraceSignatureVisitor sv = new TraceSignatureVisitor(0);
SignatureReader r = new SignatureReader(signature);
r.acceptType(sv);
buf.append(tab2).append("// declaration: ")
.append(sv.getDeclaration()).append('\n');
}
text.add(buf.toString());
}
@Override
public Printer visitLocalVariableAnnotation(int typeRef, TypePath typePath,
Label[] start, Label[] end, int[] index, String desc,
boolean visible) {
buf.setLength(0);
buf.append(tab2).append("LOCALVARIABLE @");
appendDescriptor(FIELD_DESCRIPTOR, desc);
buf.append('(');
text.add(buf.toString());
Textifier t = createTextifier();
text.add(t.getText());
buf.setLength(0);
buf.append(") : ");
appendTypeReference(typeRef);
buf.append(", ").append(typePath);
for (int i = 0; i < start.length; ++i) {
buf.append(" [ ");
appendLabel(start[i]);
buf.append(" - ");
appendLabel(end[i]);
buf.append(" - ").append(index[i]).append(" ]");
}
buf.append(visible ? "\n" : " // invisible\n");
text.add(buf.toString());
return t;
}
@Override
public void visitLineNumber(final int line, final Label start) {
buf.setLength(0);
buf.append(tab2).append("LINENUMBER ").append(line).append(' ');
appendLabel(start);
buf.append('\n');
text.add(buf.toString());
}
@Override
public void visitMaxs(final int maxStack, final int maxLocals) {
buf.setLength(0);
buf.append(tab2).append("MAXSTACK = ").append(maxStack).append('\n');
text.add(buf.toString());
buf.setLength(0);
buf.append(tab2).append("MAXLOCALS = ").append(maxLocals).append('\n');
text.add(buf.toString());
}
@Override
public void visitMethodEnd() {
}
// ------------------------------------------------------------------------
// Common methods
// ------------------------------------------------------------------------
/**
* Prints a disassembled view of the given annotation.
*
* @param desc
* the class descriptor of the annotation class.
* @param visible
* <tt>true</tt> if the annotation is visible at runtime.
* @return a visitor to visit the annotation values.
*/
public Textifier visitAnnotation(final String desc, final boolean visible) {
buf.setLength(0);
buf.append(tab).append('@');
appendDescriptor(FIELD_DESCRIPTOR, desc);
buf.append('(');
text.add(buf.toString());
Textifier t = createTextifier();
text.add(t.getText());
text.add(visible ? ")\n" : ") // invisible\n");
return t;
}
/**
* Prints a disassembled view of the given type annotation.
*
* @param typeRef
* a reference to the annotated type. See {@link TypeReference}.
* @param typePath
* the path to the annotated type argument, wildcard bound, array
* element type, or static inner type within 'typeRef'. May be
* <tt>null</tt> if the annotation targets 'typeRef' as a whole.
* @param desc
* the class descriptor of the annotation class.
* @param visible
* <tt>true</tt> if the annotation is visible at runtime.
* @return a visitor to visit the annotation values.
*/
public Textifier visitTypeAnnotation(final int typeRef,
final TypePath typePath, final String desc, final boolean visible) {
buf.setLength(0);
buf.append(tab).append('@');
appendDescriptor(FIELD_DESCRIPTOR, desc);
buf.append('(');
text.add(buf.toString());
Textifier t = createTextifier();
text.add(t.getText());
buf.setLength(0);
buf.append(") : ");
appendTypeReference(typeRef);
buf.append(", ").append(typePath);
buf.append(visible ? "\n" : " // invisible\n");
text.add(buf.toString());
return t;
}
/**
* Prints a disassembled view of the given attribute.
*
* @param attr
* an attribute.
*/
public void visitAttribute(final Attribute attr) {
buf.setLength(0);
buf.append(tab).append("ATTRIBUTE ");
appendDescriptor(-1, attr.type);
if (attr instanceof Textifiable) {
((Textifiable) attr).textify(buf, null);
} else {
buf.append(" : unknown\n");
}
text.add(buf.toString());
}
// ------------------------------------------------------------------------
// Utility methods
// ------------------------------------------------------------------------
/**
* Creates a new TraceVisitor instance.
*
* @return a new TraceVisitor.
*/
protected Textifier createTextifier() {
return new Textifier();
}
/**
* Appends an internal name, a type descriptor or a type signature to
* {@link #buf buf}.
*
* @param type
* indicates if desc is an internal name, a field descriptor, a
* method descriptor, a class signature, ...
* @param desc
* an internal name, type descriptor, or type signature. May be
* <tt>null</tt>.
*/
protected void appendDescriptor(final int type, final String desc) {
if (type == CLASS_SIGNATURE || type == FIELD_SIGNATURE
|| type == METHOD_SIGNATURE) {
if (desc != null) {
buf.append("// signature ").append(desc).append('\n');
}
} else {
buf.append(desc);
}
}
/**
* Appends the name of the given label to {@link #buf buf}. Creates a new
* label name if the given label does not yet have one.
*
* @param l
* a label.
*/
protected void appendLabel(final Label l) {
if (labelNames == null) {
labelNames = new HashMap<Label, String>();
}
String name = labelNames.get(l);
if (name == null) {
name = "L" + labelNames.size();
labelNames.put(l, name);
}
buf.append(name);
}
/**
* Appends the information about the given handle to {@link #buf buf}.
*
* @param h
* a handle, non null.
*/
protected void appendHandle(final Handle h) {
int tag = h.getTag();
buf.append("// handle kind 0x").append(Integer.toHexString(tag))
.append(" : ");
boolean isMethodHandle = false;
switch (tag) {
case Opcodes.H_GETFIELD:
buf.append("GETFIELD");
break;
case Opcodes.H_GETSTATIC:
buf.append("GETSTATIC");
break;
case Opcodes.H_PUTFIELD:
buf.append("PUTFIELD");
break;
case Opcodes.H_PUTSTATIC:
buf.append("PUTSTATIC");
break;
case Opcodes.H_INVOKEINTERFACE:
buf.append("INVOKEINTERFACE");
isMethodHandle = true;
break;
case Opcodes.H_INVOKESPECIAL:
buf.append("INVOKESPECIAL");
isMethodHandle = true;
break;
case Opcodes.H_INVOKESTATIC:
buf.append("INVOKESTATIC");
isMethodHandle = true;
break;
case Opcodes.H_INVOKEVIRTUAL:
buf.append("INVOKEVIRTUAL");
isMethodHandle = true;
break;
case Opcodes.H_NEWINVOKESPECIAL:
buf.append("NEWINVOKESPECIAL");
isMethodHandle = true;
break;
}
buf.append('\n');
buf.append(tab3);
appendDescriptor(INTERNAL_NAME, h.getOwner());
buf.append('.');
buf.append(h.getName());
if(!isMethodHandle){
buf.append('(');
}
appendDescriptor(HANDLE_DESCRIPTOR, h.getDesc());
if(!isMethodHandle){
buf.append(')');
}
}
/**
* Appends a string representation of the given access modifiers to
* {@link #buf buf}.
*
* @param access
* some access modifiers.
*/
private void appendAccess(final int access) {
if ((access & Opcodes.ACC_PUBLIC) != 0) {
buf.append("public ");
}
if ((access & Opcodes.ACC_PRIVATE) != 0) {
buf.append("private ");
}
if ((access & Opcodes.ACC_PROTECTED) != 0) {
buf.append("protected ");
}
if ((access & Opcodes.ACC_FINAL) != 0) {
buf.append("final ");
}
if ((access & Opcodes.ACC_STATIC) != 0) {
buf.append("static ");
}
if ((access & Opcodes.ACC_SYNCHRONIZED) != 0) {
buf.append("synchronized ");
}
if ((access & Opcodes.ACC_VOLATILE) != 0) {
buf.append("volatile ");
}
if ((access & Opcodes.ACC_TRANSIENT) != 0) {
buf.append("transient ");
}
if ((access & Opcodes.ACC_ABSTRACT) != 0) {
buf.append("abstract ");
}
if ((access & Opcodes.ACC_STRICT) != 0) {
buf.append("strictfp ");
}
if ((access & Opcodes.ACC_SYNTHETIC) != 0) {
buf.append("synthetic ");
}
if ((access & Opcodes.ACC_MANDATED) != 0) {
buf.append("mandated ");
}
if ((access & Opcodes.ACC_ENUM) != 0) {
buf.append("enum ");
}
}
private void appendComa(final int i) {
if (i != 0) {
buf.append(", ");
}
}
private void appendTypeReference(final int typeRef) {
TypeReference ref = new TypeReference(typeRef);
switch (ref.getSort()) {
case TypeReference.CLASS_TYPE_PARAMETER:
buf.append("CLASS_TYPE_PARAMETER ").append(
ref.getTypeParameterIndex());
break;
case TypeReference.METHOD_TYPE_PARAMETER:
buf.append("METHOD_TYPE_PARAMETER ").append(
ref.getTypeParameterIndex());
break;
case TypeReference.CLASS_EXTENDS:
buf.append("CLASS_EXTENDS ").append(ref.getSuperTypeIndex());
break;
case TypeReference.CLASS_TYPE_PARAMETER_BOUND:
buf.append("CLASS_TYPE_PARAMETER_BOUND ")
.append(ref.getTypeParameterIndex()).append(", ")
.append(ref.getTypeParameterBoundIndex());
break;
case TypeReference.METHOD_TYPE_PARAMETER_BOUND:
buf.append("METHOD_TYPE_PARAMETER_BOUND ")
.append(ref.getTypeParameterIndex()).append(", ")
.append(ref.getTypeParameterBoundIndex());
break;
case TypeReference.FIELD:
buf.append("FIELD");
break;
case TypeReference.METHOD_RETURN:
buf.append("METHOD_RETURN");
break;
case TypeReference.METHOD_RECEIVER:
buf.append("METHOD_RECEIVER");
break;
case TypeReference.METHOD_FORMAL_PARAMETER:
buf.append("METHOD_FORMAL_PARAMETER ").append(
ref.getFormalParameterIndex());
break;
case TypeReference.THROWS:
buf.append("THROWS ").append(ref.getExceptionIndex());
break;
case TypeReference.LOCAL_VARIABLE:
buf.append("LOCAL_VARIABLE");
break;
case TypeReference.RESOURCE_VARIABLE:
buf.append("RESOURCE_VARIABLE");
break;
case TypeReference.EXCEPTION_PARAMETER:
buf.append("EXCEPTION_PARAMETER ").append(
ref.getTryCatchBlockIndex());
break;
case TypeReference.INSTANCEOF:
buf.append("INSTANCEOF");
break;
case TypeReference.NEW:
buf.append("NEW");
break;
case TypeReference.CONSTRUCTOR_REFERENCE:
buf.append("CONSTRUCTOR_REFERENCE");
break;
case TypeReference.METHOD_REFERENCE:
buf.append("METHOD_REFERENCE");
break;
case TypeReference.CAST:
buf.append("CAST ").append(ref.getTypeArgumentIndex());
break;
case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
buf.append("CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT ").append(
ref.getTypeArgumentIndex());
break;
case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT:
buf.append("METHOD_INVOCATION_TYPE_ARGUMENT ").append(
ref.getTypeArgumentIndex());
break;
case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
buf.append("CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT ").append(
ref.getTypeArgumentIndex());
break;
case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT:
buf.append("METHOD_REFERENCE_TYPE_ARGUMENT ").append(
ref.getTypeArgumentIndex());
break;
}
}
private void appendFrameTypes(final int n, final Object[] o) {
for (int i = 0; i < n; ++i) {
if (i > 0) {
buf.append(' ');
}
if (o[i] instanceof String) {
String desc = (String) o[i];
if (desc.startsWith("[")) {
appendDescriptor(FIELD_DESCRIPTOR, desc);
} else {
appendDescriptor(INTERNAL_NAME, desc);
}
} else if (o[i] instanceof Integer) {
switch (((Integer) o[i]).intValue()) {
case 0:
appendDescriptor(FIELD_DESCRIPTOR, "T");
break;
case 1:
appendDescriptor(FIELD_DESCRIPTOR, "I");
break;
case 2:
appendDescriptor(FIELD_DESCRIPTOR, "F");
break;
case 3:
appendDescriptor(FIELD_DESCRIPTOR, "D");
break;
case 4:
appendDescriptor(FIELD_DESCRIPTOR, "J");
break;
case 5:
appendDescriptor(FIELD_DESCRIPTOR, "N");
break;
case 6:
appendDescriptor(FIELD_DESCRIPTOR, "U");
break;
}
} else {
appendLabel((Label) o[i]);
}
}
}
}
| mit |
groz/node-lmdb | example8-multiple-cursors-single-transaction.js | 3438 | var lmdb = require('./build/Release/node-lmdb');
var env = new lmdb.Env();
env.open({
// Path to the environment
path: "./testdata",
// Maximum number of databases
maxDbs: 10
});
function createTestDb(dbName) {
// Ensure that the database is empty
var dbi = env.openDbi({
name: dbName,
create: true
});
dbi.drop();
dbi = env.openDbi({
name: dbName,
create: true
});
// Write test values
var txn0 = env.beginTxn();
txn0.putString(dbi, "a", "Helló1");
txn0.putString(dbi, "b", "Hello2");
txn0.putNumber(dbi, "c", 43);
/* key 'd' is omitted intentionally */
txn0.putBinary(dbi, "e", new Buffer("öüóőúéáű"));
txn0.putBoolean(dbi, "f", false);
txn0.putString(dbi, "g", "Hello6");
txn0.commit();
console.log("wrote initial values");
dbi.close()
}
createTestDb("mydb8.1");
createTestDb("mydb8.2");
var printFunc = function (key, data) {
console.log("-----> key:", key);
console.log("-----> data:", data);
}
//Open DB1
var dbi1 = env.openDbi({
name: "mydb8.1"
});
// Begin shared readOnly transaction
var txn = env.beginTxn({readOnly: true});
// Create cursor for DB1
var cursor1 = new lmdb.Cursor(txn, dbi1);
console.log("cursor1 - first (expected a)");
cursor1.goToFirst();
cursor1.getCurrentString(printFunc);
console.log("cursor1 - next (expected b)");
cursor1.goToNext();
cursor1.getCurrentString(printFunc);
//Open DB2
var dbi2 = env.openDbi({
name: "mydb8.2"
});
//txn does not know about dbi2 yet, opening a cursor to it will fail with "Error: Invalid argument"
//Reset the transaction to make it aware of dbi2
txn.reset()
//Renew the transaction to keep cursor1 valid, without this calls on cursor1 will fail
txn.renew()
// Create cursor for DB2
var cursor2 = new lmdb.Cursor(txn, dbi2);
console.log("cursor2 - first (expected a)");
cursor2.goToFirst();
cursor2.getCurrentString(printFunc);
console.log("cursor2 - next (expected b)");
cursor2.goToNext();
cursor2.getCurrentString(printFunc);
//cursor1 still is at its old position and reads the expected values
console.log("cursor1 - next (expected c)");
cursor1.goToNext();
cursor1.getCurrentNumber(printFunc);
console.log("cursor1 - next (expected e)");
cursor1.goToNext();
cursor1.getCurrentBinary(printFunc);
// Randomly reading on different cursors
console.log("cursor2 - next (expected c)");
cursor2.goToNext();
cursor2.getCurrentNumber(printFunc);
console.log("cursor2 - next (expected e)");
cursor2.goToNext();
cursor2.getCurrentBinary(printFunc);
console.log("cursor1 - prev (expected c)");
cursor1.goToPrev();
cursor1.getCurrentNumber(printFunc);
console.log("cursor1 - last (expected g)");
cursor1.goToLast();
cursor1.getCurrentString(printFunc);
console.log("cursor2 - prev (expected c)");
cursor2.goToPrev();
cursor2.getCurrentNumber(printFunc);
console.log("cursor2 - last (expected g)");
cursor2.goToLast();
cursor2.getCurrentString(printFunc);
console.log("");
console.log("cursor1 - now iterating through all the keys");
for (var found = cursor1.goToFirst(); found; found = cursor1.goToNext()) {
console.log("-----> key:", found);
}
console.log("");
console.log("cursor2 - now iterating through all the keys");
for (var found = cursor2.goToFirst(); found; found = cursor2.goToNext()) {
console.log("-----> key:", found);
}
// Close cursors
cursor1.close();
cursor2.close();
// Commit transaction
txn.commit();
dbi1.close();
dbi2.close();
env.close();
| mit |
rodrigocipriani/br-react-utils | lib/layout/Loading.js | 2196 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import React, { Component } from 'react';
var Loading = function (_Component) {
_inherits(Loading, _Component);
function Loading() {
_classCallCheck(this, Loading);
return _possibleConstructorReturn(this, (Loading.__proto__ || Object.getPrototypeOf(Loading)).apply(this, arguments));
}
_createClass(Loading, [{
key: "render",
value: function render() {
return React.createElement(
"div",
{ className: "progress", style: { margin: 0 } },
React.createElement("div", { className: "indeterminate" })
);
}
}]);
return Loading;
}(Component);
export default Loading;
//# sourceMappingURL=Loading.js.map | mit |
hobrien/AgaricalesGenomics | CountGaps.py | 258 | import sys
from os import path
from glob import glob
from Bio import SeqIO
infile=sys.argv[1]
for seq_record in SeqIO.parse(infile, "fasta"):
print seq_record.id, 100-(float(seq_record.seq.count('X')+seq_record.seq.count('-'))/len(seq_record.seq) * 100)
| mit |
codeBelt/Grunt-Browserify-Example | src/assets/vendor/structurejs/ts/model/Route.ts | 6052 | 'use strict';
/*
UMD Stuff
@export Route
*/
/**
* The **Route** class is a model that keeps track of a specific route for the {{#crossLink "Router"}}{{/crossLink}} class.
*
* @class Route
* @module StructureJS
* @submodule model
* @param routePattern {string} The string pattern you want to have match, which can be any of the following combinations {}, ::, *, ''
* @param callback {Function} The function that should be executed when a request matches the routePattern.
* @param callbackScope {any} The scope of the callback function that should be executed.
* @constructor
* @author Robert S. (www.codeBelt.com)
* @example
* // Example of adding a route listener and the function callback below.
* var route = new Route('/games/{gameName}/:level:/', this.onRouteHandler, this);
*
* // The above route would match the string below:
* route.match('/games/asteroids/2/');
*
* Route Pattern Options:
* ----------------------
* **:optional:** The two colons **::** means a part of the hash url is optional for the match. The text between can be anything you want it to be.
*
* var route = new Route('/contact/:name:/', this.method, this);
*
* // Will match one of the following:
* route.match('/contact/');
* route.match('/contact/heather/');
* route.match('/contact/john/');
*
*
* **{required}** The two curly brackets **{}** means a part of the hash url is required for the match. The text between can be anything you want it to be.
*
* var route = new Route('/product/{productName}/', this.method, this);
*
* // Will match one of the following:
* route.match('/product/shoes/');
* route.match('/product/jackets/');
*
*
* **\*** The asterisk character means it will match all or part of part the hash url.
*
* var route = new Route('*', this.method, this);
*
* // Will match one of the following:
* route.match('/anything/');
* route.match('/matches/any/hash/url/');
* route.match('/really/it/matches/any/and/all/hash/urls/');
*
*
* **''** The empty string means it will match when there are no hash url.
*
* var route = new Route('', this.method, this);
* var route = new Route('/', this.method, this);
*
* // Will match one of the following:
* route.match('');
* route.match('/');
*
*
* Other possible combinations but not limited too:
*
* var route = new Route('/games/{gameName}/:level:/', this.method1, this);
* var route = new Route('/{category}/blog/', this.method2, this);
* var route = new Route('/about/*', this.method4, this);
*
*/
class Route
{
/**
* The string pattern you want to have match, which can be any of the following combinations {}, ::, *, ?, "". See below for examples.
*
* @property routePattern
* @type String
* @public
*/
public routePattern = '';
/**
* The regex representation for the routePattern that was passed into the constructor.
*
* @property regex
* @type RegExp
* @public
* @readOnly
*/
public regex:RegExp = null;
/**
* The function that should be executed when a request matches the routePattern. The {{#crossLink "Router"}}{{/crossLink}} class will be using this property.
*
* @property callback
* @type {Function}
* @public
*/
public callback:Function = null;
/**
* The scope of the callback function that should be executed. The {{#crossLink "Router"}}{{/crossLink}} class will be using this property.
*
* @property callbackScope
* @type {any}
* @public
*/
public callbackScope:any = null;
constructor(routePattern:string, callback:Function, scope:any)
{
this.routePattern = routePattern;
this.regex = this.routePatternToRegexp(routePattern);
this.callback = callback;
this.callbackScope = scope;
}
/**
* Converts the routePattern that was passed into the constructor to a regexp object.
*
* @method routePatternToRegexp
* @param {String} routePattern
* @returns {RegExp}
* @private
*/
private routePatternToRegexp(routePattern):RegExp
{
var findFirstOrLastForwardSlash:RegExp = new RegExp('^\/|\/$', 'g'); // Finds if the first character OR if the last character is a forward slash
var findOptionalColons:RegExp = new RegExp(':([^:]*):', 'g'); // Finds the colons : :
var findRequiredBrackets:RegExp = new RegExp('{([^}]+)}', 'g'); // Finds the brackets { }
var optionalFirstCharSlash = '^/?';// Allows the first character to be if a forward slash to be optional.
var optionalLastCharSlash = '/?$';// Allows the last character to be if a forward slash to be optional.
// Remove first and last forward slash.
routePattern = routePattern.replace(findFirstOrLastForwardSlash, '');
// Convert the wild card * be a regex ?(.*) to select all.
routePattern = routePattern.replace('*', '?(.*)');
// Make any :alphanumeric: optional
routePattern = routePattern.replace(findOptionalColons, '?([^/]*)');
// Make any {alphanumeric} required
routePattern = routePattern.replace(findRequiredBrackets, '([^/]+)');
return new RegExp(optionalFirstCharSlash + routePattern + optionalLastCharSlash, 'i');
}
/**
* Determine if a route matches a routePattern.
*
* @method match
* @param route {String} The route or path to match against the routePattern that was passed into the constructor.
* @returns {Array}
* @example
* var route = new Route('/games/{gameName}/:level:/', this.method, this);
* console.log( route.match('/games/asteroids/2/') );
*/
public match(route):any[]
{
// Remove the query string before matching against the route pattern.
var routeWithoutQueryString:string = route.replace(/\?.*/, '');
return routeWithoutQueryString.match(this.regex);
}
}
export = Route;
| mit |
dansimpson/satchel | core/tests/deep/deep/deep/test.js | 5 | !ddd
| mit |
elegault/BCMMigrationAssistant | CheckDuplicates_Result.cs | 907 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace BcmMigrationTool
{
using System;
public partial class CheckDuplicates_Result
{
public Nullable<System.Guid> EntryGUID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FileAs { get; set; }
public string FullName { get; set; }
public string Email1 { get; set; }
public string Email2 { get; set; }
public string Email3 { get; set; }
}
}
| mit |
smart-home-technology/it-btswitch-python | intertechno/__init__.py | 22 | from .timers import *
| mit |
VeselinTodorov2000/Exercises_Csharp | Distance/Program.cs | 935 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Distance
{
class Program
{
static void Main(string[] args)
{
int speedBeginning = Int32.Parse(Console.ReadLine());
int minutesFirstTime = Int32.Parse(Console.ReadLine());
int minutesSecondTime = Int32.Parse(Console.ReadLine());
int minutesThirdTime = Int32.Parse(Console.ReadLine());
var allS = speedBeginning * ((double)minutesFirstTime / 60);
var afterF = (speedBeginning + (0.1 * speedBeginning)) * ((double)minutesSecondTime/60);
var afterS = (((speedBeginning + (0.1 * speedBeginning)) - (0.05 * (speedBeginning + (0.1 * speedBeginning)))) * ((double)minutesThirdTime / 60));
var result = allS + afterF + afterS;
Console.WriteLine("{0:F2}", result);
}
}
}
| mit |
code16/sharp | src/Utils/Transformers/SharpAttributeTransformer.php | 343 | <?php
namespace Code16\Sharp\Utils\Transformers;
interface SharpAttributeTransformer
{
/**
* Transform a model attribute to array (json-able).
*
* @param $value
* @param $instance
* @param string $attribute
* @return mixed
*/
public function apply($value, $instance = null, $attribute = null);
}
| mit |
phaxio/phaxio-java | client/src/test/java/com/phaxio/integrationtests/scenarios/PhaxCodeRepositoryScenario.java | 851 | package com.phaxio.integrationtests.scenarios;
import com.phaxio.Phaxio;
import com.phaxio.helpers.Config;
import com.phaxio.resources.PhaxCode;
import org.junit.Test;
import java.io.IOException;
public class PhaxCodeRepositoryScenario extends RateLimitedScenario {
@Test
public void createPhaxCodeAndRetrievePng () throws IOException, InterruptedException {
Phaxio phaxio = new Phaxio(Config.get("key"), Config.get("secret"));
PhaxCode code = phaxio.phaxCode.create("1234");
Thread.sleep(1000);
code.png();
}
@Test
public void retrieveDefaultPhaxCodeAndPng () throws IOException, InterruptedException {
Phaxio phaxio = new Phaxio(Config.get("key"), Config.get("secret"));
PhaxCode code = phaxio.phaxCode.retrieve();
Thread.sleep(1000);
code.png();
}
}
| mit |
kmiyashiro/grunt-mocha | Gruntfile.js | 5293 | /**
* Example Gruntfile for Mocha setup
*/
'use strict';
module.exports = function(grunt) {
var port = 8981;
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/**/*.js', ],
options: {
jshintrc: '.jshintrc'
}
},
watch: {
// If you want to watch files and run tests automatically on change
test: {
files: [
'example/js/**/*.js',
'example/test/spec/**/*.js',
'phantomjs/*',
'tasks/*',
'Gruntfile.js'
],
tasks: 'test'
}
},
mocha: {
// runs all html files (except test2.html) in the test dir
// In this example, there's only one, but you can add as many as
// you want. You can split them up into different groups here
// ex: admin: [ 'test/admin.html' ]
all: ['example/test/**/!(test2|testBail|testPage).html'],
// Runs 'test/test2.html' with specified mocha options.
// This variant auto-includes 'bridge.js' so you do not have
// to include it in your HTML spec file. Instead, you must add an
// environment check before you run `mocha.run` in your HTML.
test2: {
// Test files
src: ['example/test/test2.html'],
options: {
// mocha options
mocha: {
ignoreLeaks: false,
grep: 'food'
},
reporter: 'Spec',
timeout: 10000
}
},
// Runs the same as test2 but with URL's
testUrls: {
options: {
// mocha options
mocha: {
ignoreLeaks: false,
grep: 'food'
},
reporter: 'Nyan',
// URLs passed through as options
urls: ['http://localhost:' + port + '/example/test/test2.html'],
}
},
// Test using a custom reporter
testReporter: {
src: ['example/test/test.html', 'example/test/test2.html'],
options: {
mocha: {
ignoreLeaks: false,
grep: 'food'
},
reporter: './example/test/reporter/simple',
}
},
// Test log option
testLog: {
src: ['example/test/test.html'],
options: {
mocha: {
ignoreLeaks: false,
grep: 'food'
},
log: true
}
},
testDest1: {
// Test files
src: ['example/test/test2.html'],
dest: 'example/test/results/spec.out',
options: {
reporter: 'Spec',
}
},
// Same as above, but with URLS + Xunit
testDest2: {
options: {
reporter: 'XUnit',
// URLs passed through as options
urls: ['http://localhost:' + (port + 1) + '/example/test/test2.html'],
},
dest: 'example/test/results/xunit.out'
},
// Test a failing test with bail: true
testBail: {
src: ['example/test/testBail.html'],
// Bail option
options: {
bail: true
}
},
// This test should never run
neverTest: {
src: ['example/test/test.html'],
},
// Test page options
testPage: {
src: ['example/test/testPage.html'],
options: {
page: {
settings: {
userAgent: 'grunt-mocha-agent'
}
}
}
}
},
connect: {
testUrls: {
options: {
port: port,
base: '.'
}
},
testDest: {
options: {
port: port + 1,
base: '.'
}
}
}
});
grunt.registerTask('verifyDestResults', function () {
var expected = ['spec', 'xunit'];
expected.forEach(function (reporter) {
var output = 'example/test/results/' + reporter + '.out';
// simply check if the file is non-empty since verifying if the output is
// correct based on the spec is kind of hard due to changing test running
// times and different ways to report this time in reporters.
if (!grunt.file.read(output, 'utf8'))
grunt.fatal('Empty reporter output: ' + reporter);
// Clean-up
grunt.file.delete(output);
grunt.log.ok('Reporter output non-empty for %s', reporter);
});
});
grunt.loadTasks('tasks');
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.task.registerTask('testUrls', ['connect:testUrls', 'mocha:testUrls']);
grunt.task.registerTask('testLog', ['mocha:testLog']);
grunt.task.registerTask('testReporter', ['mocha:testReporter']);
grunt.task.registerTask('testDest', [
'mocha:testDest1',
'connect:testDest',
'mocha:testDest2',
'verifyDestResults'
]);
grunt.task.registerTask('testPage', ['mocha:testPage']);
// WARNING: Running this test will cause grunt to fail after mocha:testBail
grunt.task.registerTask('testBail', ['mocha:testBail', 'mocha:neverTest']);
grunt.task.registerTask('test', [
'mocha:all',
'testUrls',
'testLog',
'testReporter',
'testDest',
'testPage',
]);
// By default, lint and run all tests.
grunt.task.registerTask('default', ['jshint', 'test']);
};
| mit |
catalinmiron/hackathon-granditude | src/models/post.js | 418 | "use strict";
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var User = require('./user');
var PostSchema = mongoose.Schema({
description: { type: "string", required: true},
created_by: Object,
created_at: { type: "date", default: Date.now },
location: {type: "array"},
realLocation: {type: "string"},
isPublic: {type: "boolean", default: true}
})
mongoose.model("Post", PostSchema);
| mit |
Scheffer/gulp-asvn | commands/exec.js | 954 | 'use strict';
var exec = require('child_process').exec,
gutil = require('gulp-util');
module.exports = function (options, cb) {
if(!cb && typeof options === 'function') {
cb = options;
options = {};
}
if(!cb || typeof cb !== 'function') cb = function () {};
if(!options) options = {};
if(!options.log) options.log = !cb;
if(!options.cwd) options.cwd = process.cwd();
if(!options.args) options.args = ' ';
var cmd = 'svn ' + options.args;
if(options.username && options.password) {
cmd += ' --username '+ options.username + ' --password ' + options.password;
}
return exec(cmd, {cwd: options.cwd}, function(err, stdout, stderr){
if(err) return cb(err);
if(options.log && !options.quiet) gutil.log(cmd+ '\n' + stdout, stderr);
else {
if(!options.quiet) gutil.log(cmd + ' (log : false)', stderr);
}
cb(err, stdout);
});
}; | mit |
MuhammadNurHuda/SMK-YPS-Samarinda | application/views/admin/slide/edit_data.php | 893 | <!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php echo form_open_multipart('admin/edit_slide');?>
<hr>
<input type="hidden" name="id" value="<?php echo $record['id_gambar']; ?>"></input>
<table class="table table-bordered">
<tr>
<td>File</td>
<td>
<img style="padding-bottom: 10px;width: 250px;height: 200px;" src="<?php echo base_url('uploads/'.$record['nama_file']); ?>">
<input type="file" name="userfile"></input></td>
</tr>
<tr>
<td>Title</td>
<td><input type="text" value="<?php echo $record['title_file']; ?>" name="title" class="form-control" placeholder="Title File"></input></td>
<input type="hidden" name="pict" value="<?php echo $record['nama_file']; ?>"></input>
</tr>
</table>
<input type="submit" name="submit" value="Upload" class="btn btn-success"></input>
<?php echo anchor('admin/slide','Kembali',array('class'=>'btn btn-danger')); ?>
</body>
</html> | mit |
occam-proof-assistant/Parsers | es6/customGrammarLexicalPattern/bnf.js | 271 | 'use strict';
const bnf = `
document ::= lexicalPattern ( verticalSpace | error )* | ( verticalSpace | error )+ ;
lexicalPattern ::= [unassigned]+ ;
verticalSpace ::= <END_OF_LINE>+ ;
error ::= . ;
`;
module.exports = bnf;
| mit |
dannynelson/javascript-koans | koans/AboutArrays.js | 2930 | describe("About Arrays", function() {
//We shall contemplate truth by testing reality, via spec expectations.
it("should create arrays", function() {
var emptyArray = [];
expect(typeof(emptyArray)).toBe("object"); //A mistake? - http:javascript.crockford.com/remedial.html
expect(emptyArray.length).toBe(0);
var multiTypeArray = [0, 1, "two", function () { return 3; }, {value1: 4, value2: 5}, [6, 7]];
expect(multiTypeArray[0]).toBe(0);
expect(multiTypeArray[2]).toBe("two");
expect(multiTypeArray[3]()).toBe(3); //even for === ?
expect(multiTypeArray[4].value1).toBe(4);
expect(multiTypeArray[4]["value2"]).toBe(5);
expect(multiTypeArray[5][0]).toBe(6);
});
it("should understand array literals", function () {
var array = [];
expect(array).toEqual([]);
array[0] = 1;
expect(array).toEqual([1]);
array[1] = 2;
expect(array).toEqual([1, 2]);
array.push(3);
expect(array).toEqual([1,2,3]);
});
it("should understand array length", function () {
var fourNumberArray = [1, 2, 3, 4];
expect(fourNumberArray.length).toBe(4);
fourNumberArray.push(5, 6);
expect(fourNumberArray.length).toBe(6);
var tenEmptyElementArray = new Array(10);
expect(tenEmptyElementArray.length).toBe(10);
tenEmptyElementArray.length = 5;
expect(tenEmptyElementArray.length).toBe(5);
});
it("should slice arrays", function () {
var array = ["peanut", "butter", "and", "jelly"];
expect(array.slice(0, 1)).toEqual(["peanut"]);
expect(array.slice(0, 2)).toEqual(["peanut", "butter"]);
expect(array.slice(2, 2)).toEqual([]);
expect(array.slice(2, 20)).toEqual(["and", "jelly"]);
expect(array.slice(3, 0)).toEqual([]);
expect(array.slice(3, 100)).toEqual(["jelly"]);
expect(array.slice(5, 1)).toEqual([]);
});
//what???
it("should know array references", function () {
var array = [ "zero", "one", "two", "three", "four", "five" ];
function passedByReference(refArray) {
refArray[1] = "changed in function";
}
passedByReference(array);
expect(array[1]).toBe("changed in function");
var assignedArray = array;
assignedArray[5] = "changed in assignedArray";
expect(array[5]).toBe("changed in assignedArray");
var copyOfArray = array.slice();
copyOfArray[3] = "changed in copyOfArray";
expect(array[3]).toBe("three");
});
it("should push and pop", function () {
var array = [1, 2];
array.push(3);
expect(array).toEqual([1,2,3]);
var poppedValue = array.pop();
expect(poppedValue).toBe(3);
expect(array).toEqual([1,2]);
});
it("should know about shifting arrays", function () {
var array = [1, 2];
array.unshift(3);
expect(array).toEqual([3,1,2]);
var shiftedValue = array.shift();
expect(shiftedValue).toEqual(3);
expect(array).toEqual([1,2]);
});
});
| mit |
liuxx001/BodeAbp | src/queue/BodeAbp.Queue/Broker/RequestHandlers/Admin/QueryTopicQueueInfoRequestHandler.cs | 2251 | using Abp.Dependency;
using Abp.Net.Remoting;
using Abp.Net.Remoting.Args;
using Abp.Serialization;
using BodeAbp.Queue.Protocols;
using BodeAbp.Queue.Utils;
using EQueue.Broker.Exceptions;
using System.Collections.Generic;
using System.Linq;
namespace BodeAbp.Queue.Broker.RequestHandlers.Admin
{
public class QueryTopicQueueInfoRequestHandler : IRequestHandler
{
private ISerializer<byte[]> _binarySerializer;
private IQueueStore _queueStore;
private IConsumeOffsetStore _offsetStore;
public QueryTopicQueueInfoRequestHandler()
{
_binarySerializer = IocManager.Instance.Resolve<ISerializer<byte[]>>();
_queueStore = IocManager.Instance.Resolve<IQueueStore>();
_offsetStore = IocManager.Instance.Resolve<IConsumeOffsetStore>();
}
public RemotingResponse HandleRequest(IRequestHandlerContext context, RemotingRequest remotingRequest)
{
if (BrokerController.Instance.IsCleaning)
{
throw new BrokerCleanningException();
}
var request = _binarySerializer.Deserialize<byte[],QueryTopicQueueInfoRequest>(remotingRequest.Body);
var topicQueueInfoList = new List<TopicQueueInfo>();
var queues = _queueStore.QueryQueues(request.Topic).ToList().OrderBy(x => x.Topic).ThenBy(x => x.QueueId);
foreach (var queue in queues)
{
var topicQueueInfo = new TopicQueueInfo();
topicQueueInfo.Topic = queue.Topic;
topicQueueInfo.QueueId = queue.QueueId;
topicQueueInfo.QueueCurrentOffset = queue.NextOffset - 1;
topicQueueInfo.QueueMinOffset = queue.GetMinQueueOffset();
topicQueueInfo.QueueMinConsumedOffset = _offsetStore.GetMinConsumedOffset(queue.Topic, queue.QueueId);
topicQueueInfo.ProducerVisible = queue.Setting.ProducerVisible;
topicQueueInfo.ConsumerVisible = queue.Setting.ConsumerVisible;
topicQueueInfoList.Add(topicQueueInfo);
}
return RemotingResponseFactory.CreateResponse(remotingRequest, _binarySerializer.Serialize(topicQueueInfoList));
}
}
}
| mit |
yefy/skp | super-knowledge-platform/skpServer/trunk/src/utility/skpMalloc.cpp | 1070 | #include "skpMalloc.h"
void *SkpMalloc::malloc(const char *file, uint16 line, const char *function, int size)
{
SKP_UNUSED(file);
SKP_UNUSED(line);
SKP_UNUSED(function);
void *p = ::malloc(size);
SKP_ASSERT(p);
return p;
}
void *SkpMalloc::calloc(const char *file, uint16 line, const char *function, int size)
{
void *p = SkpMalloc::malloc(file, line, function, size);
SKP_ASSERT(p);
if (p) {
skp_memzero(p, size);
}
return p;
}
void *SkpMalloc::realloc(const char *file, uint16 line, const char *function, void *buffer, int size)
{
SKP_UNUSED(file);
SKP_UNUSED(line);
SKP_UNUSED(function);
void *p = ::realloc(buffer, size);
SKP_ASSERT(p);
return p;
}
#if (SKP_HAVE_POSIX_MEMALIGN)
void *SkpMalloc::memalign(const char *file, uint16 line, const char *function, int alignment, int size)
{
SKP_UNUSED(file);
SKP_UNUSED(line);
SKP_UNUSED(function);
void *p;
int err;
err = posix_memalign(&p, alignment, size);
SKP_ASSERT(!err);
return p;
}
#endif
| mit |
boyhavoc/craigs_gem_pub | lib/craigs_gem/bulk_poster.rb | 16174 | module CraigsGem
class BulkPoster
URLS = YAML.load_file "config/urls.yml"
attr_reader :account, :postings, :errors, :submission_rss
def initialize(account, postings)
@errors = []
@account = account
@postings = postings
end
# Validations ########################
def validate!
validate_postings
validate_at_craigslist
end
def validate_postings
check_postings_uniqness
@postings.each(&:validate!)
end
def validate_at_craigslist
create_rss unless @submission_rss
code, response = http_post(URLS['validate'])
case code
when "403"
log_error(MSG_SUBMISSION_FAILED, response)
when "415"
log_error(MSG_SUBMISSION_PARSE_FAILED, response)
when "200"
parse_validation_response(response)
end
end
def post_to_craigslist
create_rss unless @submission_rss
code, response = http_post(URLS['post'])
case code
when "403"
log_error(MSG_SUBMISSION_FAILED, response)
when "415"
log_error(MSG_SUBMISSION_PARSE_FAILED, response)
when "200"
parse_posting_response(response)
end
end
def parse_validation_response(res)
doc = Nokogiri::XML res
doc.css('item').each do |item|
name = item.attributes['about'].value
preview_html = item.css('cl|previewHTML').text
posted_status = item.css('cl|postedStatus').text
posted_explanation = item.css('cl|postedExplanation').text
posting = @postings.find { |p| p.name == name }
next unless posting
posting.craigslist_posting_status = OpenStruct.new(
preview_html: preview_html,
posted_status: posted_status,
posted_explanation: posted_explanation
)
end
end
def parse_posting_response(res)
doc = Nokogiri::XML res
doc.css('item').each do |item|
name = item.attributes['about'].value
preview_html = item.css('cl|previewHTML').text
posting_id = item.css('cl|postingID').text
posted_status = item.css('cl|postedStatus').text
posting_manage_url = item.css('cl|postingManageURL').text
posted_explanation = item.css('cl|postedExplanation').text
posting = @postings.find { |p| p.name == name }
next unless posting
posting.craigslist_posting_status = OpenStruct.new(
posting_id: posting_id,
preview_html: preview_html,
posted_status: posted_status,
posting_manage_url: posting_manage_url,
posted_explanation: posted_explanation
)
end
end
def http_post(url)
uri = URI(url)
req = Net::HTTP::Post.new(uri)
req['Content-Type'] = "application/x-www-form-urlencoded"
req.body = @submission_rss
res = nil
Net::HTTP.start(uri.host, uri.port, use_ssl: (uri.scheme=='https')) do |h|
res = h.request req
end
[res.code, res.body]
end
# RSS Creation ########################
def create_rss
builder = Nokogiri::XML::Builder.new do |xml|
xmlns_stuff = {
xmlns: "http://purl.org/rss/1.0/",
"xmlns:rdf" => "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"xmlns:cl" => "http://www.craigslist.org/about/cl-bulk-ns/1.0"
}
xml['rdf'].RDF(xmlns_stuff) do
rss_create_channel(xml)
@postings.each { |posting| rss_create_item(xml, posting) }
end
end
@submission_rss = builder.to_xml
end
def rss_create_channel(xml)
xml.channel do
xml.items do
@postings.map(&:name).each { |name|
xml['rdf'].li("rdf:resource" => name)
}
end
auth_stuff = {
username: @account[:username],
password: @account[:password],
accountID: @account[:account_id]
}
xml['cl'].auth(auth_stuff)
end
end
def rss_create_item(xml, posting)
xml.item("rdf:about" => posting.name) do
rss_create_required_items(xml, posting.required_items)
rss_create_optional_items(xml, posting.optional_items)
end
end
def rss_create_required_items(xml, required)
xml.title required[:title]
xml.description { xml.cdata required[:description] }
xml['cl'].category required[:category]
xml['cl'].area required[:area]
rss_create_reply_email(xml, required[:reply_email])
end
def rss_create_optional_items(xml, optional)
rss_create_optional_images xml, optional[:images]
rss_create_optional_subarea xml, optional[:subarea]
rss_create_optional_neighborhood xml, optional[:neighborhood]
rss_create_optional_price xml, optional[:price]
rss_create_optional_map_location xml, optional[:map_location]
rss_create_optional_po_number xml, optional[:po_number]
rss_create_optional_housing_info xml, optional[:housing_info]
rss_create_optional_broker_info xml, optional[:broker_info]
rss_create_optional_job_info xml, optional[:job_info]
rss_create_optional_auto_basics xml, optional[:auto_basics]
rss_create_optional_events xml, optional[:events]
rss_create_optional_forsale xml, optional[:forsale]
rss_create_optional_generic xml, optional[:generic]
rss_create_optional_housing_basics xml, optional[:housing_basics]
rss_create_optional_housing_terms xml, optional[:housing_terms]
rss_create_optional_job_basics xml, optional[:job_basics]
rss_create_optional_personals xml, optional[:personals]
end
# Individual elements ################
def rss_create_reply_email(xml, email)
attrs = {
privacy: email[:privacy],
outsideContactOK: email[:outside_contact_ok],
otherContactInfo: email[:other_contact_info]
}
attrs.delete_if { |_,v| v.nil? }
xml['cl'].replyEmail(attrs) {
xml.text email[:value]
}
end
def rss_create_optional_images(xml, images)
return if images.nil? or images.empty?
images.each do |image|
xml['cl'].image(position: image[:position]) {
xml.text image[:base64_encoded_image]
}
end
end
def rss_create_optional_subarea(xml, subarea)
return if subarea.nil?
xml['cl'].subarea subarea
end
def rss_create_optional_neighborhood(xml, neighborhood)
return if neighborhood.nil?
xml['cl'].neighborhood neighborhood
end
def rss_create_optional_price(xml, price)
return if price.nil?
xml['cl'].price price
end
def rss_create_optional_map_location(xml, map)
return if map.nil?
attrs = {
city: map[:city],
state: map[:state],
postal: map[:postal],
crossStreet1: map[:cross_street1],
crossStreet2: map[:cross_street2],
latitude: map[:latitude],
longitude: map[:longitude]
}
attrs.delete_if { |_,v| v.nil? }
xml['cl'].mapLocation(attrs)
end
def rss_create_optional_po_number(xml, po_number)
return if po_number.nil?
xml['cl'].PONumber po_number
end
def rss_create_optional_housing_info(xml, housing_info)
return if housing_info.nil? or housing_info.empty?
attrs = {
price: housing_info[:price],
bedrooms: housing_info[:bedrooms],
sqft: housing_info[:sqft],
catsOK: housing_info[:cats_ok],
dogsOK: housing_info[:dogs_ok]
}
attrs.delete_if { |_,v| v.nil? }
xml['cl'].housingInfo(attrs)
end
def rss_create_optional_broker_info(xml, broker_info)
return if broker_info.nil? or broker_info.empty?
attrs = {
companyName: broker_info[:company_name],
feeDisclosure: broker_info[:fee_disclosure]
}
attrs.delete_if { |_,v| v.nil? }
xml['cl'].brokerInfo(attrs)
end
def rss_create_optional_job_info(xml, info)
return if info.nil? or info.empty?
attrs = {
compensation: info[:compensation],
telecommuting: info[:telecommuting],
partTime: info[:part_time],
contract: info[:contract],
nonprofit: info[:nonprofit],
internship: info[:internship],
disability: info[:disability],
recruitersOK: info[:recruiters_ok],
phoneCallsOK: info[:phone_calls_ok],
okToContact: info[:ok_to_contact],
okToRepost: info[:ok_to_repost]
}
attrs.delete_if { |_,v| v.nil? }
xml['cl'].jobInfo(attrs)
end
def rss_create_optional_auto_basics(xml, auto)
return if auto.nil? or auto.empty?
attrs = {
auto_bodytype: auto[:auto_bodytype],
auto_drivetrain: auto[:auto_drivetrain],
auto_fuel_type: auto[:auto_fuel_type],
auto_make_model: auto[:auto_make_model],
auto_miles: auto[:auto_miles],
auto_paint: auto[:auto_paint],
auto_size: auto[:auto_size],
auto_title_status: auto[:auto_title_status],
auto_trans_auto: auto[:auto_trans_auto],
auto_trans_manual: auto[:auto_trans_manual],
auto_transmission: auto[:auto_transmission],
auto_vin: auto[:auto_vin],
auto_year: auto[:auto_year]
}
attrs.delete_if { |_,v| v.nil? }
xml['cl'].auto_basics(attrs)
end
def rss_create_optional_events(xml, events)
return if events.nil? or events.empty?
attrs = {
event_art: events[:event_art],
event_athletics: events[:event_athletics],
event_career: events[:event_career],
event_dance: events[:event_dance],
event_festival: events[:event_festival],
event_fitness_wellness: events[:event_fitness_wellness],
event_food: events[:event_food],
event_free: events[:event_free],
event_fundraiser_vol: events[:event_fundraiser_vol],
event_geek: events[:event_geek],
event_kidfriendly: events[:event_kidfriendly],
event_literary: events[:event_literary],
event_music: events[:event_music],
event_outdoor: events[:event_outdoor],
event_sale: events[:event_sale],
event_singles: events[:event_singles]
}
attrs.delete_if { |_,v| v.nil? }
xml['cl'].events(attrs)
end
def rss_create_optional_forsale(xml, forsale)
return if forsale.nil? or forsale.empty?
attrs = {
sale_condition: forsale[:sale_condition],
sale_date_1: forsale[:sale_date_1],
sale_date_2: forsale[:sale_date_2],
sale_date_3: forsale[:sale_date_3],
sale_size: forsale[:sale_size],
sale_time: forsale[:sale_time]
}
attrs.delete_if { |_,v| v.nil? }
xml['cl'].forsale(attrs)
end
def rss_create_optional_generic(xml, generic)
return if generic.nil? or generic.empty?
attrs = {
contact_method: generic[:contact_method],
contact_name: generic[:contact_name],
contact_ok: generic[:contact_ok],
contact_phone: generic[:contact_phone],
contact_phone_ok: generic[:contact_phone_ok],
contact_text_ok: generic[:contact_text_ok],
fee_disclosure: generic[:fee_disclosure],
has_license: generic[:has_license],
license_info: generic[:license_info],
phonecalls_ok: generic[:phonecalls_ok],
repost_ok: generic[:repost_ok],
see_my_other: generic[:see_my_other]
}
attrs.delete_if { |_,v| v.nil? }
xml['cl'].generic(attrs)
end
def rss_create_optional_housing_basics(xml, housing)
return if housing.nil? or housing.empty?
attrs = {
bathrooms: housing[:bathrooms],
housing_type: housing[:housing_type],
is_furnished: housing[:is_furnished],
laundry: housing[:laundry],
movein_date: housing[:movein_date],
no_smoking: housing[:no_smoking],
parking: housing[:parking],
private_bath: housing[:private_bath],
private_room: housing[:private_room],
wheelchaccess: housing[:wheelchaccess]
}
attrs.delete_if { |_,v| v.nil? }
xml['cl'].housing_basics(attrs)
end
def rss_create_optional_housing_terms(xml, terms)
return if terms.nil? or terms.empty?
attrs = {
rent_period: terms[:rent_period]
}
attrs.delete_if { |_,v| v.nil? }
xml['cl'].housing_terms(attrs)
end
def rss_create_optional_job_basics(xml, job)
return if job.nil? or job.empty?
attrs = {
company_name: job[:company_name],
disability_ok: job[:disability_ok],
is_contract: job[:is_contract],
is_forpay: job[:is_forpay],
is_internship: job[:is_internship],
is_nonprofit: job[:is_nonprofit],
is_parttime: job[:is_parttime],
is_telecommuting: job[:is_telecommuting],
is_volunteer: job[:is_volunteer],
recruiters_ok: job[:recruiters_ok],
remuneration: job[:remuneration]
}
attrs.delete_if { |_,v| v.nil? }
xml['cl'].job_basics(attrs)
end
def rss_create_optional_personals(xml, personals)
p = personals
return if p.nil? or p.empty?
attrs = {
pers_body_art_is: p[:pers_body_art_is],
pers_body_type_is: p[:pers_body_type_is],
pers_diet_is: p[:pers_diet_is],
pers_dislikes_is: p[:pers_dislikes_is],
pers_drinking_is: p[:pers_drinking_is],
pers_drugs_is: p[:pers_drugs_is],
pers_education_is: p[:pers_education_is],
pers_ethnicity_is: p[:pers_ethnicity_is],
pers_eyes_is: p[:pers_eyes_is],
pers_facial_hair_is: p[:pers_facial_hair_is],
pers_fears_is: p[:pers_fears_is],
pers_freeform_answer_0_is: p[:pers_freeform_answer_0_is],
pers_freeform_answer_1_is: p[:pers_freeform_answer_1_is],
pers_freeform_answer_2_is: p[:pers_freeform_answer_2_is],
pers_freeform_answer_3_is: p[:pers_freeform_answer_3_is],
pers_freeform_answer_4_is: p[:pers_freeform_answer_4_is],
pers_freeform_answer_5_is: p[:pers_freeform_answer_5_is],
pers_freeform_answer_6_is: p[:pers_freeform_answer_6_is],
pers_freeform_answer_7_is: p[:pers_freeform_answer_7_is],
pers_freeform_question_0_is: p[:pers_freeform_question_0_is],
pers_freeform_question_1_is: p[:pers_freeform_question_1_is],
pers_freeform_question_2_is: p[:pers_freeform_question_2_is],
pers_freeform_question_3_is: p[:pers_freeform_question_3_is],
pers_freeform_question_4_is: p[:pers_freeform_question_4_is],
pers_freeform_question_5_is: p[:pers_freeform_question_5_is],
pers_freeform_question_6_is: p[:pers_freeform_question_6_is],
pers_freeform_question_7_is: p[:pers_freeform_question_7_is],
pers_hair_is: p[:pers_hair_is],
pers_height_is: p[:pers_height_is],
pers_interests_is: p[:pers_interests_is],
pers_kids_has_is: p[:pers_kids_has_is],
pers_kids_want_is: p[:pers_kids_want_is],
pers_lang_native_is: p[:pers_lang_native_is],
pers_likes_is: p[:pers_likes_is],
pers_occupation_is: p[:pers_occupation_is],
pers_personality_is: p[:pers_personality_is],
pers_pets_is: p[:pers_pets_is],
pers_politics_is: p[:pers_politics_is],
pers_relationship_status_is: p[:pers_relationship_status_is],
pers_religion_is: p[:pers_religion_is],
pers_resembles_is: p[:pers_resembles_is],
pers_smoking_is: p[:pers_smoking_is],
pers_std_status_is: p[:pers_std_status_is],
pers_weight_is: p[:pers_weight_is],
pers_zodiac_is: p[:pers_zodiac_is]
}
attrs.delete_if { |_,v| v.nil? }
xml['cl'].personals(attrs)
end
# Helpers ###########
def check_postings_uniqness
names = @postings.map(&:name)
if names.length != names.uniq.length
log_error(MSG_NONUNIQ_POSTINGS, "Postings must have unique names")
end
end
def log_error(msg, value)
final_msg = "#{msg}: '#{value}'"
error = {
type: :general,
msg: final_msg
}
@errors << error
end
end # class
end # module
| mit |
pzdeb/SimpleCommander | src/simple_commander/game/init_game.py | 852 | #!/usr/bin/env python3
from simple_commander.game.game_controller import GameController
'''
In this game we have two role - invader and hero. Both can bullet.
Invaders are located at the top of game field and always move from the right side to the left and revert.
Also they slowly move to the bottom.
Main hero is located at the centre at the bottom. He can move to the left and to the right.
If he bullet some invader, his bonus is grow.
When invader bullet to main hero, the main hero's life is decrease.
'''
__game = None
def get_game(height=None, width=None, invaders_count=None):
global __game
if not __game and height and width and invaders_count is not None:
__game = GameController(height=height,
width=width,
invaders_count=invaders_count)
return __game | mit |
afdw/fastcloud | src/main/java/com/anton/fastcloud/client/FileSystemMain.java | 6348 | package com.anton.fastcloud.client;
import com.anton.fastcloud.natives.Natives;
import com.anton.fastcloud.bindings.FuseLibNative;
import com.anton.fastcloud.bindings.SystemNative;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Random;
@SuppressWarnings("OctalInteger")
public class FileSystemMain {
static {
Natives.init();
}
public static void main(String[] args) {
String[] fuseArgs = new String[args.length + 1];
fuseArgs[0] = "fastcloud";
System.arraycopy(args, 0, fuseArgs, 1, args.length);
String fileName = "hello";
byte[] fileContent = new byte[1 * 1024 * 1024 * 1024];
new Random().nextBytes(fileContent);
// byte[] fileContent = "Hello, World!\n".getBytes(StandardCharsets.UTF_8);
ByteBuffer fileContentBuffer = ByteBuffer.allocateDirect(fileContent.length);
fileContentBuffer.put(fileContent);
fileContentBuffer.position(0);
FuseLibNative.fuse_session fuse_session = FuseLibNative.fuse_session_new(
fuseArgs,
new FuseLibNative.fuse_lowlevel_ops() {
@Override
public void lookup(FuseLibNative.fuse_req_t req, long parent, String name) {
FuseLibNative.fuse_entry_param fuse_entry_param = new FuseLibNative.fuse_entry_param();
if (parent != 1 || !name.equals(fileName)) {
FuseLibNative.fuse_reply_err(req, SystemNative.ENOENT);
} else {
fuse_entry_param.ino = 2;
fuse_entry_param.attr_timeout = 1;
fuse_entry_param.entry_timeout = 1;
fuse_entry_param.attr.st_ino = fuse_entry_param.ino;
fuse_entry_param.attr.st_mode = SystemNative.S_IFREG | 0444;
fuse_entry_param.attr.st_nlink = 1;
fuse_entry_param.attr.st_size = fileContent.length;
FuseLibNative.fuse_reply_entry(req, fuse_entry_param);
}
}
@Override
public void getattr(FuseLibNative.fuse_req_t req, long ino, FuseLibNative.fuse_file_info fi) {
SystemNative.stat attr = new SystemNative.stat();
attr.st_ino = ino;
boolean found = false;
if (ino == 1) {
attr.st_mode = SystemNative.S_IFDIR | 0755;
attr.st_nlink = 2;
found = true;
}
if (ino == 2) {
attr.st_mode = SystemNative.S_IFREG | 0444;
attr.st_nlink = 1;
attr.st_size = fileContent.length;
found = true;
}
if (found) {
FuseLibNative.fuse_reply_attr(req, attr, 1);
} else {
FuseLibNative.fuse_reply_err(req, SystemNative.ENOENT);
}
}
@Override
public void open(FuseLibNative.fuse_req_t req, long ino, FuseLibNative.fuse_file_info fi) {
if (ino != 2) {
FuseLibNative.fuse_reply_err(req, SystemNative.EISDIR);
} else if ((fi.flags & 3) != SystemNative.O_RDONLY) {
FuseLibNative.fuse_reply_err(req, SystemNative.EACCES);
} else {
FuseLibNative.fuse_reply_open(req, fi);
}
}
@Override
public void read(FuseLibNative.fuse_req_t req, long ino, long size, long off, FuseLibNative.fuse_file_info fi) {
if (ino == 2) {
FuseLibNative.fuse_reply_bufNio(req, fileContentBuffer.slice().position((int) off), (int) size);
} else {
FuseLibNative.fuse_reply_err(req, SystemNative.ENOENT);
}
}
@Override
public void readdir(FuseLibNative.fuse_req_t req, long ino, long size, long off, FuseLibNative.fuse_file_info fi) {
if (ino != 1) {
FuseLibNative.fuse_reply_err(req, SystemNative.ENOTDIR);
} else {
String[] names = {".", "..", fileName};
int[] inos = {1, 1, 2};
int count = 3;
byte[] buffer = new byte[0];
for (long i = off; i < count; i++) {
byte[] entryBuf = new byte[(int) FuseLibNative.fuse_add_direntry(req, null, 0, names[(int) i], null, 0)];
if (buffer.length + entryBuf.length <= size) {
SystemNative.stat stat = new SystemNative.stat();
stat.st_ino = inos[(int) i];
FuseLibNative.fuse_add_direntry(req, entryBuf, entryBuf.length, names[(int) i], stat, i + 1);
byte[] newBuffer = Arrays.copyOf(buffer, buffer.length + entryBuf.length);
System.arraycopy(entryBuf, 0, newBuffer, buffer.length, entryBuf.length);
buffer = newBuffer;
} else {
break;
}
}
FuseLibNative.fuse_reply_buf(req, buffer.length == 0 ? null : buffer, buffer.length);
}
}
},
"123"
);
FuseLibNative.fuse_set_signal_handlers(fuse_session);
FuseLibNative.fuse_session_mount(fuse_session, fuseArgs);
FuseLibNative.fuse_session_loop(fuse_session);
FuseLibNative.fuse_session_unmount(fuse_session);
}
}
| mit |
jadesouth/xy001 | application/views/home/password/find.php | 2600 | <style>
.checkout-indicator {
display: inline-block;
float: left;
margin: 30px 0 0 30px;
}
</style>
<div class="main-content">
<div class="container">
<div class="text-center repwd" style="margin: 100px 0">
<input type="password" class="input-lg" placeholder="新密码" required name="password" id="password"/>
<input type="password" class="input-lg" placeholder="确认新密码" required name="password_confirmation"
id="password_confirmation"/>
<button type="button" class="btn btn-reset" title="" id="find">确定</button>
</div>
</div>
</div>
<div class="modal fade" id="foremail" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-body text-center">
<h5 style="padding:30px 0;">密码重置成功 <span></span></h5>
</div>
</div>
</div>
</div>
<script src="/resources/assets/js/home/jquery.min.js"></script>
<script src="/resources/assets/js/home/swiper-3.4.0.jquery.min.js"></script>
<script src="/resources/assets/js/home/bootstrap.min.js"></script>
<script src="/resources/assets/js/home/main.js"></script>
<script src="/resources/assets/libs/layui/layui.js" type="application/javascript"></script>
<script>
$(function () {
// 加载layer
layui.use('layer', function () {
var layer = layui.layer;
});
$('.btn-reset').on('click', function () {
var password = $('#password').val();
var password_confirmation = $('#password_confirmation').val();
$.ajax({
type: "POST",
url: "<?=$url?>",
data: {"password": password, "password_confirmation": password_confirmation},
dataType: "json",
success: function (response) {
if (0 == response.status) {
$("#foremail").modal("show");// 弹窗显示
setTimeout(function () {
$("#foremail").modal("hide");
window.location.href = '/';
}, 3000);//3秒后自动关闭
return;
} else if (1 == response.status) {
layer.alert(response.msg, {icon: 2});
return false;
}
}
});
});
})
</script>
</body>
</html> | mit |
waynemunro/orleans | src/Orleans.Runtime/Hosting/ISiloHostBuilder.cs | 3066 | using System;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Orleans.Hosting
{
/// <summary>
/// Functionality for building <see cref="ISiloHost"/> instances.
/// </summary>
public interface ISiloHostBuilder
{
/// <summary>
/// A central location for sharing state between components during the host building process.
/// </summary>
IDictionary<object, object> Properties { get; }
/// <summary>
/// Run the given actions to initialize the host. This can only be called once.
/// </summary>
/// <returns>An initialized <see cref="ISiloHost"/></returns>
ISiloHost Build();
/// <summary>
/// Sets up the configuration for the remainder of the build process and application. This can be called multiple times and
/// the results will be additive. The results will be available at <see cref="HostBuilderContext.Configuration"/> for
/// subsequent operations, as well as in <see cref="ISiloHost.Services"/>.
/// </summary>
/// <param name="configureDelegate">The delegate for configuring the <see cref="IConfigurationBuilder"/> that will be used
/// to construct the <see cref="IConfiguration"/> for the application.</param>
/// <returns>The same instance of the host builder for chaining.</returns>
ISiloHostBuilder ConfigureAppConfiguration(Action<HostBuilderContext, IConfigurationBuilder> configureDelegate);
/// <summary>
/// Adds services to the container. This can be called multiple times and the results will be additive.
/// </summary>
/// <param name="configureDelegate">The delegate for configuring the <see cref="IServiceCollection"/> that will be used
/// to construct the <see cref="IServiceProvider"/>.</param>
/// <returns>The same instance of the host builder for chaining.</returns>
ISiloHostBuilder ConfigureServices(Action<HostBuilderContext, IServiceCollection> configureDelegate);
/// <summary>
/// Overrides the factory used to create the service provider.
/// </summary>
/// <typeparam name="TContainerBuilder"></typeparam>
/// <param name="factory"></param>
/// <returns>The same instance of the host builder for chaining.</returns>
ISiloHostBuilder UseServiceProviderFactory<TContainerBuilder>(IServiceProviderFactory<TContainerBuilder> factory);
/// <summary>
/// Enables configuring the instantiated dependency container. This can be called multiple times and
/// the results will be additive.
/// </summary>
/// <typeparam name="TContainerBuilder"></typeparam>
/// <param name="configureDelegate"></param>
/// <returns>The same instance of the host builder for chaining.</returns>
ISiloHostBuilder ConfigureContainer<TContainerBuilder>(Action<HostBuilderContext, TContainerBuilder> configureDelegate);
}
} | mit |
julienaubert/clothstream | frontend/app/scripts/lib/repository.js | 13202 | require.register("scripts/repository", function(exports, require, module) {
// Simplify interacting with a restful resource: cache locally fetched objects, filters etc.
//
// How cache is handled:
// - fetch: assumes local cache is not dirty
// - force-fetch: assumes local cache is dirty
// - apply-filter: assumes local cache is dirty
// - when write to cache: object instance is invariant (i.e. use same object always and update its fields):
// var o1 = repo.fetch(1);
// var o1_again = repo.force_fetch(1);
// // o1 and o1_again are the same objects (i.e. o1 is updated)
// - create/delete: only writes to cache once received success from server
// - deleted objects are kept in cache with property _destroyed:
// makes it easy to subscribe to deletes,
// and, to maintain entity identity:
// obj = fetch pk 1,
// delete pk 1
// server creates pk 1 again,
// obj_again = force_fetch
// => obj===obj_again
//
// Main features:
// - simple to hookup to a json api (list_url, detail_url. action urls to be supported)
// - supports paging when reading lists
// - supports caching
// - memory efficient (by default, just store the returned json data, see on_init for making observables,
// note: deleted objects will remain in cache with one observable though)
// - easy hook-in to modify the objects (e.g. add fields or methods) (see on_init)
//
// Decision:
// - no "local-querying", this is a dumb repository
// (however, maybe: js code mocking django-queryset, serialize as a param and django-app deserialize this param
// into a queryset and return list:
// var qs = Query("User", "django.contrib.auth.models").filter(pk__in=[1,2]))
// qs_repo = repo.create_filter(qs)
// (deserializing must take white-listed models/fields for security though)
// - no "relations", you can set this up yourself in on_init
//
// TODO:
// - use promises!!
// - rename fetch to get / force_get
// - think about filters and when objects are created - currently filters are not affected at all
// create filters - take optional callback which is called each time a new object is added to its source-repo
// that way can decide if include in filter and where to insert it (consider eg "new collection" which now
// manually is added to user.collections - a filtered repo)
var pageLoader = require('scripts/pageLoader');
var req = require('scripts/req');
var FilteredRepo = function(repository, list_url, filter) {
// Represents a filtered resource (from list_url), the filter is the params in the list_url
// See repository.create_filter
//
// Shares cache with repository
// will write to local cache (subsequent fetch will be O(1))
// when loading filtered results, it will NOT read from local cache
//
// Decisions:
// - no caching on filter:
// it may be faster in some cases to instead say: hey server give me each id for this filter,
// then locally filter out all id's we already know and ask server for only that data we do not have.
// that case is likely vary rare (possibly for low bandwidth when client has built-up large local cache).
// we are however, *totally ignorant* of this case. the typical case is that the round-trip is expensive
// and client does not have that much of the resulting-filter in cache). to be ignorant makes it less
// complex
//
// Todo:
// - support cache filters, e.g. apply_filter(filter) and force_apply_filter(filter)
// so if ask apply same filter, will do e.g. self.objects(_filter_caches[hash_key_from_filter(filter)])
var self = this;
self.repo = repository;
self.objects = ko.observableArray([]);
var make_loader = function(filter) {
var loader = new pageLoader.Sequential(
20,
function(page_size, page) {
return list_url(page_size, page, filter);
},
function(props, page_loaded, data){
var i;
var objs = [];
for (i = 0; i < data.results.length; i++) {
objs.push(self.repo._update(data.results[i]));
}
ko.utils.arrayPushAll(self.objects, objs);
self.objects.valueHasMutated();
});
return loader;
}
self.loader = make_loader(filter);
self.load_until_entry= function(end_index) {
self.loader.loadUntilEntry(end_index);
};
self.fetch = repository.fetch;
self.force_fetch = repository.force_fetch;
self.apply_filter = function(filter) {
self.objects([]);
self.loader = make_loader(filter);
self.load_until_entry(20);
}
};
var Repository = function(spec) {
// Simplifies loading objects from a rest-api for read/delete purposes. Uses cache to avoid re-fetching.
// spec:
// list_url: function(page_size, page, filter) returning an url to a restful backend giving a list of objects
// detail_url: function(db_id) returning a url to a restful backend giving object with db_id
// create_url: function(data) returning a url to a restful backend (data is the data to be sent)
// delete_url: function(db_id) returning a url to a restful backend to POST delete to
// [on_init]: function(target) called exactly once, the first time when object is created (is optional),
// target is the object you should update, you can make fields observables, add methods, subscribe
// to your observables etc. If, after on_init the same object is fetched again
// (e.g. force_fecth or apply_filter), on_init will NOT be called. However, repository will check
// type of fields and if they are observables, it will write to them the new data, so you can get
// changes the normal way (by subscribing to the observables).
// repo_relations: key-value where key is field and value is a repository instance, this is used to ensure
// that nested-data is registered to other repositories as required.
// for example, if we have a collection repository, and a collection has an array of items
// where each item should be in an item_repository, then we declare:
// { items: item_repo }
// this repository will then ensure that item_repo.register(item_data) is called whenever
// a collection is updated.
//
// Note: use on_init to make observables, or add additional fields/methods, example:
// spec['on_init'] = function(target) {
// target.first_name = ko.observable(target.first_name);
// target.last_name = ko.observable(target.last_name);
// target.full_name = ko.computed(function() {
// return target.first_name() + ' ' + target.last_name();
// });
// }
// Note: each object has a _destroy ko.observable (delete will write true to it)
var self = this;
var _by_dbid = {}; // contains all objects ever loaded
var _prev_filter = {};
var _destroy_field = '_destroy';
spec.requests = spec.requests || {};
spec.requests.post = spec.requests.post || req.post;
spec.requests.put = spec.requests.put || req.put;
spec.requests.delete = spec.requests.delete || req.delete;
spec.requests.get = spec.requests.get || req.get;
self._delete = function(db_id) {
var target = _by_dbid[db_id];
target[_destroy_field](true);
};
self._update = function(data) {
// We need preserve identity, e.g., force_fetch(1) === force_fetch(1) must be an invariant.
// We guarantee this by always querying _by_dbid and making sure that an entry is created at most once.
// Subsequent updates only updates the object (does not recreate it).
// Since javascript is single-threaded, we do not need to consider re-entrance issues.
// I.e, while code is being executed in _update, there is no chance some other thread will re-enter it.
// Therefore, we need no locks, just simply check if _by_dbid[x] has been defined yet or not.
// There seems to be some cases where this is not exactly true:
// http://stackoverflow.com/questions/2734025/is-javascript-guaranteed-to-be-single-threaded
// however, _update does not by itself cause any dom-events, nor brings up any modal dialogs - so should be
// fine.
var initial = !_by_dbid[data.id];
_by_dbid[data.id] = _by_dbid[data.id] || {};
var target = _by_dbid[data.id],
field;
for (field in data) {
if (spec.repo_relations && spec.repo_relations[field]) {
var repo = spec.repo_relations[field];
if (data[field] instanceof Array) {
var i;
for (i = 0; i < data[field].length; ++i) {
data[field][i] = repo.register(data[field][i]);
}
} else {
data[field] = repo.register(data[field]);
}
}
if (ko.isWriteableObservable(target[field])) {
target[field](data[field]);
} else {
target[field] = data[field];
}
}
if (initial) {
target[_destroy_field] = ko.observable(false);
}
if (initial && spec.on_init) {
spec.on_init(target, data);
}
return target;
};
self.create_filter = function(filter) {
// returns a FilteredRepo, which shares cache with this repository
filter = filter || {};
return new FilteredRepo(self, spec.list_url, filter);
};
self.cached = function(db_id) {
return _by_dbid[db_id];
};
self.fetch = function(db_id, success, failure) {
// will read and write to local cache (re-fetching will be O(1))
if (_by_dbid[db_id]) {
if (_by_dbid[db_id][_destroy_field]()) {
if (failure) {
failure({status: 404});
}
} else {
if (success) {
success(_by_dbid[db_id]);
}
}
} else {
self.force_fetch(db_id, success, failure);
}
};
self.force_fetch = function(db_id, success, failure) {
// will write to local cache (always goes to detail_url to read)
spec.requests.get({
url: spec.detail_url(db_id),
success: function(result) {
self._update(result);
if (success) {
success(_by_dbid[db_id]);
}
},
error: function(jqXHR, textStatus, errorThrown) {
if (failure) {
failure({status:jqXHR.status})
}
}
});
};
self.register = function(obj_data) {
// normally should use `create` or `force_fetch`, this should only be used if you have a complete/correct
// json representation of the object (retrieved not via this repository) and you need to register it in this
// repository's cache.
// NOTE: use the returned object after calling, do not use the object 'obj_data'
self._update(obj_data);
return _by_dbid[obj_data.id];
};
self.create = function(data, callback) {
spec.requests.post(spec.create_url(data), JSON.stringify(data), function(result) {
self._update(result);
if (callback) {
callback(_by_dbid[result.id]);
}
});
};
self.delete = function(db_id, callback) {
// will write to _destroy observable
var success = function() {
self._delete(db_id);
if (callback) {
callback();
}
};
var error = function() {
};
spec.requests.delete(spec.delete_url(db_id), success, error);
};
};
exports.Repository = Repository;
});
| mit |
jweissman/roguecraft | lib/roguecraft/entity.rb | 659 | module Roguecraft
class Entity
include Minotaur::Geometry
include Navigation
# hmm, might as well start using 3d positions...?
attr_accessor :uuid
attr_accessor :position
attr_accessor :current_depth
def initialize(opts={})
@uuid = SecureRandom.uuid
@current_depth = 0
@name = opts.delete(:name) { 'unnamed' }
@position = opts.delete(:position) { Position.new(0,0) } # [0,0]
end
def move(direction)
@position = @position.translate(direction)
end
def x; @position.x end
def y; @position.y end
def x=(_x); position.x = _x end
def y=(_y); position.y = _y end
end
end
| mit |
sogyf/trial_examples | jasperreoprt-sample/src/test/java/jasperreport/utils/Test.java | 865 | package jasperreport.utils;
import net.sf.jasperreports.engine.JRQuery;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRStringUtil;
/**
* <p>
* .
* </p>
*
* @author poplar.yfyang
* @version 1.0 2013-01-05 4:52 PM
* @since JDK 1.5
*/
public class Test {
@org.junit.Test
public void testName() throws Exception {
JasperReport reportFile = JasperCompileManager.compileReport("/iflytek/erms/xc归档文件目录_二维表格.jrxml");
JRQuery jrQuery = reportFile.getQuery();
String language = jrQuery.getLanguage();
System.out.println(language);
System.out.println("");
String sql = jrQuery.getText();
System.out.println(sql);
System.out.println("");
String s1 = JRStringUtil.escapeJavaStringLiteral(sql);
System.out.println(s1);
}
}
| mit |
mlechler/Bewerbungscoaching | app/Http/Requests/Backend/UpdateEmployeeRequest.php | 3714 | <?php
namespace App\Http\Requests\Backend;
use App\Employee;
use Illuminate\Foundation\Http\FormRequest;
class UpdateEmployeeRequest extends FormRequest
{
protected $fileindex;
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$id = $this->route('employee');
$rules = [
'lastname' => ['required'],
'firstname' => ['required'],
'birthday' => ['required', 'date_format:Y-m-d'],
'phone' => ['required'],
'mobile' => ['required', 'unique:employees,mobile,' . $id],
'email' => ['required', 'email', 'unique:employees,email,' . $id],
'files' => ['array'],
'color' => ['required', 'unique:employees,color,' . $id],
'zip' => ['required'],
'city' => ['required'],
'street' => ['required'],
'housenumber' => ['required'],
'password' => ['required_with:password_confirmation', 'min:8', 'max:50', 'numbers', 'case_diff', 'letters', 'symbols', 'confirmed']
];
$files = $this->file('files');
if (!empty($files)) {
foreach ($files as $key => $file) // add individual rules to each image
{
$rules[sprintf('files.%d', $key)] = ['required', 'mimes:' . config('app.allowedFileTypes'), 'max:' . config('app.maxFileSize')];
$this->fileindex[] = [
sprintf('files.%d', $key) . '.required',
sprintf('files.%d', $key) . '.mimes',
sprintf('files.%d', $key) . '.max'
];
}
}
return $rules;
}
public function messages()
{
$messages = [
'lastname.required' => 'Lastname is required',
'firstname.required' => 'Firstname is required',
'birthday.required' => 'Birthday is required',
'phone.required' => 'Phone is required',
'mobile.required' => 'Mobile is required',
'mobile.unique' => 'Mobile has to be unique in Employees',
'email.required' => 'Email is required',
'email.unique' => 'Email has to be unique in Employees',
'email.email' => 'Email has to be a valid Email',
'color.required' => 'Color is required',
'color.unique' => 'Color has to be unique in Employees',
'zip.required' => 'Zip is required',
'city.required' => 'City is required',
'street.required' => 'Street is required',
'housenumber.required' => 'Housenumber is required',
'password.min' => 'Password has to have at least eight characters',
'password.max' => 'Password could have a maximum of 50 characters',
'password.numbers' => 'Password has to have at least one number',
'password.case_diff' => 'Password has to have upper and lower case letters',
'password.letters' => 'Password has to have at least one letter',
'password.symbols' => 'Password has to have at least one symbol',
'password.confirmed' => 'Password has to be confirmed'
];
if ($this->fileindex) {
foreach ($this->fileindex as $file) {
$messages[$file[0]] = 'File is required';
$messages[$file[1]] = 'Wrong Filetype';
$messages[$file[2]] = 'Filesize exceeded';
}
}
return $messages;
}
}
| mit |
disperse/ripping-yarns | module_system-1.166/module_particle_systems.py | 50082 | from header_particle_systems import *
#psf_always_emit = 0x0000000002
#psf_global_emit_dir = 0x0000000010
#psf_emit_at_water_level = 0x0000000020
#psf_billboard_2d = 0x0000000100 # up_vec = dir, front rotated towards camera
#psf_billboard_3d = 0x0000000200 # front_vec point to camera.
#psf_turn_to_velocity = 0x0000000400
#psf_randomize_rotation = 0x0000001000
#psf_randomize_size = 0x0000002000
#psf_2d_turbulance = 0x0000010000
####################################################################################################################
# Each particle system contains the following fields:
#
# 1) Particle system id (string): used for referencing particle systems in other files.
# The prefix psys_ is automatically added before each particle system id.
# 2) Particle system flags (int). See header_particle_systems.py for a list of available flags
# 3) mesh-name.
####
# 4) Num particles per second: Number of particles emitted per second.
# 5) Particle Life: Each particle lives this long (in seconds).
# 6) Damping: How much particle's speed is lost due to friction.
# 7) Gravity strength: Effect of gravity. (Negative values make the particles float upwards.)
# 8) Turbulance size: Size of random turbulance (in meters)
# 9) Turbulance strength: How much a particle is affected by turbulance.
####
# 10,11) Alpha keys : Each attribute is controlled by two keys and
# 12,13) Red keys : each key has two fields: (time, magnitude)
# 14,15) Green keys : For example scale key (0.3,0.6) means
# 16,17) Blue keys : scale of each particle will be 0.6 at the
# 18,19) Scale keys : time 0.3 (where time=0 means creation and time=1 means end of the particle)
#
# The magnitudes are interpolated in between the two keys and remain constant beyond the keys.
# Except the alpha always starts from 0 at time 0.
####
# 20) Emit Box Size : The dimension of the box particles are emitted from.
# 21) Emit velocity : Particles are initially shot with this velocity.
# 22) Emit dir randomness
# 23) Particle rotation speed: Particles start to rotate with this (angular) speed (degrees per second).
# 24) Particle rotation damping: How quickly particles stop their rotation
####################################################################################################################
particle_systems = [
("game_rain", psf_billboard_2d|psf_global_emit_dir|psf_always_emit, "prtcl_rain",
500, 0.5, 0.33, 1.0, 10.0, 0.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(1.0, 0.3), (1, 0.3), #alpha keys
(1.0, 1.0), (1, 1.0), #red keys
(1.0, 1.0), (1, 1.0), #green keys
(1.0, 1.0), (1, 1.0), #blue keys
(1.0, 1.0), (1.0, 1.0), #scale keys
(8.2, 8.2, 0.2), #emit box size
(0, 0, -10.0), #emit velocity
0.0, #emit dir randomness
0, #rotation speed
0.5 #rotation damping
),
("game_snow", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_size|psf_randomize_rotation, "prt_mesh_snow_fall_1",
150, 2, 0.2, 0.1, 30, 20, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.2, 1), (1, 1), #alpha keys
(1.0, 1.0), (1, 1.0), #red keys
(1.0, 1.0), (1, 1.0), #green keys
(1.0, 1.0), (1, 1.0), #blue keys
(1.0, 1.0), (1.0, 1.0), #scale keys
(10, 10, 0.5), #emit box size
(0, 0, -5.0), #emit velocity
1, #emit dir randomness
200, #rotation speed
0.5 #rotation damping
),
## ("game_blood", psf_billboard_3d|psf_randomize_size|psf_randomize_rotation, "prtcl_dust_a",
## 50, 0.65, 0.95, 1.0, 10.0, 0.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
## (0.3, 0.3), (1, 0.2), #alpha keys
## (1.0, 0.4), (1, 0.05), #red keys
## (1.0, 0.05),(1, 0.05), #green keys
## (1.0, 0.05),(1, 0.05), #blue keys
## (0.3, 0.5), (1.0, 2.5), #scale keys
## (0.04, 0.01, 0.01), #emit box size
## (0, 1, 0.0), #emit velocity
## 0.05, #emit dir randomness
## 0, #rotation speed
## 0.5 #rotation damping
## ),
##
("game_blood", psf_billboard_3d |psf_randomize_size|psf_randomize_rotation, "prt_mesh_blood_1",
500, 0.65, 3, 0.5, 0, 0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.0, 0.7), (0.7, 0.7), #alpha keys
(0.1, 0.7), (1, 0.7), #red keys
(0.1, 0.7), (1, 0.7), #green keys
(0.1, 0.7), (1, 0.7), #blue keys
(0.0, 0.015), (1, 0.018), #scale keys
(0, 0.05, 0), #emit box size
(0, 1.0, 0.3), #emit velocity
0.9, #emit dir randomness
0, #rotation speed
0, #rotation damping
),
("game_blood_2", psf_billboard_3d | psf_randomize_size|psf_randomize_rotation , "prt_mesh_blood_3",
2000, 0.6, 3, 0.3, 0, 0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.0, 0.25), (0.7, 0.1), #alpha keys
(0.1, 0.7), (1, 0.7), #red keys
(0.1, 0.7), (1, 0.7), #green keys
(0.1, 0.7), (1, 0.7), #blue keys
(0.0, 0.15), (1, 0.35), #scale keys
(0.01, 0.2, 0.01), #emit box size
(0.2, 0.3, 0), #emit velocity
0.3, #emit dir randomness
150, #rotation speed
0, #rotation damping
),
# ("game_hoof_dust", psf_billboard_3d|psf_randomize_size|psf_randomize_rotation, "prtcl_dust_a",
# 50, 1.0, 0.95, -0.1, 10.0, 0.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
# (0.0, 0.5), (1, 0.0), #alpha keys
# (1.0, 0.9), (1, 0.05), #red keys
# (1.0, 0.8),(1, 0.05), #green keys
# (1.0, 0.7),(1, 0.05), #blue keys
# (0.0, 7.5), (1.0, 15.5), #scale keys
# (0.2, 0.3, 0.2), #emit box size
# (0, 0, 2.5), #emit velocity
# 0.05, #emit dir randomness
# 100, #rotation speed
# 0.5 #rotation damping
# ),
("game_hoof_dust", psf_billboard_3d|psf_randomize_size|psf_randomize_rotation|psf_2d_turbulance, "prt_mesh_dust_1",#prt_mesh_dust_1
5, 2.0, 10, 0.05, 10.0, 39.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.2, 0.5), (1, 0.0), #alpha keys
(0, 1), (1, 1), #red keys
(0, 0.9),(1, 0.9), #green keys
(0, 0.78),(1, 0.78), #blue keys
(0.0, 2.0), (1.0, 3.5), #scale keys
(0.2, 0.3, 0.2), #emit box size
(0, 0, 3.9), #emit velocity
0.5, #emit dir randomness
130, #rotation speed
0.5 #rotation damping
),
("game_hoof_dust_snow", psf_billboard_3d|psf_randomize_size, "prt_mesh_snow_dust_1",#prt_mesh_dust_1
6, 2, 3.5, 1, 10.0, 0.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.2, 1), (1, 1), #alpha keys
(0, 1), (1, 1), #red keys
(0, 1),(1, 1), #green keys
(0, 1),(1, 1), #blue keys
(0.5, 4), (1.0, 5.7), #scale keys
(0.2, 1, 0.1), #emit box size
(0, 0, 1), #emit velocity
2, #emit dir randomness
0, #rotation speed
0 #rotation damping
),
("game_hoof_dust_mud", psf_billboard_2d|psf_randomize_size|psf_randomize_rotation|psf_2d_turbulance, "prt_mesh_mud_1",#prt_mesh_dust_1
5, .7, 10, 3, 0, 0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0, 1), (1, 1), #alpha keys
(0, .7), (1, .7), #red keys
(0, 0.6),(1, 0.6), #green keys
(0, 0.4),(1, 0.4), #blue keys
(0.0, 0.2), (1.0, 0.22), #scale keys
(0.15, 0.5, 0.1), #emit box size
(0, 0, 15), #emit velocity
6, #emit dir randomness
200, #rotation speed
0.5 #rotation damping
),
("game_water_splash_1", psf_billboard_3d|psf_randomize_size|psf_randomize_rotation|psf_emit_at_water_level, "prtcl_drop",
20, 0.85, 0.25, 0.9, 10.0, 0.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.3, 0.5), (1, 0.0), #alpha keys
(1.0, 1.0), (1, 1.0), #red keys
(1.0, 1.0), (1, 1.0), #green keys
(1.0, 1.0), (1, 1.0), #blue keys
(0.0, 0.3), (1.0, 0.18), #scale keys
(0.3, 0.2, 0.1), #emit box size
(0, 1.2, 2.3), #emit velocity
0.3, #emit dir randomness
50, #rotation speed
0.5 #rotation damping
),
("game_water_splash_2", psf_billboard_3d|psf_randomize_size|psf_randomize_rotation|psf_emit_at_water_level, "prtcl_splash_b",
30, 0.4, 0.7, 0.5, 10.0, 0.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.3, 1.0), (1, 0.3), #alpha keys
(1.0, 1.0), (1, 1.0), #red keys
(1.0, 1.0), (1, 1.0), #green keys
(1.0, 1.0), (1, 1.0), #blue keys
(0.0, 0.25), (1.0, 0.7), #scale keys
(0.4, 0.3, 0.1), #emit box size
(0, 1.3, 1.1), #emit velocity
0.1, #emit dir randomness
50, #rotation speed
0.5 #rotation damping
),
("game_water_splash_3", psf_emit_at_water_level , "prt_mesh_water_wave_1",
5, 2.0, 0, 0.0, 10.0, 0.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.03, 0.2), (1, 0.0), #alpha keys
(1.0, 1.0), (1, 1.0), #red keys
(1.0, 1.0), (1, 1.0), #green keys
(1.0, 1.0), (1, 1.0), #blue keys
(0.0, 3), (1.0, 10), #scale keys
(0.0, 0.0, 0.0), #emit box size
(0, 0, 0), #emit velocity
0.0, #emit dir randomness
0, #rotation speed
0.5 #rotation damping
),
("torch_fire", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_size|psf_randomize_rotation, "prt_mesh_fire_1",
50, 0.35, 0.2, 0.03, 10.0, 0.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.5, 0.8), (1, 0), #alpha keys
(0.5, 1.0), (1, 0.9), #red keys
(0.5, 0.7),(1, 0.3), #green keys
(0.5, 0.2), (1, 0.0), #blue keys
(0, 0.15), (0.4, 0.3), #scale keys
(0.04, 0.04, 0.01), #emit box size
(0, 0, 0.5), #emit velocity
0.0, #emit dir randomness
200, #rotation speed
0.5 #rotation damping
),
("fire_glow_1", psf_billboard_3d|psf_global_emit_dir|psf_always_emit, "prt_mesh_fire_2",
2, 0.55, 0.2, 0.0, 10.0, 0.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.5, 0.9), (1, 0), #alpha keys
(0.0, 0.9), (1, 0.9), #red keys
(0.0, 0.7),(1, 0.7), #green keys
(0.0, 0.4), (1, 0.4), #blue keys
(0, 2), (1.0, 2), #scale keys
(0.0, 0.0, 0.0), #emit box size
(0, 0, 0), #emit velocity
0.0, #emit dir randomness
0,
0
),
("fire_glow_fixed", psf_billboard_3d|psf_global_emit_dir, "prt_mesh_fire_2",
4, 100.0, 0.2, 0.0, 10.0, 0.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(-0.01, 1.0), (1, 1.0), #alpha keys
(0.0, 0.9), (1, 0.9), #red keys
(0.0, 0.7),(1, 0.7), #green keys
(0.0, 0.4), (1, 0.4), #blue keys
(0, 2), (1.0, 2), #scale keys
(0.0, 0.0, 0.0), #emit box size
(0, 0, 0), #emit velocity
0.0, #emit dir randomness
0,
0
),
("torch_smoke", psf_billboard_3d|psf_global_emit_dir|psf_always_emit, "prtcl_dust_a",
15, 0.5, 0.2, -0.2, 10.0, 0.1, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.5, 0.25), (1, 0), #alpha keys
(0.0, 0.2), (1, 0.1), #red keys
(0.0, 0.2),(1, 0.09), #green keys
(0.0, 0.2), (1, 0.08), #blue keys
(0, 0.5), (0.8, 2.5), #scale keys
(0.1, 0.1, 0.1), #emit box size
(0, 0, 1.5), #emit velocity
0.1 #emit dir randomness
),
("flue_smoke_short", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_rotation|psf_randomize_size, "prtcl_dust_a",
15, 1.5, 0.1, -0.0, 10.0, 12, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.0, 0.3), (1, 0), #alpha keys
(0.0, 0.2), (1, 0.1), #red keys
(0.0, 0.2),(1, 0.09), #green keys
(0.0, 0.2), (1, 0.08), #blue keys
(0, 1.5), (1, 7), #scale keys
(0, 0, 0), #emit box size
(0, 0, 1.5), #emit velocity
0.1, #emit dir randomness
150,
0.8,
),
("flue_smoke_tall", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_rotation|psf_randomize_size, "prtcl_dust_a",
15, 3, 0.5, -0.0, 15.0, 12,#num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0, 0.35), (1, 0), #alpha keys
(0.0, 0.3), (1, 0.1), #red keys
(0.0, 0.3),(1, 0.1), #green keys
(0.0, 0.3), (1, 0.1), #blue keys
(0, 2), (1, 7), #scale keys
(0, 0, 0), #emit box size
(0, 0, 1.5), #emit velocity
0.1, #emit dir randomness
150,
0.5,
),
("war_smoke_tall", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_rotation|psf_randomize_size, "prt_mesh_smoke_1",
5, 12, 0, 0, 7, 7, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0, 0.25), (1, 0), #alpha keys
(0.0, 1), (1, 0.8), #red keys
(0.0, 1),(1, 0.8), #green keys
(0.0, 1), (1, 0.8), #blue keys
(0, 2.2), (1, 15), #scale keys
(0, 0, 0), #emit box size
(0, 0, 2.2), #emit velocity
0.1, #emit dir randomness
100,
0.2,
),
("ladder_dust_6m", psf_billboard_3d, "prt_mesh_smoke_1",
700, 0.9, 0, 0, 7, 7, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0, 0.25), (1, 0), #alpha keys
(0.0, 1), (1, 0.8), #red keys
(0.0, 1),(1, 0.8), #green keys
(0.0, 1), (1, 0.8), #blue keys
(0, 1), (1, 2), #scale keys
(0.75, 0.75, 3.5), #emit box size (6.5 is equal to (12m / 2) + 0.5)
(0, 0, 0), #emit velocity
0.1, #emit dir randomness
100,
0.2,
),
("ladder_dust_8m", psf_billboard_3d, "prt_mesh_smoke_1",
900, 0.9, 0, 0, 7, 7, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0, 0.25), (1, 0), #alpha keys
(0.0, 1), (1, 0.8), #red keys
(0.0, 1),(1, 0.8), #green keys
(0.0, 1), (1, 0.8), #blue keys
(0, 1), (1, 2), #scale keys
(0.75, 0.75, 4.5), #emit box size (6.5 is equal to (12m / 2) + 0.5)
(0, 0, 0), #emit velocity
0.1, #emit dir randomness
100,
0.2,
),
("ladder_dust_10m", psf_billboard_3d, "prt_mesh_smoke_1",
1100, 0.9, 0, 0, 7, 7, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0, 0.25), (1, 0), #alpha keys
(0.0, 1), (1, 0.8), #red keys
(0.0, 1),(1, 0.8), #green keys
(0.0, 1), (1, 0.8), #blue keys
(0, 1), (1, 2), #scale keys
(0.75, 0.75, 5.5), #emit box size (6.5 is equal to (12m / 2) + 0.5)
(0, 0, 0), #emit velocity
0.1, #emit dir randomness
100,
0.2,
),
("ladder_dust_12m", psf_billboard_3d, "prt_mesh_smoke_1",
1300, 0.9, 0, 0, 7, 7, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0, 0.25), (1, 0), #alpha keys
(0.0, 1), (1, 0.8), #red keys
(0.0, 1),(1, 0.8), #green keys
(0.0, 1), (1, 0.8), #blue keys
(0, 1), (1, 2), #scale keys
(0.75, 0.75, 6.5), #emit box size (6.5 is equal to (12m / 2) + 0.5)
(0, 0, 0), #emit velocity
0.1, #emit dir randomness
100,
0.2,
),
("ladder_dust_14m", psf_billboard_3d, "prt_mesh_smoke_1",
1500, 0.9, 0, 0, 7, 7, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0, 0.25), (1, 0), #alpha keys
(0.0, 1), (1, 0.8), #red keys
(0.0, 1),(1, 0.8), #green keys
(0.0, 1), (1, 0.8), #blue keys
(0, 1), (1, 2), #scale keys
(0.75, 0.75, 7.5), #emit box size (7.5 is equal to (14m / 2) + 0.5)
(0, 0, 0), #emit velocity
0.1, #emit dir randomness
100,
0.2,
),
("ladder_straw_6m", psf_randomize_size | psf_randomize_rotation, "prt_mesh_straw_1",
700, 1, 2, 0.9, 10, 2, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.1, 1), (1, 1), #alpha keys
(0.1, 0.6), (1, 0.6), #red keys
(0.1, 0.5),(1, 0.5), #green keys
(0.1, 0.4), (1, 0.4), #blue keys
(0.0, 0.3), (1, 0.3), #scale keys
(0.75, 0.75, 3.5), #emit box size
(0, 0, 0), #emit velocity
2.3, #emit dir randomness
200, #rotation speed
0, #rotation damping
),
("ladder_straw_8m", psf_randomize_size | psf_randomize_rotation, "prt_mesh_straw_1",
900, 1, 2, 0.9, 10, 2, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.1, 1), (1, 1), #alpha keys
(0.1, 0.6), (1, 0.6), #red keys
(0.1, 0.5),(1, 0.5), #green keys
(0.1, 0.4), (1, 0.4), #blue keys
(0.0, 0.3), (1, 0.3), #scale keys
(0.75, 0.75, 4.5), #emit box size
(0, 0, 0), #emit velocity
2.3, #emit dir randomness
200, #rotation speed
0, #rotation damping
),
("ladder_straw_10m", psf_randomize_size | psf_randomize_rotation, "prt_mesh_straw_1",
1100, 1, 2, 0.9, 10, 2, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.1, 1), (1, 1), #alpha keys
(0.1, 0.6), (1, 0.6), #red keys
(0.1, 0.5),(1, 0.5), #green keys
(0.1, 0.4), (1, 0.4), #blue keys
(0.0, 0.3), (1, 0.3), #scale keys
(0.75, 0.75, 5.5), #emit box size
(0, 0, 0), #emit velocity
2.3, #emit dir randomness
200, #rotation speed
0, #rotation damping
),
("ladder_straw_12m", psf_randomize_size | psf_randomize_rotation, "prt_mesh_straw_1",
1300, 1, 2, 0.9, 10, 2, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.1, 1), (1, 1), #alpha keys
(0.1, 0.6), (1, 0.6), #red keys
(0.1, 0.5),(1, 0.5), #green keys
(0.1, 0.4), (1, 0.4), #blue keys
(0.0, 0.3), (1, 0.3), #scale keys
(0.75, 0.75, 6.5), #emit box size
(0, 0, 0), #emit velocity
2.3, #emit dir randomness
200, #rotation speed
0, #rotation damping
),
("ladder_straw_14m", psf_randomize_size | psf_randomize_rotation, "prt_mesh_straw_1",
1500, 1, 2, 0.9, 10, 2, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.1, 1), (1, 1), #alpha keys
(0.1, 0.6), (1, 0.6), #red keys
(0.1, 0.5),(1, 0.5), #green keys
(0.1, 0.4), (1, 0.4), #blue keys
(0.0, 0.3), (1, 0.3), #scale keys
(0.75, 0.75, 7.5), #emit box size
(0, 0, 0), #emit velocity
2.3, #emit dir randomness
200, #rotation speed
0, #rotation damping
),
("torch_fire_sparks", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_size, "prt_sparks_mesh_1",
10, 0.7, 0.2, 0, 10.0, 0.02, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.66, 1), (1, 0), #alpha keys
(0.1, 0.7), (1, 0.7), #red keys
(0.1, 0.5),(1, 0.5), #green keys
(0.1, 0.1), (1, 0.1), #blue keys
(0.1, 0.05), (1, 0.05), #scale keys
(0.1, 0.1, 0.1), #emit box size
(0, 0, 0.9), #emit velocity
0.0, #emit dir randomness
0,
0,
),
("fire_sparks_1", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_size, "prt_sparks_mesh_1",
10, 1.5, 0.2, 0, 3, 10, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.6, 1), (1, 1), #alpha keys
(0.1, 0.7), (1, 0.7), #red keys
(0.1, 0.5),(1, 0.5), #green keys
(0.1, 0.1), (1, 0.1), #blue keys
(0.1, 0.07), (1, 0.03), #scale keys
(0.17, 0.17, 0.01), #emit box size
(0, 0, 1), #emit velocity
0.0, #emit dir randomness
0,
0,
),
("pistol_smoke", psf_billboard_3d, "prtcl_dust_a",
90, 2.5, 0.6, -0.2, 60.0, 1.5, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.0, 0.75), (1, 0), #alpha keys
(0.0, 0.7), (1, 0.4), #red keys
(0.0, 0.7),(1, 0.4), #green keys
(0.0, 0.7), (1, 0.4), #blue keys
(0, 1.5), (0.5, 11.0), #scale keys
(0.1, 0.1, 0.1), #emit box size
(2, 2, 0), #emit velocity
0.1 #emit dir randomness
),
# ("cooking_fire", psf_billboard_3d|psf_global_emit_dir|psf_always_emit, "prtcl_fire",
# 50, 0.5, 0.2, -0.05, 30.0, 0.3, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
# (0.5, 1), (1, 1), #alpha keys
# (0.5, 1.0), (1, 0.9), #red keys
# (0.5, 0.4), (1, 0.1), #green keys
# (0.5, 0.2), (1, 0.0), #blue keys
# (0.3, 0.9), (0.9, 2), #scale keys
# (0.07, 0.07, 0.01), #emit box size
# (0, 0, 0.1), #emit velocity
# 0.1 #emit dir randomness
# ),
("brazier_fire_1", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_size|psf_randomize_rotation, "prt_mesh_fire_1",
25, 0.5, 0.1, 0.0, 10.0, 0.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.5, 0.4), (1.0, 0), #alpha keys
(0.5, 1.0), (1.0, 0.9), #red keys
(0.5, 0.7),(1.0, 0.3), #green keys
(0.5, 0.2), (1, 0.0), #blue keys
(0.1, 0.2), (1.0, 0.5), #scale keys
(0.1, 0.1, 0.01), #emit box size
(0.0, 0.0, 0.4), #emit velocity
0.0, #emit dir randomness
100, #rotation speed
0.2 #rotation damping
),
# ("cooking_smoke", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_rotation|psf_randomize_size, "prt_mesh_steam_1",
# 3, 3.5, 0.4, -0.03, 10.0, 10.9, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
# (0.4, 1), (1, 0), #alpha keys
# (0.0, 0.6), (1, 0.3), #red keys
# (0.0, 0.6),(1, 0.3), #green keys
# (0.0, 0.6), (1, 0.3), #blue keys
# (0, 2.5), (0.9, 7.5), #scale keys
# (0.1, 0.1, 0.06), #emit box size
# (0, 0, 1.3), #emit velocity
# 0.2, #emit dir randomness
# 200, #rotation speed
# 0.2, #rotation damping
# ),
("cooking_fire_1", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_size|psf_randomize_rotation, "prt_mesh_fire_1",
25, 0.35, 0.1, 0.03, 10.0, 0.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.5, 0.8), (1, 0), #alpha keys
(0.5, 0.5*1.0), (1, 0.3*0.9), #red keys
(0.5, 0.5*0.7),(1, 0.3*0.3), #green keys
(0.5, 0.5*0.2), (1, 0.0), #blue keys
(0.1, 0.5), (1, 1), #scale keys
(0.05, 0.05, 0.01), #emit box size
(0, 0, 1), #emit velocity
0.0, #emit dir randomness
200, #rotation speed
0.0 #rotation damping
),
("cooking_smoke", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_rotation|psf_randomize_size, "prt_mesh_smoke_1",
4, 4, 0.1, 0, 3, 5, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.2, 0.20), (1.0, 0.0), #alpha keys
(0.0, 0.8), (1.0, 1.0), #red keys
(0.0, 0.8),(1.0, 1.0), #green keys
(0.0, 0.85), (1.0, 1.0), #blue keys
(0.0, 0.65), (1.0, 3.0), #scale keys
(0.0, 0.0, 0.0), #emit box size
(0.0, 0.0, 1.2), #emit velocity
0.0, #emit dir randomness
0,
0,
),
("food_steam", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_rotation|psf_randomize_size, "prt_mesh_steam_1",
3, 1, 0, 0, 8.0, 1, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.5, 0.1), (1, 0), #alpha keys
(0.0, 1), (1, 0.1), #red keys
(0.0, 1),(1, 0.1), #green keys
(0.0, 1), (1, 0.1), #blue keys
(0, 0.2), (0.9, 0.5), #scale keys
(0.05, 0.05, 0), #emit box size
(0, 0, 0.1), #emit velocity
0, #emit dir randomness
100, #rotation speed
0.5, #rotation damping
),
("candle_light", psf_billboard_3d|psf_global_emit_dir|psf_always_emit, "prt_mesh_candle_fire_1",
7, 1.1, 0.6, -0.0, 10.0, 0.2, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.1, 0.5), (1, 0), #alpha keys
(0.5, 1.0), (1, 0.9), #red keys
(0.5, 0.6), (1, 0.1), #green keys
(0.5, 0.2), (1, 0.0), #blue keys
(0.3, 0.2), (1, 0.0), #scale keys
(0.0, 0.0, 0.0), #emit box size
(0, 0, 0.09), #emit velocity
0, #emit dir randomness
0, #rotation speed
0 #rotation damping
),
("candle_light_small", psf_billboard_3d|psf_global_emit_dir|psf_always_emit, "prt_mesh_candle_fire_1",
4, 1.1, 0.6, -0.0, 10.0, 0.2, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.1, 0.8), (1, 0), #alpha keys
(0.5, 1.0), (1, 0.9), #red keys
(0.5, 0.6), (1, 0.1), #green keys
(0.5, 0.2), (1, 0.0), #blue keys
(0.3, 0.13), (1, 0.0), #scale keys
(0.0, 0.0, 0.0), #emit box size
(0, 0, 0.06), #emit velocity
0, #emit dir randomness
0, #rotation speed
0 #rotation damping
),
("lamp_fire", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_rotation|psf_randomize_size, "prt_mesh_fire_1",
10, 0.8, 0.6, -0.0, 10.0, 0.4, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.1, 0.5), (1, 0), #alpha keys
(0.5, 1.0), (1, 0.9), #red keys
(0.5, 0.8), (1, 0.1), #green keys
(0.5, 0.4), (1, 0.0), #blue keys
(0.3, 0.35), (0.9, 0.5), #scale keys
(0.01, 0.01, 0.0), #emit box size
(0, 0, 0.35), #emit velocity
0.03, #emit dir randomness
100, #rotation speed
0.5, #rotation damping
),
#*-*-*-*-* D U M M Y *-*-*-*-#
("dummy_smoke", psf_billboard_3d|psf_randomize_size, "prt_mesh_dust_1",
500, 3, 15, -0.05, 10.0, 0.2, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.1, 0.5), (1, 0), #alpha keys
(0.1, 0.8), (1, 0.8), #red keys
(0.1, 0.7),(1, 0.7), #green keys
(0.1, 0.6), (1, 0.7), #blue keys
(0.0, 0.7), (1, 2.2), #scale keys
(0.2, 0.2, 0.5), #emit box size
(0, 0, 0.05), #emit velocity
2, #emit dir randomness
10, #rotation speed
0.1, #rotation damping
),
("dummy_straw", psf_randomize_size | psf_randomize_rotation, "prt_mesh_straw_1",
500, 1, 2, 0.9, 10, 2, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.1, 1), (1, 1), #alpha keys
(0.1, 0.6), (1, 0.6), #red keys
(0.1, 0.5),(1, 0.5), #green keys
(0.1, 0.4), (1, 0.4), #blue keys
(0.0, 0.3), (1, 0.3), #scale keys
(0.2, 0.2, 0.5), #emit box size
(0, 0, 0), #emit velocity
2.3, #emit dir randomness
200, #rotation speed
0, #rotation damping
),
("dummy_smoke_big", psf_billboard_3d|psf_randomize_size, "prt_mesh_dust_1",
500, 9, 15, -0.05, 10.0, 0.2, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.1, 0.9), (1, 0), #alpha keys
(0.1, 0.8), (1, 0.8), #red keys
(0.1, 0.7),(1, 0.7), #green keys
(0.1, 0.6), (1, 0.7), #blue keys
(0.0, 5), (1, 15.0), #scale keys
(3, 3, 5), #emit box size
(0, 0, 0.05), #emit velocity
2, #emit dir randomness
10, #rotation speed
0.1, #rotation damping
),
("dummy_straw_big", psf_randomize_size | psf_randomize_rotation, "prt_mesh_straw_1",
500, 3, 2, 2.0, 10, 2, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.1, 1), (1, 1), #alpha keys
(0.1, 0.6), (1, 0.6), #red keys
(0.1, 0.5),(1, 0.5), #green keys
(0.1, 0.4), (1, 0.4), #blue keys
(0.0, 0.8), (1, 0.8), #scale keys
(3, 3, 3), #emit box size
(0, 0, 0), #emit velocity
2.3, #emit dir randomness
200, #rotation speed
0, #rotation damping
),
#*-*-*-*-* D U M M Y E N D *-*-*-*-#
#*-*-*-*-* GOURD *-*-*-*-#
("gourd_smoke", psf_billboard_3d|psf_randomize_size, "prt_mesh_dust_1",
500, 3, 15, -0.05, 10.0, 0.2, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.1, 0.5), (1, 0), #alpha keys
(0.1, 0.8), (1, 0.8), #red keys
(0.1, 0.7),(1, 0.7), #green keys
(0.1, 0.6), (1, 0.7), #blue keys
(0.0, 0.5), (1, 1), #scale keys
(0.2, 0.2, 0.5), #emit box size
(0, 0, 0.05), #emit velocity
2, #emit dir randomness
10, #rotation speed
0.1, #rotation damping
),
("gourd_piece_1", psf_randomize_rotation, "prt_gourd_piece_1",
15, 1, 2, 0.9, 10, 2, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.1, 1), (1, 1), #alpha keys
(0.1, 0.6), (1, 0.6), #red keys
(0.1, 0.5),(1, 0.5), #green keys
(0.1, 0.4), (1, 0.4), #blue keys
(0.0, 1), (1, 1), #scale keys
(0.2, 0.2, 0.5), #emit box size
(0, 0, 0), #emit velocity
2.3, #emit dir randomness
200, #rotation speed
0, #rotation damping
),
("gourd_piece_2", psf_randomize_size | psf_randomize_rotation, "prt_gourd_piece_2",
50, 1, 2, 0.9, 10, 2, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.1, 1), (1, 1), #alpha keys
(0.1, 0.6), (1, 0.6), #red keys
(0.1, 0.5),(1, 0.5), #green keys
(0.1, 0.4), (1, 0.4), #blue keys
(0.0, 1), (1, 1), #scale keys
(0.2, 0.2, 0.5), #emit box size
(0, 0, 0), #emit velocity
2.3, #emit dir randomness
200, #rotation speed
0, #rotation damping
),
## ("rat_particle", psf_global_emit_dir|psf_2d_turbulance | psf_randomize_size |psf_billboard_3d, "rat_particle",
## 500, 4, 0, 0, 20, 10, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
## (0.1, 1), (1, 1), #alpha keys
## (0.1, 0.6), (1, 0.6), #red keys
## (0.1, 0.5),(1, 0.5), #green keys
## (0.1, 0.4), (1, 0.4), #blue keys
## (0.1, 1), (1, 1), #scale keys
## (0.1, 0.1, 0.1), #emit box size
## (0, 0, 0), #emit velocity
## 5, #emit dir randomness
## ),
#*-*-*-**** BLOOD ****-*-*-*#
##("blood_hit_1", psf_billboard_3d | psf_randomize_size , "prt_mesh_blood_1",
## 5000, 0.5, 6, 0.5, 0, 0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
## (0.1, 1), (1, 0), #alpha keys
## (0.1, 0.6), (1, 0.6), #red keys
## (0.1, 0.5),(1, 0.5), #green keys
## (0.1, 0.4), (1, 0.4), #blue keys
## (0.0, 0.05), (1, 0.05), #scale keys
## (0, 0.5, 0), #emit box size
## (0, -1, 0), #emit velocity
## 1.5, #emit dir randomness
## 0, #rotation speed
## 0, #rotation damping
## ),
## #("blood_hit_2", 0 , "prt_mesh_blood_2",
## # 500, 0.3, 0,0, 0, 0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
## # (0.1, 1), (1, 0.0), #alpha keys
## # (0.1, 0.6), (1, 0.6), #red keys
## # (0.1, 0.5),(1, 0.5), #green keys
## # (0.1, 0.4), (1, 0.4), #blue keys
## # (0.0, 0.4), (1, 2), #scale keys
## # (0.0, 0.0, 0.0), #emit box size
## # (0, -0.1, 0), #emit velocity
## # 0, #emit dir randomness
## # 0, #rotation speed
## # 0, #rotation damping
## # ),
## ("blood_hit_3", psf_billboard_3d | psf_randomize_size , "prt_mesh_blood_3",
## 500, 0.3, 1,0.0, 0, 0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
## (0.1, 1), (1, 0.0), #alpha keys
## (0.1, 0.6), (1, 0.6), #red keys
## (0.1, 0.5),(1, 0.5), #green keys
## (0.1, 0.4), (1, 0.4), #blue keys
## (0.0, 0.2), (1, 0.8), #scale keys
## (0.0, 0.3, 0.0), #emit box size
## (0, 1, 0), #emit velocity
## 1, #emit dir randomness
## 250, #rotation speed
## 0, #rotation damping
## ),
#*-*-*-**** BLOOD END ****-*-*-*#
#-*-*-*- Fire Fly Deneme *-*-*-*-#
("fire_fly_1", psf_billboard_3d|psf_global_emit_dir|psf_always_emit, "prt_sparks_mesh_1",
2, 5, 1.2, 0, 50, 7, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.1, 0.8), (1, 0.2), #alpha keys
(0.5, .7), (1, 0.7), #red keys
(0.5, 0.8), (1, 0.8), #green keys
(0.5, 1), (1, 1), #blue keys
(0, 0.1), (1, 0.1), #scale keys
(20, 20, 0.5), #emit box size
(0, 0, 0), #emit velocity
5, #emit dir randomness
0, #rotation speed
0 #rotation damping
),
("bug_fly_1", psf_billboard_2d | psf_always_emit, "prt_mesh_rose_a",
20, 8, 0.02, 0.025, 1, 5, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0, 1), (1, 1), #alpha keys
(0, 0.5), (1, 0.5), #red keys
(0, 0.5), (1, 0.5), #green keys
(0, 0.5), (1, 0.5), #blue keys
(0, 0.25), (1, 0.25), #scale keys
(10, 5, 0.1), #emit box size
(0, 0, -0.9), #emit velocity
0.01, #emit dir randomness
10, #rotation speed
0, #rotation damping
),
#-*-*-*- Fire Fly End*-*-*-*-#
#-*-*-*- Moon Beam *-*-*-*-*-*-*#
("moon_beam_1", psf_billboard_2d|psf_global_emit_dir|psf_always_emit|psf_randomize_size, "prt_mesh_moon_beam",#prt_mesh_moon_beam
2, 4, 1.2, 0, 0, 0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.5, 1), (1, 0), #alpha keys
(0, 0.4), (1, 0.4), #red keys
(0, 0.5), (1, 0.5), #green keys
(0, 0.6), (1, 0.6), #blue keys
(0, 2), (1, 2.2), #scale keys
(1, 1, 0.2), #emit box size
(0, 0, -2), #emit velocity
0, #emit dir randomness
100, #rotation speed
0.5, #rotation damping
),
("moon_beam_paricle_1", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_size, "prt_sparks_mesh_1",
10, 1.5, 1.5, 0, 10, 10, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.5, 1), (1, 0.0), #alpha keys
(0.5, .5), (1, 0.5), #red keys
(0.5, 0.7), (1, 0.7), #green keys
(0.5, 1), (1, 1), #blue keys
(0, 0.1), (1, 0.1), #scale keys
(1, 1, 4), #emit box size
(0, 0, 0), #emit velocity
0.5, #emit dir randomness
0, #rotation speed
0 #rotation damping
),
#-*-*-*- Moon Beam End *-*-*-*-*-*-*#
#-*-*-*- Stone Smoke *-*-*-*-*-*-*#
##("stone_hit_1", psf_billboard_3d | psf_randomize_size | psf_randomize_rotation, "prt_mesh_dust_1",
## 5000, 0.5, 6, 0.1, 0, 0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
## (0.1, .2), (1, 0), #alpha keys
## (0.5, 0.7), (1, 0.7), #red keys
## (0.5, 0.6), (1, 0.6), #green keys
## (0.5, 0.6), (1, 0.6), #blue keys
## (0.0, .2), (1, 0.7), #scale keys
## (0, 0.3, 0), #emit box size
## (0, 0, 0), #emit velocity
## 1.1, #emit dir randomness
## 200, #rotation speed
## 0.8, #rotation damping
## ),
#-*-*-*- Stone Smoke END -*-*-*-*-*#
("night_smoke_1", psf_billboard_3d|psf_global_emit_dir|psf_always_emit, "prt_mesh_dust_1",
5, 10, 1.5, 0, 50, 2, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.3, 0.1), (1, 0), #alpha keys
(0.5, 0.5), (1, 0.5), #red keys
(0.5, 0.5), (1, 0.5), #green keys
(0.5, 0.5), (1, 0.6), #blue keys
(0, 10), (1, 10), #scale keys
(25, 25, 0.5), #emit box size
(0, 1, 0), #emit velocity
2, #emit dir randomness
20, #rotation speed
1 #rotation damping
),
#-*-*-*- Fire For Fireplace -*-*-*-#
("fireplace_fire_small", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_size|psf_randomize_rotation, "prt_mesh_fire_1",
25, 0.8, 0.2, -0.1, 10.0, 0.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.5, 0.5), (1, 0), #alpha keys
(0.5, 1.0), (1, 0.9), #red keys
(0.5, 0.7),(1, 0.3), #green keys
(0.5, 0.2), (1, 0.0), #blue keys
(0, 0.2), (1, 0.7), #scale keys
(0.2, 0.1, 0.01), #emit box size
(0, 0, 0.2), #emit velocity
0.1, #emit dir randomness
100, #rotation speed
0.5 #rotation damping
),
("fireplace_fire_big", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_size|psf_randomize_rotation, "prt_mesh_fire_1",
35, 0.6, 0.2, -0.2, 10.0, 0.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.5, 0.5), (1, 0), #alpha keys
(0.5, 1.0), (1, 0.9), #red keys
(0.5, 0.7),(1, 0.3), #green keys
(0.5, 0.2), (1, 0.0), #blue keys
(0, 0.4), (1, 1), #scale keys
(0.4, 0.2, 0.01), #emit box size
(0, 0, 0.4), #emit velocity
0.1, #emit dir randomness
100, #rotation speed
0.5 #rotation damping
),
#-*-*-*- Fire For Fireplace -*-*-*-#
#-*-*-*- Village Fire *-*-*-*-#
("village_fire_big", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_size|psf_randomize_rotation, "prt_mesh_fire_1",
50, 1.0, 0, -1.2, 25.0, 10.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.2, 0.7), (1, 0), #alpha keys
(0.2, 1.0), (1, 0.9), #red keys
(0.2, 0.7),(1, 0.3), #green keys
(0.2, 0.2), (1, 0.0), #blue keys
(0, 2), (1, 6), #scale keys
(2.2, 2.2, 0.2), #emit box size
(0, 0, 0.0), #emit velocity
0.0, #emit dir randomness
250, #rotation speed
0.3 #rotation damping
),
("village_fire_smoke_big", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_size|psf_randomize_rotation, "prt_mesh_smoke_1",
30, 2, 0.3, -1, 50.0, 10.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.5, 0.15), (1, 0), #alpha keys
(0.2, 0.4), (1, 0.2), #red keys
(0.2, 0.4),(1, 0.2), #green keys
(0.2, 0.4), (1, 0.2), #blue keys
(0, 6), (1, 8), #scale keys
(2, 2, 1), #emit box size
(0, 0, 5), #emit velocity
0.0, #emit dir randomness
0, #rotation speed
0.1 #rotation damping
),
("map_village_fire", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_size|psf_randomize_rotation, "prt_mesh_fire_1",
20, 1.0, 0, -0.2, 3.0, 3.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.2, 0.7), (1, 0), #alpha keys
(0.2, 1.0), (1, 0.9), #red keys
(0.2, 0.7),(1, 0.3), #green keys
(0.2, 0.2), (1, 0.0), #blue keys
(0, 0.15), (1, 0.45), #scale keys
(0.2, 0.2, 0.02), #emit box size
(0, 0, 0.0), #emit velocity
0.0, #emit dir randomness
250, #rotation speed
0.3 #rotation damping
),
("map_village_fire_smoke", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_size|psf_randomize_rotation, "prt_mesh_smoke_1",
25, 2.5, 0.3, -0.15, 3.0, 3.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.5, 0.15), (1, 0), #alpha keys
(0.2, 0.4), (1, 0.3), #red keys
(0.2, 0.4),(1, 0.3), #green keys
(0.2, 0.4), (1, 0.3), #blue keys
(0, 0.6), (1, 0.9), #scale keys
(0.2, 0.2, 0.1), #emit box size
(0, 0, 0.03), #emit velocity
0.0, #emit dir randomness
0, #rotation speed
0.1 #rotation damping
),
("map_village_looted_smoke", psf_billboard_3d|psf_global_emit_dir|psf_always_emit|psf_randomize_size|psf_randomize_rotation, "prt_mesh_smoke_1",
20, 3, 0.3, -0.11, 3.0, 2.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.5, 0.15), (1, 0), #alpha keys
(0.2, 0.5), (1, 0.5), #red keys
(0.2, 0.5),(1, 0.5), #green keys
(0.2, 0.5), (1, 0.5), #blue keys
(0, 0.7), (1, 1.3), #scale keys
(0.2, 0.2, 0.1), #emit box size
(0, 0, 0.015), #emit velocity
0.0, #emit dir randomness
0, #rotation speed
0.1 #rotation damping
),
##### Dungeon Water Drops #####
("dungeon_water_drops", psf_billboard_2d|psf_global_emit_dir|psf_always_emit, "prtcl_rain",
1, 1, 0.33, 0.8, 0, 0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(1.0, 0.2), (1, 0.2), #alpha keys
(1.0, 1.0), (1, 1.0), #red keys
(1.0, 1.0), (1, 1.0), #green keys
(1.0, 1.0), (1, 1.0), #blue keys
(1.0, 0.8), (1.0, 0.8), #scale keys
(0.05, 0.05, 0.5), #emit box size
(0, 0, -5.0), #emit velocity
0.0, #emit dir randomness
0, #rotation speed
0, #rotation damping
),
##### Dungeon Water Drops END #####
("wedding_rose", psf_billboard_2d | psf_always_emit, "prt_mesh_rose_a",
50, 8, 0.02, 0.025, 1, 5, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0, 1), (1, 1), #alpha keys
(0, 0.5), (1, 0.5), #red keys
(0, 0.5), (1, 0.5), #green keys
(0, 0.5), (1, 0.5), #blue keys
(0, 0.25), (1, 0.25), #scale keys
(4, 4, 0.1), #emit box size
(0, 0, -0.9), #emit velocity
0.01, #emit dir randomness
10, #rotation speed
0, #rotation damping
),
("sea_foam_a", psf_turn_to_velocity | psf_always_emit|psf_randomize_size, "prt_foam_a",
1, 3.0, 1, 0.0, 0.0, 0.0, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0.7, 0.1), (1, 0.0), #alpha keys
(1.0, 1.0), (1, 1.0), #red keys
(1.0, 1.0), (1, 1.0), #green keys
(1.0, 1.0), (1, 1.0), #blue keys
(0.0, 4), (1.0, 4.5), #scale keys
(10.0, 1.0, 0), #emit box size
(0, 1, 0), #emit velocity
0.0, #emit dir randomness
0, #rotation speed
0.5 #rotation damping
),
("fall_leafs_a", psf_billboard_2d | psf_always_emit, "prt_mesh_yrellow_leaf_a",
1, 9, 0, 0.025, 4, 4, #num_particles, life, damping, gravity_strength, turbulance_size, turbulance_strength
(0, 1), (1, 1), #alpha keys
(0, 0.5), (1, 0.5), #red keys
(0, 0.5), (1, 0.5), #green keys
(0, 0.5), (1, 0.5), #blue keys
(0, 0.25), (1, 0.25), #scale keys
(4, 4, 4), #emit box size
(0, 0.01, -0.9), #emit velocity
0.02, #emit dir randomness
15, #rotation speed
0, #rotation damping
),
]
| mit |
sonnym/gourdian | test/unit/ext/sync.js | 281 | var ext = require("./../../../lib/ext");
exports.wait_for = function(test) {
var condition = false;
Gourdian.ext.Sync.wait_for(function() { return condition }, function() {
test.ok(condition);
test.done();
});
setTimeout(function() { condition = true; }, 20);
}
| mit |
gracianani/PntMinisite | js/main.js | 23819 | requirejs.config({
//By default load any module IDs from js/lib
'baseUrl': 'js/vendor'
});
var app = {
Models: {},
Views: {},
User: {},
weiboApp: {
authorize_uri: 'https://api.weibo.com/oauth2/authorize',
app_id: '3695496477',
app_secret: '942214d88b57723ad419854c67d3c49c',
redirect_uri: 'http://pantene.app.social-touch.com/'
},
qqApp: {
authorize_uri: 'https://api.weibo.com/oauth2/authorize',
app_id:'100516646',
app_key:'6b346735b25a53425c4eda8e41553e96',
redirect_uri: 'http://pantene.app.social-touch.com/qc_callback.html'
},
Settings: {
isMobile: false,
click: "click",
mouseenter : "mouseenter",
mouseleave : "mouseleave",
clickSplashLogin : false
}
};
window.AppFacade = {
maxSceneId: 0,
init: function () {
if (typeof app.Views.BasicFrameView == 'undefined') {
this.initLoading();
}
if (isMobile()) {
app.Settings.isMobile = true;
app.Settings.click = "touchstart";
app.Settings.mouseenter = "touchstart";
app.Settings.mouseleave = "touchend";
}
if ( supportsSvg()) {
app.Settings.supportsSvg = true;
} else {
app.Settings.supportsSvg = false;
}
},
setStartView: function () {
var isStartFromSplash = false;
if (this.currentView == undefined) {
isStartFromSplash = true;
} else if (typeof (app.ReportId) == 'undefined' && !app.Views.BasicInfoView.model.isAnswered(22)) {
isStartFromSplash = true;
}
if (isStartFromSplash) {
this.initSplash();
} else {
this.initBasicFrame();
}
},
initLoading: function () {
app.Views.LoadingView = new LoadingView();
},
initSplash: function () {
app.Views.SplashView = new SplashView();
},
initBasicFrame: function () {
app.Views.BasicFrameView = new BasicFrameView();
},
exitLoading: function () {
app.Views.LoadingView.onExitLoading();
},
getMaxFinishedSceneId: function () {
if (this.maxSceneId > 0) {
return this.maxSceneId;
}
var index = 0;
for (index in app.SceneViews) {
if (app.SceneViews[index].model) {
if (app.SceneViews[index].model.isSceneFinished().length > 0) {
this.maxSceneId = parseInt(index) + 1;
return this.maxSceneId;
}
}
}
this.maxSceneId = parseInt(index) + 1;
return this.maxSceneId;
},
getCurrentSceneId: function () {
var id = 1;
if (typeof (this.getCurrentView()) !== 'undefined' && this.getCurrentView().model && this.getCurrentView().model.get('scene_id')) {
id = parseInt(this.getCurrentView().model.get('scene_id'));
}
return id;
},
setCurrentView: function (view) {
this.currentView = view;
},
getCurrentView: function () {
return this.currentView;
},
getUserAnswers: function () {
var user_answers = [];
user_answers.push({ scene_id: '1', user_answers: app.Views.BasicInfoView.model.get("user_answers") });
user_answers.push({ scene_id: '2', user_answers: app.Views.HairStyleView.model.get("user_answers") });
user_answers.push({ scene_id: '3', user_answers: app.Views.HairQualityView.model.get("user_answers") });
user_answers.push({ scene_id: '4', user_answers: app.Views.LifeView.model.get("user_answers") });
user_answers.push({ scene_id: '5', user_answers: app.Views.HealthView.model.get("user_answers") });
user_answers.push({ scene_id: '6', user_answers: app.Views.DietView.model.get("user_answers") });
user_answers.push({ scene_id: '7', user_answers: app.Views.CleaningView.model.get("user_answers") });
user_answers.push({ scene_id: '8', user_answers: app.Views.SalonView.model.get("user_answers") });
return user_answers;
},
setUserAnswers: function (user_answers) {
for (var i = 0; i < user_answers.length; i++) {
var user_answer = user_answers[i];
if (user_answer.scene_id == 1) {
app.Views.BasicInfoView.model.set("user_answers", user_answer.user_answers);
}
else if (user_answer.scene_id == 2) {
app.Views.HairStyleView.model.set("user_answers", user_answer.user_answers);
}
else if (user_answer.scene_id == 3) {
app.Views.HairQualityView.model.set("user_answers", user_answer.user_answers);
}
else if (user_answer.scene_id == 4) {
app.Views.LifeView.model.set("user_answers", user_answer.user_answers);
}
else if (user_answer.scene_id == 5) {
app.Views.HealthView.model.set("user_answers", user_answer.user_answers);
}
else if (user_answer.scene_id == 6) {
app.Views.DietView.model.set("user_answers", user_answer.user_answers);
}
else if (user_answer.scene_id == 7) {
app.Views.CleaningView.model.set("user_answers", user_answer.user_answers);
}
else if (user_answer.scene_id == 8) {
app.Views.SalonView.model.set("user_answers", user_answer.user_answers);
}
}
},
saveToCookie: function () {
var user_answers = this.getUserAnswers();
var str_user_answers = JSON.stringify(user_answers);
createCookie("user_answers", str_user_answers, 14);
var current_scene_id = AppFacade.getCurrentView().model.get("scene_id");
createCookie("current_scene_id", current_scene_id, 14);
var user_info = app.User;
var str_user_info = JSON.stringify(user_info);
createCookie("current_user_info", str_user_info, 14);
},
loadFromCookie: function (isTrigger) {
var str_user_answers = readCookie("user_answers");
if (str_user_answers) {
this.setUserAnswers($.parseJSON(str_user_answers));
var current_scene_id = readCookie("current_scene_id");
var str_user_info = readCookie("user_info");
if (str_user_info) {
var user_info = $.parseJSON(str_user_info);
if ( user_info ) {
app.User = user_info;
}
}
var startScene = this.getCurrentSceneId();
this.maxScene = this.getMaxFinishedSceneId();
if (startScene > this.maxScene) {
app.Router.navigate("Survey/" + this.maxScene, { trigger: isTrigger });
}
}
else {
app.Router.navigate("", { trigger: isTrigger });
}
},
initSplashLogin: function () {
QC.Login({//按默认样式插入QQ登录按钮
btnId: "splash-qq",
size: "A_L"
},
window.AppFacade.onQQLoginSuccess, window.AppFacade.onQQLogoutSuccess);
WB2.anyWhere(function (W) {
W.widget.connectButton({
id: "splash-weibo",
type: '2,2',
callback: {
login: window.AppFacade.onWbLoginSuccess,
logout: window.AppFacade.onWbLooutSuccess
}
});
});
},
initInQuizLogin: function () {
QC.Login({//按默认样式插入QQ登录按钮
btnId: "inquiz_qqlogin",
size: "A_XL"
},
window.AppFacade.onInQuizQQLoginSuccess, window.AppFacade.onQQLogoutSuccess);
WB2.anyWhere(function (W) {
W.widget.connectButton({
id: "inquiz_wb_connection_btn",
type: '1,1',
callback: {
login: window.AppFacade.onWbInQuizLoginSuccess,
logout: window.AppFacade.onWbLooutSuccess
}
});
});
},
initFinishLogin: function () {
QC.Login({//按默认样式插入QQ登录按钮
btnId: "qqlogin",
size: "A_XL"
},
window.AppFacade.onQQReportLoginSuccess, window.AppFacade.onQQLogoutSuccess);
WB2.anyWhere(function (W) {
W.widget.connectButton({
id: "wb_connect_btn",
type: '1,1',
callback: {
login: window.AppFacade.onWbReportLoginSuccess,
logout: window.AppFacade.onWbLooutSuccess
}
});
});
},
onQQLoginSuccess: function (reqData, opts) {
_logoutTemplate = [
'<span class="profile-avatar"><img src="{figureurl}" class="{size_key}"/></span>',
'<span class="profile-nickname onDesktop">{nickname}</span>',
'<span class="profile-logout"><a href="javascript:QC.Login.signOut();">退出</a></span>'
].join("");
$('#prifile-login').html(
QC.String.format(_logoutTemplate, {
nickname: QC.String.escHTML(reqData.nickname), //做xss过滤
figureurl: reqData.figureurl
})
);
//$("#social_login").hide();
$("#splash-login").hide();
var self = this;
QC.Login.getMe(function (openId, accessToken) {
app.User.qq_uid = openId;
app.User.qq_token = accessToken;
QC.api("get_info",{}).success(function(res){
app.User.weibo_country = res.data.data.country_code;
app.User.weibo_province = res.data.data.province_code;
app.User.weibo_city = res.data.data.city_code;
app.User.weibo_location = res.data.data.location;
}).complete(function(c){
if (app.LoginFrom != 'end' && AppFacade.getCurrentView().id != 'report' && typeof (app.ReportId) == 'undefined') {
// 在开始页面 login by qq
app.Report.getReportByUserId();
}
});
});
},
onInQuizQQLoginSuccess: function (reqData, opts) {
_logoutTemplate = [
'<span class="profile-avatar"><img src="{figureurl}" class="{size_key}"/></span>',
'<span class="profile-nickname onDesktop">{nickname}</span>',
'<span class="profile-logout"><a href="javascript:QC.Login.signOut();">退出</a></span>'
].join("");
$('#prifile-login').html(
QC.String.format(_logoutTemplate, {
nickname: QC.String.escHTML(reqData.nickname), //做xss过滤
figureurl: reqData.figureurl
})
);
//$("#social_login").hide();
$("#inquiz-login").hide();
var self = this;
QC.Login.getMe(function (openId, accessToken) {
app.User.qq_uid = openId;
app.User.qq_token = accessToken;
QC.api("get_info",{}).success(function(res){
app.User.weibo_country = res.data.data.country_code;
app.User.weibo_province = res.data.data.province_code;
app.User.weibo_city = res.data.data.city_code;
app.User.weibo_location = res.data.data.location;
});
});
},
onQQReportLoginSuccess: function (reqData, opts) {
_logoutTemplate = [
'<span class="profile-avatar"><img src="{figureurl}" class="{size_key}"/></span>',
'<span class="profile-nickname onDesktop">{nickname}</span>',
'<span class="profile-logout"><a href="javascript:QC.Login.signOut();">退出</a></span>'
].join("");
$('#prifile-login').html(
QC.String.format(_logoutTemplate, {
nickname: QC.String.escHTML(reqData.nickname), //做xss过滤
figureurl: reqData.figureurl
})
);
//$("#social_login").hide();
$("#login").addClass("hidden");
var self = this;
QC.Login.getMe(function (openId, accessToken) {
app.User.qq_uid = openId;
app.User.qq_token = accessToken;
QC.api("get_info",{}).success(function(res){
app.User.weibo_country = res.data.data.country_code;
app.User.weibo_province = res.data.data.province_code;
app.User.weibo_city = res.data.data.city_code;
app.User.weibo_location = res.data.data.location;
}).complete(function(c){
if (typeof (app.ReportId) != 'undefined' && app.ReportId > 0 && app.LoginFrom == 'end' ) {
app.LoginFrom = "";
app.Report.bind(app.ReportId);
AppFacade.askForReport();
}
});
});
},
onQQLogoutSuccess: function (opts) {//注销成功
$('#prifile-login').html('');
$("#splash-login").show();
eraseCookie("user_answers");
window.location.href = 'http://pantene.app.social-touch.com/';
},
getQQUserInfo: function(openId, accessToken) {
QC.api("get_info",{}).success(function(res){
app.User.weibo_country = res.data.data.country_code;
app.User.weibo_province = res.data.data.province_code;
app.User.weibo.city = res.data.data.city_code;
app.User.weibo_location = res.data.data.location;
}).complete(function(c){
});
},
initWbLogin: function () {
},
weiboLogout: function () {
WB2.logout(function () {
window.AppFacade.onWbLogoutSuccess();
});
},
onWbLoginSuccess: function (o) {
_logoutTemplate = [
'<span class="profile-avatar"><img src="{{figureurl}}" class="{size_key}"/></span>',
'<span class="profile-nickname onDesktop">{{nickname}}</span>',
'<span class="profile-logout"><a onclick="window.AppFacade.weiboLogout();">退出</a></span>'
].join("");
$('#prifile-login').html(Mustache.render(_logoutTemplate, {
nickname: o.screen_name,
figureurl: o.profile_image_url
})
);
$("#login").addClass("hidden");
$("#splash-login").hide();
$("#login").addClass("hidden");
app.User.weibo_uid = o.id;
app.User.weibo_province = o.province;
app.User.weibo_city = o.city;
app.User.weibo_location = o.location;
var tokencookiename = "weibojs_" + app.weiboApp.app_id;
var tokencookie = readCookie(tokencookiename);
if (tokencookie) {
var param = tokencookie.split("%26");
var token = param[0].split("%3D")[1];
app.User.weibo_token = token;
}
if (app.LoginFrom != 'end' && AppFacade.getCurrentView().id != 'report' && typeof (app.ReportId) == 'undefined') {
// 在开始页面 login by qq
app.Report.getReportByUserId();
}
},
onWbInQuizLoginSuccess: function (o) {
_logoutTemplate = [
'<span class="profile-avatar"><img src="{{figureurl}}" class="{size_key}"/></span>',
'<span class="profile-nickname onDesktop">{{nickname}}</span>',
'<span class="profile-logout"><a onclick="window.AppFacade.weiboLogout();">退出</a></span>'
].join("");
$('#prifile-login').html(Mustache.render(_logoutTemplate, {
nickname: o.screen_name,
figureurl: o.profile_image_url
})
);
$("#inquiz-login").addClass("hidden");
//$("#social_login").hide();
app.User.weibo_uid = o.id;
app.User.weibo_province = o.province;
app.User.weibo_city = o.city;
app.User.weibo_location = o.location;
//console.log(o);
var tokencookiename = "weibojs_" + app.weiboApp.app_id;
var tokencookie = readCookie(tokencookiename);
if (tokencookie) {
var param = tokencookie.split("%26");
var token = param[0].split("%3D")[1];
app.User.weibo_token = token;
}
},
onWbReportLoginSuccess: function (o) {
_logoutTemplate = [
'<span class="profile-avatar"><img src="{{figureurl}}" class="{size_key}"/></span>',
'<span class="profile-nickname onDesktop">{{nickname}}</span>',
'<span class="profile-logout"><a onclick="window.AppFacade.weiboLogout();">退出</a></span>'
].join("");
$('#prifile-login').html(Mustache.render(_logoutTemplate, {
nickname: o.screen_name,
figureurl: o.profile_image_url
})
);
$("#login").addClass("hidden");
$("#splash-login").hide();
$("#login").addClass("hidden");
app.User.weibo_uid = o.id;
app.User.weibo_province = o.province;
app.User.weibo_city = o.city;
app.User.weibo_location = o.location;
var tokencookiename = "weibojs_" + app.weiboApp.app_id;
var tokencookie = readCookie(tokencookiename);
if (tokencookie) {
var param = tokencookie.split("%26");
var token = param[0].split("%3D")[1];
app.User.weibo_token = token;
}
if (typeof (app.ReportId) != 'undefined' && app.ReportId > 0 && app.LoginFrom == 'end' ) {
app.LoginFrom = "";
AppFacade.askForReport();
app.Report.bind(app.ReportId);
}
},
onWbLogoutSuccess: function () {
$('#prifile-login').html('');
$("#splash-login").show();
eraseCookie("user_answers");
window.location.href = 'http://pantene.app.social-touch.com/';
},
isLogin: function () {
return (app.User.weibo_uid || app.User.qq_uid);
},
isQuizFinish: function () {
if (this.getMaxFinishedSceneId() < app.SceneViews.length - 1) {
return false;
} else {
return true;
}
},
askForReport: function () {
if (this.isQuizFinish()) {
app.Report.getReport();
} else {
alert("您还有未完成的题目,请仔细检查一下哦!");
}
},
submitAnswer: function () {
if (!app.ReportLogged) {
app.Report.saveAnswer(function () {
if (!AppFacade.isLogin()) {
AppFacade.initFinishLogin();
$("#login").removeClass("hidden");
app.LoginFrom = "end";
} else {
AppFacade.askForReport();
}
});
app.ReportLogged = true;
} else {
if (!AppFacade.isLogin()) {
AppFacade.initFinishLogin();
$("#login").removeClass("hidden");
app.LoginFrom = "end";
} else {
AppFacade.askForReport();
}
}
},
showHelp: function (unfinishedQuestions) {
for (var i in unfinishedQuestions) {
$('.help [data-help-id="' + unfinishedQuestions[i] + '"]').addClass('unfinished');
}
$('.help').addClass('showUnfinished').show();
$('#help-switch').addClass('opened');
},
gotoScene: function (step) {
if (step < (this.getMaxFinishedSceneId() + 1)) {
var currentView = this.getCurrentView();
app.Router.navigate("Survey/" + step, { "trigger": true });
currentView.onexit();
}
app.Views.MainView.setProgressBar();
},
handleError: function (type) {
//window.location.href = "/";
}
};
// Start the main app logic.
requirejs(['../backbone/models/Avatar', '../backbone/models/Scene', '../backbone/models/Report', '../backbone/utils/Utils', '../backbone/views/AvatarView', '../backbone/views/ReportView', '../backbone/views/SceneView', '../backbone/Router'],
function (avatar, scene, utils, avatarView, sceneView, router) {
AppFacade.init();
app.QuestionRepo = new QuestionsCollection;
app.QuestionRepo.fetch().done(
function () {
app.SuggestionRepo = new SuggestionsCollection;
app.SuggestionRepo.fetch().done(function () {
app.ProductRepo = new ProductsCollection;
app.ProductRepo.fetch();
app.GeneralSuggestionRepo = new GeneralSuggestionsCollection;
app.GeneralSuggestionRepo.fetch();
app.SceneSettings = new SceneSettingsCollection;
app.SceneSettings.fetch().done(
function () {
app.Views.MainView = new MainView();
var avatar = new Avatar;
app.Views.AvatarView = new AvatarView({ model: avatar });
var basicInfoScene = new Scene(app.SceneSettings.findWhere({ scene_id: 1 }).toJSON());
var basicInfoView = new BasicInfoView({ model: basicInfoScene });
var hairStyleScene = new Scene(app.SceneSettings.findWhere({ scene_id: 2 }).toJSON());
var hairStyleView = new HairStyleView({ model: hairStyleScene });
var hairQualityScene = new Scene(app.SceneSettings.findWhere({ scene_id: 3 }).toJSON());
var hairQualityView = new HairQualityView({ model: hairQualityScene });
var lifeScene = new Scene(app.SceneSettings.findWhere({ scene_id: 4 }).toJSON());
var lifeView = new LifeView({ model: lifeScene });
var dietScene = new Scene(app.SceneSettings.findWhere({ scene_id: 6 }).toJSON());
var dietView = new DietView({ model: dietScene });
var healthScene = new Scene(app.SceneSettings.findWhere({ scene_id: 5 }).toJSON());
var healthView = new HealthView({ model: healthScene });
var cleaningScene = new Scene(app.SceneSettings.findWhere({ scene_id: 7 }).toJSON());
var cleaningView = new CleaningView({ model: cleaningScene });
var salonScene = new Scene(app.SceneSettings.findWhere({ scene_id: 8 }).toJSON());
var salonView = new SalonView({ model: salonScene });
var report = new Report;
var reportView = new ReportView({ model: report });
app.Report = report;
app.Views.BasicInfoView = basicInfoView;
app.Views.HairStyleView = hairStyleView;
app.Views.HairQualityView = hairQualityView;
app.Views.DietView = dietView;
app.Views.HealthView = healthView;
app.Views.CleaningView = cleaningView;
app.Views.LifeView = lifeView;
app.Views.SalonView = salonView;
app.Views.ReportView = reportView;
app.SceneViews = [
app.Views.BasicInfoView,
app.Views.HairStyleView,
app.Views.HairQualityView,
app.Views.LifeView,
app.Views.HealthView,
app.Views.DietView,
app.Views.CleaningView,
app.Views.SalonView
];
app.Router = new Router();
Backbone.history.start();
var isTrigger = typeof (app.ReportId) == 'undefined';
if (isTrigger) {
AppFacade.loadFromCookie(true);
AppFacade.exitLoading();
}
}); //end scenesettings fetch
});
});
}
);
| mit |
karim/adila | database/src/main/java/adila/db/hwu9201l_201hw.java | 199 | // This file is automatically generated.
package adila.db;
/*
* Huawei
*
* DEVICE: hwu9201L
* MODEL: 201HW
*/
final class hwu9201l_201hw {
public static final String DATA = "Huawei||";
}
| mit |
iamwithnail/react-redux | src/components/video_list_item.js | 865 | /**
* Created by chris on 04/03/2017.
*/
import React from 'react';
const VideoListItem = ({video, onVideoSelect}) => {
// that {video} means that the first props has a property called video
// equivalent to const video = props.video;
const imageUrl = video.snippet.thumbnails.default.url;
return (
<li onClick={ () => onVideoSelect(video)} className="list-group-item">
<div className="video-list media">
<div className="media-left">
<img className="media-object" src={imageUrl}/>
</div>
<div className="media-body">
<div className="media-heading">
{video.snippet.title}
</div>
</div>
</div>
</li>
);
};
export default VideoListItem;
| mit |
stas-vilchik/bdd-ml | data/818.js | 231 | {
test.equal(success, false, "request should not succeed");
test.equal(failure, true, "request should fail");
test.equal(error.code, "ECONNABORTED");
test.equal(error.message, "timeout of 250ms exceeded");
test.done();
}
| mit |
yassine-essadik/gestion-pub | src/GP/PoseurBundle/GPPoseurBundle.php | 124 | <?php
namespace GP\PoseurBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class GPPoseurBundle extends Bundle
{
}
| mit |
MichaelHu/mcphp | apps/scaffold/conf/RequestConfig.conf.php | 643 | <?php
/*
* 逻辑选择参数配置
* default: 默认值,当前上下文获取不到的时候,使用默认值
* source: 参数来源,例子如下:
* requestParams|tn 表示来自请求参数, request->requestParams['tn']
* cookie|baiduid 表示来自Cookie, request->cookie['baiduid']
* requestData|fname 表示来自请求数据, request->requestData['fname']
* pattern: 正则表达式,用于参数有效性检查
*/
RequestConfig::$logicParams = array(
'tn' => array(
'default'=>'index',
'source'=>'requestParams|tn',
'pattern'=>'/^(?:index|othertemplate)$/',
),
);
| mit |
winnitron/winnitron_reborn | db/migrate/20160926033137_add_player_counts.rb | 163 | class AddPlayerCounts < ActiveRecord::Migration
def change
add_column :games, :min_players, :integer
add_column :games, :max_players, :integer
end
end
| mit |
afogel/iArrived | application.rb | 1099 | require 'sinatra'
require 'rack-flash'
require 'dotenv'
require 'twilio-ruby'
require 'json'
# Configuration
Dotenv.load
APP_ROOT = Pathname.new(File.expand_path('../', __FILE__))
configure do
set :root, APP_ROOT.to_path
set :views, File.join(Sinatra::Application.root, "app", "views")
end
enable :sessions
use Rack::Flash
# Routing
get '/' do
@contact_names = JSON.parse(ENV['CONTACTS_ARRAY']).map { |name, number| name }
erb :home
end
post '/arrived_safely' do
client = Twilio::REST::Client.new(ENV['TWILIO_ACCOUNT_SID'], ENV['TWILIO_AUTH_TOKEN'])
contacts = Hash[JSON.parse(ENV['CONTACTS_ARRAY']).map {|key, value| [key, value]}]
location = params[:location]
begin
contacts.each do |name, number|
client.messages.create(
from: '+12406502723',
to: "+1#{number}",
body: "Hi #{name}, it's Ariel. I'm sending you a text from #{location}. I just wanted to let you know I got in safe and sound :) Hope you're doing well! XOXO"
)
end
flash[:success] = "sent a message from #{location}"
rescue => e
flash[:error] = e.message
end
end
| mit |
meatwallace/strap | src/common/lib/genActionType.js | 88 | export default function genActionType(scope, action) {
return `${scope}/${action}`;
}
| mit |
Nexmo/nexmo-java-sdk | src/main/java/com/vonage/client/verify/VerifyControlCommand.java | 1082 | /*
* Copyright 2020 Vonage
*
* 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.vonage.client.verify;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
public enum VerifyControlCommand {
CANCEL,
TRIGGER_NEXT_EVENT;
@JsonValue
@Override
public String toString() {
return name().toLowerCase();
}
@JsonCreator
public static VerifyControlCommand fromString(String name) {
return VerifyControlCommand.valueOf(name.toUpperCase());
}
}
| mit |
SurgicalSteel/Competitive-Programming | Codeforces-Solutions/A and B and Team Training.cpp | 599 | #include <bits/stdc++.h>
using namespace std;
int main() {
int xp,nb;
cin>>xp>>nb;
if(xp>nb&&xp>0&&nb>0)
{
if(nb*2<=xp){cout<<nb<<"\n";}
else
{cout<<(((xp+nb)-((xp+nb)%3)))/3<<"\n";}
}
else if(nb==0||xp==0){cout<<"0\n";}
else if(xp<nb)
{
if((xp*3)<=(xp+nb)){cout<<xp<<"\n";}
else
{cout<<(((xp+nb)-((xp+nb)%3)))/3<<"\n";}
}
else if(xp+nb<3){cout<<"0\n";}
else if (xp==nb)
{
if((xp*3)<=(xp+nb)){cout<<xp<<"\n";}
else
{cout<<(((xp+nb)-((xp+nb)%3)))/3<<"\n";}
}
return 0;
}
| mit |
xpharry/Leetcode | leetcode/cpp/038.cpp | 904 | /**
* Code description
*
* Author: xpharry
* Date: 11/11/2018
*
* Data structure:
* String, Array
*
* Idea:
* - DP
* - 可以用recursion,也可以直接iteration。下次实现下后者。
* - 参考(Reference):
* http://bangbingsyb.blogspot.com/2014/11/leetcode-count-and-say.html
*
* Complexity:
* Time: O(?)
*
*/
class Solution {
public:
string countAndSay(int n) {
if(n == 1) return "1";
string str = countAndSay(n-1);
char c = str[0];
int count = 0;
string res = "";
for(int i = 0; i < str.length(); i++) {
if(c == str[i]) count++;
else {
res += to_string(count) + c;
c = str[i];
count = 1;
}
if(i == str.length()-1)
res += to_string(count) + str[i];
}
return res;
}
};
| mit |
Pro/three.js | examples/js/controls/TrackballControls.js | 13853 | /**
* @author Eberhard Graether / http://egraether.com/
* @author Mark Lundin / http://mark-lundin.com
* @author Simone Manini / http://daron1337.github.io
* @author Luca Antiga / http://lantiga.github.io
*/
THREE.TrackballControls = function ( object, domElement ) {
var _this = this;
var STATE = { NONE: -1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM_PAN: 4 };
this.object = object;
this.domElement = ( domElement !== undefined ) ? domElement : document;
// API
this.enabled = true;
this.screen = { left: 0, top: 0, width: 0, height: 0 };
this.rotateSpeed = 1.0;
this.zoomSpeed = 1.2;
this.panSpeed = 0.3;
this.noRotate = false;
this.noZoom = false;
this.noPan = false;
this.staticMoving = false;
this.dynamicDampingFactor = 0.2;
this.minDistance = 0;
this.maxDistance = Infinity;
this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ];
// internals
this.target = new THREE.Vector3();
var EPS = 0.000001;
var lastPosition = new THREE.Vector3();
var _state = STATE.NONE,
_prevState = STATE.NONE,
_eye = new THREE.Vector3(),
_movePrev = new THREE.Vector2(),
_moveCurr = new THREE.Vector2(),
_lastAxis = new THREE.Vector3(),
_lastAngle = 0,
_zoomStart = new THREE.Vector2(),
_zoomEnd = new THREE.Vector2(),
_touchZoomDistanceStart = 0,
_touchZoomDistanceEnd = 0,
_panStart = new THREE.Vector2(),
_panEnd = new THREE.Vector2();
// for reset
this.target0 = this.target.clone();
this.position0 = this.object.position.clone();
this.up0 = this.object.up.clone();
// events
var changeEvent = { type: 'change' };
var startEvent = { type: 'start' };
var endEvent = { type: 'end' };
// methods
this.handleResize = function () {
if ( this.domElement === document ) {
this.screen.left = 0;
this.screen.top = 0;
this.screen.width = window.innerWidth;
this.screen.height = window.innerHeight;
} else {
var box = this.domElement.getBoundingClientRect();
// adjustments come from similar code in the jquery offset() function
var d = this.domElement.ownerDocument.documentElement;
this.screen.left = box.left + window.pageXOffset - d.clientLeft;
this.screen.top = box.top + window.pageYOffset - d.clientTop;
this.screen.width = box.width;
this.screen.height = box.height;
}
};
this.handleEvent = function ( event ) {
if ( typeof this[ event.type ] == 'function' ) {
this[ event.type ]( event );
}
};
var getMouseOnScreen = ( function () {
var vector = new THREE.Vector2();
return function ( pageX, pageY ) {
vector.set(
( pageX - _this.screen.left ) / _this.screen.width,
( pageY - _this.screen.top ) / _this.screen.height
);
return vector;
};
}() );
var getMouseOnCircle = ( function () {
var vector = new THREE.Vector2();
return function ( pageX, pageY ) {
vector.set(
( ( pageX - _this.screen.width * 0.5 - _this.screen.left ) / ( _this.screen.width * 0.5 ) ),
( ( _this.screen.height + 2 * ( _this.screen.top - pageY ) ) / _this.screen.width ) // screen.width intentional
);
return vector;
};
}() );
this.rotateCamera = (function() {
var axis = new THREE.Vector3(),
quaternion = new THREE.Quaternion(),
eyeDirection = new THREE.Vector3(),
objectUpDirection = new THREE.Vector3(),
objectSidewaysDirection = new THREE.Vector3(),
moveDirection = new THREE.Vector3(),
angle;
return function () {
moveDirection.set( _moveCurr.x - _movePrev.x, _moveCurr.y - _movePrev.y, 0 );
angle = moveDirection.length();
if ( angle ) {
_eye.copy( _this.object.position ).sub( _this.target );
eyeDirection.copy( _eye ).normalize();
objectUpDirection.copy( _this.object.up ).normalize();
objectSidewaysDirection.crossVectors( objectUpDirection, eyeDirection ).normalize();
objectUpDirection.setLength( _moveCurr.y - _movePrev.y );
objectSidewaysDirection.setLength( _moveCurr.x - _movePrev.x );
moveDirection.copy( objectUpDirection.add( objectSidewaysDirection ) );
axis.crossVectors( moveDirection, _eye ).normalize();
angle *= _this.rotateSpeed;
quaternion.setFromAxisAngle( axis, angle );
_eye.applyQuaternion( quaternion );
_this.object.up.applyQuaternion( quaternion );
_lastAxis.copy( axis );
_lastAngle = angle;
}
else if ( !_this.staticMoving && _lastAngle ) {
_lastAngle *= Math.sqrt( 1.0 - _this.dynamicDampingFactor );
_eye.copy( _this.object.position ).sub( _this.target );
quaternion.setFromAxisAngle( _lastAxis, _lastAngle );
_eye.applyQuaternion( quaternion );
_this.object.up.applyQuaternion( quaternion );
}
_movePrev.copy( _moveCurr );
};
}());
this.zoomCamera = function () {
var factor;
if ( _state === STATE.TOUCH_ZOOM_PAN ) {
factor = _touchZoomDistanceStart / _touchZoomDistanceEnd;
_touchZoomDistanceStart = _touchZoomDistanceEnd;
if ( this.object instanceof THREE.PerspectiveCamera ) {
_eye.multiplyScalar( factor );
} else {
this.object.left *= factor;
this.object.right *= factor;
this.object.top *= factor;
this.object.bottom *= factor;
this.object.updateProjectionMatrix();
}
} else {
factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed;
if ( factor !== 1.0 && factor > 0.0 ) {
if ( this.object instanceof THREE.PerspectiveCamera ) {
_eye.multiplyScalar( factor );
} else {
this.object.left *= factor;
this.object.right *= factor;
this.object.top *= factor;
this.object.bottom *= factor;
this.object.updateProjectionMatrix();
}
if ( _this.staticMoving ) {
_zoomStart.copy( _zoomEnd );
} else {
_zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;
}
}
}
};
this.panCamera = (function() {
var mouseChange = new THREE.Vector2(),
objectUp = new THREE.Vector3(),
pan = new THREE.Vector3();
return function () {
mouseChange.copy( _panEnd ).sub( _panStart );
if ( mouseChange.lengthSq() ) {
mouseChange.multiplyScalar( _eye.length() * _this.panSpeed );
pan.copy( _eye ).cross( _this.object.up ).setLength( mouseChange.x );
pan.add( objectUp.copy( _this.object.up ).setLength( mouseChange.y ) );
_this.object.position.add( pan );
_this.target.add( pan );
if ( _this.staticMoving ) {
_panStart.copy( _panEnd );
} else {
_panStart.add( mouseChange.subVectors( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) );
}
}
};
}());
this.checkDistances = function () {
if ( !_this.noZoom || !_this.noPan ) {
if ( _eye.lengthSq() > _this.maxDistance * _this.maxDistance ) {
_this.object.position.addVectors( _this.target, _eye.setLength( _this.maxDistance ) );
}
if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) {
_this.object.position.addVectors( _this.target, _eye.setLength( _this.minDistance ) );
}
}
};
this.update = function () {
_eye.subVectors( _this.object.position, _this.target );
if ( !_this.noRotate ) {
_this.rotateCamera();
}
if ( !_this.noZoom ) {
_this.zoomCamera();
}
if ( !_this.noPan ) {
_this.panCamera();
}
_this.object.position.addVectors( _this.target, _eye );
_this.checkDistances();
_this.object.lookAt( _this.target );
if ( lastPosition.distanceToSquared( _this.object.position ) > EPS ) {
_this.dispatchEvent( changeEvent );
lastPosition.copy( _this.object.position );
}
};
this.reset = function () {
_state = STATE.NONE;
_prevState = STATE.NONE;
_this.target.copy( _this.target0 );
_this.object.position.copy( _this.position0 );
_this.object.up.copy( _this.up0 );
_eye.subVectors( _this.object.position, _this.target );
_this.object.lookAt( _this.target );
_this.dispatchEvent( changeEvent );
lastPosition.copy( _this.object.position );
};
// listeners
function keydown( event ) {
if ( _this.enabled === false ) return;
window.removeEventListener( 'keydown', keydown );
_prevState = _state;
if ( _state !== STATE.NONE ) {
return;
} else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && !_this.noRotate ) {
_state = STATE.ROTATE;
} else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && !_this.noZoom ) {
_state = STATE.ZOOM;
} else if ( event.keyCode === _this.keys[ STATE.PAN ] && !_this.noPan ) {
_state = STATE.PAN;
}
}
function keyup( event ) {
if ( _this.enabled === false ) return;
_state = _prevState;
window.addEventListener( 'keydown', keydown, false );
}
function mousedown( event ) {
if ( _this.enabled === false ) return;
event.preventDefault();
event.stopPropagation();
if ( _state === STATE.NONE ) {
_state = event.button;
}
if ( _state === STATE.ROTATE && !_this.noRotate ) {
_moveCurr.copy( getMouseOnCircle( event.pageX, event.pageY ) );
_movePrev.copy(_moveCurr);
} else if ( _state === STATE.ZOOM && !_this.noZoom ) {
_zoomStart.copy( getMouseOnScreen( event.pageX, event.pageY ) );
_zoomEnd.copy(_zoomStart);
} else if ( _state === STATE.PAN && !_this.noPan ) {
_panStart.copy( getMouseOnScreen( event.pageX, event.pageY ) );
_panEnd.copy(_panStart);
}
document.addEventListener( 'mousemove', mousemove, false );
document.addEventListener( 'mouseup', mouseup, false );
_this.dispatchEvent( startEvent );
}
function mousemove( event ) {
if ( _this.enabled === false ) return;
event.preventDefault();
event.stopPropagation();
if ( _state === STATE.ROTATE && !_this.noRotate ) {
_movePrev.copy(_moveCurr);
_moveCurr.copy( getMouseOnCircle( event.pageX, event.pageY ) );
} else if ( _state === STATE.ZOOM && !_this.noZoom ) {
_zoomEnd.copy( getMouseOnScreen( event.pageX, event.pageY ) );
} else if ( _state === STATE.PAN && !_this.noPan ) {
_panEnd.copy( getMouseOnScreen( event.pageX, event.pageY ) );
}
}
function mouseup( event ) {
if ( _this.enabled === false ) return;
event.preventDefault();
event.stopPropagation();
_state = STATE.NONE;
document.removeEventListener( 'mousemove', mousemove );
document.removeEventListener( 'mouseup', mouseup );
_this.dispatchEvent( endEvent );
}
function mousewheel( event ) {
if ( _this.enabled === false ) return;
event.preventDefault();
event.stopPropagation();
var delta = 0;
if ( event.wheelDelta ) { // WebKit / Opera / Explorer 9
delta = event.wheelDelta / 40;
} else if ( event.detail ) { // Firefox
delta = - event.detail / 3;
}
_zoomStart.y += delta * 0.01;
_this.dispatchEvent( startEvent );
_this.dispatchEvent( endEvent );
}
function touchstart( event ) {
if ( _this.enabled === false ) return;
switch ( event.touches.length ) {
case 1:
_state = STATE.TOUCH_ROTATE;
_moveCurr.copy( getMouseOnCircle( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ) );
_movePrev.copy(_moveCurr);
break;
case 2:
_state = STATE.TOUCH_ZOOM_PAN;
var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
_touchZoomDistanceEnd = _touchZoomDistanceStart = Math.sqrt( dx * dx + dy * dy );
var x = ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ) / 2;
var y = ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ) / 2;
_panStart.copy( getMouseOnScreen( x, y ) );
_panEnd.copy( _panStart );
break;
default:
_state = STATE.NONE;
}
_this.dispatchEvent( startEvent );
}
function touchmove( event ) {
if ( _this.enabled === false ) return;
event.preventDefault();
event.stopPropagation();
switch ( event.touches.length ) {
case 1:
_movePrev.copy(_moveCurr);
_moveCurr.copy( getMouseOnCircle( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ) );
break;
case 2:
var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
_touchZoomDistanceEnd = Math.sqrt( dx * dx + dy * dy );
var x = ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ) / 2;
var y = ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ) / 2;
_panEnd.copy( getMouseOnScreen( x, y ) );
break;
default:
_state = STATE.NONE;
}
}
function touchend( event ) {
if ( _this.enabled === false ) return;
switch ( event.touches.length ) {
case 1:
_movePrev.copy(_moveCurr);
_moveCurr.copy( getMouseOnCircle( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ) );
break;
case 2:
_touchZoomDistanceStart = _touchZoomDistanceEnd = 0;
var x = ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ) / 2;
var y = ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ) / 2;
_panEnd.copy( getMouseOnScreen( x, y ) );
_panStart.copy( _panEnd );
break;
}
_state = STATE.NONE;
_this.dispatchEvent( endEvent );
}
this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
this.domElement.addEventListener( 'mousedown', mousedown, false );
this.domElement.addEventListener( 'mousewheel', mousewheel, false );
this.domElement.addEventListener( 'DOMMouseScroll', mousewheel, false ); // firefox
this.domElement.addEventListener( 'touchstart', touchstart, false );
this.domElement.addEventListener( 'touchend', touchend, false );
this.domElement.addEventListener( 'touchmove', touchmove, false );
window.addEventListener( 'keydown', keydown, false );
window.addEventListener( 'keyup', keyup, false );
this.handleResize();
// force an update at start
this.update();
};
THREE.TrackballControls.prototype = Object.create( THREE.EventDispatcher.prototype );
THREE.TrackballControls.prototype.constructor = THREE.TrackballControls;
| mit |
DBWangGroupUNSW/revs | scripts/ttl2tsv.py | 1691 | #!/usr/bin/python
import os
import sys
def convert(ttl_file):
print('Processing %s...' % ttl_file)
if ttl_file.endswith('.ttl'):
tsv_file = ttl_file.replace('.ttl', '.tsv')
elif ttl_file.endswith('.nt'):
tsv_file = ttl_file.replace('.nt', '.tsv')
else:
raise RuntimeError("File type not supported: %s" % ttl_file)
with open(ttl_file) as f_ttl:
with open(tsv_file, 'w') as f_tsv:
for line in f_ttl:
line = line.strip()
if line.startswith('#'):
continue
if line.startswith('@'):
raise NotImplementedError("@ directive cannot be digested now")
assert line[-1] == '.', line
line = line[:-1].strip()
predicate_start = None
object_start = None
for pos, ch in enumerate(line):
if ch == ' ':
if predicate_start is None:
predicate_start = pos + 1
continue
if object_start is None:
object_start = pos + 1
break
subject = line[:predicate_start - 1]
predicate = line[predicate_start:object_start - 1]
obj = line[object_start:]
f_tsv.write('\t'.join((subject, predicate, obj)))
f_tsv.write('\n')
if __name__ == '__main__':
if len(sys.argv) <= 1:
print('Usage: %s a.ttl b.ttl...' % os.path.basename(sys.argv[0]))
exit(1)
for i in range(1, len(sys.argv)):
convert(sys.argv[i])
| mit |
Stefan-Lazarevic/JSL | src/game/com/jsl/game/main/Game.java | 423 | package game.com.jsl.game.main;
import engine.ScreenManager;
public class Game extends ScreenManager{
private static final long serialVersionUID = 1L;
//private GameStateManager gsm;
public Game(){
setScreenEnvironment("Game", 800, 600, 32, false);
gameStart(60, true);
gsm.add(new Menu(gsm, this));
}
public static void main(String[] args) {
new Game();
}
}
| mit |
deannariddlespur/Frame-Work | public/js/views/index.js | 1064 | var ListView = Backbone.View.extend({
el: $('#item-list'), // el attaches to existing element
// `events`: Where DOM events are bound to View methods. Backbone doesn't have a separate controller to handle such bindings; it all happens in a View.
events: {
'click button#add': 'addItem'
},
initialize: function(){
_.bindAll(this, 'render', 'addItem'); // every function that uses 'this' as the current object should be in here
this.counter = 0; // total number of items added thus far
this.render();
},
// `render()` now introduces a button to add a new list item.
render: function(){
$(this.el).append("<button id='add' class='btn btn-primary'>Click me</button>");
$(this.el).append("<ul class='list-group list-style'></ul>");
},
// `addItem()`: Custom function called via `click` event above.
addItem: function(){
this.counter++;
$('ul', this.el).append("<li class='list-group-item'>You click "+this.counter+" times</li>");
}
});
var listView = new ListView();
| mit |