repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
DJBuro/Telerik | JavaScriptFund/ArrayMethods/Problem3.UnderagePeople/js/script.js | 1303 | taskName = "Problem 3. Underage people";
function Main(bufferElement) {
var people,
result;
people = makePeople(10);
result = people.filter(function (item) {
return item.age >= 18;
});
result.forEach(function(item) {
item.print();
});
function makePerson(fname, lname, age, gender) {
return {
firstName: fname,
lastName: lname,
age: age,
gender: gender,
print: function () {
return WriteLine(this.firstName + ' ' + this.lastName + ' ' + this.age + ' years old ' + this.gender)
},
toString: function () {
return this.firstName + ' ' + this.lastName;
}
};
}
function makePeople(lenght) {
var i,
people = [],
firstNames = ['Pavel', 'Milena', 'Sandy', 'Mindi', 'Sali', 'Lenka', 'Slavei', 'Mimi', 'Stefcho', 'Ani'],
lastNames = ['Lenkov', 'Vo', 'Rivera', 'Mindilq', 'Salov', 'Salvador', 'Peevski', 'Peneva', 'Kecov', 'Dudova'];
for (i = 0; i < lenght; i += 1) {
people[i] = makePerson(firstNames[i % 10], lastNames[i % 10], Math.round(Math.random()*100 + 1), ((i % 2) ? 'female' : 'male'));
}
return people;
}
} | mit |
kubatyszko/gitea | models/migrations/v45.go | 834 | // Copyright 2017 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package migrations
import (
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"github.com/go-xorm/xorm"
)
func removeIndexColumnFromRepoUnitTable(x *xorm.Engine) (err error) {
switch {
case setting.Database.UseSQLite3:
log.Warn("Unable to drop columns in SQLite")
case setting.Database.UseMySQL, setting.Database.UsePostgreSQL, setting.Database.UseMSSQL:
if _, err := x.Exec("ALTER TABLE repo_unit DROP COLUMN `index`"); err != nil {
// Ignoring this error in case we run this migration second time (after migration reordering)
log.Warn("DROP COLUMN index: %v", err)
}
default:
log.Fatal("Unrecognized DB")
}
return nil
}
| mit |
minibhati93/drawing-app-ionic | platforms/ios/www/plugins/nl.x-services.plugins.toast/test/tests.js | 1850 | cordova.define("nl.x-services.plugins.toast.tests", function(require, exports, module) { exports.defineAutoTests = function() {
var fail = function (done) {
expect(true).toBe(false);
done();
},
succeed = function (done) {
expect(true).toBe(true);
done();
};
describe('Plugin availability', function () {
it("window.plugins.toast should exist", function() {
expect(window.plugins.toast).toBeDefined();
});
});
describe('API functions', function () {
it("should define show", function() {
expect(window.plugins.toast.show).toBeDefined();
});
it("should define showWithOptions", function() {
expect(window.plugins.toast.showWithOptions).toBeDefined();
});
it("should define optionsBuilder", function() {
expect(window.plugins.toast.optionsBuilder).toBeDefined();
});
it("should define showShortTop", function() {
expect(window.plugins.toast.showShortTop).toBeDefined();
});
it("should define showShortCenter", function() {
expect(window.plugins.toast.showShortCenter).toBeDefined();
});
it("should define showShortBottom", function() {
expect(window.plugins.toast.showShortBottom).toBeDefined();
});
it("should define showLongTop", function() {
expect(window.plugins.toast.showLongTop).toBeDefined();
});
it("should define showLongCenter", function() {
expect(window.plugins.toast.showLongCenter).toBeDefined();
});
it("should define showLongBottom", function() {
expect(window.plugins.toast.showLongBottom).toBeDefined();
});
});
describe('Invalid usage', function () {
it("should fail due to an invalid position", function(done) {
window.plugins.toast.show('hi', 'short', 'nowhere', fail.bind(null, done), succeed.bind(null, done));
});
});
};
});
| mit |
maurer/tiamat | samples/Juliet/testcases/CWE78_OS_Command_Injection/s04/CWE78_OS_Command_Injection__char_listen_socket_execl_73a.cpp | 5815 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__char_listen_socket_execl_73a.cpp
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-73a.tmpl.cpp
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: listen_socket Read data using a listen socket (server side)
* GoodSource: Fixed string
* Sinks: execl
* BadSink : execute command with execl
* Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <list>
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT "cmd.exe"
#define COMMAND_ARG1 "/c"
#define COMMAND_ARG2 "dir"
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH "/bin/sh"
#define COMMAND_INT "sh"
#define COMMAND_ARG1 "ls"
#define COMMAND_ARG2 "-la"
#define COMMAND_ARG3 data
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define LISTEN_BACKLOG 5
using namespace std;
namespace CWE78_OS_Command_Injection__char_listen_socket_execl_73
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(list<char *> dataList);
void bad()
{
char * data;
list<char *> dataList;
char dataBuffer[100] = "";
data = dataBuffer;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
char *replace;
SOCKET listenSocket = INVALID_SOCKET;
SOCKET acceptSocket = INVALID_SOCKET;
size_t dataLen = strlen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a listen socket */
listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY;
service.sin_port = htons(TCP_PORT);
if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
{
break;
}
acceptSocket = accept(listenSocket, NULL, NULL);
if (acceptSocket == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed */
recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(char)] = '\0';
/* Eliminate CRLF */
replace = strchr(data, '\r');
if (replace)
{
*replace = '\0';
}
replace = strchr(data, '\n');
if (replace)
{
*replace = '\0';
}
}
while (0);
if (listenSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(listenSocket);
}
if (acceptSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(acceptSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
/* Put data in a list */
dataList.push_back(data);
dataList.push_back(data);
dataList.push_back(data);
badSink(dataList);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(list<char *> dataList);
static void goodG2B()
{
char * data;
list<char *> dataList;
char dataBuffer[100] = "";
data = dataBuffer;
/* FIX: Append a fixed string to data (not user / external input) */
strcat(data, "*.*");
/* Put data in a list */
dataList.push_back(data);
dataList.push_back(data);
dataList.push_back(data);
goodG2BSink(dataList);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
using namespace CWE78_OS_Command_Injection__char_listen_socket_execl_73; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| mit |
ldaptools/ldaptools | src/LdapTools/Ldif/LdifParser.php | 21069 | <?php
/**
* This file is part of the LdapTools package.
*
* (c) Chad Sikorra <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace LdapTools\Ldif;
use LdapTools\Connection\LdapControl;
use LdapTools\Exception\LdifParserException;
use LdapTools\Exception\LdifUrlLoaderException;
use LdapTools\Ldif\Entry\LdifEntryAdd;
use LdapTools\Ldif\Entry\LdifEntryDelete;
use LdapTools\Ldif\Entry\LdifEntryModDn;
use LdapTools\Ldif\Entry\LdifEntryModify;
use LdapTools\Ldif\Entry\LdifEntryModRdn;
use LdapTools\Ldif\Ldif;
use LdapTools\Ldif\Entry\LdifEntryInterface;
use LdapTools\Ldif\UrlLoader\BaseUrlLoader;
use LdapTools\Ldif\UrlLoader\UrlLoaderInterface;
use LdapTools\Utilities\LdapUtilities;
/**
* Parses a LDIF string to a form that can be easily entered into LDAP with LdapTools.
*
* @author Chad Sikorra <[email protected]>
*/
class LdifParser
{
/**
* Valid directives for certain changetypes.
*/
const VALID_DIRECTIVES = [
LdifEntryInterface::TYPE_MODIFY => [
LdifEntryModify::DIRECTIVE_ADD,
LdifEntryModify::DIRECTIVE_DELETE,
LdifEntryModify::DIRECTIVE_REPLACE,
],
LdifEntryInterface::TYPE_MODDN => [
LdifEntryModDn::DIRECTIVE_NEWRDN,
LdifEntryModDn::DIRECTIVE_DELETEOLDRDN,
LdifEntryModDn::DIRECTIVE_NEWSUPERIOR,
],
LdifEntryInterface::TYPE_MODRDN => [
LdifEntryModRdn::DIRECTIVE_NEWRDN,
LdifEntryModRdn::DIRECTIVE_DELETEOLDRDN,
LdifEntryModRdn::DIRECTIVE_NEWSUPERIOR,
],
];
/**
* @var array A simple changetype to full class name mapping.
*/
protected $changeTypeMap = [
LdifEntryInterface::TYPE_ADD => LdifEntryAdd::class,
LdifEntryInterface::TYPE_DELETE => LdifEntryDelete::class,
LdifEntryInterface::TYPE_MODDN => LdifEntryModDn::class,
LdifEntryInterface::TYPE_MODRDN => LdifEntryModRdn::class,
LdifEntryInterface::TYPE_MODIFY => LdifEntryModify::class,
];
/**
* An array of UrlLoaders with the key set to the type of URL they handle.
*
* @var UrlLoaderInterface[]
*/
protected $urlLoaders = [];
/**
* @var int The current line number we are on during parsing.
*/
protected $line = 0;
/**
* @var string[]
*/
protected $lines;
/**
* @var string[] Any comments pending for the next entry in the LDIF.
*/
protected $commentQueue = [];
public function __construct()
{
$this->urlLoaders[UrlLoaderInterface::TYPE_FILE] = new BaseUrlLoader();
$this->urlLoaders[UrlLoaderInterface::TYPE_HTTP] = new BaseUrlLoader();
$this->urlLoaders[UrlLoaderInterface::TYPE_HTTPS] = new BaseUrlLoader();
}
/**
* Parses a string containing LDIF data and returns an object with the entries it contains.
*
* @param string $ldif
* @return Ldif
* @throws LdifParserException
*/
public function parse($ldif)
{
$ldifObject = new Ldif();
$this->setup($ldif);
while (!$this->isEndOfLdif()) {
if ($this->isComment()) {
$this->addCommentToQueueOrLdif($ldifObject);
$this->nextLine();
} elseif ($this->isStartOfEntry()) {
$ldifObject->addEntry($this->parseEntry());
} elseif ($this->startsWith(Ldif::DIRECTIVE_VERSION.Ldif::KEY_VALUE_SEPARATOR)) {
$this->setLdifVersion($ldifObject, $this->getKeyAndValue($this->currentLine())[1]);
$this->nextLine();
} elseif ($this->isEndOfEntry()) {
$this->nextLine();
} else {
$this->throwException('Unexpected line in LDIF');
}
}
$this->cleanup();
return $ldifObject;
}
/**
* Set a URL loader to be used by the parser.
*
* @param string $type The URL type (ie. file, http, etc)
* @param UrlLoaderInterface $loader
*/
public function setUrlLoader($type, UrlLoaderInterface $loader)
{
$this->urlLoaders[$type] = $loader;
}
/**
* Check if a URL loader for a specific URL type exists.
*
* @param string $type
* @return bool
*/
public function hasUrlLoader($type)
{
return array_key_exists($type, $this->urlLoaders);
}
/**
* Remove a URL loader by its string type.
*
* @param string $type
*/
public function removeUrlLoader($type)
{
unset($this->urlLoaders[$type]);
}
/**
* @param string $ldif
*/
protected function setup($ldif)
{
$this->line = 0;
// This accounts for various line endings across different OS types and forces it to one type.
$this->lines = explode("\n", str_replace(["\r\n", "\r"], "\n", $ldif));
}
/**
* Do a bit of cleanup post parsing.
*/
protected function cleanup()
{
$this->lines = null;
$this->line = 0;
}
/**
* Parse an entry from the DN position until we reach the start of the next entry. Return the entry that was parsed.
*
* @return LdifEntryInterface
*/
protected function parseEntry()
{
$entry = $this->parseCommonDirectives($this->getKeyAndValue($this->currentLine())[1]);
if (!empty($this->commentQueue)) {
$entry->addComment(...$this->commentQueue);
$this->commentQueue = [];
}
// Nothing further to do with a simple deletion...
if ($entry instanceof LdifEntryDelete) {
return $entry;
}
while (!$this->isEndOfLdif() && !$this->isStartOfEntry()) {
if ($this->isComment()) {
$entry->addComment(substr($this->currentLine(), 1));
$this->nextLine();
} elseif ($this->isEndOfEntry()) {
break;
} else {
list($key, $value) = $this->getKeyAndValue($this->currentLine());
$this->addDirectiveToEntry($key, $value, $entry);
$this->nextLine();
}
}
return $entry;
}
/**
* Parses directives that are potentially common to all entries and returns the LdifEntry object. Common directives
* include: changetype, control
*
* @param $dn
* @return LdifEntryInterface
* @throws LdifParserException
*/
protected function parseCommonDirectives($dn)
{
$changeType = null;
$controls = [];
$this->nextLine();
while ($this->isCommonDirective()) {
if ($this->isComment()) {
$this->nextLine();
continue;
// We need to exit the loop completely in this case...
} elseif ($this->isEndOfLdif() || $this->isStartOfEntry()) {
break;
} elseif ($this->isCommonDirective()) {
list($key, $value) = $this->getKeyAndValue($this->currentLine());
if ($key == Ldif::DIRECTIVE_CHANGETYPE && is_null($changeType)) {
$changeType = $value;
} elseif ($key == Ldif::DIRECTIVE_CHANGETYPE && !is_null($changeType)) {
$this->throwException('The changetype directive has already been defined');
} else {
$controls[] = $this->getLdapControl($value);
}
}
$this->nextLine();
}
$changeType = $changeType ?: LdifEntryInterface::TYPE_ADD;
$entry = $this->getLdifEntryObject($dn, $changeType);
foreach ($controls as $control) {
$entry->addControl($control);
}
return $entry;
}
/**
* Get the LdifEntry for the changetype.
*
* @param string $dn
* @param string $changeType
* @return LdifEntryInterface
* @throws LdifParserException
*/
protected function getLdifEntryObject($dn, $changeType)
{
if (!array_key_exists($changeType, $this->changeTypeMap)) {
$this->throwException(sprintf('The changetype "%s" is invalid', $changeType));
}
return new $this->changeTypeMap[$changeType]($dn);
}
/**
* @param bool $advance Whether to advance the currently active line ahead or not.
* @return string|false
*/
protected function nextLine($advance = true)
{
$line = $this->line + 1;
if ($advance) {
$this->line++;
}
if (!isset($this->lines[$line])) {
return false;
}
return $this->lines[$line];
}
/**
* @return bool|string
*/
protected function currentLine()
{
if (!isset($this->lines[$this->line])) {
return false;
}
return $this->lines[$this->line];
}
/**
* Check if the current line starts with a specific value.
*
* @param string $value
* @param null|string $line
* @return bool
*/
protected function startsWith($value, $line = null)
{
if (is_null($line)) {
$line = $this->currentLine();
}
return (substr($line, 0, strlen($value)) === $value);
}
/**
* Checks for the start of a LDIF entry on the current line.
*
* @return bool
*/
protected function isStartOfEntry()
{
return $this->startsWith(Ldif::DIRECTIVE_DN.Ldif::KEY_VALUE_SEPARATOR);
}
/**
* Check if we are at the end of the LDIF string.
*
* @return bool
*/
protected function isEndOfLdif()
{
return $this->currentLine() === false;
}
/**
* Check if we are at the end of a LDIF entry.
*
* @return bool
*/
protected function isEndOfEntry()
{
return $this->currentLine() === '';
}
/**
* Check if the current line is a comment.
*
* @return bool
*/
protected function isComment()
{
return $this->startsWith(Ldif::COMMENT);
}
/**
* Check if the line is a directive common to any change type (ie. changetype or control).
*
* @return bool
*/
protected function isCommonDirective()
{
return $this->startsWith(Ldif::DIRECTIVE_CONTROL) || $this->startsWith(Ldif::DIRECTIVE_CHANGETYPE);
}
/**
* Check if a line is a continuation of a previous value.
*
* @param string $line
* @return bool
*/
protected function isContinuedValue($line)
{
return (!empty($line) && $line[0] === " ");
}
/**
* @param string $line
* @return array
* @throws LdifParserException
*/
protected function getKeyAndValue($line)
{
$position = strpos($line, Ldif::KEY_VALUE_SEPARATOR);
// There must be a key/value separator ':' present in the line, and it cannot be the first value
if ($position === false || $position === 0) {
$this->throwException('Expecting a LDIF directive');
}
// This accounts for double '::' base64 format.
$key = rtrim(substr($line, 0, $position), ':');
// Base64 encoded format...
if ($this->startsWith(Ldif::KEY_VALUE_SEPARATOR, substr($line, $position + 1))) {
$value = base64_decode($this->getContinuedValues(ltrim(substr($line, $position + 2), ' ')));
// The value needs to be retrieved from a URL...
} elseif ($this->startsWith(Ldif::URL, substr($line, $position + 1))) {
// Start the position after the URL indicator and remove any spaces.
$value = $this->getValueFromUrl($this->getContinuedValues(ltrim(substr($line, $position + 2), ' ')));
// Just a typical value format...
} else {
// A space at the start of the value should be ignored. A value beginning with a space should be base64 encoded.
$value = $this->getContinuedValues(ltrim(substr($line, $position + 1), " "));
}
return [$key, $value];
}
/**
* Check for any continued values and concatenate them into one.
*
* @param $value
* @return string
*/
protected function getContinuedValues($value)
{
while ($this->isContinuedValue($this->nextLine(false))) {
$value .= substr($this->nextLine(), 1);
}
return $value;
}
/**
* Get the value of the URL data via a UrlLoader.
*
* @param string $url
* @return string
*/
protected function getValueFromUrl($url)
{
$type = substr($url, 0, strpos($url, Ldif::KEY_VALUE_SEPARATOR));
if (!$this->hasUrlLoader($type)) {
$this->throwException(sprintf('Cannot find a URL loader for type "%s"', $type));
}
try {
return $this->urlLoaders[$type]->load($url);
} catch (LdifUrlLoaderException $e) {
$this->throwException($e->getMessage());
}
}
/**
* Figures out what to add to the LDIF entry for a specific key/value directive given.
*
* @param string $key
* @param string $value
* @param LdifEntryInterface $entry
*/
protected function addDirectiveToEntry($key, $value, LdifEntryInterface $entry)
{
if ($entry instanceof LdifEntryAdd) {
$entry->addAttribute($key, $value);
} elseif ($entry instanceof LdifEntryModDn) {
$this->addModDnDirective($entry, $key, $value);
} elseif ($entry instanceof LdifEntryModify) {
$this->addModifyDirective($entry, $key, $value);
}
}
/**
* @param LdifEntryModDn $entry
* @param string $key
* @param string $value
* @throws LdifParserException
*/
protected function addModDnDirective(LdifEntryModDn $entry, $key, $value)
{
$this->validateDirectiveInChange(LdifEntryInterface::TYPE_MODDN, $key);
if ($key == LdifEntryModDn::DIRECTIVE_DELETEOLDRDN) {
$entry->setDeleteOldRdn($this->getBoolFromStringInt($value));
} elseif ($key == LdifEntryModDn::DIRECTIVE_NEWRDN) {
$entry->setNewRdn($value);
} elseif ($key == LdifEntryModDn::DIRECTIVE_NEWSUPERIOR) {
$entry->setNewLocation($value);
}
}
/**
* @param LdifEntryModify $entry
* @param string $key
* @param string $value
* @throws LdifParserException
*/
protected function addModifyDirective(LdifEntryModify $entry, $key, $value)
{
$this->validateDirectiveInChange(LdifEntryInterface::TYPE_MODIFY, $key);
$this->nextLine();
if ($key == LdifEntryModify::DIRECTIVE_ADD) {
$values = $this->getValuesForModifyAction($value, 'adding');
$entry->add($value, $values);
} elseif ($key == LdifEntryModify::DIRECTIVE_DELETE) {
$values = $this->getValuesForModifyAction($value, 'deleting');
if (empty($values)) {
$entry->reset($value);
} else {
$entry->delete($value, $values);
}
} elseif ($key == LdifEntryModify::DIRECTIVE_REPLACE) {
$values = $this->getValuesForModifyAction($value, 'replacing');
$entry->replace($value, $values);
}
}
/**
* Validate a control directive and get the value for the control and the criticality.
*
* @param string $value
* @return LdapControl
* @throws LdifParserException
*/
protected function getLdapControl($value)
{
$values = explode(' ', $value);
// This should never happen, but it seems better to cover it in case...
if (empty($values) || $values === false) {
$this->throwException(sprintf('Expecting a LDAP control but got "%s"', $value));
}
// The first value should be an actual OID...
if (!preg_match(LdapUtilities::MATCH_OID, $values[0])) {
$this->throwException(sprintf('The control directive has an invalid OID format "%s"', $values[0]));
}
$control = new LdapControl($values[0]);
if (isset($values[1])) {
$control->setCriticality($this->getBoolFromStringBool($values[1]));
}
if (isset($values[2])) {
$control->setValue($values[2]);
}
return $control;
}
/**
* @param Ldif $ldif
* @param int $version
* @throws LdifParserException
*/
protected function setLdifVersion(Ldif $ldif, $version)
{
if ($version != '1') {
$this->throwException(sprintf('LDIF version "%s" is not currently supported.', $version));
} elseif (count($ldif->getEntries()) !== 0) {
$this->throwException('The LDIF version must be defined before any entries.');
}
$ldif->setVersion($version);
}
/**
* @param string $type The changetype.
* @param string $directive The directive used.
* @throws LdifParserException If the directive is not valid for the changetype.
*/
protected function validateDirectiveInChange($type, $directive)
{
if (!in_array($directive, self::VALID_DIRECTIVES[$type])) {
$this->throwException(sprintf(
'Directive "%s" is not valid for a "%s" changetype',
$directive,
$type
));
}
}
/**
* @param string $attribute
* @param string $action
* @return array
* @throws LdifParserException
*/
protected function getValuesForModifyAction($attribute, $action)
{
$values = [];
while ($this->currentLine() !== LdifEntryModify::SEPARATOR && !$this->isEndOfLdif() && !$this->isEndOfEntry()) {
if ($this->isComment()) {
$this->nextLine();
continue;
}
list($attrKey, $attrValue) = $this->getKeyAndValue($this->currentLine());
if ($attribute !== $attrKey) {
$this->throwException(sprintf(
'Attribute "%s" does not match "%s" for %s values.',
$attrValue,
$attribute,
$action
));
}
$values[] = $attrValue;
$this->nextLine();
}
return $values;
}
/**
* Convert an expected string "true" or "false" to bool.
*
* @param string $value
* @return bool
* @throws LdifParserException
*/
protected function getBoolFromStringBool($value)
{
if (!($value == 'true' || $value == 'false')) {
$this->throwException(sprintf('Expected "true" or "false" but got %s', $value));
}
return $value === 'true' ? true : false;
}
/**
* Convert an expected string "0" or "1" to bool.
*
* @param string $value
* @return bool
* @throws LdifParserException
*/
protected function getBoolFromStringInt($value)
{
if (!($value == '0' || $value == '1')) {
$this->throwException(sprintf('Expected "0" or "1" but got: %s', $value));
}
return (bool) $value;
}
/**
* A simple helper to add additional information to the exception.
*
* @param string $message
* @throws LdifParserException
*/
protected function throwException($message)
{
throw new LdifParserException($message, $this->currentLine(), $this->line + 1);
}
/**
* Determine whether the comment should be added to the LDIF itself, or if it's a comment for an entry within the
* LDIF. If it's for an entry in the LDIF, then we make the assumption that we an empty line separates comments
* between the LDIF comments overall and the start of a comment for an entry. This seems like the most reasonable
* way to do it, though it still may not be perfect.
*
* @param \LdapTools\Ldif\Ldif $ldif
*/
protected function addCommentToQueueOrLdif(Ldif $ldif)
{
$comment = $this->getContinuedValues(substr($this->currentLine(), 1));
// Remove the single space from the start of a comment, but leave the others intact.
if ($this->startsWith(' ', $comment)) {
$comment = substr($comment, 1);
}
// If we already have an entry added to LDIF, then the comment should go in the queue for the next entry.
if (count($ldif->getEntries()) > 0) {
$this->commentQueue[] = $comment;
// Check the section of the LDIF to look for an empty line. If so, assume it's for a future entry.
} elseif (array_search('', array_slice($this->lines, 0, $this->line))) {
$this->commentQueue[] = $comment;
// No empty lines and we have not reached an entry yet, so this should be a comment for the LDIF overall.
} else {
$ldif->addComment($comment);
}
}
}
| mit |
whyleee/Raiden | GameStore/static/app.js | 87 | import 'bootstrap/dist/css/bootstrap.min.css';
import './app.css';
import 'bootstrap'
| mit |
influencetech/ivx-js | examples/basic-analytics-experience/config/multiple-tracker/states/input-scene-test/events/_settings.js | 211 | import onInputReady from "./_settings.on-input-ready.js";
import onEnter from "./_settings.on-enter.js";
import onExit from "./_settings.on-exit.js";
export default {
onInputReady,
onEnter,
onExit
} | mit |
chrishtanaka/architect | src/Creational/FactoryMethod/CreatorVariation.cs | 166 | using System;
namespace FactoryMethod
{
public abstract class CreatorVariation
{
public abstract IProduct FactoryMethod(string productId);
}
}
| mit |
zwhite/keyholer | keyholer/client.py | 1889 | #!/usr/bin/env python
from socket import socket, AF_UNIX, SOCK_STREAM
from keyholer import conf
class KeyholerException(Exception):
pass
class KeyholerClient(object):
"""
Class for interacting with the keyholer backend.
"""
def __init__(self, sock=conf['socket']):
self.s = None
self.socket = sock
def _readline(self):
"""Iterate over the data in a socket's receive buffer line by line
"""
buffer = self.s.recv(4096)
while True:
if '\n' in buffer:
line, buffer = buffer.split('\n', 1)
yield line
else:
more = self.s.recv(4096)
if not more:
break
buffer = buffer+more
if buffer:
yield buffer
def command(self, command):
"""Send a command to the backend and return the response
"""
self.s = socket(AF_UNIX, SOCK_STREAM)
self.s.connect(self.socket)
self.s.sendall(command + "\n")
result = '\n'.join([line for line in self._readline()])
self.s.close()
if result == 'Exception':
raise KeyholerException
return result
# Commands the user can use to interact with KeyholerD
def login(self, user):
"""Sends a code to the phone number on file for user.
"""
return self.command('login %s' % user)
def verify(self, user, code):
"""Verifies that a user's code is correct
Returns a list of SSH keys that are already available for the user,
or False.
"""
return self.command('verify %s %s' % (user, code))
def add_key(self, user, code, ssh_keytext):
"""Adds a key to the user's authorized_keys file.
"""
return self.command('add_key %s %s %s' % (user, code, ssh_keytext))
| mit |
janng0/Android-J0Util | src/main/java/ru/jango/j0util/PathUtil.java | 5045 | /*
* The MIT License Copyright (c) 2014 Krayushkin Konstantin ([email protected])
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package ru.jango.j0util;
import android.net.Uri;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
/**
* Utility class for working with paths in {@link java.io.File}, {@link java.net.URL} and
* {@link java.net.URI}.
*/
public class PathUtil {
public static String getLastPathSegment(String path) {
if (path == null) return null;
try {
String segment = path;
if (segment.endsWith("/"))
segment = segment.substring(0, segment.length() - 1);
return segment.substring(segment.lastIndexOf("/") + 1);
} catch(Exception e) { return null; }
}
public static String getLastPathSegment(URL url) {
if (url == null) return null;
return getLastPathSegment(Uri.decode(url.toString()));
}
public static String getLastPathSegment(URI uri) {
if (uri == null) return null;
return getLastPathSegment(Uri.decode(uri.toString()));
}
public static String getLastPathSegment(File file) {
if (file == null) return null;
return getLastPathSegment(file.getAbsolutePath());
}
////////////////////////////////////////////////////////////////////////////
public static String getFilenameWithoutExt(String path) {
if (path == null) return null;
final String lastSegment = getLastPathSegment(path);
if (!lastSegment.contains(".")) return lastSegment;
return lastSegment.substring(0, lastSegment.lastIndexOf("."));
}
public static String getFilenameWithoutExt(URI uri) {
if (uri == null) return null;
return getFilenameWithoutExt(uri.toString());
}
public static String getFilenameWithoutExt(URL url) {
if (url == null) return null;
return getFilenameWithoutExt(url.toString());
}
public static String getFilenameWithoutExt(File file) {
if (file == null) return null;
return getFilenameWithoutExt(file.getAbsolutePath());
}
////////////////////////////////////////////////////////////////////////////
public static String getExt(String path) {
if (path == null) return null;
if (path.endsWith("/")) return null;
final String lastSegment = getLastPathSegment(path);
if (!lastSegment.contains(".")) return null;
return lastSegment.substring(lastSegment.lastIndexOf(".") + 1);
}
public static String getExt(URI uri) {
if (uri == null) return null;
return getExt(uri.toString());
}
public static String getExt(URL url) {
if (url == null) return null;
return getExt(url.toString());
}
public static String getExt(File file) {
if (file == null) return null;
return getExt(file.getAbsolutePath());
}
////////////////////////////////////////////////////////////////////////////
public static URI stringToURI(String str) throws URISyntaxException {
if (str == null) return null;
return new URI(Uri.encode(Uri.decode(str), ":/?="));
}
public static URI safeStringToURI(String str) {
try { return stringToURI(str); }
catch(Exception e) { return null; }
}
public static URI urlToURI(URL url) throws URISyntaxException {
if (url == null) return null;
return stringToURI(url.toString());
}
public static URI safeUrlToURI(URL url) {
try { return urlToURI(url); }
catch(Exception e) { return null; }
}
public static boolean uriEquals(URI u1, URI u2) {
if (u1 == u2) return true;
if (u1 == null || u2 == null) return false;
try {
final URI du1 = stringToURI(u1.toString());
final URI du2 = stringToURI(u2.toString());
return du1.equals(du2);
} catch(Exception e) { return false; }
}
}
| mit |
firepick1/firenodejs | www/js/app.js | 1537 | 'use strict';
// Declare app level module which depends on filters, and services
angular.module('firenodejs', [
'ui.bootstrap',
'ngRoute',
// 'firenodejs.filters',
'firenodejs.services',
// 'firenodejs.directives',
'firenodejs.controllers',
'd3',
'd3AngularApp',
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/home', {
templateUrl: 'partials/view-home.html',
controller: 'HomeCtrl'
});
$routeProvider.when('/calibrate', {
templateUrl: 'partials/view-calibrate.html',
controller: 'CalibrateCtrl'
});
$routeProvider.when('/jobs', {
templateUrl: 'partials/view-jobs.html',
controller: 'JobsCtrl'
});
$routeProvider.when('/fs', {
templateUrl: 'partials/view-fs.html',
controller: 'FireStepCtrl'
});
$routeProvider.when('/cnc', {
templateUrl: 'partials/view-cnc.html',
controller: 'CncCtrl'
});
$routeProvider.when('/cve', {
templateUrl: 'partials/view-cve.html',
controller: 'CveCtrl'
});
$routeProvider.when('/vcal', {
templateUrl: 'partials/view-vcal.html',
controller: 'VcalCtrl'
});
$routeProvider.when('/delta', {
templateUrl: 'partials/view-delta.html',
controller: 'DeltaCtrl'
});
$routeProvider.when('/test', {
templateUrl: 'partials/view-test.html',
controller: 'TestCtrl'
});
$routeProvider.otherwise({
redirectTo: '/home'
});
}]);
| mit |
activecollab/databasestructure | test/src/ScalarFields/RequiredJsonSerializationTest.php | 3624 | <?php
/*
* This file is part of the Active Collab DatabaseStructure project.
*
* (c) A51 doo <[email protected]>. All rights reserved.
*/
namespace ActiveCollab\DatabaseStructure\Test\ScalarFields;
use ActiveCollab\DatabaseObject\Exception\ValidationException;
use ActiveCollab\DatabaseObject\Pool;
use ActiveCollab\DatabaseObject\PoolInterface;
use ActiveCollab\DatabaseStructure\Builder\TypeTableBuilder;
use ActiveCollab\DatabaseStructure\Field\Scalar\JsonField;
use ActiveCollab\DatabaseStructure\Test\Fixtures\JsonSerialization\RequiredJsonSerializationStructure;
use ActiveCollab\DatabaseStructure\Test\TestCase;
use Psr\Log\LoggerInterface;
/**
* @package ActiveCollab\DatabaseStructure\Test\ScalarFields
*/
class RequiredJsonSerializationTest extends TestCase
{
/**
* @var string
*/
private $type_class_name = 'ActiveCollab\\DatabaseStructure\\Test\\Fixtures\\JsonSerialization\\RequiredKeyValue';
/**
* @var PoolInterface
*/
private $pool;
/**
* @var RequiredJsonSerializationStructure
*/
private $required_json_serialization_structure;
/**
* Set up test environment.
*/
public function setUp(): void
{
parent::setUp();
$this->pool = new Pool($this->connection, $this->createMock(LoggerInterface::class));
$this->required_json_serialization_structure = new RequiredJsonSerializationStructure();
if (!class_exists($this->type_class_name, false)) {
$this->required_json_serialization_structure->build(null, $this->connection);
}
if ($this->connection->tableExists('required_key_values')) {
$this->connection->dropTable('required_key_values');
}
$type_table_builder = new TypeTableBuilder($this->required_json_serialization_structure);
$type_table_builder->setConnection($this->connection);
$type_table_builder->buildType($this->required_json_serialization_structure->getType('required_key_values'));
$this->assertTrue($this->connection->tableExists('required_key_values'));
$this->pool->registerType($this->type_class_name);
$this->assertTrue($this->pool->isTypeRegistered($this->type_class_name));
}
/**
* Tear down test environment.
*/
public function tearDown(): void
{
if ($this->connection->tableExists('required_key_values')) {
$this->connection->dropTable('required_key_values');
}
parent::tearDown();
}
/**
* Test if value field is not required.
*/
public function testValueIsRequired()
{
/** @var JsonField $value_field */
$value_field = $this->required_json_serialization_structure->getType('required_key_values')->getFields()['value'];
$this->assertInstanceOf(JsonField::class, $value_field);
$this->assertTrue($value_field->isRequired());
}
public function testValueCantBeNull()
{
$this->expectException(ValidationException::class);
$this->expectExceptionMessage("Validation failed: Value of 'value' is required");
$this->pool->produce($this->type_class_name, ['name' => 'xyz']);
}
/**
* Test if non-empty value can be set.
*/
public function testValueCanBeSet()
{
$key_value = $this->pool->produce($this->type_class_name, ['name' => 'xyz', 'value' => 123]);
$this->assertInstanceOf($this->type_class_name, $key_value);
$key_value = $this->pool->reload($this->type_class_name, $key_value->getId());
$this->assertSame(123, $key_value->getValue());
}
}
| mit |
noderaider/localsync | packages/localsync-core/src/utils/createLogger.ts | 1023 | import { Options, LogLevel, Logger } from "../types";
import { supportsLevelFactory } from "./supportsLevelFactory";
/**
* Creates a logger used in this instance of localsync.
*
* @param options The options object used to configure this instance of localsync.
*/
export const createLogger = (options: Options): Logger => {
const supportsLevel = supportsLevelFactory(options);
const supportsDebug = supportsLevel(LogLevel.DEBUG);
const supportsInfo = supportsLevel(LogLevel.INFO);
const supportsWarn = supportsLevel(LogLevel.WARN);
const supportsError = supportsLevel(LogLevel.ERROR);
return {
debug(message: string) {
if (supportsDebug) {
console.debug(message);
}
},
info(message: string) {
if (supportsInfo) {
console.info(message);
}
},
warn(message: string) {
if (supportsWarn) {
console.warn(message);
}
},
error(message: string) {
if (supportsError) {
console.error(message);
}
}
};
};
| mit |
wbenmurimi/ash-SE-2015-group8 | ash-SE-2015-group8/pages/logout.php | 179 | <?php
session_start();
session_destroy();
echo "Logged out succesfully";
$message=$_SESSION['error']='Logged out succesfully';
header("location:login.php?error=$message")
?> | mit |
duivvv/generator-module-boilerplate | generators/app/templates/rollup.config.js | 666 | import babel from 'rollup-plugin-babel';
import nodeResolve from 'rollup-plugin-node-resolve';
import uglify from 'rollup-plugin-uglify';
import filesize from 'rollup-plugin-filesize';
import commonjs from 'rollup-plugin-commonjs';
const name = `<%= ccname %>`;
const plugins = [
babel(),
nodeResolve({
module: true,
jsnext: true
}),
commonjs({
include: `node_modules/**`
}),
filesize()
];
const isProd = process.env.NODE_ENV === `production`;
if (isProd) plugins.push(uglify());
export default {
input: `src/index.js`,
plugins,
output: {
file: `dist/${name}${isProd ? `.min` : ``}.js`,
name: name,
format: `umd`
}
};
| mit |
Screeder/SAssemblies | SStandalones/SDetectors/SRecallDetector/Program.cs | 7556 | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Reflection;
using System.Threading;
using LeagueSharp.Common;
using LeagueSharp.SDK.Core.UI;
using SAssemblies.Detectors;
namespace SAssemblies
{
internal class MainMenu : Menu
{
public static MenuItemSettings Detector = new MenuItemSettings();
public static MenuItemSettings RecallDetector = new MenuItemSettings();
private readonly Dictionary<MenuItemSettings, Func<dynamic>> MenuEntries;
public MainMenu()
{
MenuEntries = new Dictionary<MenuItemSettings, Func<dynamic>>
{
{ RecallDetector, () => new Recall() },
};
}
public Tuple<MenuItemSettings, Func<dynamic>> GetDirEntry(MenuItemSettings menuItem)
{
return new Tuple<MenuItemSettings, Func<dynamic>>(menuItem, MenuEntries[menuItem]);
}
public Dictionary<MenuItemSettings, Func<dynamic>> GetDirEntries()
{
return MenuEntries;
}
public void UpdateDirEntry(ref MenuItemSettings oldMenuItem, MenuItemSettings newMenuItem)
{
var save = MenuEntries[oldMenuItem];
MenuEntries.Remove(oldMenuItem);
MenuEntries.Add(newMenuItem, save);
oldMenuItem = newMenuItem;
}
}
class MainMenu2 : Menu2
{
public static MenuItemSettings Detector = new MenuItemSettings();
public static MenuItemSettings RecallDetector = new MenuItemSettings();
public MainMenu2()
{
MenuEntries =
new Dictionary<MenuItemSettings, Func<dynamic>>
{
{ RecallDetector, () => new Recall() },
};
}
}
internal class Program
{
private static bool threadActive = true;
private static float lastDebugTime = 0;
private static readonly Program instance = new Program();
private MainMenu mainMenu;
public static void Main(string[] args)
{
AssemblyResolver.Init();
AppDomain.CurrentDomain.DomainUnload += delegate { threadActive = false; };
AppDomain.CurrentDomain.ProcessExit += delegate { threadActive = false; };
Instance().Load();
}
public void Load()
{
mainMenu = new MainMenu();
LeagueSharp.SDK.Core.Events.Load.OnLoad += Game_OnGameLoad;
}
public static Program Instance()
{
return instance;
}
private async void Game_OnGameLoad(Object obj, EventArgs args)
{
CreateMenu();
Common.ShowNotification("SRecallDetector loaded!", Color.LawnGreen, 5000);
new Thread(GameOnOnGameUpdate).Start();
}
private void CreateMenu()
{
try
{
//Menu.MenuItemSettings tempSettings;
//var menu = new LeagueSharp.Common.Menu("SRecallDetector", "SRecallDetector", true);
//MainMenu.Detector = Detector.SetupMenu(menu, true);
//mainMenu.UpdateDirEntry(ref MainMenu.RecallDetector, Recall.SetupMenu(MainMenu.Detector.Menu));
//Menu.GlobalSettings.Menu =
// menu.AddSubMenu(new LeagueSharp.Common.Menu("Global Settings", "SAssembliesGlobalSettings"));
//Menu.GlobalSettings.MenuItems.Add(
// Menu.GlobalSettings.Menu.AddItem(
// new MenuItem("SAssembliesGlobalSettingsServerChatPingActive", "Server Chat/Ping").SetValue(
// false)));
//Menu.GlobalSettings.MenuItems.Add(
// Menu.GlobalSettings.Menu.AddItem(
// new MenuItem("SAssembliesGlobalSettingsVoiceVolume", "Voice Volume").SetValue(
// new Slider(100, 0, 100))));
//menu.AddItem(
// new MenuItem("By Screeder", "By Screeder V" + Assembly.GetExecutingAssembly().GetName().Version));
//menu.AddToMainMenu();
var menu = Menu2.CreateMainMenu();
Menu2.CreateGlobalMenuItems(menu);
//MainMenu.Detector = Detector.SetupMenu(menu, true);
//mainMenu.UpdateDirEntry(ref MainMenu.RecallDetector, Recall.SetupMenu(MainMenu.Detector.Menu));
Menu2.MenuItemSettings RecallDetector = new Menu2.MenuItemSettings(typeof(Recall));
RecallDetector.Menu = Menu2.AddMenu(ref menu, new LeagueSharp.SDK.Core.UI.IMenu.Menu("SAssembliesDetectorsRecall", Language.GetString("DETECTORS_RECALL_MAIN")));
Menu2.AddComponent(ref RecallDetector.Menu, new LeagueSharp.SDK.Core.UI.IMenu.Values.MenuSlider("SAssembliesDetectorsRecallPingTimes", Language.GetString("GLOBAL_PING_TIMES"), 0, 0, 5));
Menu2.AddComponent(ref RecallDetector.Menu, new LeagueSharp.SDK.Core.UI.IMenu.Values.MenuBool("SAssembliesDetectorsRecallLocalPing", Language.GetString("GLOBAL_PING_LOCAL"), true));
Menu2.AddComponent(ref RecallDetector.Menu, new LeagueSharp.SDK.Core.UI.IMenu.Values.MenuBool("SAssembliesDetectorsRecallChat", Language.GetString("GLOBAL_CHAT")));
Menu2.AddComponent(ref RecallDetector.Menu, new LeagueSharp.SDK.Core.UI.IMenu.Values.MenuBool("SAssembliesDetectorsRecallNotification", Language.GetString("GLOBAL_NOTIFICATION")));
Menu2.AddComponent(ref RecallDetector.Menu, new LeagueSharp.SDK.Core.UI.IMenu.Values.MenuBool("SAssembliesDetectorsRecallSpeech", Language.GetString("GLOBAL_VOICE")));
RecallDetector.CreateActiveMenuItem("SAssembliesDetectorsRecallActive");
MainMenu2.RecallDetector = RecallDetector;
}
catch (Exception)
{
throw;
}
}
private void GameOnOnGameUpdate()
{
try
{
while (threadActive)
{
Thread.Sleep(1000);
if (mainMenu == null)
{
continue;
}
foreach (var entry in mainMenu.GetDirEntries())
{
var item = entry.Key;
if (item == null)
{
continue;
}
try
{
if (item.GetActive() == false && item.Item != null)
{
item.Item = null;
}
else if (item.GetActive() && item.Item == null && !item.ForceDisable && item.Type != null)
{
try
{
item.Item = entry.Value();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
catch (Exception e) { }
}
}
}
catch (Exception e)
{
Console.WriteLine("SAssemblies: " + e);
threadActive = false;
}
}
}
} | mit |
Mobytes/landpage | src/Mobytes/Landpage/Controllers/LandPageController.php | 878 | <?php
/*
*
* * Copyright (C) 2015 eveR Vásquez.
* *
* * 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.
*
*/
namespace Mobytes\Landpage\Controllers;
use View;
use Config;
class LandPageController extends BaseController
{
public function home()
{
return View::make(Config::get('landpage::views.home.index'));
}
} | mit |
maritaria/UnityReader | UnityReader/Types/Quaternion.cs | 257 | using System;
using System.Collections.Generic;
using System.Linq;
namespace UnityReader.Types
{
public class Quaternion
{
public float X { get; set; }
public float Y { get; set; }
public float Z { get; set; }
public float W { get; set; }
}
} | mit |
nicolasmsg/react-blog | src/actions/index.js | 1033 | import axios from 'axios';
export const FETCH_POSTS = 'fetch_posts';
export const CREATE_POST = 'create_post';
export const FETCH_POST = 'fetch_post';
export const DELETE_POST = 'delete_post';
const ROOT_URL = "http://reduxblog.herokuapp.com/api";
const API_KEY = "?key=PAAsdfsdfsRRREE";
export function fetchPosts(){
const request = axios.get(`${ROOT_URL}/posts${API_KEY}`);
return {
type: FETCH_POSTS,
payload: request
};
}
export function createPost(values, callback){
const request = axios.post(`${ROOT_URL}/posts${API_KEY}`, values)
.then(() => callback());
return {
type: CREATE_POST,
payload: request
};
}
export function fetchPost(id){
const request = axios.get(`${ROOT_URL}/posts/${id}$${API_KEY}`);
return {
type: FETCH_POST,
payload: request
}
}
export function deletePost(id, callback){
const request = axios.delete(`${ROOT_URL}/posts/${id}$${API_KEY}`)
.then(() => callback());
return {
type: DELETE_POST,
payload: id
}
} | mit |
fweber1/Annies-Ancestors | add/php/testName.php | 6287 | <?php
error_reporting(E_ALL);
ini_set('display_errors', true);
date_default_timezone_set('EST5EDT'); // need to set time zone of server for date --> epoch time
$error = 'pending';
$response = array();
$returnStr = array();
include dirname(__FILE__) . "/../../php/database.php";
$link = mysqli_connect($host,$username,$password,$db_name);
if (!$link) {
$error = "an internal error was encountered";
returnWithError($error, $link);
}
// text input to run script as stand-alone for debugging
$data = "surname=johnson&namePrefix=&givenName=&middleName=&nameSuffix=&theNote=&theSource=&theQual=";
// get input to run script as forms handler
$data = $_SERVER['QUERY_STRING'];
// text input to run script as stand-alone for debugging
parse_str($data, $output);
if(isset($output['namePrefix'])) {$namePrefix = $output['namePrefix'];} else {$namePrefix = '';};
if(isset($output['givenName'])) {$givenName = $output['givenName'];} else {$givenName = '';};
if(isset($output['middleName'])) {$middleName = $output['middleName'];} else {$middleName = '';};
if(isset($output['surname'])) {$surname = $output['surname'];} else {$surname = '';};
if(isset($output['nameSuffix'])) {$nameSuffix = $output['nameSuffix'];} else {$nameSuffix = '';};
if(isset($output['theNote'])) {$theNote = $output['theNote'];} else {$theNote = '';};
if(isset($output['theSource'])) {$theSource = $output['theSource'];} else {$theSource = '';};
if(isset($output['theQual'])) {$theQual = $output['theQual'];} else {$theQual = '';};
// test for required inputs
if ($surname=="") {
$error = "The last name is required";
returnWithError($error, $link);
}
// remove any possible SQL injections in the form data
$namePrefix = test_input($link, $namePrefix);
$givenName = test_input($link, $givenName);
$middleName = test_input($link, $middleName);
$surname = test_input($link, $surname);
$nameSuffix = test_input($link, $nameSuffix);
$theNote = test_input($link, $theNote);
$theQual = test_input($link, $theQual);
$theSource = test_input($link, $theSource);
if ($theQual=='') $theQual = 0;
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$error = "Only letters and white spaces are allowed in the surname";
returnWithError($error, $link);
}
if (!preg_match("/^[a-zA-Z ]*$/",$namePrefix)) {
$error = "Only letters and white spaces are allowed in the name prefix";
returnWithError($error, $link);
}
if (!preg_match("/^[a-zA-Z ]*$/",$givenName)) {
$error = "Only letters and white spaces are allowed in the given name";
returnWithError($error, $link);
}
if (!preg_match("/^[a-zA-Z ]*$/",$middleName)) {
$error = "Only letters and white spaces are allowed in the middle name";
returnWithError($error, $link);
}
if (!preg_match("/^[a-zA-Z ]*$/",$nameSuffix)) {
$error = "Only letters and white spaces are allowed in the name suffix";
returnWithError($error, $link);
}
// check if person already exists
$which = "mainID, givenName, surname, if(birth IS NULL,'N/A', birth) AS birth, if(death IS NULL,'N/A', death) AS death, birthCity, deathCity, gender";
$where = "surname='$surname'";
if($namePrefix!='') $where = $where . " AND namePrefix='$namePrefix'";
if($givenName!='') $where = $where . " AND givenName='$givenName'";
if($middleName!='') $where = $where . " AND middleName='$middleName'";
if($nameSuffix!='') $where = $where . " AND nameSuffix='$nameSuffix'";
$sql = mysqli_query($link, "SELECT $which FROM main WHERE $where");
if($sql) {
$nRows = mysqli_num_rows($sql);
if($nRows>0) {
$response['nHits'] = "$nRows";
for ($i=0;$i<mysqli_num_rows($sql);$i++) {
$theName[$i] = mysqli_fetch_assoc($sql);
}
foreach ($theName as &$value) {
$value['fullName'] = $value['givenName'] . $value['surname'];
if($value['birth'] != 'N/A') $value['birth'] = date('F d, Y', strtotime($value['birth']));
if($value['death'] != 'N/A') $value['death'] = date('F d, Y', strtotime($value['death']));
if($value['birth'] != 'N/A') {
$value['birthDate'] = date('F d, Y', strtotime($value['birth']));
$value['birthYear'] = date('Y', strtotime($value['birth']));
} else {
$value['birthDate'] = 'N/A';
$value['birthYear'] = 'N/A';
}
if($value['death'] != 'N/A') {
$value['deathDate'] = date('F d, Y', strtotime($value['death']));
$value['deathYear'] = date('Y', strtotime($value['death']));
$value['showPerson']= true;
$value['living'] = false;
} else {
$value['deathDate'] = 'Living';
$value['deathYear'] = 'Living';
$value['showPerson']= true;
$value['living'] = true;
}
} $response['value'] = $theName;
returnWithDuplicates($response, $link);
};
}
// no one with the submitted name exists, so continue
// Attempt insert query execution
$createDate = date('Y-m-d h:i:s');
$which = "namePrefix,givenName,middleName,surname,nameSuffix,theNote,theQual,theSource,CREATEDATE";
$value = "'$namePrefix','$givenName','$middleName','$surname','$nameSuffix','$theNote','$theQual','$theSource','$createDate'";
mysqli_query($link, "INSERT INTO main ($which) VALUES ($value)");
if ($user_id = mysqli_insert_id($link)) {
$response = $user_id; // INSERT success
$source = dirname(__FILE__) . '/../../sheet/profilePhotos/missing.jpeg';
$dest = dirname(__FILE__) . '/../../sheet/profilePhotos/' . $user_id . '.jpeg';
$tmp = copy($source , $dest);
echo $tmp;
} else { // INSERT failure
$error = "Error: " . mysqli_error($link);
returnWithError($error, $link);
}
// return a response
http_response_code(200); //See https://docs.angularjs.org/api/ng/service/$http#json-vulnerability-protection
echo ")]}',\n" . json_encode($response); // )]}', is used to stop JSON attacks, angular strips it off for you.
mysqli_close($link);
return;
function returnWithDuplicates($response, $link) {
http_response_code(302);
echo ")]}',\n" . json_encode($response);
mysqli_close($link);
exit;
}
function returnWithError($response, $link) {
http_response_code(303);
echo ")]}',\n" . json_encode($response);
mysqli_close($link);
exit;
}
function test_input($link, $data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = mysqli_real_escape_string($link, $data);
return $data;
}
?> | mit |
TTtie/TTtie-Bot | commands/userinfo.js | 4432 | /**
* Copyright (C) 2020 tt.bot dev team
*
* This file is part of tt.bot.
*
* tt.bot is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* tt.bot is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with tt.bot. If not, see <http://www.gnu.org/licenses/>.
*/
"use strict";
const { Command, SerializedArgumentParser,
Serializers: { Member } } = require("sosamba");
const userByID = require("../lib/util/userByID");
const moment = require("moment");
const config = require("../config");
class UserCommand extends Command {
constructor(sosamba, ...args) {
super(sosamba, ...args, {
name: "userinfo",
argParser: new SerializedArgumentParser(sosamba, {
args: [{
default: ctx => ctx.member,
type: [Member, userByID],
rest: true,
name: "user",
description: "the user to get the information for"
}]
}),
description: "Gets some information about the user.",
aliases: ["uinfo"]
});
}
async run(ctx, [user]) {
if (user instanceof Member) {
const roles = user.roles.map(r => ctx.guild.roles.get(r).name);
roles.unshift("@everyone");
const nick = user.nick || this.sosamba.getTag(user);
ctx.send({
embed: {
author: {
name: await ctx.t("USER_INFO", `${nick} ${nick === this.sosamba.getTag(user) ? "" : `(${this.sosamba.getTag(user)})`} (${user.id}) ${user.bot ? "(BOT)" : ""}`)
},
thumbnail: {
url: user.user.avatarURL
},
fields: [{
name: await ctx.t("ROLES"),
value: roles.join(", ").length > 1024 ? await ctx.t("TOOLONG") : roles.join(", "),
inline: false
}, {
name: await ctx.t("CREATED_ON"),
value: await ctx.userProfile && (await ctx.userProfile).timezone ?
moment(new Date(user.createdAt)).tz((await ctx.userProfile).timezone).format(config.tzDateFormat) :
moment(new Date(user.createdAt)).format(config.normalDateFormat),
inline: true
}, {
name: await ctx.t("CURRENT_VOICE"),
value: ctx.guild.voiceStates.has(user.id) ?
ctx.guild.channels.get(ctx.guild.voiceStates.get(user.id).channelID)
.name : await ctx.t("NONE"),
inline: true
}],
timestamp: new Date(user.joinedAt),
footer: {
text: await ctx.t("JOINED_ON")
}
}
});
} else {
await ctx.send({
embed: {
title: await ctx.t("USER_INFO", this.sosamba.getTag(user)),
thumbnail: {
url: user.avatarURL
},
fields: [{
name: await ctx.t("CREATED_ON"),
value: await ctx.userProfile && (await ctx.userProfile).timezone ?
moment(new Date(user.createdAt)).tz((await ctx.userProfile).timezone).format(config.tzDateFormat) :
moment(new Date(user.createdAt)).format(config.normalDateFormat),
inline: true
}],
footer: {
// NOT_IN_SERVER
text: "They're not in this server, so that's everything I know 😥"
}
}
});
}
}
}
module.exports = UserCommand; | mit |
ScottLogic/bitflux-openfin | webpack/webpack.config.shared.js | 970 | module.exports = {
entry: {
child: ['babel-polyfill', './src/child/index.js'],
parent: ['babel-polyfill', './src/parent/parent.js'],
analytics: ['./src/parent/analytics/analytics.js']
},
output: {
filename: './[name]_bundle.js'
},
module: {
rules: [
{ test: /\.js$/, exclude: /node_modules(?!(\/|\\)openfin-layouts)/, loader: 'babel-loader' },
{ test: /\.less$/, loader: 'style-loader!css-loader!less-loader' },
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{ test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' },
{ test: /\.svg$/, loader: 'file-loader' },
{ test: /\.eot$/, loader: 'file-loader' },
{ test: /\.ttf$/, loader: 'file-loader' },
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'file-loader' }
]
},
resolve: {
extensions: ['.js']
},
plugins: []
};
| mit |
artsy/force-public | src/desktop/apps/partner2/test/routes.test.js | 2066 | /*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const { fabricate } = require("@artsy/antigravity")
const _ = require("underscore")
const sinon = require("sinon")
const Backbone = require("backbone")
const routes = require("../routes")
const Profile = require("../../../models/profile.coffee")
describe("Partner routes", function () {
beforeEach(function () {
sinon.stub(Backbone, "sync")
this.req = { body: {}, query: {}, params: { id: "foo" } }
this.res = { render: sinon.stub(), locals: { sd: {} } }
return (this.next = sinon.stub())
})
afterEach(() => Backbone.sync.restore())
return describe("#requireNewLayout", function () {
_.each(
["gallery_one", "gallery_two", "gallery_three", "institution"],
layout =>
it(`nexts to the middleware in this route stack if the profile layout is ${layout}`, function () {
const partnerProfile = new Profile(
fabricate("partner_profile", {
owner: fabricate("partner", { profile_layout: layout }),
})
)
this.res.locals.profile = partnerProfile
routes.requireNewLayout(this.req, this.res, this.next)
this.next.calledOnce.should.be.ok
return _.isUndefined(this.next.args[0][0]).should.be.ok()
})
)
return _.each(["gellery_default", "gallery_deprecated"], layout =>
it(`skips the middlewares from this route stack if the profile layout is ${layout}`, function () {
const deprecatedLayoutPartnerProfile = new Profile(
fabricate("partner_profile", {
owner: fabricate("partner", { profile_layout: layout }),
})
)
this.res.locals.profile = deprecatedLayoutPartnerProfile
routes.requireNewLayout(this.req, this.res, this.next)
this.next.calledOnce.should.be.ok
return this.next.args[0][0].should.equal("route")
})
)
})
})
| mit |
Tropicalista/axisJS | src/app/head/head.controller.js | 635 | /**
* @ngdoc function
* @name AxisJS.controller:HeadController
* @description
* # HeadController
* Adds stylesheets, fonts and other stuff in the `<head>` section.
*/
(function() {
'use strict';
angular
.module('axis')
.controller('HeadController', HeadController);
/** @ngInject */
function HeadController($scope, configProvider) {
configProvider.then(function(appConfig){
$scope.conf = appConfig;
$scope.stylesheet = typeof appConfig.stylesheet !== 'undefined' ? appConfig.stylesheet : '';
$scope.fonts = typeof appConfig.fonts !== 'undefined' ? appConfig.fonts : [];
});
}
})();
| mit |
redding/ns-options | test/unit/option_tests.rb | 16143 | require 'assert'
require 'ns-options/option'
require 'ns-options/boolean'
class NsOptions::Option
class BaseTests < Assert::Context
desc "NsOptions::Option"
setup do
@rules = { :default => "development" }
@option = NsOptions::Option.new(:stage, nil, @rules)
end
subject{ @option }
should have_class_methods :rules, :args
should have_accessors :name, :value, :type_class, :rules
should have_imeths :is_set?, :required?, :reset
should "know its name" do
assert_equal :stage, subject.name
end
should "know its type class" do
assert_equal Object, subject.type_class
end
should "know its rules" do
exp_rules = {
:default => "development",
:args => []
}
assert_equal exp_rules, subject.rules
end
should "not be required? by default" do
assert_equal false, subject.required?
end
end
class ParseArgsTests < BaseTests
desc "when parsing args"
setup do
@pname, @ptype_class, @prules = NsOptions::Option.args([:stage, String, @rules])
end
should "parse the name arg and convert to a string" do
assert_equal "stage", @pname
@pname, @ptype_class, @prules = NsOptions::Option.args(['test'])
assert_equal 'test', @pname
end
should "parse the type_class arg and default it to Object" do
assert_equal String, @ptype_class
@pname, @ptype_class, @prules = NsOptions::Option.args(['test'])
assert_equal Object, @ptype_class
end
should "parse the type_class arg and default it to a given default type class" do
assert_equal String, @ptype_class
@pname, @ptype_class, @prules = NsOptions::Option.args(['test'], Fixnum)
assert_equal Fixnum, @ptype_class
end
should "parse option rules arguments, defaulting to {:args => []}" do
assert_equal @rules, @prules
@pname, @ptype_class, @prules = NsOptions::Option.args(['test'])
assert_equal({:args => []}, @prules)
end
end
class DefaultRuleTests < BaseTests
desc "using the :default rule"
setup do
@option = NsOptions::Option.new(:opt, Object, :default => {})
end
should "have defaulted value based on the rule" do
assert_equal Hash.new, subject.value
end
should "allow overwriting the default value" do
assert_nothing_raised { subject.value = "overwritten" }
assert_equal "overwritten", subject.value
end
should "allow setting the value to nil" do
assert_nothing_raised { subject.value = nil }
assert_nil subject.value
end
should "return the value to its default when `reset` is called" do
subject.value = {:hash => 'overwritten'}
subject.reset
assert_equal Hash.new, subject.value
subject.value[:hash] = 'overwritten'
subject.reset
assert_equal Hash.new, subject.value
end
end
class RequiredRuleTests < BaseTests
desc "using the :required rule"
setup do
@option = NsOptions::Option.new(:opt, Object, :required => true)
end
should "return true with a call to #required?" do
assert_equal true, subject.required?
end
end
class ParseRulesTests < BaseTests
desc "parsing rules"
setup do
@cases = [nil, {}, {:args => 'is'}].map do |c|
NsOptions::Option.rules(c)
end
end
should "always return them as a Hash" do
@cases.each { |c| assert_kind_of Hash, c }
end
should "always return with an array args rule" do
@cases.each do |c|
assert c.has_key? :args
assert_kind_of Array, c[:args]
end
end
end
class IsSetTests < BaseTests
desc "is_set method"
setup do
@type_class = Class.new(String) do
def is_set?
self.gsub(/\s+/, '').size != 0
end
end
@special = NsOptions::Option.new(:no_blank, @type_class)
@boolean = NsOptions::Option.new(:boolean, NsOptions::Boolean)
end
should "return appropriately" do
@option.value = "abc"
assert_equal true, @option.is_set?
@option.value = nil
assert_equal false, @option.is_set?
@boolean.value = true
assert_equal true, @boolean.is_set?
@boolean.value = false
assert_equal true, @boolean.is_set?
end
should "use the type class's is_set method if available" do
@special.value = "not blank"
assert_equal true, @special.is_set?
@special.value = " "
assert_equal false, @special.is_set?
end
end
class EqualityOperatorTests < BaseTests
desc "== operator"
setup do
@first = NsOptions::Option.new(:stage, String)
@first.value = "test"
@second = NsOptions::Option.new(:stage, String)
@second.value = "test"
end
should "return true if their attributes are equal" do
[ :name, :type_class, :value, :rules ].each do |attribute|
assert_equal @first.send(attribute), @second.send(attribute)
end
assert_equal @first, @second
@first.value = "staging"
assert_not_equal @first, @second
end
end
class WithIntegerTypeClassTests < BaseTests
desc "with an Integer type class"
setup do
@option = NsOptions::Option.new(:something, Integer)
end
subject{ @option }
should "allow setting it's value" do
subject.value = 12
assert_equal 12, subject.value
end
should "allow setting it's value with a string and convert it" do
subject.value = "13"
assert_equal "13".to_i, subject.value
end
end
class WithFixnumTypeClassTests < BaseTests
desc "with a Fixnum type class"
setup do
@option = NsOptions::Option.new(:something, Fixnum)
end
subject{ @option }
should "allow setting it's value" do
subject.value = 12
assert_equal 12, subject.value
end
should "allow setting it's value with a string and convert it" do
subject.value = "13"
assert_equal "13".to_i, subject.value
end
end
class WithFloatTypeClassTests < BaseTests
desc "with a Float type class"
setup do
@option = NsOptions::Option.new(:something, Float)
end
subject{ @option }
should "allow setting it's value" do
subject.value = 12.5
assert_equal 12.5, subject.value
end
should "allow setting it's value with a string and convert it" do
subject.value = "13.4"
assert_equal "13.4".to_f, subject.value
end
should "allow setting it's value with an integer and convert it" do
subject.value = 1
assert_equal 1.to_f, subject.value
end
end
class WithStringTypeClassTests < BaseTests
desc "with an String type class"
setup do
@option = NsOptions::Option.new(:something, String)
end
subject{ @option }
should "allow setting it's value" do
subject.value = "12"
assert_equal "12", subject.value
end
should "allow setting it's value with a numeric and convert it" do
subject.value = 13
assert_equal 13.to_s, subject.value
subject.value = 13.5
assert_equal 13.5.to_s, subject.value
end
should "allow setting it's value with other things and convert it" do
subject.value = true
assert_equal true.to_s, subject.value
subject.value = NsOptions
assert_equal NsOptions.to_s, subject.value
end
end
class WithSymbolTypeClasstests < BaseTests
desc "with a Symbol as a type class"
setup do
@option = NsOptions::Option.new(:something, Symbol)
end
should "allow setting it with any object that responds to #to_sym" do
value = "amazing"
subject.value = value
assert_equal value.to_sym, subject.value
value = :another
subject.value = value
assert_equal value, subject.value
object_class = Class.new do
def to_sym; :object_sym; end
end
value = object_class.new
subject.value = value
assert_equal object_class.new.to_sym, subject.value
end
should "error on anything that doesn't define #to_sym" do
assert_raises(NsOptions::Option::CoerceError) do
subject.value = true
end
end
end
class WithHashTypeClassTests < BaseTests
desc "with a Hash as a type class"
setup do
@option = NsOptions::Option.new(:something, Hash)
end
subject{ @option }
should "allow setting it with a hash" do
new_value = { :another => true }
subject.value = new_value
assert_equal new_value, subject.value
end
end
class WithArrayTypeClassTests < BaseTests
desc "with an Array as a type class"
setup do
@option = NsOptions::Option.new(:something, Array)
end
subject{ @option }
should "allow setting it with a array" do
expected = [ :something, :else, :another ]
subject.value = [ :something, :else, :another ]
assert_equal expected, subject.value
end
should "allow setting it with a single value" do
expected = [ :something ]
subject.value = :something
assert_equal expected, subject.value
end
end
class WithTypeClassArgErrorTests < BaseTests
desc "setting a value with arg error"
setup do
@err = begin
raise ArgumentError, "some test error"
rescue ArgumentError => err
err
end
class SuperSuperTestTest
def initialize(*args)
raise ArgumentError, "some test error"
end
end
@option = NsOptions::Option.new(:something, SuperSuperTestTest)
end
should "reraise as a CoerceError with a custom message and backtrace" do
err = begin
@option.value = "arg error should be raised"
rescue Exception => err
err
end
assert_equal NsOptions::Option::CoerceError, err.class
assert_included @option.type_class.to_s, err.message
assert_included 'test/unit/option_tests.rb:', err.backtrace.first
end
end
class WithAValueOfTheSameClassTests < BaseTests
desc "with a value of the same class"
setup do
@class = Class.new
@option = NsOptions::Option.new(:something, @class)
end
should "use the object passed to it instead of creating a new one" do
value = @class.new
@option.value = value
assert_same value, @option.value
end
end
class WithAValueKindOfTests < BaseTests
desc "with a value that is a kind of the class"
setup do
@class = Class.new
@child_class = Class.new(@class)
@option = NsOptions::Option.new(:something, @class)
end
should "use the object passed to it instead of creating a new one" do
value = @child_class.new
@option.value = value
assert_same value, @option.value
end
end
class ProcHandlingTests < BaseTests
setup do
class KindOfProc < Proc; end
@a_string = "a string"
@direct_proc = Proc.new { "I can haz eval: #{@a_string}" }
@subclass_proc = KindOfProc.new { 12345 }
@direct_opt = NsOptions::Option.new(:direct, Proc)
@subclass_opt = NsOptions::Option.new(:subclass, KindOfProc)
end
end
class WithProcTypeClassTests < ProcHandlingTests
desc "with Proc as a type class"
setup do
@direct_opt.value = @direct_proc
@subclass_opt.value = @subclass_proc
end
should "allow setting it with a proc" do
assert_kind_of Proc, @direct_opt.value
assert_kind_of KindOfProc, @subclass_opt.value
assert_equal @direct_proc, @direct_opt.value
assert_equal @subclass_proc, @subclass_opt.value
end
end
class WithLazyProcTests < ProcHandlingTests
desc "with a Proc value but no Proc-ancestor type class"
setup do
@string_opt = NsOptions::Option.new(:string, String)
end
should "set the Proc and coerce the Proc return val when read" do
@string_opt.value = @direct_proc
assert_kind_of String, @string_opt.value
assert_equal "I can haz eval: a string", @string_opt.value
@a_string = "a new string"
assert_equal "I can haz eval: a new string", @string_opt.value
@string_opt.value = @subclass_proc
assert_kind_of String, @string_opt.value
assert_equal "12345", @string_opt.value
end
end
class WithReturnValueTests < BaseTests
setup do
# test control values
@string = NsOptions::Option.new :string, String
@symbol = NsOptions::Option.new :symbol, Symbol
@integer = NsOptions::Option.new :integer, Integer
@float = NsOptions::Option.new :float, Float
@hash = NsOptions::Option.new :hash, Hash
@array = NsOptions::Option.new :array, Array
@proc = NsOptions::Option.new :proc, Proc
@lazy_proc = NsOptions::Option.new :lazy_proc, Object
# custom return value
class HostedAt
# sanitized :hosted_at config
# remove any trailing '/'
# ensure single leading '/'
def initialize(value)
@hosted_at = value.sub(/\/+$/, '').sub(/^\/*/, '/')
end
def returned_value
@hosted_at
end
end
@hosted_at = NsOptions::Option.new(:hosted_at, HostedAt)
end
should "return values normally when no `returned_value` is specified" do
@string.value = "test"
assert_equal "test", @string.value
@symbol.value = :test
assert_equal :test, @symbol.value
@integer.value = 1
assert_equal 1, @integer.value
@float.value = 1.1
assert_equal 1.1, @float.value
@hash.value = {:test => 'test'}
assert_equal({:test => 'test'}, @hash.value)
@array.value = ['test']
assert_equal ['test'], @array.value
@proc.value = Proc.new { 'test' }
assert_kind_of Proc, @proc.value
@lazy_proc.value = Proc.new { 'lazy test' }
assert_equal 'lazy test', @lazy_proc.value
end
should "should honor `returned_value` when returning option values" do
@hosted_at.value = "path/to/resource/"
assert_equal '/path/to/resource', @hosted_at.value
@hosted_at.value = proc{ "path/to/resource/" }
assert_equal '/path/to/resource', @hosted_at.value
end
end
class WithArgsTests < BaseTests
desc "with args rule"
setup do
@class = Class.new do
attr_accessor :args
def initialize(*args)
self.args = args
end
end
end
class AsArrayTests < WithArgsTests
desc "as an array"
setup do
@args = [ true, false, { :hash => "yes" } ]
@option = NsOptions::Option.new(:something, @class, { :args => @args })
@option.value = "amazing"
end
should "pass the args to the type class with the value" do
expected = ["amazing", *@args]
assert_equal expected, subject.value.args
end
end
class AsSingleValueTests < WithArgsTests
desc "as a single value"
setup do
@args = lambda{ "something" }
@option = NsOptions::Option.new(:something, @class, { :args => @args })
@option.value = "amazing"
end
should "pass the single value to the type class with the value" do
expected = ["amazing", *@args]
assert_equal expected, subject.value.args
end
end
class AsNilValueTests < WithArgsTests
desc "as a nil value"
setup do
@args = nil
@option = NsOptions::Option.new(:something, @class, { :args => @args })
@option.value = "amazing"
end
should "just pass the value to the type class and that's it" do
expected = ["amazing"]
assert_equal expected, subject.value.args
end
end
class AsEmptyArrayValueTests < WithArgsTests
desc "as an empty Array value"
setup do
@args = []
@option = NsOptions::Option.new(:something, @class, { :args => @args })
@option.value = "amazing"
end
should "just pass the value to the type class and that's it" do
expected = ["amazing"]
assert_equal expected, subject.value.args
end
end
end
end
| mit |
redding/ns-options | test/system/user_tests.rb | 4187 | require 'assert'
require 'ns-options/assert_macros'
require 'test/support/user'
class User
class BaseTests < Assert::Context
include NsOptions::AssertMacros
desc "the User class"
setup do
@class = User
end
subject{ @class }
should have_reader :preferences
end
class ClassPreferencesTests < BaseTests
desc "preferences"
subject{ @class.preferences }
should have_option :home_url
should have_option :show_messages, NsOptions::Boolean, :required => true
should have_option :font_size, Integer, :default => 12
should have_namespace :view do
option :color
end
end
class ClassInheritedPreferencesTests < ClassPreferencesTests
desc "on a subclass of User"
setup do
User.preferences.home_url = "/home"
User.preferences.show_messages = false
User.preferences.font_size = 15
User.preferences.view.color = "green"
@a_sub_class = Class.new(User)
end
subject { @a_sub_class.preferences }
should have_option :home_url
should have_option :show_messages, NsOptions::Boolean, :required => true
should have_option :font_size, Integer, :default => 12
should have_namespace :view do
option :color
end
should "not have the same preference values as its superclass" do
assert_not_equal "/home", subject.home_url
assert_not_equal false, subject.show_messages
assert_not_equal 15, subject.font_size
assert_not_equal "green", subject.view.color
end
end
class InstanceTests < BaseTests
desc "instance"
setup do
@instance = @class.new
@class_preferences = @class.preferences
@class_preferences.home_url = "/something"
@preferences = @instance.preferences
end
subject{ @instance }
should have_instance_methods :preferences
should "have a new namespace that is a different object than the class namespace" do
assert_not_same @class_preferences, @preferences
end
should "have the same options as the class namespace, but different objects" do
@class_preferences.__data__.child_options.each do |name, class_opt|
inst_opt = @preferences.__data__.child_options[name]
assert_equal class_opt.name, inst_opt.name
assert_equal class_opt.type_class, inst_opt.type_class
assert_equal class_opt.rules, inst_opt.rules
assert_not_same class_opt, inst_opt
end
assert_not_equal @class_preferences.home_url, @preferences.home_url
end
should "have the same named namespaces as the class, but different objects" do
@class_preferences.__data__.child_namespaces.each do |name, class_ns|
assert_not_same class_ns, @preferences.__data__.child_namespaces[name]
end
end
end
class InstancePreferencesTests < InstanceTests
desc "preferences"
setup do
@instance.preferences.home_url = "/home"
@instance.preferences.show_messages = false
@instance.preferences.font_size = 15
@instance.preferences.view.color = "green"
end
subject{ @instance.preferences }
should have_option :home_url
should have_option :show_messages, NsOptions::Boolean, :required => true
should have_option :font_size, Integer, :default => 12
should have_namespace :view do
option :color
end
should "have set the preference values" do
assert_equal "/home", subject.home_url
assert_equal false, subject.show_messages
assert_equal 15, subject.font_size
assert_equal "green", subject.view.color
end
end
class InstanceInheritedPreferencesTests < InstancePreferencesTests
desc "on an instance of a subclass of User"
setup do
@a_sub_class = Class.new(User)
@the_sub_class = @a_sub_class.new
end
subject { @the_sub_class.preferences }
should have_option :home_url
should have_option :show_messages, NsOptions::Boolean, :required => true
should have_option :font_size, Integer, :default => 12
should have_namespace :view do
option :color
end
end
end
| mit |
jeremybuis/bearded-octo-archer | src/main/webapp/resources/js/aloha-config.js | 747 | (function(window, undefined) {
var jQuery = window.jQuery;
if (window.Aloha === undefined || window.Aloha === null) {
window.Aloha = {};
}
window.Aloha.settings = {
bundles : {
common:"http://aloha-editor.org/aloha-0.20/plugins/common/"
},
logLevels: {'error': true, 'warn': true, 'info': true, 'debug': false},
errorhandling : false,
ribbon: false,
"i18n": {
"current": "en"
},
"plugins": {
"format": {
config : [ 'b', 'i', 'p', 'sub', 'sup' ],
editables : {
},
// those are the tags that will be cleaned when clicking "remove formatting"
removeFormats : [ 'strong', 'em', 'b', 'i', 'cite', 'q', 'code', 'abbr', 'del', 'sub', 'sup']
}
},
"sidebar": {
disabled: true
}
};
})(window); | mit |
rutgerkok/BlockLocker | src/main/java/nl/rutgerkok/blocklocker/impl/event/InteractListener.java | 20878 | package nl.rutgerkok.blocklocker.impl.event;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.Tag;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.DoubleChest;
import org.bukkit.block.Sign;
import org.bukkit.block.data.Levelled;
import org.bukkit.block.data.Waterlogged;
import org.bukkit.block.data.type.WallSign;
import org.bukkit.entity.Player;
import org.bukkit.entity.Villager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.entity.EntityInteractEvent;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import com.google.common.collect.ImmutableSet;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ClickEvent;
import nl.rutgerkok.blocklocker.AttackType;
import nl.rutgerkok.blocklocker.Permissions;
import nl.rutgerkok.blocklocker.ProtectionSign;
import nl.rutgerkok.blocklocker.SignType;
import nl.rutgerkok.blocklocker.Translator.Translation;
import nl.rutgerkok.blocklocker.event.PlayerProtectionCreateEvent;
import nl.rutgerkok.blocklocker.impl.BlockLockerPluginImpl;
import nl.rutgerkok.blocklocker.impl.TextComponents;
import nl.rutgerkok.blocklocker.location.IllegalLocationException;
import nl.rutgerkok.blocklocker.profile.PlayerProfile;
import nl.rutgerkok.blocklocker.profile.Profile;
import nl.rutgerkok.blocklocker.protection.Protection;
import nl.rutgerkok.blocklocker.protection.Protection.SoundCondition;
public final class InteractListener extends EventListener {
private static Set<BlockFace> AUTOPLACE_BLOCK_FACES = ImmutableSet.of(BlockFace.NORTH, BlockFace.EAST,
BlockFace.SOUTH, BlockFace.WEST, BlockFace.UP);
public InteractListener(BlockLockerPluginImpl plugin) {
super(plugin);
}
private boolean allowedByBlockPlaceEvent(Block placedBlock, BlockState replacedBlockState, Block placedAgainst,
EquipmentSlot placedUsingHand, Player player) {
Material originalMaterial = placedBlock.getType();
ItemStack itemInHand = placedUsingHand == EquipmentSlot.OFF_HAND ? player.getInventory().getItemInOffHand()
: player.getInventory().getItemInMainHand();
BlockPlaceEvent placeEvent = new BlockPlaceEvent(placedBlock, replacedBlockState, placedAgainst,
itemInHand, player, true, placedUsingHand);
Bukkit.getPluginManager().callEvent(placeEvent);
Material placedMaterial = placeEvent.getBlockPlaced().getType();
if (placeEvent.isCancelled() || !placedMaterial.equals(originalMaterial)) {
// We consider the event cancelled too when the placed block was
// changed
return false;
}
return true;
}
/**
* Gets whether players are allowed to build in the given game mode.
*
* @param gameMode
* The game mode, may be null.
* @return True for survival and creative, false for the other modes.
*/
private boolean canBuildInMode(GameMode gameMode) {
if (gameMode == null) {
return false;
}
switch (gameMode) {
case ADVENTURE:
return false;
case CREATIVE:
return true;
case SPECTATOR:
return false;
case SURVIVAL:
return true;
default:
return false; // Speculative
}
}
private boolean checkAllowed(Player player, Protection protection, boolean clickedSign) {
PlayerProfile playerProfile = plugin.getProfileFactory().fromPlayer(player);
boolean allowed = protection.isAllowed(playerProfile);
// Check for expired protection
if (!allowed && isExpired(protection)) {
plugin.getTranslator().sendMessage(player, Translation.PROTECTION_EXPIRED);
allowed = true;
}
// Allow admins to bypass the protection
if (!allowed && player.hasPermission(Permissions.CAN_BYPASS)) {
allowed = true;
if (!clickedSign) {
// Only show message about bypass when not clicking a sign
String ownerName = protection.getOwnerDisplayName();
plugin.getTranslator().sendMessage(player, Translation.PROTECTION_BYPASSED, ownerName);
}
}
return allowed;
}
/**
* Gets the block the inventory is stored in, or null if the inventory is not
* stored in a block.
*
* @param inventory The inventory.
* @return The block, or null.
*/
private Block getInventoryBlockOrNull(Inventory inventory) {
InventoryHolder holder = inventory.getHolder();
if (holder instanceof BlockState) {
return ((BlockState) holder).getBlock();
}
if (holder instanceof DoubleChest) {
InventoryHolder leftHolder = ((DoubleChest) holder).getLeftSide();
if (leftHolder instanceof BlockState) {
return ((BlockState) leftHolder).getBlock();
}
}
return null;
}
private org.bukkit.block.data.type.Sign getRotatedSignPost(Player player, Material signMaterial) {
float rotation = player.getLocation().getYaw();
if (rotation < 0) {
rotation += 360.0f;
}
org.bukkit.block.data.type.Sign materialData = (org.bukkit.block.data.type.Sign) signMaterial
.createBlockData();
materialData.setRotation(rotationToBlockFace(rotation));
return materialData;
}
private Waterlogged getSignBlockData(BlockFace blockFace, Player player, Material signMaterial) {
if (blockFace == BlockFace.UP) {
// Place standing sign in direction of player
return getRotatedSignPost(player, signMaterial);
} else {
// Place attached sign
WallSign wallSignData = (WallSign) toWallSign(signMaterial).createBlockData();
wallSignData.setFacing(blockFace);
return wallSignData;
}
}
private Optional<Material> getSignInHand(Player player, EquipmentSlot hand) {
PlayerInventory inventory = player.getInventory();
ItemStack item = hand == EquipmentSlot.OFF_HAND ? inventory.getItemInOffHand() : inventory.getItemInMainHand();
if (isOfType(item, Tag.SIGNS)) {
return Optional.of(item.getType());
}
return Optional.empty();
}
private void handleAllowed(PlayerInteractEvent event, Protection protection, boolean clickedSign,
boolean usedOffHand) {
Block clickedBlock = event.getClickedBlock();
Player player = event.getPlayer();
PlayerProfile playerProfile = plugin.getProfileFactory().fromPlayer(player);
boolean isOwner = protection.isOwner(playerProfile);
// Select signs
if (clickedSign) {
if ((isOwner || player.hasPermission(Permissions.CAN_BYPASS)) && !usedOffHand) {
Sign sign = (Sign) clickedBlock.getState();
plugin.getSignSelector().setSelectedSign(player, sign);
sendSelectedSignMessage(player);
}
return;
}
// Add [More Users] sign
if (isOwner && tryPlaceSign(player, clickedBlock, event.getBlockFace(), event.getHand(), SignType.MORE_USERS)) {
event.setCancelled(true);
return;
}
// Open (double/trap/fence) doors manually
boolean clickedMainBlock = plugin.getChestSettings().canProtect(clickedBlock);
if (protection.canBeOpened() && !isSneakPlacing(player) && clickedMainBlock) {
event.setCancelled(true);
if (!usedOffHand) {
if (protection.isOpen()) {
protection.setOpen(false, SoundCondition.AUTOMATIC);
} else {
protection.setOpen(true, SoundCondition.AUTOMATIC);
}
// Schedule automatic close
scheduleClose(protection);
}
}
}
private void handleDisallowed(PlayerInteractEvent event, Protection protection, boolean clickedSign,
boolean usedOffHand) {
event.setCancelled(true);
if (usedOffHand) {
// Don't send messages
return;
}
Player player = event.getPlayer();
if (clickedSign) {
plugin.getTranslator()
.sendMessage(player, Translation.PROTECTION_IS_CLAIMED_BY, protection.getOwnerDisplayName());
} else {
plugin.getTranslator()
.sendMessage(player, Translation.PROTECTION_NO_ACCESS, protection.getOwnerDisplayName());
}
}
private boolean isNullOrAir(ItemStack stack) {
return stack == null || stack.getType() == Material.AIR || stack.getAmount() == 0;
}
private boolean isOfType(ItemStack stackOrNull, Tag<Material> tag) {
if (stackOrNull == null) {
return false;
}
return tag.isTagged(stackOrNull.getType());
}
private boolean isSneakPlacing(Player player) {
if (!player.isSneaking()) {
return false;
}
if (isNullOrAir(player.getInventory().getItemInMainHand())) {
return false;
}
if (isNullOrAir(player.getInventory().getItemInOffHand())) {
return false;
}
return true;
}
@EventHandler(ignoreCancelled = true)
public void onEntityInteract(EntityInteractEvent event) {
// Prevents villagers from opening doors
if (!(event.getEntity() instanceof Villager)) {
return;
}
if (plugin.getChestSettings().allowDestroyBy(AttackType.VILLAGER)) {
return;
}
if (isProtected(event.getBlock())) {
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true)
public void onInventoryMoveItemEvent(InventoryMoveItemEvent event) {
Block from = getInventoryBlockOrNull(event.getSource());
if(from != null) {
if (isRedstoneDenied(from)) {
event.setCancelled(true);
return;
}
}
Block to = getInventoryBlockOrNull(event.getDestination());
if (to != null) {
if (isRedstoneDenied(to)) {
event.setCancelled(true);
return;
}
}
}
/**
* Prevents access to containers.
*
* @param event The event object.
*/
@EventHandler(ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getAction() != Action.RIGHT_CLICK_BLOCK) {
return;
}
Player player = event.getPlayer();
Block block = event.getClickedBlock();
Material material = block.getType();
boolean clickedSign = Tag.STANDING_SIGNS.isTagged(material) || Tag.WALL_SIGNS.isTagged(material);
// When using the offhand check, access checks must still be performed,
// but no messages must be sent
boolean usedOffHand = event.getHand() == EquipmentSlot.OFF_HAND;
Optional<Protection> protection = plugin.getProtectionFinder().findProtection(block);
if (!protection.isPresent()) {
if (tryPlaceSign(event.getPlayer(), block, event.getBlockFace(), event.getHand(), SignType.PRIVATE)) {
event.setCancelled(true);
}
return;
}
// Check if protection needs update
plugin.getProtectionUpdater().update(protection.get(), false);
// Check if player is allowed, open door
if (checkAllowed(player, protection.get(), clickedSign)) {
handleAllowed(event, protection.get(), clickedSign, usedOffHand);
} else {
handleDisallowed(event, protection.get(), clickedSign, usedOffHand);
}
}
private ItemStack removeOneItem(ItemStack item) {
if (item.getAmount() > 1) {
item.setAmount(item.getAmount() - 1);
return item;
} else {
return null;
}
}
private void removeSingleSignFromHand(Player player) {
if (player.getGameMode() == GameMode.CREATIVE) {
return;
}
// Keep order (main, then off hand) the same as in getSignInHand - otherwise you
// might remove the wrong sign
PlayerInventory inventory = player.getInventory();
if (isOfType(inventory.getItemInMainHand(), Tag.SIGNS)) {
inventory.setItemInMainHand(removeOneItem(inventory.getItemInMainHand()));
} else if (isOfType(inventory.getItemInOffHand(), Tag.SIGNS)) {
inventory.setItemInOffHand(removeOneItem(inventory.getItemInOffHand()));
}
}
private BlockFace rotationToBlockFace(float rotation) {
int intRotation = Math.round((rotation / 360.0f) * 16.0f);
byte dataValue = (byte) ((intRotation + 8) % 16);
switch (dataValue) {
case 0x0:
return BlockFace.SOUTH;
case 0x1:
return BlockFace.SOUTH_SOUTH_WEST;
case 0x2:
return BlockFace.SOUTH_WEST;
case 0x3:
return BlockFace.WEST_SOUTH_WEST;
case 0x4:
return BlockFace.WEST;
case 0x5:
return BlockFace.WEST_NORTH_WEST;
case 0x6:
return BlockFace.NORTH_WEST;
case 0x7:
return BlockFace.NORTH_NORTH_WEST;
case 0x8:
return BlockFace.NORTH;
case 0x9:
return BlockFace.NORTH_NORTH_EAST;
case 0xA:
return BlockFace.NORTH_EAST;
case 0xB:
return BlockFace.EAST_NORTH_EAST;
case 0xC:
return BlockFace.EAST;
case 0xD:
return BlockFace.EAST_SOUTH_EAST;
case 0xE:
return BlockFace.SOUTH_EAST;
case 0xF:
return BlockFace.SOUTH_SOUTH_EAST;
}
throw new RuntimeException("Couldn't handle rotation " + rotation);
}
private void scheduleClose(final Protection protection) {
if (!protection.isOpen()) {
return;
}
int openSeconds = protection.getOpenSeconds();
if (openSeconds == -1) {
// Not specified, use default
openSeconds = plugin.getChestSettings().getDefaultDoorOpenSeconds();
}
if (openSeconds <= 0) {
return;
}
plugin.runLater(() -> protection.setOpen(false, SoundCondition.ALWAYS), openSeconds * 20);
}
private void sendSelectedSignMessage(Player player) {
String message = plugin.getTranslator().get(Translation.PROTECTION_SELECTED_SIGN);
List<BaseComponent> textComponent = new ArrayList<>();
while (true) {
int firstOpenBracket = message.indexOf("[");
if (firstOpenBracket == -1) {
// No new opening bracket
TextComponents.addLegacyText(textComponent, message);
break;
}
// Add everything up to the closing bracket
TextComponents.addLegacyText(textComponent, message.substring(0, firstOpenBracket));
// Check what's after the opening bracket
String remainingMessage = message.substring(firstOpenBracket);
int closeBracketIndex = remainingMessage.indexOf("]");
if (closeBracketIndex == -1) {
TextComponents.addLegacyText(textComponent, remainingMessage);
break;
}
// Add this part as link
String linkText = remainingMessage.substring(0, closeBracketIndex + 1);
String textOnLine = ChatColor.stripColor(linkText);
TextComponents.addLegacyText(textComponent, linkText, part -> {
part.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND,
"/blocklocker:blocklocker ~ " + textOnLine));
});
// Next!
message = remainingMessage.substring(closeBracketIndex + 1);
}
player.spigot().sendMessage(textComponent.toArray(new BaseComponent[textComponent.size()]));
}
private Material toWallSign(Material signMaterial) {
return Material.valueOf(signMaterial.name().replace("_SIGN", "_WALL_SIGN"));
}
private boolean tryPlaceSign(Player player, Block block, BlockFace clickedSide, EquipmentSlot hand,
SignType signType) {
if (player.isSneaking() || !canBuildInMode(player.getGameMode())) {
return false;
}
Optional<Material> optionalSignMaterial = getSignInHand(player, hand);
if (!optionalSignMaterial.isPresent()) {
return false;
}
Material signMaterial = optionalSignMaterial.get();
if (!plugin.getProtectionFinder().isProtectable(block)) {
return false;
}
if (!player.hasPermission(Permissions.CAN_PROTECT)) {
return false;
}
if (!AUTOPLACE_BLOCK_FACES.contains(clickedSide)) {
return false;
}
try {
plugin.getLocationCheckers().checkLocationAndPermission(player, block);
} catch (IllegalLocationException e) {
return false;
}
Block signBlock = block.getRelative(clickedSide);
boolean waterlogged = false;
if (!signBlock.getType().isAir()) {
if (signBlock.getType() != Material.WATER) {
return false;
}
// So block is a water block - check its water level
waterlogged = ((Levelled) signBlock.getBlockData()).getLevel() == 0;
}
// Fire our PlayerProtectionCreateEvent
if (this.plugin.callEvent(new PlayerProtectionCreateEvent(player, signBlock)).isCancelled()) {
return false;
}
// Create sign and fire Bukkit's BlockPlaceEvent for the sign to be placed
BlockState oldState = signBlock.getState();
Waterlogged newBlockData = getSignBlockData(clickedSide, player, signMaterial);
newBlockData.setWaterlogged(waterlogged);
signBlock.setBlockData(newBlockData);
if (!allowedByBlockPlaceEvent(signBlock, oldState, block, hand, player)) {
// Revert to old state
oldState.update(true);
return false;
}
// Get state again now that block has been changed, so that it can
// be casted to Sign
Sign sign = (Sign) signBlock.getState();
// Decide what the text on the sign is going to be
Profile profile = signType.isMainSign() ? plugin.getProfileFactory().fromPlayer(player)
: plugin.getProfileFactory().fromRedstone();
ProtectionSign protectionSign = plugin.getProtectionFinder().newProtectionSign(sign, signType, profile);
String[] newLines = plugin.getSignParser().getDisplayLines(protectionSign);
// Test if we can place it
SignChangeEvent signChangeEvent = new SignChangeEvent(sign.getBlock(), player, newLines);
Bukkit.getPluginManager().callEvent(signChangeEvent);
if (sign.getBlock().getType() != sign.getType()) {
// The plugin listening to the event removed/replaced the sign
removeSingleSignFromHand(player); // We're forced to consume the sign, to avoid item duplication
return false; // Report as failed
}
if (signChangeEvent.isCancelled()) {
// Event failed, revert to old state
oldState.update(true); // Remove the entire sign, to avoid leaving an empty sign
return false; // And report as failed (player will keep the sign)
}
// Actually write the text
for (int i = 0; i < newLines.length; i++) {
sign.setLine(i, newLines[i]);
}
sign.update();
// Remove the sign from the player's hand
removeSingleSignFromHand(player);
return true;
}
}
| mit |
Invoiced/invoiced-go | errors.go | 398 | package invoiced
import (
"encoding/json"
)
type APIError struct {
Type string `json:"type"`
Message string `json:"message"`
Param string `json:"param"`
}
func NewAPIError(typeE, message, param string) *APIError {
err := &APIError{typeE, message, param}
return err
}
func (a *APIError) Error() string {
b, err := json.Marshal(a)
if err != nil {
return ""
}
return string(b)
}
| mit |
CodePeasants/pyplan | tests/test_organizer.py | 3896 | import os
from functools import partial
import unittest
from plan.user import User
from plan.event import Event
from plan.organizer import Organizer
from plan.schedule import Schedule
from plan.time_range import TimeRange
from plan.member import Status
class TestOrganizer(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestOrganizer, self).__init__(*args, **kwargs)
self.owner = User('foo')
self.invited_user = User('bar')
self.uninvited_user = User('foobar')
self.event = Event('a', self.owner)
self.invited_member = self.event.registry.register(self.invited_user)
self.uninvited_member = self.event.registry.register(self.uninvited_user, Status.NOT_INVITED)
def test_init(self):
org = Organizer(self.event)
self.assertFalse(org.votes)
self.assertFalse(org.potential_schedules)
def test_add_potential_schedule(self):
org = Organizer(self.event)
schedule = Schedule()
org.add_potential_schedule(schedule)
self.assertEqual([schedule], list(org.potential_schedules))
def test_remove_potential_schedule(self):
org = Organizer(self.event, [Schedule()])
org.remove_potential_schedule(org.potential_schedules[0])
self.assertFalse(org.potential_schedules)
def test_vote(self):
schedule_a = Schedule()
schedule_b = Schedule()
schedule_a.add_time(TimeRange.now())
schedule_b.add_time(TimeRange.now())
org = Organizer(self.event, [schedule_a, schedule_b])
org.vote(self.invited_member, schedule_b)
self.assertEqual({self.invited_member: set([schedule_b])}, org.votes)
def test_vote_multiple(self):
schedule_a = Schedule()
schedule_b = Schedule()
schedule_a.add_time(TimeRange.now())
schedule_b.add_time(TimeRange.now())
org = Organizer(self.event, [schedule_a, schedule_b])
org.vote(self.invited_member, schedule_b)
org.vote(self.invited_member, schedule_b)
self.assertEqual({self.invited_member: set([schedule_b])}, org.votes)
def test_vote_change(self):
schedule_a = Schedule()
schedule_b = Schedule()
schedule_a.add_time(TimeRange.now())
schedule_b.add_time(TimeRange.now())
org = Organizer(self.event, [schedule_a, schedule_b])
org.vote(self.invited_member, schedule_b)
org.vote(self.invited_member, schedule_a)
self.assertEqual({self.invited_member: set([schedule_a])}, org.votes)
def test_vote_invalid_member(self):
schedule_a = Schedule()
schedule_b = Schedule()
schedule_a.add_time(TimeRange.now())
schedule_b.add_time(TimeRange.now())
org = Organizer(self.event, [schedule_a, schedule_b])
func = partial(org.vote, self.uninvited_member, schedule_a)
self.assertRaises(PermissionError, func)
self.assertEqual({}, org.votes)
def test_get_best_schedule(self):
schedule_a = Schedule()
schedule_b = Schedule()
schedule_a.add_time(TimeRange.now())
schedule_b.add_time(TimeRange.now())
org = Organizer(self.event, [schedule_a, schedule_b])
org.vote(self.invited_member, schedule_b)
self.assertEqual(schedule_b, org.get_best_schedule())
def test_confirm_schedule(self):
schedule_a = Schedule()
org = Organizer(self.event, [schedule_a])
self.assertEqual(None, org.schedule)
org.confirm_schedule(schedule_a)
self.assertEqual(schedule_a, org.schedule)
def test_unconfirm_schedule(self):
schedule_a = Schedule()
org = Organizer(self.event, [schedule_a])
org.confirm_schedule(schedule_a)
org.unconfirm_schedule()
self.assertEqual(None, org.schedule)
if __name__ == '__main__':
unittest.main()
| mit |
sevmardi/University-of-Applied-Sciences-Leiden | IIAD/week5/queue/TestQueueDeque.java | 1390 | package week5.queue;
public class TestQueueDeque
{
public static void main(String args[])
{
ListQueue listqueue = new ListQueue();
listqueue.enqueue( "Een" );
listqueue.enqueue( "Twee" );
listqueue.enqueue( "Drie" );
System.out.println(listqueue.front().toString() + " is de eerste");
System.out.println(listqueue.size() + " is het aantal");
System.out.println(listqueue.dequeue() + " is verwijderd");
System.out.println(listqueue.front() + " is de eerste");
System.out.println(listqueue.size() + " is het aantal\n");
ListDeque listdeque = new ListDeque();
listdeque.addFirst( "Een" );
listdeque.addFirst( "Twee" );
listdeque.addLast( "Nul" );
listdeque.addFirst( "Drie" );
listdeque.addLast( "MinEen" );
System.out.println(listdeque.getFirst() + " is de eerste");
System.out.println(listdeque.getLast() + " is de laatste");
System.out.println(listdeque.size() + " is het aantal");
System.out.println(listdeque.removeFirst() + " is verwijderd");
System.out.println(listdeque.removeLast() + " is verwijderd");
System.out.println(listdeque.getFirst() + " is de eerste");
System.out.println(listdeque.getLast() + " is de laatste");
System.out.println(listdeque.size() + " is het aantal");
}
}
| mit |
matheuscarius/competitive-programming | codeforces/631-a.cpp | 642 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
#define MAXN 1010
int f(int x[], int l, int r) {
int resp = 0;
for(int i = l; i <=r; i++)
resp |= x[i];
return resp;
}
int main () {
int n;
scanf("%d", &n);
int a[MAXN],b[MAXN];
for(int i = 0; i < n ; i++) {
scanf("%d", &a[i]);
}
for(int i = 0; i < n ; i++) {
scanf("%d", &b[i]);
}
int resp = 0;
for(int i = 0; i < n; i++)
for(int j = i; j < n; j++) {
resp = max(resp, f(a,i,j)+f(b,i,j));
}
printf("%d\n", resp);
return 0;
}
| mit |
PieterD/crap | kafka/tools/kafka-producer/producer.go | 1318 | package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"io"
"log"
"os"
"strings"
"github.com/PieterD/crap/kafka"
)
var (
fPeers = flag.String("peers", os.Getenv("ZOOKEEPER_PEERS"), "List of Zookeeper peer addresses (Defaults to ZOOKEEPER_PEERS env)")
fTopic = flag.String("topic", "", "Topic to send on")
fVerbose = flag.Bool("verbose", false, "Print message details")
logger = log.New(os.Stderr, "producer", log.LstdFlags)
)
func flagbad(f string, i ...interface{}) {
fmt.Fprintf(os.Stderr, f, i...)
flag.PrintDefaults()
os.Exit(1)
}
func main() {
flag.Parse()
if *fPeers == "" {
flagbad("-peers is empty\n")
}
if *fTopic == "" {
flagbad("-topic is empty\n")
}
kfk, err := kafka.New("kafka-producer", logger, strings.Split(*fPeers, ","))
if err != nil {
logger.Panicf("Failed to start kafka: %v", err)
}
defer kfk.Close()
br := bufio.NewReader(os.Stdin)
for {
line, err := br.ReadBytes('\n')
if err == io.EOF && len(line) == 0 {
break
}
if err != nil {
logger.Panicf("Reading from stdin: %v", err)
}
line = bytes.TrimRight(line, "\n")
part, offset, err := kfk.Send(nil, line, *fTopic)
if err != nil {
logger.Panicf("Sending message: %v", err)
}
if *fVerbose {
fmt.Printf("send (len=%d, part=%d, offset=%d)\n", len(line), part, offset)
}
}
}
| mit |
createuniverses/praxis | luaCBLang.cpp | 2559 |
// Author: Greg "fugue" Santucci, 2011
// Email: [email protected]
// Web: http://createuniverses.blogspot.com/
#include "luaCB.h"
int luaCBLisp(lua_State * L)
{
#ifdef __PRAXIS_WITH_LISP__
int n = lua_gettop(L);
if(n!=1) luaL_error(L, "1 argument expected.");
std::string sCode = luaL_checkstring(L, 1);
lispCall(sCode);
std::string sOut = lispGetOutput();
std::string sErr = lispGetError();
if(sErr != "")
sOut = sOut + std::string(" ") + sErr;
lua_pushstring(L, sOut.c_str());
return 1;
#else
lua_pushstring(L, "Lisp not compiled.");
return 1;
#endif
}
int luaCBForth(lua_State * L)
{
#ifdef __PRAXIS_WITH_FORTH__
int n = lua_gettop(L);
if(n!=1) luaL_error(L, "1 argument expected.");
std::string sCode = luaL_checkstring(L, 1);
forthCall(sCode);
std::string sOut = forthGetOutput();
std::string sErr = forthGetError();
if(sErr != "")
sOut = sOut + std::string(" ") + sErr;
lua_pushstring(L, sOut.c_str());
return 1;
#else
lua_pushstring(L, "Forth not compiled.");
return 1;
#endif
}
int luaCBIoLang(lua_State * L)
{
#ifdef __PRAXIS_WITH_IO__
int n = lua_gettop(L);
if(n!=1) luaL_error(L, "1 argument expected.");
std::string sCode = luaL_checkstring(L, 1);
ioCallWithReply(sCode);
lua_pushstring(L, ioGetReply().c_str());
lua_pushstring(L, ioGetTrace().c_str());
return 2;
#else
lua_pushstring(L, "Io not compiled.");
lua_pushstring(L, "");
return 2;
#endif
}
int luaCBSetLispTraceVerbosity(lua_State * L)
{
#ifdef __PRAXIS_WITH_LISP__
extern int g_nLispTraceVerbosity;
int n = lua_gettop(L);
if(n!=1) luaL_error(L, "1 argument expected.");
int nVerbosity = luaL_checknumber(L, 1);
g_nLispTraceVerbosity = nVerbosity;
#endif
return 0;
}
int luaCBGetLispTraceVerbosity(lua_State * L)
{
#ifdef __PRAXIS_WITH_LISP__
extern int g_nLispTraceVerbosity;
// int n = lua_gettop(L);
// if(n!=1) luaL_error(L, "1 argument expected.");
lua_pushnumber(L, g_nLispTraceVerbosity);
#else
lua_pushnumber(L, 0);
#endif
return 1;
}
void luaInitCallbacksLang()
{
lua_register(g_pLuaState, "lisp", luaCBLisp);
lua_register(g_pLuaState, "forth", luaCBForth);
lua_register(g_pLuaState, "iolang", luaCBIoLang);
lua_register(g_pLuaState, "setLispTraceVerbosity", luaCBSetLispTraceVerbosity);
lua_register(g_pLuaState, "getLispTraceVerbosity", luaCBGetLispTraceVerbosity);
}
| mit |
cgvarela/passenger | build/cxx_tests.rb | 8007 | # Phusion Passenger - https://www.phusionpassenger.com/
# Copyright (c) 2010-2015 Phusion
#
# "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
#
# 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.
### C++ components tests ###
TEST_CXX_TARGET = "#{TEST_OUTPUT_DIR}cxx/main"
TEST_CXX_OBJECTS = {
"#{TEST_OUTPUT_DIR}cxx/CxxTestMain.o" =>
"test/cxx/CxxTestMain.cpp",
"#{TEST_OUTPUT_DIR}cxx/TestSupport.o" =>
"test/cxx/TestSupport.cpp",
"#{TEST_OUTPUT_DIR}cxx/Core/ApplicationPool/OptionsTest.o" =>
"test/cxx/Core/ApplicationPool/OptionsTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/Core/ApplicationPool/ProcessTest.o" =>
"test/cxx/Core/ApplicationPool/ProcessTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/Core/ApplicationPool/PoolTest.o" =>
"test/cxx/Core/ApplicationPool/PoolTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/Core/SpawningKit/DirectSpawnerTest.o" =>
"test/cxx/Core/SpawningKit/DirectSpawnerTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/Core/SpawningKit/SmartSpawnerTest.o" =>
"test/cxx/Core/SpawningKit/SmartSpawnerTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/Core/UnionStationTest.o" =>
"test/cxx/Core/UnionStationTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/Core/ResponseCacheTest.o" =>
"test/cxx/Core/ResponseCacheTest.cpp",
# "#{TEST_OUTPUT_DIR}cxx/Core/RequestHandlerTest.o" =>
# "test/cxx/Core/RequestHandlerTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/ServerKit/ChannelTest.o" =>
"test/cxx/ServerKit/ChannelTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/ServerKit/FileBufferedChannelTest.o" =>
"test/cxx/ServerKit/FileBufferedChannelTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/ServerKit/HeaderTableTest.o" =>
"test/cxx/ServerKit/HeaderTableTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/ServerKit/ServerTest.o" =>
"test/cxx/ServerKit/ServerTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/ServerKit/HttpServerTest.o" =>
"test/cxx/ServerKit/HttpServerTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/ServerKit/CookieUtilsTest.o" =>
"test/cxx/ServerKit/CookieUtilsTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/MemoryKit/MbufTest.o" =>
"test/cxx/MemoryKit/MbufTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/MemoryKit/PallocTest.o" =>
"test/cxx/MemoryKit/PallocTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/DataStructures/LStringTest.o" =>
"test/cxx/DataStructures/LStringTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/DataStructures/StringKeyTableTest.o" =>
"test/cxx/DataStructures/StringKeyTableTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/MessageReadersWritersTest.o" =>
"test/cxx/MessageReadersWritersTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/StaticStringTest.o" =>
"test/cxx/StaticStringTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/FileChangeCheckerTest.o" =>
"test/cxx/FileChangeCheckerTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/FileDescriptorTest.o" =>
"test/cxx/FileDescriptorTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/SystemTimeTest.o" =>
"test/cxx/SystemTimeTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/FilterSupportTest.o" =>
"test/cxx/FilterSupportTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/CachedFileStatTest.o" =>
"test/cxx/CachedFileStatTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/BufferedIOTest.o" =>
"test/cxx/BufferedIOTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/MessageIOTest.o" =>
"test/cxx/MessageIOTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/MessagePassingTest.o" =>
"test/cxx/MessagePassingTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/VariantMapTest.o" =>
"test/cxx/VariantMapTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/StringMapTest.o" =>
"test/cxx/StringMapTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/ProcessMetricsCollectorTest.o" =>
"test/cxx/ProcessMetricsCollectorTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/DateParsingTest.o" =>
"test/cxx/DateParsingTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/UtilsTest.o" =>
"test/cxx/UtilsTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/Utils/StrIntUtilsTest.o" =>
"test/cxx/Utils/StrIntUtilsTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/IOUtilsTest.o" =>
"test/cxx/IOUtilsTest.cpp",
"#{TEST_OUTPUT_DIR}cxx/TemplateTest.o" =>
"test/cxx/TemplateTest.cpp"
}
def test_cxx_flags
@test_cxx_flags ||= begin
flags = [
"-include test/cxx/TestSupport.h",
LIBEV_CFLAGS,
LIBUV_CFLAGS,
PlatformInfo.curl_flags,
TEST_COMMON_CFLAGS
]
if USE_ASAN
flags << PlatformInfo.adress_sanitizer_flag
end
flags
end
end
def test_cxx_ldflags
@test_cxx_ldflags ||= begin
result = "#{EXTRA_PRE_CXX_LDFLAGS} " <<
"#{TEST_COMMON_LIBRARY.link_objects_as_string} " <<
"#{TEST_BOOST_OXT_LIBRARY} #{libev_libs} #{libuv_libs} " <<
"#{PlatformInfo.curl_libs} " <<
"#{PlatformInfo.zlib_libs} " <<
"#{PlatformInfo.portability_cxx_ldflags}"
result << " #{PlatformInfo.dmalloc_ldflags}" if USE_DMALLOC
result << " #{PlatformInfo.adress_sanitizer_flag}" if USE_ASAN
result << " #{EXTRA_CXX_LDFLAGS}"
result.strip!
result
end
end
# Define compilation tasks for object files.
TEST_CXX_OBJECTS.each_pair do |object, source|
define_cxx_object_compilation_task(
object,
source,
:include_paths => [
"test/cxx",
"test/support",
"src/agent",
*CXX_SUPPORTLIB_INCLUDE_PATHS
],
:flags => test_cxx_flags,
:deps => 'test/cxx/TestSupport.h.gch'
)
end
# Define compilation task for the agent executable.
dependencies = [
TEST_CXX_OBJECTS.keys,
LIBEV_TARGET,
LIBUV_TARGET,
TEST_BOOST_OXT_LIBRARY,
TEST_COMMON_LIBRARY.link_objects,
AGENT_OBJECTS.keys - [AGENT_MAIN_OBJECT]
].flatten.compact
file(TEST_CXX_TARGET => dependencies) do
create_cxx_executable(
TEST_CXX_TARGET,
TEST_CXX_OBJECTS.keys + AGENT_OBJECTS.keys - [AGENT_MAIN_OBJECT],
:flags => test_cxx_ldflags
)
end
dependencies = [
TEST_CXX_TARGET,
"#{TEST_OUTPUT_DIR}allocate_memory",
NATIVE_SUPPORT_TARGET,
AGENT_TARGET
].compact
desc "Run unit tests for the C++ components"
task 'test:cxx' => dependencies do
args = ENV['GROUPS'].to_s.split(";").map{ |name| "-g #{name}" }
command = "#{File.expand_path(TEST_CXX_TARGET)} #{args.join(' ')}".strip
if boolean_option('GDB')
command = "gdb --args #{command}"
elsif boolean_option('VALGRIND')
command = "valgrind --dsymutil=yes --db-attach=yes --child-silent-after-fork=yes #{command}"
end
if boolean_option('SUDO')
command = "#{PlatformInfo.ruby_sudo_command} #{command}"
end
if boolean_option('REPEAT')
if boolean_option('GDB')
abort "You cannot set both REPEAT=1 and GDB=1."
end
sh "cd test && while #{command}; do echo -------------------------------------------; done"
elsif boolean_option('REPEAT_FOREVER')
if boolean_option('GDB')
abort "You cannot set both REPEAT_FOREVER=1 and GDB=1."
end
sh "cd test && while true; do #{command}; echo -------------------------------------------; done"
else
sh "cd test && exec #{command}"
end
end
file('test/cxx/TestSupport.h.gch' => generate_compilation_task_dependencies('test/cxx/TestSupport.h')) do
compile_cxx(
'test/cxx/TestSupport.h',
'test/cxx/TestSupport.h.gch',
:flags => [
"-x c++-header",
TEST_CXX_CFLAGS
]
)
end
| mit |
binofet/ice | Projects/Airhockey/Source/spinstate.cpp | 7088 | //////////////////////////////////////////////////////////////////////////////
// LOCAL INCLUDES
#include "spinstate.h"
#include "Core/IO/icInput.h"
#include "Math/icRand.h"
extern icVector2 bl;
extern icVector2 tl;
extern icVector2 tr;
extern icVector2 br;
SpinState::SpinState()
{
m_pTable = NULL;
m_pTable2 = NULL;
m_pTable3 = NULL;
m_pTable4 = NULL;
m_pContent = NULL;
m_pGroundTex = NULL;
m_pGround = NULL;
halfx = 500.0;
halfy = 500.0;
numrow = 50;
numcol = 50;
edgeDist = (halfx*2)/(numrow-1);
cam_pos.Set(0.0f,0.750f,-1.54f);
look_pos.Set(0.0f,0.0f,0.0f);
m_bRenderTopOnly = false;
m_bUpdateTopOnly = false;
}
SpinState::~SpinState()
{
}
/*! Initializes the games state
*
* @param pContentLoader Pointer to main content loader
* @returns ICRESULT Success/failure/warnings of init
**/
ICRESULT SpinState::Init(icContentLoader* pContentLoader)
{
if (!pContentLoader)
return IC_FAIL_GEN;
m_pContent = pContentLoader;
icGXDevice* pDev = m_pContent->GetDevice();
// CREATE A TEMPORARY GROUND OBJECT
icVertDef vert_def;
vert_def.numPrims = (numrow-1)*(numcol-1)*2;
vert_def.uiVertSize = sizeof(ICVRT_DIF);
vert_def.uiNumVerts = (numrow-1)*(numcol-1)*4;
vert_def.usage = IC_VERT_USAGE_STATIC;
vert_def.primType = IC_PRIM_TLIST;
vert_def.vertType = IC_VERT_DIF;
pDev->CreateVB(&m_pGround, &vert_def);
icVertLock vertLock;
m_pGround->Lock(&vertLock);
ICVRT_DIF* vb = (ICVRT_DIF*)vertLock.pData;
uint cur_vert=0;
for (int row=0; row<numrow-1; ++row)
{
for (int col=0; col<numcol-1; ++col)
{
icReal x1 = (col*edgeDist)-halfx;
icReal y1 = (row*edgeDist)-halfy;
icReal x2 = ((col+1)*edgeDist)-halfx;
icReal y2 = ((row+1)*edgeDist)-halfy;
vb[cur_vert].pos.Set(x1,-10.0f,y1);
vb[cur_vert++].uv.Set(0.0f,0.0f);
vb[cur_vert].pos.Set(x1,-10.0f,y2);
vb[cur_vert++].uv.Set(0.0f,1.0f);
vb[cur_vert].pos.Set(x2,-10.0f,y2);
vb[cur_vert++].uv.Set(1.0f,1.0f);
vb[cur_vert].pos.Set(x2,-10.0f,y1);
vb[cur_vert++].uv.Set(1.0f,0.0f);
}
}
m_pGround->Unlock();
m_pContent->Load("Resource/textures/fire.tga", &m_pGroundTex);
icIndexDef ind_def;
ind_def.indexSize = IC_INDEX_SIZE_16;
ind_def.numIndex = (numrow-1)*(numcol-1)*6;
ind_def.usage = IC_INDEX_USAGE_STATIC;
pDev->CreateIB(&m_pGroundIB,&ind_def);
icIndexLock iblock;
m_pGroundIB->Lock(&iblock);
short* ib = (short*)iblock.pData;
uint cur_index = 0;
for (int row=0; row<numrow-1; ++row)
{
for (int col=0; col<numcol-1; ++col)
{
ib[cur_index++] = (numcol-1)*row*4 + col*4 ;
ib[cur_index++] = (numcol-1)*row*4 + col*4 + 1;
ib[cur_index++] = (numcol-1)*row*4 + col*4 + 2;
ib[cur_index++] = (numcol-1)*row*4 + col*4 + 2;
ib[cur_index++] = (numcol-1)*row*4 + col*4 + 3;
ib[cur_index++] = (numcol-1)*row*4 + col*4;
}
}
m_pGroundIB->Unlock();
ICRESULT res = IC_OK;
// load the table model
res |= m_pContent->Load("Resource/models/table.icm",&m_pTable);
res |= m_pContent->Load("Resource/models/table_2.icm",&m_pTable2);
//res |= m_pContent->Load("Resource/models/table_3.icm",&m_pTable3);
//res |= m_pContent->Load("Resource/models/table_4.icm",&m_pTable4);
m_Transform.Identity();
// get us a camera
icCreatePerspective((40.0f*IC_PI/180.0f),1280.0f/720.0f,1.0f,10000000.0f, m_Camera.GetProjection());
org_len = cam_pos.Length();
icCreateLookAt(cam_pos,look_pos,icVector3(0.0f,1.0f,0.0f),m_Camera.GetViewMat());
return res;
}// END FUNCTION Init(icContentLoader* pContentLoader)
/*! Updates the current game that is in session
*
* @param fDeltaTime Elapsed time since last update
* @param bFinished Pointer, set to true if ste is done
* @returns ICRESULT Success/failure/warnings of update
**/
ICRESULT SpinState::Update(const float fDeltaTime, bool *bFinished)
{
icInput* pInput = icInput::Instance();
short x,y;
pInput->GetPos(&x,&y);
icVector2 curPos((icReal)x,(icReal)y);
// camera movement
icMatrix44& view = m_Camera.GetViewMat();
icVector3& pos = view.GetPos();
static float x_rot = 0.0f;
static float y_rot = 0.0f;
icVector3 new_pos = cam_pos;
x_rot += 0.2f * fDeltaTime;
while (x_rot >= 2*IC_PI)
x_rot -= 2*IC_PI;
icMatrix44 temp;
temp.Identity();
temp.RotY(x_rot);
new_pos = temp.TransformVect(new_pos);
float cur_len = cam_pos.Length();
icCreateLookAt(new_pos,look_pos,icVector3(0.0f,1.0f,0.0f),m_Camera.GetViewMat());
icVertLock vlock;
m_pGround->Lock(&vlock);
ICVRT_DIF* vb = (ICVRT_DIF*)vlock.pData;
static float curdir = 0.0f;
icReal u1 = icCos(curdir) * 0.01f * fDeltaTime;
icReal v2 = icSin(curdir) * 0.01f * fDeltaTime;
icReal t = icRandF(0.0001f,0.001f);
curdir += icRandF(0.0f,10000000.0f) > 500000.0f ? t : -t;
uint cur_vert = 0;
for (int row=0; row<numrow-1; ++row)
{
for (int col=0; col<numcol-1; ++col)
{
vb[cur_vert].uv.x += u1;
vb[cur_vert++].uv.y += v2;
vb[cur_vert].uv.x += u1;
vb[cur_vert++].uv.y += v2;
vb[cur_vert].uv.x += u1;
vb[cur_vert++].uv.y += v2;
vb[cur_vert].uv.x += u1;
vb[cur_vert++].uv.y += v2;
}
}
m_pGround->Unlock();
// TODO: if score, win state and such
return IC_OK;
}// END FUNCTION Update(const float fDeltaTime, bool *bFinished)
/*! Renders the current game that is in session
*
* @returns ICRESULT Success/failure/warnings of render
**/
ICRESULT SpinState::Render(void)
{
icGXDevice* pDev = m_pContent->GetDevice();
// set projection and view matrix
pDev->SetProjection(m_Camera.GetProjection());
pDev->SetViewMatrix(m_Camera.GetViewMat());
//pDev->SetCullMode(IC_CULL_OFF);
// draw the temporary ground
m_Transform.Identity();
pDev->SetWorldTransform(m_Transform);
pDev->SetTexture(0, m_pGroundTex);
pDev->DrawIndexedVertBuf(m_pGround,m_pGroundIB);
// draw the table
m_Transform.RotY(IC_PI);
m_Transform.RotX(-IC_PI/2.0f);
m_pTable->Render(m_Transform);
m_pTable2->Render(m_Transform);
//m_pTable3->Render(m_Transform);
//m_pTable4->Render(m_Transform);
m_Transform.Identity();
return IC_OK;
}// END FUNCTION Render(void)
/*! This gets called when the SpinState gets pushed on the stack
* and should reset anything that needs to be reset for each game
**/
void SpinState::OnPush(void)
{
}// END FUNCTION OnPush(void)
/*! This gets called when the SpinState gets popped off the stack
* we might not need it
**/
void SpinState::OnPop(void)
{
}// END FUNCTION OnPop(void) | mit |
bsanchezdev/u_forms | U_.php | 7455 | <?php
/**
* Description of forms
*
* @author Benjamin Sanchez Cardenas
*/
include "u_encode.php";
class U_ extends u_encode{
public function load_jqueryCDN() {
$CI= &get_instance();
?>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<?php
}
public function load_jquery($jquery="jquery-1.11.3.min") {
$CI= &get_instance();
$CI->load->view("jquery/$jquery".".php");
}
protected function set_mi_id($mi_id)
{
$this->mi_id=$mi_id;
}
public function c($elemento,$id=null,$params=array()) {
$this->mi_id=$id;
require_once 'u_'.$elemento.".php";
$objeto="u_".$elemento;
$elementos["$elemento"][$id]=new $objeto();
$this->elementos[$id]=$elementos;
$elementos["$elemento"][$id]->set_mi_id($id);
if(count($params)>0):
$elementos["$elemento"][$id]->crear($params);
endif;
return $elementos["$elemento"][$id];
}
protected function attribs($param=null) {
$attribs="";
if(isset($param)):
foreach ($param as $key => $value) {
$attribs.=$key."=\"".$value."\" ";
}
endif;
return $attribs;
}
protected function prepara(){
return str_replace("%urnusdev%", "", $this->code);
}
public function p() {
$this->render();
}
public function render() {
echo $this->prepara();
}
public function ins($data) {
return $this->inserta($data);
}
public function inserta($data) {
$this->code = str_replace("%urnusdev%", $data."%urnusdev%", $this->code);
return $this;
}
public function cod()
{
return $this->codigo();
}
public function codigo()
{
return str_replace("%urnusdev%", "", $this->code);
}
public function render_buffer() {
foreach ($this->elementos as $id_elemento => $elemento):
foreach ($elemento as $key => $value):
$value[$id_elemento]->code= str_replace("%urnusdev%", "", $value[$id_elemento]->code);
echo $value[$id_elemento]->code;
$k=$key;
endforeach;
endforeach;
}
public function clear_buffer()
{unset($this->elementos); return $this;}
/* prefabricados */
public function box($texto_label="",$contenido="",$render=false,$params=null,$icono=false)
{
$default=array(
"label"=>array("class"=>"control-label col-md-2 col-sm-12 col-xs-12"),
"span"=>array("class"=>"fa fa-user form-control-feedback right")
);
if(!isset($params)):
$params=$default;
else:
endif;
if(!isset($mi_div)) $mi_div = $this->c("div", "u_div_form-group") ;
if(!isset($mi_div_a)) $mi_div_a = $this->c("div", "u_div_contendor") ;
if(!isset($mi_label)) $mi_label = $this->c("label", "u_label_text-box") ;
if(!isset($mi_span)) $mi_span = $this->c("span", "u_span") ;
if($icono):
$el_icono=$mi_span->crear($params["span"])->codigo();
else:
$el_icono="";
endif;
$mi_div->crear(array("class"=>"form-group","urnusdev"=>"u_"))
->inserta(
$mi_label->crear($params["label"])
->inserta($texto_label)->codigo().
$mi_div_a->crear(array("class"=>"col-md-10 col-sm-12 col-xs-12"))->inserta
(
$contenido.
$el_icono
)->codigo()
);;
if($render):
$mi_div->render();
else:
return $mi_div->codigo();
endif;
}
public function text_box($id="",$texto_label="",$val="",$render=false,$params=null,$icono=false) {
if($icono):
$el_icono=$icono;
$icono=true;
else:
$icono=false;
$el_icono="fa fa-user";
endif;
$default=array(
"label"=>array("class"=>"control-label col-md-2 col-sm-12 col-xs-12"),
"input"=>array("class"=>"form-control","value"=>$val,"id"=>$id,"name"=>$id),
"span"=>array("class"=>"$el_icono form-control-feedback right")
);
if(!isset($params)):
$params=$default;
else:
endif;
if(!isset($mi_input)) $mi_input = $this->c("input", $id);//"u_input") ;
return $this->box($texto_label,$mi_input->crear($params["input"])->codigo(),$render,$params,$icono);
}
public function combo_box($label="",$params,$options,$set_val="",$render=false) {
$this->box($label, $this->combo($params,$options,$set_val,false),$render);
//return $this;
}
public function combo_box_A($label="",$params,$options,$set_val="",$render=false) {
$this->box($label, $this->combo_A($params,$options,$set_val,false),$render);
}
public function combo_box_B($label="",$params_container,$params,$options,$set_val="",$render=false) {
$this->box($label, $this->combo($params,$options,$set_val,false),$render,$params_container);
}
public function campo_fecha($id="",$texto_label="",$val="",$render=false,$params=null)
{
$default=array(
"label"=>array("class"=>"control-label col-md-2 col-sm-12 col-xs-12"),
"input"=>array(
"class"=>"form-control",
"type"=>"text",
"data-inputmask"=>"'mask':'99-99-9999'",
"value"=>$val,
"id"=>$id,
"name"=>$id),
"span"=>array("class"=>"fa fa-calendar form-control-feedback right")
);
if(!isset($params)):
$params=$default;
else:
endif;
if(!isset($mi_input)) $mi_input = $this->c("input", "u_input") ;
if($render):
echo $this->box($texto_label,$mi_input->crear($params["input"])->codigo(),false,$params,true);
else:
return $this->box($texto_label,$mi_input->crear($params["input"])->codigo(),true,$params,true);
endif;
}
public function combo($params,$options,$set_val="",$render=false) {
$select=$this->c("select", "u_select")->crear($params);
foreach ($options as $key => $value){$select->option_add($key,$value);}
if($render):
$select->render();$select->set_val($set_val,true);
else:
return $select->codigo().$select->set_val($set_val);
endif;
}
public function combo_A($params,$options,$set_val="",$render=false) {
$select=$this->c("select", "u_select")->crear($params);
foreach ($options as $key => $value){
//$this->inserta($this->attribs($options));
foreach ($value as $key_ => $value_) {
$select->option_add_A($key,$key_,$value_);
}
}
if($render):
$select->render();$select->set_val($set_val,true);
else:
return $select->codigo().$select->set_val($set_val);
endif;
}
//
protected function load_f($file=false) {
return parent::load_file($file);
}
public function encode_file($file,$key="urnusdev") {
$data= $this->load_f($file);
$data = parent::encode($data, $key,$file);
return $data;
}
public function load($file,$key="urnusdev") {
$data= $this->load_f($file);
$data = parent::decode($data, $key);
return $data;
}
}
| mit |
abhilashreddyvemula/IOCL-Demo-v1 | app/pages/tabs/bayDetails/bay-details.js | 1023 | angular.module('myApp.dashboard')
.controller('BayDetailsController', ['$scope', '$uibModal', 'utility', 'BayService', 'LoaderService', function($scope, $uibModal, utility, bayService, loader) {
$scope.userRole = utility.getUserRole();
$scope.bayItems = [];
$scope.viewby = 10;
$scope.currentPage = 1;
$scope.itemsPerPage = $scope.viewby;
$scope.setItemsPerPage = function(num) {
$scope.itemsPerPage = num;
$scope.currentPage = 1; //reset to first page
}
$scope.loadBayList = function() {
loader.show();
bayService.getCurrentBayOperationalDetails().then(function(response) {
if (response.status == 200) {
$scope.bayItems = response.data;
$scope.totalItems = $scope.bayItems.length;
loader.hide();
}
}, function(error) {
alert('Unable to load the Bays details, Please reload the page...');
loader.hide();
});
}
$scope.loadBayList();
}]); | mit |
tuxetuxe/pchud | src/main/java/com/nelsonjrodrigues/pchud/net/PcMessageParser.java | 6655 | package com.nelsonjrodrigues.pchud.net;
import static com.nelsonjrodrigues.pchud.net.PcMessage.Constants.PARTICIPANT_INFO_MAX;
import static com.nelsonjrodrigues.pchud.net.PcMessage.Constants.TYRE_MAX;
import static com.nelsonjrodrigues.pchud.net.PcMessage.Constants.VEC_MAX;
import java.net.DatagramPacket;
import com.nelsonjrodrigues.pchud.net.PcMessage.ParticipantInfo;
import com.nelsonjrodrigues.pchud.net.PcMessage.ParticipantInfoStrings;
import com.nelsonjrodrigues.pchud.net.PcMessage.ParticipantInfoStringsAdditional;
import com.nelsonjrodrigues.pchud.net.PcMessage.TelemetryData;
import com.nelsonjrodrigues.pchud.net.exceptions.InvalidPacketTypeException;
public class PcMessageParser {
public PcMessage fromDatagramPacket(DatagramPacket packet) {
Extractor e = new Extractor(packet.getData(), packet.getOffset(), packet.getLength());
PcMessage message = new PcMessage();
message.sourceIpAddress(packet.getAddress().getHostAddress());
int packeTypeCode = e.u8() & 0x3;
message.buildVersionNumber(e.u16())
.packetType(PacketType.fromCode(packeTypeCode));
switch (message.packetType()) {
case TELEMETRY_DATA:
message.telemetryData(telemetryData(e));
break;
case PARTICIPANT_STRINGS:
message.participantInfoStrings(participantInfoStrings(e));
break;
case PARTICIPANT_STRING_ADDITIONAL:
message.participantInfoStringsAdditional(participantInfoStringsAdditional(e));
break;
default:
throw new InvalidPacketTypeException("Received an invalid packet type: " + packeTypeCode);
}
return message;
}
private ParticipantInfoStringsAdditional participantInfoStringsAdditional(Extractor e) {
ParticipantInfoStringsAdditional pisa = new ParticipantInfoStringsAdditional();
pisa.offset(e.u8());
pisa.name(e.str64(16));
return pisa;
}
private ParticipantInfoStrings participantInfoStrings(Extractor e) {
ParticipantInfoStrings pis = new ParticipantInfoStrings();
pis.carName(e.str64());
pis.carClassName(e.str64());
pis.trackLocation(e.str64());
pis.trackVariation(e.str64());
pis.name(e.str64(16));
return pis;
}
private TelemetryData telemetryData(Extractor e) {
TelemetryData td = new TelemetryData();
td.gameSessionState(e.u8());
td.viewedParticipantIndex(e.s8())
.numParticipants(e.s8());
td.unfilteredThrottle(e.u8())
.unfilteredBrake(e.u8())
.unfilteredSteering(e.s8())
.unfilteredClutch(e.u8())
.raceStateFlags(e.u8());
td.lapsInEvent(e.u8());
td.bestLapTime(e.f32())
.lastLapTime(e.f32())
.currentTime(e.f32())
.splitTimeAhead(e.f32())
.splitTimeBehind(e.f32())
.splitTime(e.f32())
.eventTimeRemaining(e.f32())
.personalFastestLapTime(e.f32())
.worldFastestLapTime(e.f32())
.currentSector1Time(e.f32())
.currentSector2Time(e.f32())
.currentSector3Time(e.f32())
.fastestSector1Time(e.f32())
.fastestSector2Time(e.f32())
.fastestSector3Time(e.f32())
.personalFastestSector1Time(e.f32())
.personalFastestSector2Time(e.f32())
.personalFastestSector3Time(e.f32())
.worldFastestSector1Time(e.f32())
.worldFastestSector2Time(e.f32())
.worldFastestSector3Time(e.f32());
td.joypad(e.u16());
td.highestFlag(e.u8());
td.pitModeSchedule(e.u8());
td.oilTempCelsius(e.s16())
.oilPressureKPa(e.u16())
.waterTempCelsius(e.s16())
.waterPressureKPa(e.u16())
.fuelPressureKPa(e.u16())
.carFlags(e.u8())
.fuelCapacity(e.u8())
.brake(e.u8())
.throttle(e.u8())
.clutch(e.u8())
.steering(e.s8())
.fuelLevel(e.f32())
.speed(e.f32())
.rpm(e.u16())
.maxRpm(e.u16())
.gearNumGears(e.u8())
.boostAmount(e.u8())
.enforcedPitStopLap(e.s8())
.crashState(e.s8());
td.odometerKM(e.f32())
.orientation(e.f32(VEC_MAX))
.localVelocity(e.f32(VEC_MAX))
.worldVelocity(e.f32(VEC_MAX))
.angularVelocity(e.f32(VEC_MAX))
.localAcceleration(e.f32(VEC_MAX))
.worldAcceleration(e.f32(VEC_MAX))
.extentsCentre(e.f32(VEC_MAX));
td.tyreFlags(e.u8(TYRE_MAX))
.terrain(e.u8(TYRE_MAX))
.tyreY(e.f32(TYRE_MAX))
.tyreRPS(e.f32(TYRE_MAX))
.tyreSlipSpeed(e.f32(TYRE_MAX))
.tyreTemp(e.u8(TYRE_MAX))
.tyreGrip(e.u8(TYRE_MAX))
.tyreHeightAboveGround(e.f32(TYRE_MAX))
.tyreLateralStiffness(e.f32(TYRE_MAX))
.tyreWear(e.u8(TYRE_MAX))
.brakeDamage(e.u8(TYRE_MAX))
.suspensionDamage(e.u8(TYRE_MAX))
.brakeTempCelsius(e.s16(TYRE_MAX))
.tyreTreadTemp(e.u16(TYRE_MAX))
.tyreLayerTemp(e.u16(TYRE_MAX))
.tyreCarcassTemp(e.u16(TYRE_MAX))
.tyreInternalAirTemp(e.u16(TYRE_MAX))
.wheelLocalPositionY(e.f32(TYRE_MAX))
.rideHeight(e.f32(TYRE_MAX))
.suspensionTravel(e.f32(TYRE_MAX))
.suspensionVelocity(e.f32(TYRE_MAX))
.airPressure(e.u16(TYRE_MAX));
td.engineSpeed(e.f32())
.engineTorque(e.f32());
td.ambientTemperature(e.s8())
.trackTemperature(e.s8())
.rainDensity(e.u8())
.windSpeed(e.s8())
.windDirectionX(e.s8())
.windDirectionY(e.s8());
td.participantInfo(participantInfo(PARTICIPANT_INFO_MAX, e));
td.trackLength(e.f32())
.wings(e.u8(2))
.dPad(e.u8());
return td;
}
private ParticipantInfo[] participantInfo(int length, Extractor e) {
ParticipantInfo[] pi = new ParticipantInfo[length];
for (int i = 0; i < length; i++) {
pi[i] = participantInfo(e);
}
return pi;
}
private ParticipantInfo participantInfo(Extractor e) {
ParticipantInfo pi = new ParticipantInfo();
pi.worldPosition(e.s16(VEC_MAX))
.currentLapDistance(e.u16())
.racePosition(e.u8())
.lapsCompleted(e.u8())
.currentLap(e.u8())
.sector(e.u8())
.lastSectorTime(e.f32());
return pi;
}
}
| mit |
leanovate/microzon-auth-go | common/types.go | 116 | package common
import "time"
type RevocationsListener func(version uint64, sha256 RawSha256, expiresAt time.Time)
| mit |
annkupi/picard | src/main/java/picard/analysis/CollectWgsMetricsFromQuerySorted.java | 21986 | /*
* The MIT License
*
* Copyright (c) 2015 The Broad Institute
*
* 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 picard.analysis;
import htsjdk.samtools.*;
import htsjdk.samtools.metrics.MetricsFile;
import htsjdk.samtools.util.*;
import picard.cmdline.CommandLineProgram;
import picard.cmdline.CommandLineProgramProperties;
import picard.cmdline.Option;
import picard.cmdline.StandardOptionDefinitions;
import picard.cmdline.programgroups.Metrics;
import picard.util.QuerySortedReadPairIteratorUtil;
import java.io.File;
import java.util.List;
/**
* Computes a number of metrics that are useful for evaluating coverage and performance of sequencing experiments.
*
* This tool is deprecated; please use CollectWgsMetrics instead.
*
* @author ebanks
*/
@Deprecated
@CommandLineProgramProperties(
usage = "Computes a number of metrics that are useful for evaluating coverage and performance of " +
"sequencing experiments.",
usageShort = "Writes sequencing-related metrics for a SAM or BAM file",
programGroup = Metrics.class
)
public class CollectWgsMetricsFromQuerySorted extends CommandLineProgram {
@Option(shortName = StandardOptionDefinitions.INPUT_SHORT_NAME, doc = "Input SAM or BAM file.")
public File INPUT;
@Option(shortName = StandardOptionDefinitions.OUTPUT_SHORT_NAME, doc = "Output metrics file.")
public File OUTPUT;
@Option(shortName = "USABLE_MQ", doc = "Minimum mapping quality for a read to contribute to usable coverage.", overridable = true, optional = true)
public int MINIMUM_USABLE_MAPPING_QUALITY = 20;
@Option(shortName = "USABLE_Q", doc = "Minimum base quality for a base to contribute to usable coverage.", overridable = true, optional = true)
public int MINIMUM_USABLE_BASE_QUALITY = 20;
@Option(shortName = "RAW_MQ", doc = "Minimum mapping quality for a read to contribute to raw coverage.", overridable = true, optional = true)
public int MINIMUM_RAW_MAPPING_QUALITY = 0;
@Option(shortName = "RAW_Q", doc = "Minimum base quality for a base to contribute to raw coverage.", overridable = true, optional = true)
public int MINIMUM_RAW_BASE_QUALITY = 3;
@Option(doc = "The number of bases in the genome build of the input file to be used for calculating MEAN_COVERAGE. If not provided, we will assume that ALL bases in the genome should be used (including e.g. Ns)", overridable = true, optional = true)
public Long GENOME_TERRITORY = null;
private final Log log = Log.getInstance(CollectWgsMetricsFromQuerySorted.class);
//the adapter utility class
private AdapterUtility adapterUtility;
/** the various metrics types */
public enum FILTERING_STRINGENCY { RAW, USABLE }
/** Metrics for evaluating the performance of whole genome sequencing experiments. */
public static class QuerySortedSeqMetrics extends CollectWgsMetrics.WgsMetrics {
/** Identifier for metrics type */
public FILTERING_STRINGENCY TYPE;
/** The total number of bases, before any filters are applied. */
public long PF_BASES = 0;
/** The number of passing bases, after all filters are applied. */
public long PF_PASSING_BASES = 0;
/** The number of read pairs, before all filters are applied. */
public long PF_READ_PAIRS = 0;
/** The number of duplicate read pairs, before any filters are applied. */
public long PF_DUPE_PAIRS = 0;
/** The number of aligned reads, before any filters are applied. */
public long PF_READS_ALIGNED = 0;
/**
* The number of PF reads that are marked as noise reads. A noise read is one which is composed
* entirely of A bases and/or N bases. These reads are marked as they are usually artifactual and
* are of no use in downstream analysis.
*/
public long PF_NOISE_READS = 0;
/**
* The number of PF reads that map outside of a maximum insert size (100kb) or that have
* the two ends mapping to different chromosomes.
*/
public long PF_CHIMERIC_PAIRS = 0;
/**
* The number of PF reads that are unaligned and match to a known adapter sequence right from the
* start of the read.
*/
public long PF_ADAPTER_READS = 0;
/** The number of read pairs with standard orientations from which to calculate mean insert size, after filters are applied. */
public long PF_ORIENTED_PAIRS = 0;
/** The mean insert size, after filters are applied. */
public double MEAN_INSERT_SIZE = 0.0;
}
/** A private class to track the intermediate values of certain metrics */
private class IntermediateMetrics {
final QuerySortedSeqMetrics metrics = new QuerySortedSeqMetrics();
long basesExcludedByDupes = 0;
long basesExcludedByMapq = 0;
long basesExcludedByPairing = 0;
long basesExcludedByBaseq = 0;
long basesExcludedByOverlap = 0;
double insertSizeSum = 0.0;
}
public static void main(final String[] args) {
new CollectWgsMetricsFromQuerySorted().instanceMainWithExit(args);
}
@Override
protected int doWork() {
IOUtil.assertFileIsReadable(INPUT);
IOUtil.assertFileIsWritable(OUTPUT);
// progress tracker
final ProgressLogger progress = new ProgressLogger(log, 50000000, "Processed", "read pairs");
// the SAM reader
final SamReader reader = SamReaderFactory.makeDefault().open(INPUT);
final PeekableIterator<SAMRecord> iterator = new PeekableIterator<>(reader.iterator());
// the metrics to keep track of
final IntermediateMetrics usableMetrics = new IntermediateMetrics();
usableMetrics.metrics.TYPE = FILTERING_STRINGENCY.USABLE;
final IntermediateMetrics rawMetrics = new IntermediateMetrics();
rawMetrics.metrics.TYPE = FILTERING_STRINGENCY.RAW;
adapterUtility = new AdapterUtility(AdapterUtility.DEFAULT_ADAPTER_SEQUENCE);
// Loop through all the loci by read pairs
QuerySortedReadPairIteratorUtil.ReadPair pairToAnalyze = QuerySortedReadPairIteratorUtil.getNextReadPair(iterator);
while (pairToAnalyze != null) {
// calculate intermediate metrics
calculateMetricsForRead(pairToAnalyze, usableMetrics, MINIMUM_USABLE_MAPPING_QUALITY, MINIMUM_USABLE_BASE_QUALITY);
calculateMetricsForRead(pairToAnalyze, rawMetrics, MINIMUM_RAW_MAPPING_QUALITY, MINIMUM_RAW_BASE_QUALITY);
// record progress
progress.record(pairToAnalyze.read1);
// iterate
pairToAnalyze = QuerySortedReadPairIteratorUtil.getNextReadPair(iterator);
}
// finalize and write the metrics
final long genomeTerritory = (GENOME_TERRITORY == null || GENOME_TERRITORY < 1L) ? reader.getFileHeader().getSequenceDictionary().getReferenceLength() : GENOME_TERRITORY;
usableMetrics.metrics.GENOME_TERRITORY = genomeTerritory;
finalizeMetrics(usableMetrics);
rawMetrics.metrics.GENOME_TERRITORY = genomeTerritory;
finalizeMetrics(rawMetrics);
final MetricsFile<QuerySortedSeqMetrics, Integer> out = getMetricsFile();
out.addMetric(usableMetrics.metrics);
out.addMetric(rawMetrics.metrics);
out.write(OUTPUT);
return 0;
}
/**
* Calculate the contribution to the intermediate metrics for a given read pair
*
* @param pairToAnalyze the read pair to grab metrics from
* @param metrics the intermediate metrics with all the data we need
* @param minimumMappingQuality the minimum mapping quality
* @param minimumBaseQuality the minimum base quality
*/
private void calculateMetricsForRead(final QuerySortedReadPairIteratorUtil.ReadPair pairToAnalyze,
final IntermediateMetrics metrics,
final int minimumMappingQuality,
final int minimumBaseQuality) {
// don't bother at all with non-PF read pairs; if one is non-PF then the other is too so we only need to check the first one
if (pairToAnalyze.read1.getReadFailsVendorQualityCheckFlag()) {
return;
}
final boolean isPaired = (pairToAnalyze.read2 != null);
// how many bases do we have?
final int read1bases = pairToAnalyze.read1.getReadLength();
final int read2bases = isPaired ? pairToAnalyze.read2.getReadLength() : 0;
final int totalReadBases = read1bases + read2bases;
// now compute metrics...
metrics.metrics.PF_BASES += totalReadBases;
if (isNoiseRead(pairToAnalyze.read1)) metrics.metrics.PF_NOISE_READS++;
if (!pairToAnalyze.read1.getReadUnmappedFlag()) metrics.metrics.PF_READS_ALIGNED++;
else if (isAdapterRead(pairToAnalyze.read1)) metrics.metrics.PF_ADAPTER_READS++;
if (isPaired) {
metrics.metrics.PF_READ_PAIRS++;
if (!pairToAnalyze.read2.getReadUnmappedFlag()) metrics.metrics.PF_READS_ALIGNED++;
else if (isAdapterRead(pairToAnalyze.read2)) metrics.metrics.PF_ADAPTER_READS++;
if (isChimericReadPair(pairToAnalyze, minimumMappingQuality)) metrics.metrics.PF_CHIMERIC_PAIRS++;
}
// We note here several differences between this tool and CollectWgsMetrics:
// 1. CollectWgsMetrics does NOT count paired reads that are both unmapped in the PCT_EXC_UNPAIRED, but we do so here
// because this tool isn't a locus iterator and we need to ensure that our passing base numbers are accurate in the end.
// 2. For a similar reason, we DO count soft-clipped bases (and they are usually - but not always - filtered as part of
// PCT_EXC_BASEQ), while CollectWgsMetrics does not count them.
// 3. We DO count bases from insertions as part of the total coverage, while CollectWgsMetrics does not (because it cannot).
if (!isPaired || pairToAnalyze.read1.getMateUnmappedFlag() || pairToAnalyze.read2.getMateUnmappedFlag()) {
metrics.basesExcludedByPairing += totalReadBases;
} else if (pairToAnalyze.read1.getDuplicateReadFlag()) {
metrics.metrics.PF_DUPE_PAIRS++;
metrics.basesExcludedByDupes += totalReadBases;
} else {
// determine the bad bases from the reads
final BaseExclusionHelper read1exclusions = determineBaseExclusions(pairToAnalyze.read1, minimumMappingQuality, minimumBaseQuality);
final BaseExclusionHelper read2exclusions = determineBaseExclusions(pairToAnalyze.read2, minimumMappingQuality, minimumBaseQuality);
metrics.basesExcludedByMapq += read1exclusions.basesExcludedByMapq + read2exclusions.basesExcludedByMapq;
metrics.basesExcludedByBaseq += read1exclusions.lowBQcount + read2exclusions.lowBQcount;
// keep track of the total usable bases
int usableBaseCount = totalReadBases;
usableBaseCount -= (read1exclusions.basesExcludedByMapq + read1exclusions.lowBQcount);
usableBaseCount -= (read2exclusions.basesExcludedByMapq + read2exclusions.lowBQcount);
// subtract out bad bases from overlaps between the reads, but only if both reads pass mapping quality thresholds
if (read1exclusions.basesExcludedByMapq == 0 && read2exclusions.basesExcludedByMapq == 0) {
final int overlapCount = getOverlappingBaseCount(read1exclusions, read2exclusions, minimumBaseQuality);
metrics.basesExcludedByOverlap += overlapCount;
usableBaseCount -= overlapCount;
}
metrics.metrics.PF_PASSING_BASES += usableBaseCount;
final int insertSize = Math.abs(pairToAnalyze.read1.getInferredInsertSize());
if (insertSize > 0 && pairToAnalyze.read1.getProperPairFlag()) {
metrics.metrics.PF_ORIENTED_PAIRS++;
metrics.insertSizeSum += insertSize;
}
}
}
/**
* Finalize the metrics by doing some fun but easy math
*
* @param metrics the intermediate metrics with all the data we need
*/
private void finalizeMetrics(final IntermediateMetrics metrics) {
setUnusedMetrics(metrics.metrics);
metrics.metrics.MEAN_COVERAGE = metrics.metrics.PF_PASSING_BASES / (double)metrics.metrics.GENOME_TERRITORY;
metrics.metrics.PCT_EXC_DUPE = metrics.basesExcludedByDupes / (double)metrics.metrics.PF_BASES;
metrics.metrics.PCT_EXC_MAPQ = metrics.basesExcludedByMapq / (double)metrics.metrics.PF_BASES;
metrics.metrics.PCT_EXC_UNPAIRED = metrics.basesExcludedByPairing / (double)metrics.metrics.PF_BASES;
metrics.metrics.PCT_EXC_BASEQ = metrics.basesExcludedByBaseq / (double)metrics.metrics.PF_BASES;
metrics.metrics.PCT_EXC_OVERLAP = metrics.basesExcludedByOverlap / (double)metrics.metrics.PF_BASES;
final double totalExcludedBases = metrics.metrics.PF_BASES - metrics.metrics.PF_PASSING_BASES;
metrics.metrics.PCT_EXC_TOTAL = totalExcludedBases / metrics.metrics.PF_BASES;
metrics.metrics.MEAN_INSERT_SIZE = metrics.insertSizeSum / metrics.metrics.PF_ORIENTED_PAIRS;
}
/**
* @param record the read
* @return true if the read is considered a "noise" read (all As and/or Ns), false otherwise
*/
private boolean isNoiseRead(final SAMRecord record) {
final Object noiseAttribute = record.getAttribute(ReservedTagConstants.XN);
return (noiseAttribute != null && noiseAttribute.equals(1));
}
/**
* @param record the read
* @return true if the read is from known adapter sequence, false otherwise
*/
private boolean isAdapterRead(final SAMRecord record) {
final byte[] readBases = record.getReadBases();
if (!(record instanceof BAMRecord)) StringUtil.toUpperCase(readBases);
return adapterUtility.isAdapterSequence(readBases);
}
/**
* @param readPair the read pair
* @param minimumMappingQuality the minimum mapping quality
* @return true if the read pair is considered chimeric, false otherwise
*/
private boolean isChimericReadPair(final QuerySortedReadPairIteratorUtil.ReadPair readPair, final int minimumMappingQuality) {
// Check that both ends are aligned, have mapq > minimum, and fit the bill for chimeras
return (readPair.read1.getMappingQuality() >= minimumMappingQuality && readPair.read2.getMappingQuality() >= minimumMappingQuality &&
ChimeraUtil.isChimeric(readPair.read1, readPair.read2, ChimeraUtil.DEFAULT_INSERT_SIZE_LIMIT, ChimeraUtil.DEFAULT_EXPECTED_ORIENTATIONS));
}
/**
* Get the count of low quality and/or softclip bases in the given read
*
* @param exclusions the helper object
* @param minimumBaseQuality the minimum base quality
* @return non-negative int
*/
private int getLowQualityOrSoftclipBaseCount(final BaseExclusionHelper exclusions, final int minimumBaseQuality) {
final byte[] quals = exclusions.read.getBaseQualities();
int badCount = exclusions.firstUnclippedBaseIndex + (quals.length - exclusions.firstTrailingClippedBaseIndex);
for (int i = exclusions.firstUnclippedBaseIndex; i < exclusions.firstTrailingClippedBaseIndex; i++) {
if (quals[i] < minimumBaseQuality)
badCount++;
}
return badCount;
}
/**
* set the values of the unused metrics to -1
*
* @param metrics the metrics object
*/
private void setUnusedMetrics(final QuerySortedSeqMetrics metrics) {
metrics.SD_COVERAGE = -1;
metrics.MEDIAN_COVERAGE = -1;
metrics.MAD_COVERAGE = -1;
metrics.PCT_1X = -1;
metrics.PCT_5X = -1;
metrics.PCT_10X = -1;
metrics.PCT_15X = -1;
metrics.PCT_20X = -1;
metrics.PCT_25X = -1;
metrics.PCT_30X = -1;
metrics.PCT_40X = -1;
metrics.PCT_50X = -1;
metrics.PCT_60X = -1;
metrics.PCT_70X = -1;
metrics.PCT_80X = -1;
metrics.PCT_90X = -1;
metrics.PCT_100X = -1;
metrics.PCT_EXC_CAPPED = -1;
}
/**
* Get the count of overlapping bases for the given reads
*
* @param read1exclusions the 1st read exclusions
* @param read2exclusions the 2nd read exclusions
* @param minimumBaseQuality the minimum base quality
* @return non-negative int
*/
private int getOverlappingBaseCount(final BaseExclusionHelper read1exclusions, final BaseExclusionHelper read2exclusions, final int minimumBaseQuality) {
// make life easy by ensuring that reads come in coordinate order
if ( read2exclusions.read.getAlignmentStart() < read1exclusions.read.getAlignmentStart() ) {
return getOverlappingBaseCount(read2exclusions, read1exclusions, minimumBaseQuality);
}
// must be overlapping
if ( read1exclusions.read.getAlignmentEnd() < read2exclusions.read.getAlignmentStart() ||
!read1exclusions.read.getReferenceIndex().equals(read2exclusions.read.getReferenceIndex()) )
return 0;
final byte[] read1quals = read1exclusions.read.getBaseQualities();
final byte[] read2quals = read2exclusions.read.getBaseQualities();
final int indexOfOverlapInFirstRead = read1exclusions.read.getReadPositionAtReferencePosition(read2exclusions.read.getAlignmentStart(), true) - 1;
final int maxPossibleOverlap = read1exclusions.firstTrailingClippedBaseIndex - indexOfOverlapInFirstRead;
// the overlap cannot actually be larger than the usable bases in read2
final int actualOverlap = Math.min(maxPossibleOverlap, read2exclusions.firstTrailingClippedBaseIndex - read2exclusions.firstUnclippedBaseIndex);
int numHighQualityOverlappingBases = 0;
for (int i = 0; i < actualOverlap; i++) {
// we count back from the end of the aligned bases (i.e. not included soft-clips) in read1 and from the front of read2
final int posInRead1 = read1exclusions.firstTrailingClippedBaseIndex - actualOverlap + i;
final int posInRead2 = read2exclusions.firstUnclippedBaseIndex + i;
// we only want to count it if they are both high quality (i.e. not already counted among bad bases)
if (read1quals[posInRead1] >= minimumBaseQuality && read2quals[posInRead2] >= minimumBaseQuality) {
numHighQualityOverlappingBases++;
}
}
return numHighQualityOverlappingBases;
}
/**
* Determine how many bases are excluded because of low mapping or base quality.
*
* @param read the read
* @param minimumMappingQuality the minimum mapping quality
* @param minimumBaseQuality the minimum base quality
* @return non-null object
*/
private BaseExclusionHelper determineBaseExclusions(final SAMRecord read, final int minimumMappingQuality, final int minimumBaseQuality) {
final BaseExclusionHelper exclusions = new BaseExclusionHelper(read);
if (read.getMappingQuality() < minimumMappingQuality) {
exclusions.basesExcludedByMapq = read.getReadLength();
} else {
exclusions.lowBQcount = getLowQualityOrSoftclipBaseCount(exclusions, minimumBaseQuality);
}
return exclusions;
}
private static class BaseExclusionHelper {
public SAMRecord read;
public int firstUnclippedBaseIndex;
public int firstTrailingClippedBaseIndex;
public int basesExcludedByMapq = 0;
public int lowBQcount = 0;
public BaseExclusionHelper(final SAMRecord read) {
this.read = read;
final List<CigarElement> cigarElements = read.getCigar().getCigarElements();
firstUnclippedBaseIndex = 0;
for (final CigarElement element : cigarElements) {
final CigarOperator op = element.getOperator();
if (op == CigarOperator.SOFT_CLIP) {
firstUnclippedBaseIndex = element.getLength();
} else if (op != CigarOperator.HARD_CLIP) {
break;
}
}
firstTrailingClippedBaseIndex = read.getReadLength();
for (int i = cigarElements.size() - 1; i >= 0; --i) {
final CigarElement element = cigarElements.get(i);
final CigarOperator op = element.getOperator();
if (op == CigarOperator.SOFT_CLIP) {
firstTrailingClippedBaseIndex -= element.getLength();
} else if (op != CigarOperator.HARD_CLIP) {
break;
}
}
}
}
}
| mit |
frankandoak/silo | server/Inventory/Modifier/ModifierFactory.php | 164 | <?php
namespace Silo\Inventory\Modifier;
use Silo\Inventory\Model\Modifier;
class ModifierFactory
{
public function decode(Modifier $modifier)
{
}
}
| mit |
eriksk/kawaii | lib/kawaii/intro.rb | 1133 | module Kawaii
class Intro < Scene
def load
@logo = Gosu::Image.new(game(), File.dirname(__FILE__) + '/logo.png', false)
@rotation = 0
@position = Vector2.new(game().width / 2, game().height / 2)
@scale = 1
@transition_duration = 2000
@color = Gosu::Color::WHITE
@color.alpha = 0
end
def transition_in current, duration
fake_duration = 750
if current <= fake_duration
@rotation = Kawaii::clerp(0, (360 * 2) - 145, current / (fake_duration * 0.7))
@scale = Kawaii::clerp(0.1, 1.0, current / (fake_duration * 0.8))
end
end
def transition_out current, duration
@rotation = Kawaii::clerp(@rotation, 0, (current / duration) * 1.4)
@scale = Kawaii::clerp(@scale, 0, (current / duration) * 1.4)
@position.x = Kawaii::clerp(game().width / 2, game().width + 400, (current / duration) * 1.3)
@position.y += Math::sin(current * 0.01) * 30.0
@color.alpha = Kawaii::clerp(0, 255, current / duration )
end
def update dt
end
def before_draw
@logo.draw_rot(@position.x, @position.y, 0, @rotation, 0.5, 0.5, @scale, 1.0)
end
def to_s
"Intro Scene"
end
end
end | mit |
Kunal57/MIT_6.00.1x | pset1/problem3.py | 1471 | # Problem 3
# 15.0 points possible (graded)
# Assume s is a string of lower case characters.
# Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print
# Longest substring in alphabetical order is: beggh
# In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print
# Longest substring in alphabetical order is: abc
# Note: This problem may be challenging. We encourage you to work smart. If you've spent more than a few hours on this problem, we suggest that you move on to a different part of the course. If you have time, come back to this problem after you've had a break and cleared your head.
s = 'azcbobobegghakl'
alphabet = "abcdefghijklmnopqrstuvwxyz"
longest_substring = s[0]
current_substring = ""
previous_x_value = 0
for i in range(len(s)):
for x in range(len(alphabet)):
if s[i] == alphabet[x]:
if len(current_substring) == 0:
current_substring += s[i]
previous_x_value = x
elif x >= previous_x_value:
current_substring += s[i]
previous_x_value = x
if len(current_substring) > len(longest_substring):
longest_substring = current_substring
elif x < previous_x_value:
current_substring = s[i]
previous_x_value = x
print("Longest substring in alphabetical order is: " + longest_substring)
| mit |
PeterXu/livepusher | src/com/zenvv/live/VideoPusher.java | 8513 | package com.zenvv.live;
import java.util.Iterator;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import com.zenvv.live.jni.PusherNative;
public class VideoPusher extends Pusher implements Callback, PreviewCallback {
private final static String TAG = "VideoPusher";
private boolean mPreviewRunning;
private Camera mCamera;
private SurfaceHolder mHolder;
private VideoParam mParam;
private byte[] mBuffer;
private byte[] mRaw;
private Activity mActivity;
private int mScreen;
private final static int SCREEN_PORTRAIT = 0;
private final static int SCREEN_LANDSCAPE_LEFT = 90;
private final static int SCREEN_LANDSCAPE_RIGHT = 270;
public VideoPusher(Activity activity, SurfaceHolder surfaceHolder,
VideoParam param, PusherNative pusherNative) {
super(pusherNative);
mActivity = activity;
mParam = param;
mHolder = surfaceHolder;
surfaceHolder.addCallback(this);
}
@Override
public void startPusher() {
startPreview();
mPusherRuning = true;
}
@Override
public void stopPusher() {
mPusherRuning = false;
}
@Override
public void release() {
mPusherRuning = false;
mActivity = null;
stopPreview();
}
public void switchCamera() {
if (mParam.getCameraId() == CameraInfo.CAMERA_FACING_BACK) {
mParam.setCameraId(CameraInfo.CAMERA_FACING_FRONT);
} else {
mParam.setCameraId(CameraInfo.CAMERA_FACING_BACK);
}
stopPreview();
startPreview();
}
private void stopPreview() {
if (mPreviewRunning && mCamera != null) {
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
mCamera.release();
mCamera = null;
mPreviewRunning = false;
}
}
@SuppressWarnings("deprecation")
private void startPreview() {
if (mPreviewRunning) {
return;
}
try {
mCamera = Camera.open(mParam.getCameraId());
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewFormat(ImageFormat.NV21);
setPreviewSize(parameters);
setPreviewFpsRange(parameters);
setPreviewOrientation(parameters);
mCamera.setParameters(parameters);
mBuffer = new byte[mParam.getWidth() * mParam.getHeight() * 3 / 2];
mRaw = new byte[mParam.getWidth() * mParam.getHeight() * 3 / 2];
mCamera.addCallbackBuffer(mBuffer);
mCamera.setPreviewCallbackWithBuffer(this);
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
mPreviewRunning = true;
} catch (Exception ex) {
ex.printStackTrace();
if (null != mListener) {
mListener.onErrorPusher(-100);
}
}
}
private void setPreviewSize(Camera.Parameters parameters) {
List<Integer> supportedPreviewFormats = parameters
.getSupportedPreviewFormats();
for (Integer integer : supportedPreviewFormats) {
System.out.println("setPreviewSize fmt:" + integer);
}
List<Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();
Size size = supportedPreviewSizes.get(0);
Log.d(TAG, "setPreviewSize size: " + size.width + "x" + size.height);
int m = Math.abs(size.height * size.width - mParam.getHeight() * mParam.getWidth());
supportedPreviewSizes.remove(0);
Iterator<Size> iterator = supportedPreviewSizes.iterator();
while (iterator.hasNext()) {
Size next = iterator.next();
Log.d(TAG, "setPreviewSize next: " + next.width + "x" + next.height);
int n = Math.abs(next.height * next.width - mParam.getHeight() * mParam.getWidth());
if (n < m) {
m = n;
size = next;
}
}
mParam.setHeight(size.height);
mParam.setWidth(size.width);
parameters.setPreviewSize(mParam.getWidth(), mParam.getHeight());
Log.d(TAG, "width:" + size.width + " height:" + size.height);
}
private void setPreviewFpsRange(Camera.Parameters parameters) {
int range[] = new int[2];
parameters.getPreviewFpsRange(range);
Log.d(TAG, "setPreviewFpsRange, fps:" + range[0] + " - " + range[1]);
}
private void setPreviewOrientation(Camera.Parameters parameters) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(mParam.getCameraId(), info);
int rotation = mActivity.getWindowManager().getDefaultDisplay().getRotation();
mScreen = 0;
switch (rotation) {
case Surface.ROTATION_0:
mScreen = SCREEN_PORTRAIT;
mNative.setVideoOptions(mParam.getHeight(), mParam.getWidth(),
mParam.getBitrate(), mParam.getFps());
break;
case Surface.ROTATION_90:
mScreen = SCREEN_LANDSCAPE_LEFT;
mNative.setVideoOptions(mParam.getWidth(), mParam.getHeight(),
mParam.getBitrate(), mParam.getFps());
break;
case Surface.ROTATION_180:
mScreen = 180;
break;
case Surface.ROTATION_270:
mScreen = SCREEN_LANDSCAPE_RIGHT;
mNative.setVideoOptions(mParam.getWidth(), mParam.getHeight(),
mParam.getBitrate(), mParam.getFps());
break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + mScreen) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - mScreen + 360) % 360;
}
mCamera.setDisplayOrientation(result);
//
// if (mContext.getResources().getConfiguration().orientation ==
// Configuration.ORIENTATION_PORTRAIT) {
// mNative.setVideoOptions(mParam.getHeight(), mParam.getWidth(),
// mParam.getBitrate(), mParam.getFps());
// parameters.set("orientation", "portrait");
// mCamera.setDisplayOrientation(90);
// } else {
// mNative.setVideoOptions(mParam.getWidth(), mParam.getHeight(),
// mParam.getBitrate(), mParam.getFps());
// parameters.set("orientation", "landscape");
// mCamera.setDisplayOrientation(0);
// }
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mHolder = holder;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
mHolder = holder;
stopPreview();
startPreview();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
stopPreview();
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
if (mPusherRuning) {
byte[] pData = data;
switch (mScreen) {
case SCREEN_PORTRAIT:
portraitData2Raw(data);
pData = mRaw;
break;
case SCREEN_LANDSCAPE_LEFT:
pData = data;
break;
case SCREEN_LANDSCAPE_RIGHT:
landscapeData2Raw(data);
pData = mRaw;
break;
}
mNative.fireVideo(pData);
pData = null;
}
camera.addCallbackBuffer(mBuffer);
}
private void landscapeData2Raw(byte[] data) {
int width = mParam.getWidth(), height = mParam.getHeight();
int y_len = width * height;
int k = 0;
// y => raw
for (int i = y_len - 1; i > -1; i--) {
mRaw[k] = data[i];
k++;
}
// System.arraycopy(data, y_len, raw, y_len, uv_len);
// v1 u1 v2 u2
// v3 u3 v4 u4
// vu reverse
// v4 u4 v3 u3
// v2 u2 v1 u1
int maxpos = data.length - 1;
int uv_len = y_len >> 2; // 4:1:1
for (int i = 0; i < uv_len; i++) {
int pos = i << 1;
mRaw[y_len + i * 2] = data[maxpos - pos - 1];
mRaw[y_len + i * 2 + 1] = data[maxpos - pos];
}
}
private void portraitData2Raw(byte[] data) {
// if (mContext.getResources().getConfiguration().orientation !=
// Configuration.ORIENTATION_PORTRAIT) {
// raw = data;
// return;
// }
int width = mParam.getWidth();
int height = mParam.getHeight();
int y_len = width * height;
int uvHeight = height >> 1;
int k = 0;
if (mParam.getCameraId() == CameraInfo.CAMERA_FACING_BACK) {
for (int j = 0; j < width; j++) {
for (int i = height - 1; i >= 0; i--) {
mRaw[k++] = data[width * i + j];
}
}
for (int j = 0; j < width; j += 2) {
for (int i = uvHeight - 1; i >= 0; i--) {
mRaw[k++] = data[y_len + width * i + j];
mRaw[k++] = data[y_len + width * i + j + 1];
}
}
} else {
for (int i = 0; i < width; i++) {
int nPos = width - 1;
for (int j = 0; j < height; j++) {
mRaw[k] = data[nPos - i];
k++;
nPos += width;
}
}
for (int i = 0; i < width; i += 2) {
int nPos = y_len + width - 1;
for (int j = 0; j < uvHeight; j++) {
mRaw[k] = data[nPos - i - 1];
mRaw[k + 1] = data[nPos - i];
k += 2;
nPos += width;
}
}
}
}
}
| mit |
victorherraiz/xcatalog | tests/foo/bar/bar.js | 104 | "use strict";
module.exports = { value: 12 };
module.exports.$xcatalog = { id: "bar", type: "constant" } | mit |
Universal-Model-Converter/UMC3.0a | data/Python/x86/Lib/site-packages/OpenGL/raw/GL/VERSION/GL_4_2.py | 298 | '''OpenGL extension VERSION.GL_4_2
Automatically generated by the get_gl_extensions script, do not edit!
'''
from OpenGL import platform, constants, constant, arrays
from OpenGL import extensions
from OpenGL.GL import glget
import ctypes
EXTENSION_NAME = 'GL_VERSION_GL_4_2'
_DEPRECATED = False
| mit |
werdeil/pibooth | pibooth/plugins/hookspecs.py | 12591 | # -*- coding: utf-8 -*-
import pluggy
hookspec = pluggy.HookspecMarker('pibooth')
#--- Pibooth state-independent hooks ------------------------------------------
@hookspec
def pibooth_startup(app):
"""Actions performed at the startup of pibooth.
:param app: application instance
"""
@hookspec
def pibooth_setup_picture_factory(cfg, opt_index, factory):
"""Hook used to setup the ``PictureFactory`` instance.
The ``opt_index`` is the index to use in case of configuration option
with a type tuple which depends on the selected captures number.
A hook wrapper can be used to catch the current factory and return
a customized one.
(see details https://pluggy.readthedocs.io/en/latest/#wrappers)
:param cfg: application cfg
:param opt_index: index for tuple options
:param factory: ``PictureFactory`` instance
"""
@hookspec
def pibooth_cleanup(app):
"""Actions performed at the cleanup of pibooth.
:param app: application instance
"""
#--- FailSafe State -----------------------------------------------------------
@hookspec
def state_failsafe_enter(cfg, app, win):
"""Actions performed when application enter in FailSafe state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
"""
@hookspec
def state_failsafe_do(cfg, app, win, events):
"""Actions performed when application is in FailSafe state.
This hook is called in a loop until the application can switch
to the next state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
:param events: pygame events generated since last call
"""
@hookspec(firstresult=True)
def state_failsafe_validate(cfg, app, win, events):
"""Return the next state name if application can switch to it
else return None.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
:param events: pygame events generated since last call
"""
@hookspec
def state_failsafe_exit(cfg, app, win):
"""Actions performed when application exit FailSafe state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
"""
#--- Wait State ---------------------------------------------------------------
@hookspec
def state_wait_enter(cfg, app, win):
"""Actions performed when application enter in Wait state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
"""
@hookspec
def state_wait_do(cfg, app, win, events):
"""Actions performed when application is in Wait state.
This hook is called in a loop until the application can switch
to the next state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
:param events: pygame events generated since last call
"""
@hookspec(firstresult=True)
def state_wait_validate(cfg, app, win, events):
"""Return the next state name if application can switch to it
else return None.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
:param events: pygame events generated since last call
"""
@hookspec
def state_wait_exit(cfg, app, win):
"""Actions performed when application exit Wait state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
"""
#--- Choose State -------------------------------------------------------------
@hookspec
def state_choose_enter(cfg, app, win):
"""Actions performed when application enter in Choose state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
"""
@hookspec
def state_choose_do(cfg, app, win, events):
"""Actions performed when application is in Choose state.
This hook is called in a loop until the application can switch
to the next state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
:param events: pygame events generated since last call
"""
@hookspec(firstresult=True)
def state_choose_validate(cfg, app, win, events):
"""Return the next state name if application can switch to it
else return None.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
:param events: pygame events generated since last call
"""
@hookspec
def state_choose_exit(cfg, app, win):
"""Actions performed when application exit Choose state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
"""
#--- Chosen State -------------------------------------------------------------
@hookspec
def state_chosen_enter(cfg, app, win):
"""Actions performed when application enter in Chosen state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
"""
@hookspec
def state_chosen_do(cfg, app, win, events):
"""Actions performed when application is in Chosen state.
This hook is called in a loop until the application can switch
to the next state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
:param events: pygame events generated since last call
"""
@hookspec(firstresult=True)
def state_chosen_validate(cfg, app, win, events):
"""Return the next state name if application can switch to it
else return None.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
:param events: pygame events generated since last call
"""
@hookspec
def state_chosen_exit(cfg, app, win):
"""Actions performed when application exit Chosen state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
"""
#--- Preview State ------------------------------------------------------------
@hookspec
def state_preview_enter(cfg, app, win):
"""Actions performed when application enter in Preview state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
"""
@hookspec
def state_preview_do(cfg, app, win, events):
"""Actions performed when application is in Preview state.
This hook is called in a loop until the application can switch
to the next state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
:param events: pygame events generated since last call
"""
@hookspec(firstresult=True)
def state_preview_validate(cfg, app, win, events):
"""Return the next state name if application can switch to it
else return None.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
:param events: pygame events generated since last call
"""
@hookspec
def state_preview_exit(cfg, app, win):
"""Actions performed when application exit Preview state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
"""
#--- Capture State ------------------------------------------------------------
@hookspec
def state_capture_enter(cfg, app, win):
"""Actions performed when application enter in Capture state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
"""
@hookspec
def state_capture_do(cfg, app, win, events):
"""Actions performed when application is in Capture state.
This hook is called in a loop until the application can switch
to the next state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
:param events: pygame events generated since last call
"""
@hookspec(firstresult=True)
def state_capture_validate(cfg, app, win, events):
"""Return the next state name if application can switch to it
else return None.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
:param events: pygame events generated since last call
"""
@hookspec
def state_capture_exit(cfg, app, win):
"""Actions performed when application exit Capture state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
"""
#--- Processing State ---------------------------------------------------------
@hookspec
def state_processing_enter(cfg, app, win):
"""Actions performed when application enter in Processing state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
"""
@hookspec
def state_processing_do(cfg, app, win, events):
"""Actions performed when application is in Processing state.
This hook is called in a loop until the application can switch
to the next state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
:param events: pygame events generated since last call
"""
@hookspec(firstresult=True)
def state_processing_validate(cfg, app, win, events):
"""Return the next state name if application can switch to it
else return None.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
:param events: pygame events generated since last call
"""
@hookspec
def state_processing_exit(cfg, app, win):
"""Actions performed when application exit Processing state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
"""
#--- PrintView State ----------------------------------------------------------
@hookspec
def state_print_enter(cfg, app, win):
"""Actions performed when application enter in Print state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
"""
@hookspec
def state_print_do(cfg, app, win, events):
"""Actions performed when application is in Print state.
This hook is called in a loop until the application can switch
to the next state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
:param events: pygame events generated since last call
"""
@hookspec(firstresult=True)
def state_print_validate(cfg, app, win, events):
"""Return the next state name if application can switch to it
else return None.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
:param events: pygame events generated since last call
"""
@hookspec
def state_print_exit(cfg, app, win):
"""Actions performed when application exit Print state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
"""
#--- Finish State -------------------------------------------------------------
@hookspec
def state_finish_enter(cfg, app, win):
"""Actions performed when application enter in Finish state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
"""
@hookspec
def state_finish_do(cfg, app, win, events):
"""Actions performed when application is in Finish state.
This hook is called in a loop until the application can switch
to the next state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
:param events: pygame events generated since last call
"""
@hookspec(firstresult=True)
def state_finish_validate(cfg, app, win, events):
"""Return the next state name if application can switch to it
else return None.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
:param events: pygame events generated since last call
"""
@hookspec
def state_finish_exit(cfg, app, win):
"""Actions performed when application exit Finish state.
:param cfg: application cfg
:param app: application instance
:param win: graphical window instance
"""
| mit |
appium/node-jscs | lib/rules/require-space-after-binary-operators.js | 3446 | var assert = require('assert');
var tokenHelper = require('../token-helper');
var allOperators = require('../utils').binaryOperators;
module.exports = function() {};
module.exports.prototype = {
configure: function(operators) {
var isTrue = operators === true;
assert(
Array.isArray(operators) || isTrue,
'requireSpaceAfterBinaryOperators option requires array or true value'
);
if (isTrue) {
operators = allOperators;
}
this._operatorIndex = {};
for (var i = 0, l = operators.length; i < l; i++) {
this._operatorIndex[operators[i]] = true;
}
},
getOptionName: function() {
return 'requireSpaceAfterBinaryOperators';
},
check: function(file, errors) {
var operators = this._operatorIndex;
function errorIfApplicable(token, i, tokens, operator) {
var nextToken = tokens[i + 1];
if (token && nextToken && nextToken.range[0] === token.range[1]) {
var loc = token.loc.start;
errors.add(
'Operator ' + operator + ' should not stick to following expression',
loc.line,
tokenHelper.getPointerEntities(loc.column, token.value.length)
);
}
}
// ":" for object property only but not for ternar
if (operators[':']) {
file.iterateNodesByType(['ObjectExpression'], function(node) {
node.properties.forEach(function(prop) {
var token = tokenHelper.findOperatorByRangeStart(file, prop.range[0], ':'),
tokens = file.getTokens();
errorIfApplicable(token, tokens.indexOf(token), tokens, ':');
});
});
}
// Comma
if (operators[',']) {
file.iterateTokensByType('Punctuator', function(token, i, tokens) {
var operator = token.value;
if (operator !== ',') {
return;
}
errorIfApplicable(token, i, tokens, operator);
});
}
// For everything else
file.iterateNodesByType(
['BinaryExpression', 'AssignmentExpression', 'LogicalExpression'],
function(node) {
if (operators[node.operator]) {
var indent;
var range = node.right.range[0];
if (tokenHelper.isTokenParenthesis(file, range - 1, true)) {
indent = node.operator.length + 1;
} else {
indent = node.operator.length;
}
var part = tokenHelper.getTokenByRangeStartIfPunctuator(
file,
range - indent,
node.operator,
true
);
if (part) {
var loc = part.loc.start;
errors.add(
'Operator ' + node.operator + ' should not stick to following expression',
loc.line,
tokenHelper.getPointerEntities(loc.column, node.operator.length)
);
}
}
}
);
}
};
| mit |
EPICZEUS/simple-discord.js | src/commands/info.js | 1750 | const Command = require("../command.js");
class Info extends Command {
constructor(client) {
super(client, {
name: "info",
type: "general",
description: "Displays info about the specified command.",
use: [
{
name: "command",
type: "string",
single: true,
required: true
}
],
aliases: [
"help"
]
});
this.default = true;
}
run(message, args) {
const command = args.command.toLowerCase();
const cmdFile = this.client.commands.get(command) || this.client.commands.get(this.client.aliases.get(command));
if (!cmdFile) return this.client.utils.warn(`${args[0]} is not a valid command name or alias.`);
const howTo = cmdFile.use ? cmdFile.use.map(use => use[1] ? `<${use[0]}>` : `[${use[0]}]`).join(" ") : "";
const use = this.client.prefix ? `${this.client.prefix}${cmdFile.name} ${howTo}` : `${howTo ? `${howTo} ` : ""}${cmdFile.name}${this.client.suffix}`;
const description = `${cmdFile.description}\n\n**Usage**\n\`${use}\`\n\n**Aliases**\n${cmdFile.aliases && cmdFile.aliases.length ? `\`${cmdFile.aliases.join("`, `")}\`` : "None"}`;
return (!this.client.user.bot ? message.edit.bind(message) : message.channel.send.bind(message.channel))({embed: {
title: cmdFile.name.replace(/^./, l => l.toUpperCase()),
description,
footer: {
text: "<> - required, [] - optional"
},
color: 0x4d68cc
}}).catch(this.client.utils.error);
}
}
module.exports = Info;
| mit |
coworkbuffalo/switchboard | config/initializers/session_store.rb | 150 | # Be sure to restart your server when you modify this file.
Switchboard::Application.config.session_store :cookie_store, key: '_switchboard_session'
| mit |
AHSR0x/my-exercises | app/app.js | 1322 | (function() {
'use strict';
// Include all requirement files
require('../bower_components/angular/angular.min.js');
require('../bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js');
require('../bower_components/angular-ui-router/release/angular-ui-router.min.js');
require('./modules/common.factories.js');
require('./controllers/exercise.controllers.js');
require('./modules/data-struct.factories.js');
// Inject all depencies
angular.
module('myApp', [
'ui.router',
'ui.bootstrap',
'exercise.controllers',
'common.factories',
'data-struct.factories'
])
.config(function($stateProvider) {
// Inject stateProvider from depency ui-router for routing multi-views + nested-views
$stateProvider
// Define app state
.state('app', {
url : '/app',
templateUrl : 'app/views/app/app.html'
})
// Define Exercise state
.state('app.exercise', {
url : '/exercise',
templateUrl : 'app/views/exercise/exercise.html'
})
.state('app.exercise.domino', {
url : '/domino',
templateUrl : 'app/views/exercise/exercise.domino.html',
controller : 'exerciseDominoCtrl'
});
});
})(); | mit |
marcsans/cf-cold-start | src/weightedAverage.py | 508 |
# coding: utf-8
# In[1]:
import numpy as np
from similarity import similarity
# In[2]:
def weightedAverage(neighbors, similarities, R, user, product):
if neighbors==[]:
print('no neighbor provided')
sumWeights = 0
average = 0
for n in neighbors:
if R(n,product)!=0:
w = similarities(n, user)
sumWeights = sumWeights + w
average = average + w * R(n,product)
average = average / sumWeights
return average
# In[ ]:
| mit |
6ixcoin/sixcoin | src/net.cpp | 62347 | // 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 "irc.h"
#include "db.h"
#include "net.h"
#include "init.h"
#include "strlcpy.h"
#include "addrman.h"
#include "ui_interface.h"
#ifdef WIN32
#include <string.h>
#endif
#ifdef USE_UPNP
#include <miniupnpc/miniwget.h>
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
#endif
using namespace std;
using namespace boost;
static const int MAX_OUTBOUND_CONNECTIONS = 16;
void ThreadMessageHandler2(void* parg);
void ThreadSocketHandler2(void* parg);
void ThreadOpenConnections2(void* parg);
void ThreadOpenAddedConnections2(void* parg);
#ifdef USE_UPNP
void ThreadMapPort2(void* parg);
#endif
void ThreadDNSAddressSeed2(void* parg);
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
struct LocalServiceInfo {
int nScore;
int nPort;
};
//
// Global state variables
//
bool fDiscover = true;
bool fUseUPnP = false;
uint64_t nLocalServices = NODE_NETWORK;
static CCriticalSection cs_mapLocalHost;
static map<CNetAddr, LocalServiceInfo> mapLocalHost;
static bool vfReachable[NET_MAX] = {};
static bool vfLimited[NET_MAX] = {};
static CNode* pnodeLocalHost = NULL;
CAddress addrSeenByPeer(CService("0.0.0.0", 0), nLocalServices);
uint64_t nLocalHostNonce = 0;
boost::array<int, THREAD_MAX> vnThreadsRunning;
static std::vector<SOCKET> vhListenSocket;
CAddrMan addrman;
vector<CNode*> vNodes;
CCriticalSection cs_vNodes;
map<CInv, CDataStream> mapRelay;
deque<pair<int64_t, CInv> > vRelayExpiration;
CCriticalSection cs_mapRelay;
map<CInv, int64_t> mapAlreadyAskedFor;
static deque<string> vOneShots;
CCriticalSection cs_vOneShots;
set<CNetAddr> setservAddNodeAddresses;
CCriticalSection cs_setservAddNodeAddresses;
static CSemaphore *semOutbound = NULL;
void AddOneShot(string strDest)
{
LOCK(cs_vOneShots);
vOneShots.push_back(strDest);
}
unsigned short GetListenPort()
{
return (unsigned short)(GetArg("-port", GetDefaultPort()));
}
void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)
{
// Filter out duplicate requests
if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)
return;
pindexLastGetBlocksBegin = pindexBegin;
hashLastGetBlocksEnd = hashEnd;
PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);
}
// find 'best' local address for a particular peer
bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
{
if (fNoListen)
return false;
int nBestScore = -1;
int nBestReachability = -1;
{
LOCK(cs_mapLocalHost);
for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
{
int nScore = (*it).second.nScore;
int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
{
addr = CService((*it).first, (*it).second.nPort);
nBestReachability = nReachability;
nBestScore = nScore;
}
}
}
return nBestScore >= 0;
}
// get best local address for a particular peer as a CAddress
CAddress GetLocalAddress(const CNetAddr *paddrPeer)
{
CAddress ret(CService("0.0.0.0",0),0);
CService addr;
if (GetLocal(addr, paddrPeer))
{
ret = CAddress(addr);
ret.nServices = nLocalServices;
ret.nTime = GetAdjustedTime();
}
return ret;
}
bool RecvLine(SOCKET hSocket, string& strLine)
{
strLine = "";
while (true)
{
char c;
int nBytes = recv(hSocket, &c, 1, 0);
if (nBytes > 0)
{
if (c == '\n')
continue;
if (c == '\r')
return true;
strLine += c;
if (strLine.size() >= 9000)
return true;
}
else if (nBytes <= 0)
{
if (fShutdown)
return false;
if (nBytes < 0)
{
int nErr = WSAGetLastError();
if (nErr == WSAEMSGSIZE)
continue;
if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
{
MilliSleep(10);
continue;
}
}
if (!strLine.empty())
return true;
if (nBytes == 0)
{
// socket closed
printf("socket closed\n");
return false;
}
else
{
// socket error
int nErr = WSAGetLastError();
printf("recv failed: %d\n", nErr);
return false;
}
}
}
}
// used when scores of local addresses may have changed
// pushes better local address to peers
void static AdvertizeLocal()
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->fSuccessfullyConnected)
{
CAddress addrLocal = GetLocalAddress(&pnode->addr);
if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal)
{
pnode->PushAddress(addrLocal);
pnode->addrLocal = addrLocal;
}
}
}
}
void SetReachable(enum Network net, bool fFlag)
{
LOCK(cs_mapLocalHost);
vfReachable[net] = fFlag;
if (net == NET_IPV6 && fFlag)
vfReachable[NET_IPV4] = true;
}
// learn a new local address
bool AddLocal(const CService& addr, int nScore)
{
if (!addr.IsRoutable())
return false;
if (!fDiscover && nScore < LOCAL_MANUAL)
return false;
if (IsLimited(addr))
return false;
printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore);
{
LOCK(cs_mapLocalHost);
bool fAlready = mapLocalHost.count(addr) > 0;
LocalServiceInfo &info = mapLocalHost[addr];
if (!fAlready || nScore >= info.nScore) {
info.nScore = nScore + (fAlready ? 1 : 0);
info.nPort = addr.GetPort();
}
SetReachable(addr.GetNetwork());
}
AdvertizeLocal();
return true;
}
bool AddLocal(const CNetAddr &addr, int nScore)
{
return AddLocal(CService(addr, GetListenPort()), nScore);
}
/** Make a particular network entirely off-limits (no automatic connects to it) */
void SetLimited(enum Network net, bool fLimited)
{
if (net == NET_UNROUTABLE)
return;
LOCK(cs_mapLocalHost);
vfLimited[net] = fLimited;
}
bool IsLimited(enum Network net)
{
LOCK(cs_mapLocalHost);
return vfLimited[net];
}
bool IsLimited(const CNetAddr &addr)
{
return IsLimited(addr.GetNetwork());
}
/** vote for a local address */
bool SeenLocal(const CService& addr)
{
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == 0)
return false;
mapLocalHost[addr].nScore++;
}
AdvertizeLocal();
return true;
}
/** check whether a given address is potentially local */
bool IsLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
return mapLocalHost.count(addr) > 0;
}
/** check whether a given address is in a network we can probably connect to */
bool IsReachable(const CNetAddr& addr)
{
LOCK(cs_mapLocalHost);
enum Network net = addr.GetNetwork();
return vfReachable[net] && !vfLimited[net];
}
bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
{
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());
send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
string strLine;
while (RecvLine(hSocket, strLine))
{
if (strLine.empty()) // HTTP response is separated from headers by blank line
{
while (true)
{
if (!RecvLine(hSocket, strLine))
{
closesocket(hSocket);
return false;
}
if (pszKeyword == NULL)
break;
if (strLine.find(pszKeyword) != string::npos)
{
strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
break;
}
}
closesocket(hSocket);
if (strLine.find("<") != string::npos)
strLine = strLine.substr(0, strLine.find("<"));
strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
strLine.resize(strLine.size()-1);
CService addr(strLine,0,true);
printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
if (!addr.IsValid() || !addr.IsRoutable())
return false;
ipRet.SetIP(addr);
return true;
}
}
closesocket(hSocket);
return error("GetMyExternalIP() : connection closed");
}
// We now get our external IP from the IRC server first and only use this as a backup
bool GetMyExternalIP(CNetAddr& ipRet)
{
CService addrConnect;
const char* pszGet;
const char* pszKeyword;
for (int nLookup = 0; nLookup <= 1; nLookup++)
for (int nHost = 1; nHost <= 2; nHost++)
{
// We should be phasing out our use of sites like these. If we need
// replacements, we should ask for volunteers to put this simple
// php file on their web server that prints the client IP:
// <?php echo $_SERVER["REMOTE_ADDR"]; ?>
if (nHost == 1)
{
addrConnect = CService("216.146.43.70",80); // checkip.dyndns.org
if (nLookup == 1)
{
CService addrIP("checkip.dyndns.org", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET / HTTP/1.1\r\n"
"Host: checkip.dyndns.org\r\n"
"User-Agent: Sixcoin\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = "Address:";
}
else if (nHost == 2)
{
addrConnect = CService("74.208.43.192", 80); // www.showmyip.com
if (nLookup == 1)
{
CService addrIP("www.showmyip.com", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET /simple/ HTTP/1.1\r\n"
"Host: www.showmyip.com\r\n"
"User-Agent: Sixcoin\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = NULL; // Returns just IP address
}
if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
return true;
}
return false;
}
void ThreadGetMyExternalIP(void* parg)
{
// Make this thread recognisable as the external IP detection thread
RenameThread("sixcoin-ext-ip");
CNetAddr addrLocalHost;
if (GetMyExternalIP(addrLocalHost))
{
printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
AddLocal(addrLocalHost, LOCAL_HTTP);
}
}
void AddressCurrentlyConnected(const CService& addr)
{
addrman.Connected(addr);
}
CNode* FindNode(const CNetAddr& ip)
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CNetAddr)pnode->addr == ip)
return (pnode);
}
return NULL;
}
CNode* FindNode(std::string addrName)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->addrName == addrName)
return (pnode);
return NULL;
}
CNode* FindNode(const CService& addr)
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CService)pnode->addr == addr)
return (pnode);
}
return NULL;
}
CNode* ConnectNode(CAddress addrConnect, const char *pszDest)
{
if (pszDest == NULL) {
if (IsLocal(addrConnect))
return NULL;
// Look for an existing connection
CNode* pnode = FindNode((CService)addrConnect);
if (pnode)
{
pnode->AddRef();
return pnode;
}
}
/// debug print
printf("trying connection %s lastseen=%.1fhrs\n",
pszDest ? pszDest : addrConnect.ToString().c_str(),
pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
// Connect
SOCKET hSocket;
if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
{
addrman.Attempt(addrConnect);
/// debug print
printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
// Set to non-blocking
#ifdef WIN32
u_long nOne = 1;
if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError());
#else
if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno);
#endif
// Add node
CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
pnode->nTimeConnected = GetTime();
return pnode;
}
else
{
return NULL;
}
}
void CNode::CloseSocketDisconnect()
{
fDisconnect = true;
if (hSocket != INVALID_SOCKET)
{
printf("disconnecting node %s\n", addrName.c_str());
closesocket(hSocket);
hSocket = INVALID_SOCKET;
// in case this fails, we'll empty the recv buffer when the CNode is deleted
TRY_LOCK(cs_vRecvMsg, lockRecv);
if (lockRecv)
vRecvMsg.clear();
}
}
void CNode::PushVersion()
{
/// when NTP implemented, change to just nTime = GetAdjustedTime()
int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime());
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
CAddress addrMe = GetLocalAddress(&addr);
RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str());
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight);
}
std::map<CNetAddr, int64_t> CNode::setBanned;
CCriticalSection CNode::cs_setBanned;
void CNode::ClearBanned()
{
setBanned.clear();
}
bool CNode::IsBanned(CNetAddr ip)
{
bool fResult = false;
{
LOCK(cs_setBanned);
std::map<CNetAddr, int64_t>::iterator i = setBanned.find(ip);
if (i != setBanned.end())
{
int64_t t = (*i).second;
if (GetTime() < t)
fResult = true;
}
}
return fResult;
}
bool CNode::Misbehaving(int howmuch)
{
if (addr.IsLocal())
{
printf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName.c_str(), howmuch);
return false;
}
nMisbehavior += howmuch;
if (nMisbehavior >= GetArg("-banscore", 100))
{
int64_t banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
printf("Misbehaving: %s (%d -> %d) DISCONNECTING\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
{
LOCK(cs_setBanned);
if (setBanned[addr] < banTime)
setBanned[addr] = banTime;
}
CloseSocketDisconnect();
return true;
} else
printf("Misbehaving: %s (%d -> %d)\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
return false;
}
#undef X
#define X(name) stats.name = name
void CNode::copyStats(CNodeStats &stats)
{
X(nServices);
X(nLastSend);
X(nLastRecv);
X(nTimeConnected);
X(addrName);
X(nVersion);
X(strSubVer);
X(fInbound);
X(nStartingHeight);
X(nMisbehavior);
}
#undef X
// requires LOCK(cs_vRecvMsg)
bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes)
{
while (nBytes > 0) {
// get current incomplete message, or create a new one
if (vRecvMsg.empty() ||
vRecvMsg.back().complete())
vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion));
CNetMessage& msg = vRecvMsg.back();
// absorb network data
int handled;
if (!msg.in_data)
handled = msg.readHeader(pch, nBytes);
else
handled = msg.readData(pch, nBytes);
if (handled < 0)
return false;
pch += handled;
nBytes -= handled;
}
return true;
}
int CNetMessage::readHeader(const char *pch, unsigned int nBytes)
{
// copy data to temporary parsing buffer
unsigned int nRemaining = 24 - nHdrPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
memcpy(&hdrbuf[nHdrPos], pch, nCopy);
nHdrPos += nCopy;
// if header incomplete, exit
if (nHdrPos < 24)
return nCopy;
// deserialize to CMessageHeader
try {
hdrbuf >> hdr;
}
catch (std::exception &e) {
return -1;
}
// reject messages larger than MAX_SIZE
if (hdr.nMessageSize > MAX_SIZE)
return -1;
// switch state to reading message data
in_data = true;
return nCopy;
}
int CNetMessage::readData(const char *pch, unsigned int nBytes)
{
unsigned int nRemaining = hdr.nMessageSize - nDataPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
if (vRecv.size() < nDataPos + nCopy) {
// Allocate up to 256 KiB ahead, but never more than the total message size.
vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
}
memcpy(&vRecv[nDataPos], pch, nCopy);
nDataPos += nCopy;
return nCopy;
}
// requires LOCK(cs_vSend)
void SocketSendData(CNode *pnode)
{
std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin();
while (it != pnode->vSendMsg.end()) {
const CSerializeData &data = *it;
assert(data.size() > pnode->nSendOffset);
int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
if (nBytes > 0) {
pnode->nLastSend = GetTime();
pnode->nSendOffset += nBytes;
if (pnode->nSendOffset == data.size()) {
pnode->nSendOffset = 0;
pnode->nSendSize -= data.size();
it++;
} else {
// could not send full message; stop sending more
break;
}
} else {
if (nBytes < 0) {
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
printf("socket send error %d\n", nErr);
pnode->CloseSocketDisconnect();
}
}
// couldn't send anything at all
break;
}
}
if (it == pnode->vSendMsg.end()) {
assert(pnode->nSendOffset == 0);
assert(pnode->nSendSize == 0);
}
pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
}
void ThreadSocketHandler(void* parg)
{
// Make this thread recognisable as the networking thread
RenameThread("sixcoin-net");
try
{
vnThreadsRunning[THREAD_SOCKETHANDLER]++;
ThreadSocketHandler2(parg);
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
PrintException(&e, "ThreadSocketHandler()");
} catch (...) {
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
throw; // support pthread_cancel()
}
printf("ThreadSocketHandler exited\n");
}
void ThreadSocketHandler2(void* parg)
{
printf("ThreadSocketHandler started\n");
list<CNode*> vNodesDisconnected;
unsigned int nPrevNodeCount = 0;
while (true)
{
//
// Disconnect nodes
//
{
LOCK(cs_vNodes);
// Disconnect unused nodes
vector<CNode*> vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (pnode->fDisconnect ||
(pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty()))
{
// remove from vNodes
vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
// release outbound grant (if any)
pnode->grantOutbound.Release();
// close socket and cleanup
pnode->CloseSocketDisconnect();
// hold in disconnected pool until all refs are released
if (pnode->fNetworkNode || pnode->fInbound)
pnode->Release();
vNodesDisconnected.push_back(pnode);
}
}
// Delete disconnected nodes
list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
{
// wait until threads are done using it
if (pnode->GetRefCount() <= 0)
{
bool fDelete = false;
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv)
{
TRY_LOCK(pnode->cs_mapRequests, lockReq);
if (lockReq)
{
TRY_LOCK(pnode->cs_inventory, lockInv);
if (lockInv)
fDelete = true;
}
}
}
}
if (fDelete)
{
vNodesDisconnected.remove(pnode);
delete pnode;
}
}
}
}
if (vNodes.size() != nPrevNodeCount)
{
nPrevNodeCount = vNodes.size();
uiInterface.NotifyNumConnectionsChanged(vNodes.size());
}
//
// Find which sockets have data to receive
//
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 50000; // frequency to poll pnode->vSend
fd_set fdsetRecv;
fd_set fdsetSend;
fd_set fdsetError;
FD_ZERO(&fdsetRecv);
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
SOCKET hSocketMax = 0;
bool have_fds = false;
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
FD_SET(hListenSocket, &fdsetRecv);
hSocketMax = max(hSocketMax, hListenSocket);
have_fds = true;
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->hSocket == INVALID_SOCKET)
continue;
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend) {
// do not read, if draining write queue
if (!pnode->vSendMsg.empty())
FD_SET(pnode->hSocket, &fdsetSend);
else
FD_SET(pnode->hSocket, &fdsetRecv);
FD_SET(pnode->hSocket, &fdsetError);
hSocketMax = max(hSocketMax, pnode->hSocket);
have_fds = true;
}
}
}
}
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
int nSelect = select(have_fds ? hSocketMax + 1 : 0,
&fdsetRecv, &fdsetSend, &fdsetError, &timeout);
vnThreadsRunning[THREAD_SOCKETHANDLER]++;
if (fShutdown)
return;
if (nSelect == SOCKET_ERROR)
{
if (have_fds)
{
int nErr = WSAGetLastError();
printf("socket select error %d\n", nErr);
for (unsigned int i = 0; i <= hSocketMax; i++)
FD_SET(i, &fdsetRecv);
}
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
MilliSleep(timeout.tv_usec/1000);
}
//
// Accept new connections
//
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
{
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
CAddress addr;
int nInbound = 0;
if (hSocket != INVALID_SOCKET)
if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
printf("Warning: Unknown socket family\n");
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->fInbound)
nInbound++;
}
if (hSocket == INVALID_SOCKET)
{
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK)
printf("socket error accept failed: %d\n", nErr);
}
else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS)
{
closesocket(hSocket);
}
else if (CNode::IsBanned(addr))
{
printf("connection from %s dropped (banned)\n", addr.ToString().c_str());
closesocket(hSocket);
}
else
{
printf("accepted connection %s\n", addr.ToString().c_str());
CNode* pnode = new CNode(hSocket, addr, "", true);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
}
}
//
// Service each socket
//
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->AddRef();
}
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (fShutdown)
return;
//
// Receive
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv)
{
if (pnode->GetTotalRecvSize() > ReceiveFloodSize()) {
if (!pnode->fDisconnect)
printf("socket recv flood control disconnect (%u bytes)\n", pnode->GetTotalRecvSize());
pnode->CloseSocketDisconnect();
}
else {
// typical socket buffer is 8K-64K
char pchBuf[0x10000];
int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
if (nBytes > 0)
{
if (!pnode->ReceiveMsgBytes(pchBuf, nBytes))
pnode->CloseSocketDisconnect();
pnode->nLastRecv = GetTime();
}
else if (nBytes == 0)
{
// socket closed gracefully
if (!pnode->fDisconnect)
printf("socket closed\n");
pnode->CloseSocketDisconnect();
}
else if (nBytes < 0)
{
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
if (!pnode->fDisconnect)
printf("socket recv error %d\n", nErr);
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Send
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetSend))
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SocketSendData(pnode);
}
//
// Inactivity checking
//
if (pnode->vSendMsg.empty())
pnode->nLastSendEmpty = GetTime();
if (GetTime() - pnode->nTimeConnected > 60)
{
if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
{
printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
{
printf("socket not sending\n");
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastRecv > 90*60)
{
printf("socket inactivity timeout\n");
pnode->fDisconnect = true;
}
}
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
MilliSleep(10);
}
}
#ifdef USE_UPNP
void ThreadMapPort(void* parg)
{
// Make this thread recognisable as the UPnP thread
RenameThread("sixcoin-UPnP");
try
{
vnThreadsRunning[THREAD_UPNP]++;
ThreadMapPort2(parg);
vnThreadsRunning[THREAD_UPNP]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_UPNP]--;
PrintException(&e, "ThreadMapPort()");
} catch (...) {
vnThreadsRunning[THREAD_UPNP]--;
PrintException(NULL, "ThreadMapPort()");
}
printf("ThreadMapPort exited\n");
}
void ThreadMapPort2(void* parg)
{
printf("ThreadMapPort started\n");
std::string port = strprintf("%u", GetListenPort());
const char * multicastif = 0;
const char * minissdpdpath = 0;
struct UPNPDev * devlist = 0;
char lanaddr[64];
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
#else
/* miniupnpc 1.6 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
#endif
struct UPNPUrls urls;
struct IGDdatas data;
int r;
r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
if (r == 1)
{
if (fDiscover) {
char externalIPAddress[40];
r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
if(r != UPNPCOMMAND_SUCCESS)
printf("UPnP: GetExternalIPAddress() returned %d\n", r);
else
{
if(externalIPAddress[0])
{
printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
}
else
printf("UPnP: GetExternalIPAddress failed.\n");
}
}
string strDesc = "Sixcoin " + FormatFullVersion();
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
#endif
if(r!=UPNPCOMMAND_SUCCESS)
printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
else
printf("UPnP Port Mapping successful.\n");
int i = 1;
while (true)
{
if (fShutdown || !fUseUPnP)
{
r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
printf("UPNP_DeletePortMapping() returned : %d\n", r);
freeUPNPDevlist(devlist); devlist = 0;
FreeUPNPUrls(&urls);
return;
}
if (i % 600 == 0) // Refresh every 20 minutes
{
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
#endif
if(r!=UPNPCOMMAND_SUCCESS)
printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
else
printf("UPnP Port Mapping successful.\n");;
}
MilliSleep(2000);
i++;
}
} else {
printf("No valid UPnP IGDs found\n");
freeUPNPDevlist(devlist); devlist = 0;
if (r != 0)
FreeUPNPUrls(&urls);
while (true)
{
if (fShutdown || !fUseUPnP)
return;
MilliSleep(2000);
}
}
}
void MapPort()
{
if (fUseUPnP && vnThreadsRunning[THREAD_UPNP] < 1)
{
if (!NewThread(ThreadMapPort, NULL))
printf("Error: ThreadMapPort(ThreadMapPort) failed\n");
}
}
#else
void MapPort()
{
// Intentionally left blank.
}
#endif
// DNS seeds
// Each pair gives a source name and a seed name.
// The first name is used as information source for addrman.
// The second name should resolve to a list of seed addresses.
static const char *strDNSSeed[][2] = {
{"dnsseed", "dnsseed.6ixcoin.com"},
{"node1", "dnsseed.node1.6ixcoin.com"},
{"blockchain", "dnsseed.blockchain.6ixcoin.com"},
{"wallet", "dnsseed.wallet.6ixcoin.com"},
};
void ThreadDNSAddressSeed(void* parg)
{
// Make this thread recognisable as the DNS seeding thread
RenameThread("sixcoin-dnsseed");
try
{
vnThreadsRunning[THREAD_DNSSEED]++;
ThreadDNSAddressSeed2(parg);
vnThreadsRunning[THREAD_DNSSEED]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_DNSSEED]--;
PrintException(&e, "ThreadDNSAddressSeed()");
} catch (...) {
vnThreadsRunning[THREAD_DNSSEED]--;
throw; // support pthread_cancel()
}
printf("ThreadDNSAddressSeed exited\n");
}
void ThreadDNSAddressSeed2(void* parg)
{
printf("ThreadDNSAddressSeed started\n");
int found = 0;
if (!fTestNet)
{
printf("Loading addresses from DNS seeds (could take a while)\n");
for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {
if (HaveNameProxy()) {
AddOneShot(strDNSSeed[seed_idx][1]);
} else {
vector<CNetAddr> vaddr;
vector<CAddress> vAdd;
if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
{
BOOST_FOREACH(CNetAddr& ip, vaddr)
{
int nOneDay = 24*3600;
CAddress addr = CAddress(CService(ip, GetDefaultPort()));
addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
vAdd.push_back(addr);
found++;
}
}
addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true));
}
}
}
printf("%d addresses found from DNS seeds\n", found);
}
unsigned int pnSeed[] =
{
};
void DumpAddresses()
{
int64_t nStart = GetTimeMillis();
CAddrDB adb;
adb.Write(addrman);
printf("Flushed %d addresses to peers.dat %"PRId64"ms\n",
addrman.size(), GetTimeMillis() - nStart);
}
void ThreadDumpAddress2(void* parg)
{
vnThreadsRunning[THREAD_DUMPADDRESS]++;
while (!fShutdown)
{
DumpAddresses();
vnThreadsRunning[THREAD_DUMPADDRESS]--;
MilliSleep(600000);
vnThreadsRunning[THREAD_DUMPADDRESS]++;
}
vnThreadsRunning[THREAD_DUMPADDRESS]--;
}
void ThreadDumpAddress(void* parg)
{
// Make this thread recognisable as the address dumping thread
RenameThread("sixcoin-adrdump");
try
{
ThreadDumpAddress2(parg);
}
catch (std::exception& e) {
PrintException(&e, "ThreadDumpAddress()");
}
printf("ThreadDumpAddress exited\n");
}
void ThreadOpenConnections(void* parg)
{
// Make this thread recognisable as the connection opening thread
RenameThread("sixcoin-opencon");
try
{
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
ThreadOpenConnections2(parg);
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
PrintException(&e, "ThreadOpenConnections()");
} catch (...) {
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
PrintException(NULL, "ThreadOpenConnections()");
}
printf("ThreadOpenConnections exited\n");
}
void static ProcessOneShot()
{
string strDest;
{
LOCK(cs_vOneShots);
if (vOneShots.empty())
return;
strDest = vOneShots.front();
vOneShots.pop_front();
}
CAddress addr;
CSemaphoreGrant grant(*semOutbound, true);
if (grant) {
if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
AddOneShot(strDest);
}
}
void static ThreadStakeMiner(void* parg)
{
printf("ThreadStakeMiner started\n");
CWallet* pwallet = (CWallet*)parg;
try
{
vnThreadsRunning[THREAD_STAKE_MINER]++;
StakeMiner(pwallet);
vnThreadsRunning[THREAD_STAKE_MINER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_STAKE_MINER]--;
PrintException(&e, "ThreadStakeMiner()");
} catch (...) {
vnThreadsRunning[THREAD_STAKE_MINER]--;
PrintException(NULL, "ThreadStakeMiner()");
}
printf("ThreadStakeMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_STAKE_MINER]);
}
void ThreadOpenConnections2(void* parg)
{
printf("ThreadOpenConnections started\n");
// Connect to specific addresses
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
{
for (int64_t nLoop = 0;; nLoop++)
{
ProcessOneShot();
BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
{
CAddress addr;
OpenNetworkConnection(addr, NULL, strAddr.c_str());
for (int i = 0; i < 10 && i < nLoop; i++)
{
MilliSleep(500);
if (fShutdown)
return;
}
}
MilliSleep(500);
}
}
// Initiate network connections
int64_t nStart = GetTime();
while (true)
{
ProcessOneShot();
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
MilliSleep(500);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return;
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
CSemaphoreGrant grant(*semOutbound);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return;
// Add seed nodes if IRC isn't working
if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet)
{
std::vector<CAddress> vAdd;
for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
struct in_addr ip;
memcpy(&ip, &pnSeed[i], sizeof(ip));
CAddress addr(CService(ip, GetDefaultPort()));
addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
vAdd.push_back(addr);
}
addrman.Add(vAdd, CNetAddr("127.0.0.1"));
}
//
// Choose an address to connect to based on most recently seen
//
CAddress addrConnect;
// Only connect out to one peer per network group (/16 for IPv4).
// Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
int nOutbound = 0;
set<vector<unsigned char> > setConnected;
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes) {
if (!pnode->fInbound) {
setConnected.insert(pnode->addr.GetGroup());
nOutbound++;
}
}
}
int64_t nANow = GetAdjustedTime();
int nTries = 0;
while (true)
{
// use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
// if we selected an invalid address, restart
if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
break;
// If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
// stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
// already-connected network ranges, ...) before trying new addrman addresses.
nTries++;
if (nTries > 100)
break;
if (IsLimited(addr))
continue;
// only consider very recently tried nodes after 30 failed attempts
if (nANow - addr.nLastTry < 600 && nTries < 30)
continue;
// do not allow non-default ports, unless after 50 invalid addresses selected already
if (addr.GetPort() != GetDefaultPort() && nTries < 50)
continue;
addrConnect = addr;
break;
}
if (addrConnect.IsValid())
OpenNetworkConnection(addrConnect, &grant);
}
}
void ThreadOpenAddedConnections(void* parg)
{
// Make this thread recognisable as the connection opening thread
RenameThread("sixcoin-opencon");
try
{
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
ThreadOpenAddedConnections2(parg);
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
PrintException(&e, "ThreadOpenAddedConnections()");
} catch (...) {
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
PrintException(NULL, "ThreadOpenAddedConnections()");
}
printf("ThreadOpenAddedConnections exited\n");
}
void ThreadOpenAddedConnections2(void* parg)
{
printf("ThreadOpenAddedConnections started\n");
if (mapArgs.count("-addnode") == 0)
return;
if (HaveNameProxy()) {
while(!fShutdown) {
BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) {
CAddress addr;
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(addr, &grant, strAddNode.c_str());
MilliSleep(500);
}
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
MilliSleep(120000); // Retry every 2 minutes
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
}
return;
}
vector<vector<CService> > vservAddressesToAdd(0);
BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"])
{
vector<CService> vservNode(0);
if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
{
vservAddressesToAdd.push_back(vservNode);
{
LOCK(cs_setservAddNodeAddresses);
BOOST_FOREACH(CService& serv, vservNode)
setservAddNodeAddresses.insert(serv);
}
}
}
while (true)
{
vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd;
// Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
// (keeping in mind that addnode entries can have many IPs if fNameLookup)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
BOOST_FOREACH(CService& addrNode, *(it))
if (pnode->addr == addrNode)
{
it = vservConnectAddresses.erase(it);
it--;
break;
}
}
BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses)
{
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(CAddress(*(vserv.begin())), &grant);
MilliSleep(500);
if (fShutdown)
return;
}
if (fShutdown)
return;
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
MilliSleep(120000); // Retry every 2 minutes
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
if (fShutdown)
return;
}
}
// if successful, this moves the passed grant to the constructed node
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
{
//
// Initiate outbound network connection
//
if (fShutdown)
return false;
if (!strDest)
if (IsLocal(addrConnect) ||
FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
FindNode(addrConnect.ToStringIPPort().c_str()))
return false;
if (strDest && FindNode(strDest))
return false;
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
CNode* pnode = ConnectNode(addrConnect, strDest);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return false;
if (!pnode)
return false;
if (grantOutbound)
grantOutbound->MoveTo(pnode->grantOutbound);
pnode->fNetworkNode = true;
if (fOneShot)
pnode->fOneShot = true;
return true;
}
void ThreadMessageHandler(void* parg)
{
// Make this thread recognisable as the message handling thread
RenameThread("sixcoin-msghand");
try
{
vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
ThreadMessageHandler2(parg);
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
PrintException(&e, "ThreadMessageHandler()");
} catch (...) {
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
PrintException(NULL, "ThreadMessageHandler()");
}
printf("ThreadMessageHandler exited\n");
}
void ThreadMessageHandler2(void* parg)
{
printf("ThreadMessageHandler started\n");
SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
while (!fShutdown)
{
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->AddRef();
}
// Poll the connected nodes for messages
CNode* pnodeTrickle = NULL;
if (!vNodesCopy.empty())
pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (pnode->fDisconnect)
continue;
// Receive messages
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv)
if (!ProcessMessages(pnode))
pnode->CloseSocketDisconnect();
}
if (fShutdown)
return;
// Send messages
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SendMessages(pnode, pnode == pnodeTrickle);
}
if (fShutdown)
return;
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
// Wait and allow messages to bunch up.
// Reduce vnThreadsRunning so StopNode has permission to exit while
// we're sleeping, but we must always check fShutdown after doing this.
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
MilliSleep(100);
if (fRequestShutdown)
StartShutdown();
vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
if (fShutdown)
return;
}
}
bool BindListenPort(const CService &addrBind, string& strError)
{
strError = "";
int nOne = 1;
#ifdef WIN32
// Initialize Windows Sockets
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR)
{
strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);
printf("%s\n", strError.c_str());
return false;
}
#endif
// Create socket for listening for incoming connections
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
{
strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
printf("%s\n", strError.c_str());
return false;
}
SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hListenSocket == INVALID_SOCKET)
{
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
#ifdef SO_NOSIGPIPE
// Different way of disabling SIGPIPE on BSD
setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
#endif
#ifndef WIN32
// Allow binding if the port is still in TIME_WAIT state after
// the program was closed and restarted. Not an issue on windows.
setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
#endif
#ifdef WIN32
// Set to non-blocking, incoming connections will also inherit this
if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
#else
if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
#endif
{
strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
// some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
// and enable it by default or not. Try to enable it, if possible.
if (addrBind.IsIPv6()) {
#ifdef IPV6_V6ONLY
#ifdef WIN32
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
#else
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
#endif
#endif
#ifdef WIN32
int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
// this call is allowed to fail
setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
#endif
}
if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
if (nErr == WSAEADDRINUSE)
strError = strprintf(_("Unable to bind to %s on this computer. Sixcoin is probably already running."), addrBind.ToString().c_str());
else
strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
printf("%s\n", strError.c_str());
return false;
}
printf("Bound to %s\n", addrBind.ToString().c_str());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
{
strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
vhListenSocket.push_back(hListenSocket);
if (addrBind.IsRoutable() && fDiscover)
AddLocal(addrBind, LOCAL_BIND);
return true;
}
void static Discover()
{
if (!fDiscover)
return;
#ifdef WIN32
// Get local host IP
char pszHostName[1000] = "";
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
{
vector<CNetAddr> vaddr;
if (LookupHost(pszHostName, vaddr))
{
BOOST_FOREACH (const CNetAddr &addr, vaddr)
{
AddLocal(addr, LOCAL_IF);
}
}
}
#else
// Get local host ip
struct ifaddrs* myaddrs;
if (getifaddrs(&myaddrs) == 0)
{
for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr == NULL) continue;
if ((ifa->ifa_flags & IFF_UP) == 0) continue;
if (strcmp(ifa->ifa_name, "lo") == 0) continue;
if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
if (ifa->ifa_addr->sa_family == AF_INET)
{
struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
CNetAddr addr(s4->sin_addr);
if (AddLocal(addr, LOCAL_IF))
printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
else if (ifa->ifa_addr->sa_family == AF_INET6)
{
struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
CNetAddr addr(s6->sin6_addr);
if (AddLocal(addr, LOCAL_IF))
printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
}
freeifaddrs(myaddrs);
}
#endif
// Don't use external IPv4 discovery, when -onlynet="IPv6"
if (!IsLimited(NET_IPV4))
NewThread(ThreadGetMyExternalIP, NULL);
}
void StartNode(void* parg)
{
// Make this thread recognisable as the startup thread
RenameThread("sixcoin-start");
if (semOutbound == NULL) {
// initialize semaphore
int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
semOutbound = new CSemaphore(nMaxOutbound);
}
if (pnodeLocalHost == NULL)
pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
Discover();
//
// Start threads
//
if (!GetBoolArg("-dnsseed", true))
printf("DNS seeding disabled\n");
else
if (!NewThread(ThreadDNSAddressSeed, NULL))
printf("Error: NewThread(ThreadDNSAddressSeed) failed\n");
// Map ports with UPnP
if (fUseUPnP)
MapPort();
// Get addresses from IRC and advertise ours
if (!NewThread(ThreadIRCSeed, NULL))
printf("Error: NewThread(ThreadIRCSeed) failed\n");
// Send and receive from sockets, accept connections
if (!NewThread(ThreadSocketHandler, NULL))
printf("Error: NewThread(ThreadSocketHandler) failed\n");
// Initiate outbound connections from -addnode
if (!NewThread(ThreadOpenAddedConnections, NULL))
printf("Error: NewThread(ThreadOpenAddedConnections) failed\n");
// Initiate outbound connections
if (!NewThread(ThreadOpenConnections, NULL))
printf("Error: NewThread(ThreadOpenConnections) failed\n");
// Process messages
if (!NewThread(ThreadMessageHandler, NULL))
printf("Error: NewThread(ThreadMessageHandler) failed\n");
// Dump network addresses
if (!NewThread(ThreadDumpAddress, NULL))
printf("Error; NewThread(ThreadDumpAddress) failed\n");
// Mine proof-of-stake blocks in the background
if (!GetBoolArg("-staking", true))
printf("Staking disabled\n");
else
if (!NewThread(ThreadStakeMiner, pwalletMain))
printf("Error: NewThread(ThreadStakeMiner) failed\n");
}
bool StopNode()
{
printf("StopNode()\n");
fShutdown = true;
nTransactionsUpdated++;
int64_t nStart = GetTime();
if (semOutbound)
for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
semOutbound->post();
do
{
int nThreadsRunning = 0;
for (int n = 0; n < THREAD_MAX; n++)
nThreadsRunning += vnThreadsRunning[n];
if (nThreadsRunning == 0)
break;
if (GetTime() - nStart > 20)
break;
MilliSleep(20);
} while(true);
if (vnThreadsRunning[THREAD_SOCKETHANDLER] > 0) printf("ThreadSocketHandler still running\n");
if (vnThreadsRunning[THREAD_OPENCONNECTIONS] > 0) printf("ThreadOpenConnections still running\n");
if (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0) printf("ThreadMessageHandler still running\n");
if (vnThreadsRunning[THREAD_RPCLISTENER] > 0) printf("ThreadRPCListener still running\n");
if (vnThreadsRunning[THREAD_RPCHANDLER] > 0) printf("ThreadsRPCServer still running\n");
#ifdef USE_UPNP
if (vnThreadsRunning[THREAD_UPNP] > 0) printf("ThreadMapPort still running\n");
#endif
if (vnThreadsRunning[THREAD_DNSSEED] > 0) printf("ThreadDNSAddressSeed still running\n");
if (vnThreadsRunning[THREAD_ADDEDCONNECTIONS] > 0) printf("ThreadOpenAddedConnections still running\n");
if (vnThreadsRunning[THREAD_DUMPADDRESS] > 0) printf("ThreadDumpAddresses still running\n");
if (vnThreadsRunning[THREAD_STAKE_MINER] > 0) printf("ThreadStakeMiner still running\n");
while (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0 || vnThreadsRunning[THREAD_RPCHANDLER] > 0)
MilliSleep(20);
MilliSleep(50);
DumpAddresses();
return true;
}
class CNetCleanup
{
public:
CNetCleanup()
{
}
~CNetCleanup()
{
// Close sockets
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->hSocket != INVALID_SOCKET)
closesocket(pnode->hSocket);
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET)
if (closesocket(hListenSocket) == SOCKET_ERROR)
printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
#ifdef WIN32
// Shutdown Windows Sockets
WSACleanup();
#endif
}
}
instance_of_cnetcleanup;
void RelayTransaction(const CTransaction& tx, const uint256& hash)
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(10000);
ss << tx;
RelayTransaction(tx, hash, ss);
}
void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss)
{
CInv inv(MSG_TX, hash);
{
LOCK(cs_mapRelay);
// Expire old relay messages
while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
{
mapRelay.erase(vRelayExpiration.front().second);
vRelayExpiration.pop_front();
}
// Save original serialized message so newer versions are preserved
mapRelay.insert(std::make_pair(inv, ss));
vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
}
RelayInventory(inv);
}
| mit |
jcsena/pcc | tareas/6/numeros.cpp | 1276 | //
// Copyright (c) 2015 by Julio Seña. All Rights Reserved.
//
/**
1. Escriba el programa correspondiente. Debe funcionar correctamente.
Dado como datos de entrada tres números enteros, determine si los mismos
están en orden creciente y los imprima en pantalla.
Datos: A, B, C (variables de tipo entero. Los números deben ser diferentes entre sí, de lo contrario no procede).
Se deben imprimir los resultados. Sugerencia: recuerde utilizar operador lógico. HAGA EL ALGORITMO. (10 puntos)
*/
#include <iomanip>
#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
/**
* @A : Numero ingreasado por patalla
* @B : Numero ingreasado por patalla
* @C : Numero ingreasado por patalla
*/
int A, B, C;
//se solitan los dos numeros a ingresar por pantalla
cout << "Por favor escriba tres numeros en order creciente: ";
cin >> A >> B >> C;
//se realiza la validacion de que si es creciente los numeros
if ( ( A < B ) && (B < C) ) {
// impresion de resultados
cout << "Numeros correctamente ordenados" << endl;
cout << "A: " <<A << endl;
cout << "B: " <<B << endl;
cout << "C: " <<C << endl;
}
else{
cout << "Los numeros deben estar en order creciente!" << endl;
}
return 0;
}
| mit |
TomPallister/Ocelot | test/Ocelot.UnitTests/Requester/HttpClientBuilderTests.cs | 17166 | using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Moq;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Logging;
using Ocelot.Middleware;
using Ocelot.Request.Middleware;
using Ocelot.Requester;
using Ocelot.Responses;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Requester
{
public class HttpClientBuilderTests : IDisposable
{
private HttpClientBuilder _builder;
private readonly Mock<IDelegatingHandlerHandlerFactory> _factory;
private IHttpClient _httpClient;
private HttpResponseMessage _response;
private DownstreamContext _context;
private readonly Mock<IHttpClientCache> _cacheHandlers;
private readonly Mock<IOcelotLogger> _logger;
private int _count;
private IWebHost _host;
private IHttpClient _againHttpClient;
private IHttpClient _firstHttpClient;
private MemoryHttpClientCache _realCache;
public HttpClientBuilderTests()
{
_cacheHandlers = new Mock<IHttpClientCache>();
_logger = new Mock<IOcelotLogger>();
_factory = new Mock<IDelegatingHandlerHandlerFactory>();
_builder = new HttpClientBuilder(_factory.Object, _cacheHandlers.Object, _logger.Object);
}
[Fact]
public void should_build_http_client()
{
var qosOptions = new QoSOptionsBuilder()
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true))
.WithLoadBalancerKey("")
.WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build())
.WithQosOptions(new QoSOptionsBuilder().Build())
.Build();
this.Given(x => GivenTheFactoryReturns())
.And(x => GivenARequest(reRoute))
.When(x => WhenIBuild())
.Then(x => ThenTheHttpClientShouldNotBeNull())
.BDDfy();
}
[Fact]
public void should_get_from_cache()
{
var qosOptions = new QoSOptionsBuilder()
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true))
.WithLoadBalancerKey("")
.WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build())
.WithQosOptions(new QoSOptionsBuilder().Build())
.Build();
this.Given(x => GivenARealCache())
.And(x => GivenTheFactoryReturns())
.And(x => GivenARequest(reRoute))
.And(x => WhenIBuildTheFirstTime())
.And(x => WhenISave())
.And(x => WhenIBuildAgain())
.And(x => WhenISave())
.When(x => WhenIBuildAgain())
.Then(x => ThenTheHttpClientIsFromTheCache())
.BDDfy();
}
[Fact]
public void should_get_from_cache_with_different_query_string()
{
var qosOptions = new QoSOptionsBuilder()
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true))
.WithLoadBalancerKey("")
.WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build())
.WithQosOptions(new QoSOptionsBuilder().Build())
.Build();
this.Given(x => GivenARealCache())
.And(x => GivenTheFactoryReturns())
.And(x => GivenARequest(reRoute, "http://wwww.someawesomewebsite.com/woot?badman=1"))
.And(x => WhenIBuildTheFirstTime())
.And(x => WhenISave())
.And(x => WhenIBuildAgain())
.And(x => GivenARequest(reRoute, "http://wwww.someawesomewebsite.com/woot?badman=2"))
.And(x => WhenISave())
.When(x => WhenIBuildAgain())
.Then(x => ThenTheHttpClientIsFromTheCache())
.BDDfy();
}
[Fact]
public void should_not_get_from_cache_with_different_query_string()
{
var qosOptions = new QoSOptionsBuilder()
.Build();
var reRouteA = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true))
.WithLoadBalancerKey("")
.WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithContainsQueryString(true).WithOriginalValue("").Build())
.WithQosOptions(new QoSOptionsBuilder().Build())
.Build();
var reRouteB = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true))
.WithLoadBalancerKey("")
.WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithContainsQueryString(true).WithOriginalValue("").Build())
.WithQosOptions(new QoSOptionsBuilder().Build())
.Build();
this.Given(x => GivenARealCache())
.And(x => GivenTheFactoryReturns())
.And(x => GivenARequest(reRouteA, "http://wwww.someawesomewebsite.com/woot?badman=1"))
.And(x => WhenIBuildTheFirstTime())
.And(x => WhenISave())
.And(x => WhenIBuildAgain())
.And(x => GivenARequest(reRouteB, "http://wwww.someawesomewebsite.com/woot?badman=2"))
.And(x => WhenISave())
.When(x => WhenIBuildAgain())
.Then(x => ThenTheHttpClientIsNotFromTheCache())
.BDDfy();
}
[Fact]
public void should_log_if_ignoring_ssl_errors()
{
var qosOptions = new QoSOptionsBuilder()
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true))
.WithLoadBalancerKey("")
.WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build())
.WithQosOptions(new QoSOptionsBuilder().Build())
.WithDangerousAcceptAnyServerCertificateValidator(true)
.Build();
this.Given(x => GivenTheFactoryReturns())
.And(x => GivenARequest(reRoute))
.When(x => WhenIBuild())
.Then(x => ThenTheHttpClientShouldNotBeNull())
.Then(x => ThenTheDangerousAcceptAnyServerCertificateValidatorWarningIsLogged())
.BDDfy();
}
[Fact]
public void should_call_delegating_handlers_in_order()
{
var qosOptions = new QoSOptionsBuilder()
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true))
.WithLoadBalancerKey("")
.WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build())
.WithQosOptions(new QoSOptionsBuilder().Build())
.Build();
var fakeOne = new FakeDelegatingHandler();
var fakeTwo = new FakeDelegatingHandler();
var handlers = new List<Func<DelegatingHandler>>()
{
() => fakeOne,
() => fakeTwo
};
this.Given(x => GivenTheFactoryReturns(handlers))
.And(x => GivenARequest(reRoute))
.And(x => WhenIBuild())
.When(x => WhenICallTheClient())
.Then(x => ThenTheFakeAreHandledInOrder(fakeOne, fakeTwo))
.And(x => ThenSomethingIsReturned())
.BDDfy();
}
[Fact]
public void should_re_use_cookies_from_container()
{
var qosOptions = new QoSOptionsBuilder()
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(false, true, false, true))
.WithLoadBalancerKey("")
.WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build())
.WithQosOptions(new QoSOptionsBuilder().Build())
.Build();
this.Given(_ => GivenADownstreamService())
.And(_ => GivenARequest(reRoute))
.And(_ => GivenTheFactoryReturnsNothing())
.And(_ => WhenIBuild())
.And(_ => WhenICallTheClient("http://localhost:5003"))
.And(_ => ThenTheCookieIsSet())
.And(_ => GivenTheClientIsCached())
.And(_ => WhenIBuild())
.When(_ => WhenICallTheClient("http://localhost:5003"))
.Then(_ => ThenTheResponseIsOk())
.BDDfy();
}
[Theory]
[InlineData("GET")]
[InlineData("POST")]
[InlineData("PUT")]
[InlineData("DELETE")]
[InlineData("PATCH")]
public void should_add_verb_to_cache_key(string verb)
{
var downstreamUrl = "http://localhost:5012/";
var method = new HttpMethod(verb);
var qosOptions = new QoSOptionsBuilder()
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true))
.WithLoadBalancerKey("")
.WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build())
.WithQosOptions(new QoSOptionsBuilder().Build())
.Build();
this.Given(_ => GivenADownstreamService())
.And(_ => GivenARequestWithAUrlAndMethod(reRoute, downstreamUrl, method))
.And(_ => GivenTheFactoryReturnsNothing())
.And(_ => WhenIBuild())
.And(_ => GivenCacheIsCalledWithExpectedKey($"{method.ToString()}:{downstreamUrl}"))
.BDDfy();
}
private void GivenARealCache()
{
_realCache = new MemoryHttpClientCache();
_builder = new HttpClientBuilder(_factory.Object, _realCache, _logger.Object);
}
private void ThenTheHttpClientIsFromTheCache()
{
_againHttpClient.ShouldBe(_firstHttpClient);
}
private void ThenTheHttpClientIsNotFromTheCache()
{
_againHttpClient.ShouldNotBe(_firstHttpClient);
}
private void WhenISave()
{
_builder.Save();
}
private void GivenCacheIsCalledWithExpectedKey(string expectedKey)
{
_cacheHandlers.Verify(x => x.Get(It.IsAny<DownstreamReRoute>()), Times.Once);
}
private void ThenTheDangerousAcceptAnyServerCertificateValidatorWarningIsLogged()
{
_logger.Verify(x => x.LogWarning($"You have ignored all SSL warnings by using DangerousAcceptAnyServerCertificateValidator for this DownstreamReRoute, UpstreamPathTemplate: {_context.DownstreamReRoute.UpstreamPathTemplate}, DownstreamPathTemplate: {_context.DownstreamReRoute.DownstreamPathTemplate}"), Times.Once);
}
private void GivenTheClientIsCached()
{
_cacheHandlers.Setup(x => x.Get(It.IsAny<DownstreamReRoute>())).Returns(_httpClient);
}
private void ThenTheCookieIsSet()
{
_response.Headers.TryGetValues("Set-Cookie", out var test).ShouldBeTrue();
}
private void WhenICallTheClient(string url)
{
_response = _httpClient
.SendAsync(new HttpRequestMessage(HttpMethod.Get, url))
.GetAwaiter()
.GetResult();
}
private void ThenTheResponseIsOk()
{
_response.StatusCode.ShouldBe(HttpStatusCode.OK);
}
private void GivenADownstreamService()
{
_host = new WebHostBuilder()
.UseUrls("http://localhost:5003")
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.Configure(app =>
{
app.Run(context =>
{
if (_count == 0)
{
context.Response.Cookies.Append("test", "0");
context.Response.StatusCode = 200;
_count++;
return Task.CompletedTask;
}
if (_count == 1)
{
if (context.Request.Cookies.TryGetValue("test", out var cookieValue) || context.Request.Headers.TryGetValue("Set-Cookie", out var headerValue))
{
context.Response.StatusCode = 200;
return Task.CompletedTask;
}
context.Response.StatusCode = 500;
}
return Task.CompletedTask;
});
})
.Build();
_host.Start();
}
private void GivenARequest(DownstreamReRoute downstream)
{
GivenARequest(downstream, "http://localhost:5003");
}
private void GivenARequest(DownstreamReRoute downstream, string downstreamUrl)
{
GivenARequestWithAUrlAndMethod(downstream, downstreamUrl, HttpMethod.Get);
}
private void GivenARequestWithAUrlAndMethod(DownstreamReRoute downstream, string url, HttpMethod method)
{
var context = new DownstreamContext(new DefaultHttpContext())
{
DownstreamReRoute = downstream,
DownstreamRequest = new DownstreamRequest(new HttpRequestMessage() { RequestUri = new Uri(url), Method = method }),
};
_context = context;
}
private void ThenSomethingIsReturned()
{
_response.ShouldNotBeNull();
}
private void WhenICallTheClient()
{
_response = _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, "http://test.com")).GetAwaiter().GetResult();
}
private void ThenTheFakeAreHandledInOrder(FakeDelegatingHandler fakeOne, FakeDelegatingHandler fakeTwo)
{
fakeOne.TimeCalled.ShouldBeGreaterThan(fakeTwo.TimeCalled);
}
private void GivenTheFactoryReturns()
{
var handlers = new List<Func<DelegatingHandler>>(){ () => new FakeDelegatingHandler()};
_factory
.Setup(x => x.Get(It.IsAny<DownstreamReRoute>()))
.Returns(new OkResponse<List<Func<DelegatingHandler>>>(handlers));
}
private void GivenTheFactoryReturnsNothing()
{
var handlers = new List<Func<DelegatingHandler>>();
_factory
.Setup(x => x.Get(It.IsAny<DownstreamReRoute>()))
.Returns(new OkResponse<List<Func<DelegatingHandler>>>(handlers));
}
private void GivenTheFactoryReturns(List<Func<DelegatingHandler>> handlers)
{
_factory
.Setup(x => x.Get(It.IsAny<DownstreamReRoute>()))
.Returns(new OkResponse<List<Func<DelegatingHandler>>>(handlers));
}
private void WhenIBuild()
{
_httpClient = _builder.Create(_context);
}
private void WhenIBuildTheFirstTime()
{
_firstHttpClient = _builder.Create(_context);
}
private void WhenIBuildAgain()
{
_builder = new HttpClientBuilder(_factory.Object, _realCache, _logger.Object);
_againHttpClient = _builder.Create(_context);
}
private void ThenTheHttpClientShouldNotBeNull()
{
_httpClient.ShouldNotBeNull();
}
public void Dispose()
{
_response?.Dispose();
_host?.Dispose();
}
}
}
| mit |
levjj/esverify | examples/contradiction.js | 505 | // Proofs: Simple contradiction
function contradiction(p, p1, a3) {
// p1: { x: nat | p(x) <=> 0 <= x <= 3}
requires(spec(p1, (x) => Number.isInteger(x),
(x) => pure() && p(x) === (0 <= x && x <= 3)));
// a3: { x: nat | p(x) => p(x+1) }
requires(spec(a3, (x) => Number.isInteger(x) && p(x),
(x) => pure() && p(x+1)));
ensures(false);
// have p(3) from p1(3);
p1(3);
// have p(4) from a3(3);
a3(3);
// have 0 <= 4 <= 3 from p1(4);
p1(4);
}
| mit |
UKHomeOffice/platform-hub | platform-hub-web/src/app/shared/util/object-rollup.service.js | 1385 | export const objectRollupService = function (_) {
'ngInject';
const service = {};
service.rollup = rollup;
return service;
function rollup(obj, into) {
return _rollup(_.cloneDeep(obj), _.cloneDeep(into));
}
function _rollup(obj, into) {
return _.mergeWith(into, obj, (objValue, srcValue) => {
const [v1, v2] = reconcile(objValue, srcValue);
if (_.isPlainObject(v1)) {
return _rollup(v2, v1);
} else if (_.isArray(v1)) {
return v1.concat(v2);
} else if (_.isString(v1)) {
return v2;
}
return v1 + v2;
});
}
function reconcile(objValue, srcValue) {
if (
(_.isUndefined(objValue) || _.isNull(objValue)) &&
(!_.isUndefined(srcValue) || !_.isNull(srcValue))
) {
return [defaultValue(srcValue), srcValue];
} else if (
(!_.isUndefined(objValue) || !_.isNull(objValue)) &&
(_.isUndefined(srcValue) || _.isNull(srcValue))
) {
return [objValue, defaultValue(objValue)];
}
return [objValue, srcValue];
}
function defaultValue(source) {
if (_.isPlainObject(source)) {
return {};
} else if (_.isArray(source)) {
return [];
} else if (_.isString(source)) {
return '';
} else if (_.isInteger(source)) {
return 0;
} else if (_.isNumber(source)) {
return 0.0;
}
return null;
}
};
| mit |
melnelen/CSharpPart2 | H01Arrays/P05MaximalIncreasingSequence/Properties/AssemblyInfo.cs | 1444 | 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("P05MaximalIncreasingSequence")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SAP AG")]
[assembly: AssemblyProduct("P05MaximalIncreasingSequence")]
[assembly: AssemblyCopyright("Copyright © SAP AG 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("a81e729e-1272-44aa-a388-7369766a48d6")]
// 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 |
alannesta/tinto | lib/html/components/button.js | 436 | 'use strict';
var Component = require('../../component');
var text = require('../properties/text');
var inherits = require('../../utils/inherits');
/**
* @memberOf tinto.html.components
* @extends tinto.Component
* @constructor
* @inheritDoc
* @property {tinto.Attribute} label
*/
function Button() {
Component.apply(this, arguments);
this.property('label', text);
}
inherits(Button, Component);
module.exports = Button;
| mit |
SUNYCortland/SystemsStatus | SystemsStatus.Data/Repositories/Nh/Mappings/MsSql/OnlineServiceStatusMapping.cs | 541 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SystemsStatus.Core.Data.Entities.Statuses;
using FluentNHibernate.Mapping;
namespace SystemsStatus.Data.Repositories.Nh.Mappings.MsSql
{
public class OnlineServiceStatusMapping : SubclassMap<OnlineServiceStatus>
{
public OnlineServiceStatusMapping()
{
Table("ss_online_statuses");
KeyColumn("status_id");
Map(x => x.OnlineSince).Column("online_status_online_since");
}
}
}
| mit |
raph-ael/foodsharing | packages/foodsharing/platform/src/app/team/team.model.php | 2138 | <?php
class TeamModel extends Model
{
public function getTeam($bezirkId = 1373)
{
$out = array();
if($orgas = $this->q('
SELECT
fs.id,
CONCAT(mb.name,"@'.DEFAULT_HOST.'") AS email,
fs.name,
fs.nachname,
fs.photo,
fs.about_me_public AS `desc`,
fs.rolle,
fs.geschlecht,
fs.homepage,
fs.github,
fs.tox,
fs.twitter,
fs.position,
fs.contact_public
FROM
'.PREFIX.'foodsaver_has_bezirk hb
LEFT JOIN
'.PREFIX.'foodsaver fs
ON
hb.foodsaver_id = fs.id
LEFT JOIN
'.PREFIX.'mailbox mb
ON
fs.mailbox_id = mb.id
WHERE
hb.bezirk_id = '.$bezirkId.'
ORDER BY fs.name
'))
{
foreach ($orgas as $o)
{
$out[(int)$o['id']] = $o;
}
}
return $out;
}
public function getUser($id)
{
if($user = $this->qRow('
SELECT
fs.id,
CONCAT(fs.name," ",fs.nachname) AS name,
fs.about_me_public AS `desc`,
fs.rolle,
fs.geschlecht,
fs.photo,
fs.twitter,
fs.tox,
fs.homepage,
fs.github,
fs.position,
fs.email,
fs.contact_public
FROM
'.PREFIX.'foodsaver_has_bezirk fb
INNER JOIN '.PREFIX.'foodsaver fs ON
fb.foodsaver_id = fs.id
WHERE
fb.foodsaver_id = '.(int)$id.' AND(
fb.bezirk_id = 1564 OR fb.bezirk_id = 1565 OR fb.bezirk_id = 1373
)
LIMIT 1
'))
{
$user['groups'] = $this->q('
SELECT
b.id,
b.name,
b.type
FROM
'.PREFIX.'botschafter bot,
'.PREFIX.'bezirk b
WHERE
bot.bezirk_id = b.id
AND
bot.foodsaver_id = '.(int)$id.'
AND
b.type = 7');
return $user;
}
}
}
| mit |
ccolleyh/AngularIgnition | app/controllers/grocery-list-ctrl.js | 1050 | 'use strict';
angular.module('myApp.GroceryList', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/GroceryList', {
templateUrl: 'views/grocery-list.html',
controller: 'GroceryListCtrl'
});
}])
.controller('GroceryListCtrl', ['$scope', function($scope) {
$scope.sayHi = "Now we have a grocery list!";
$scope.topic = "You've got";
$scope.task = "items to buy!";
$scope.placeholder = "I need...";
$scope.submitButton = "Add";
$scope.clearButton = "Clear Completed";
$scope.list = [
{text: 'Poh-TAT-Toes', done:false},
{text: 'Bacon', done:true},
{text: 'More bacon', done:false},
{text: 'milk', done:true}
];
$scope.getTotalList = function () {
return $scope.list.length;
};
$scope.addItem = function () {
$scope.list.push({text:$scope.formItemText, done:false});
$scope.formItemText = '';
};
$scope.clearCompleted = function () {
$scope.list = _.filter($scope.list, function(item){
return !item.done;
});
};
}]);
| mit |
microcom/angular-strap | src/directives/select.js | 1430 | 'use strict';
angular.module('$strap.directives')
.directive('bsSelect', function($timeout, $strapConfig) {
var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/;
return {
restrict: 'A',
require: '?ngModel',
link: function postLink(scope, element, attrs, controller) {
var options = scope.$eval(attrs.bsSelect) || {};
angular.extend(options, $strapConfig.select);
angular.forEach(
[
'container',
'hideDisabled',
'selectedTextFormat',
'countSelectedText',
'size',
'showSubtext',
'showIcon',
'style',
'title',
'width'
],
function (key) {
if (angular.isDefined(attrs[key])) {
options[key] = attrs[key];
}
}
);
$timeout(function() {
element.selectpicker(options);
element.next().removeClass('ng-scope');
});
// If we have a controller (i.e. ngModelController) then wire it up
if(controller) {
// Watch for changes to the model value
scope.$watch(attrs.ngModel, function(newValue, oldValue) {
if (!angular.equals(newValue, oldValue)) {
element.selectpicker('refresh');
}
});
}
}
};
});
| mit |
ensjo/jsmc1000 | MC1000.js | 117379 | function MC1000(mc1000HtmlDelegate) {
this.delegate = mc1000HtmlDelegate;
this.init();
}
MC1000.prototype.init = function() {
this.z80 = null;
this.vdg = null;
this.looper = null;
this.filter = null;
this.masterChannel = null;
this.psg = null;
this.keyboard = null;
this.ram = null;
this.vram = null;
this.rom = null;
this.core = new MC1000Core(this);
};
MC1000.prototype.executeStart = function() {
if (!this.core) {
this.init();
}
// https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio
try {
this.looper.audioContext.resume().then(function(){console.log('Playback resumed successfully.')});
} catch(e) {
// Ignore exception.
console.log(e);
}
this.core.executeStart();
};
MC1000.prototype.executeStop = function() {
if (!this.core) {
this.init();
}
this.core.executeStop();
};
MC1000.prototype.reset = function() {
if (!this.core) {
this.init();
}
this.core.reset();
};
// MC-1000 Core delegate methods.
MC1000.prototype.mc1000CoreGetZ80 = function(mc1000Core) {
if (this.z80 == null) {
this.z80 = new Z80_(mc1000Core);
}
return this.z80;
};
MC1000.prototype.mc1000CoreGetVdg = function(mc1000Core) {
if (this.vdg == null) {
//this.vdg = new MC6847(mc1000Core);
this.vdg = new MC6847EnsjoMod(mc1000Core);
}
return this.vdg;
};
MC1000.prototype.mc1000CoreGetPsg = function(mc1000Core) {
if (this.psg == null) {
this.masterChannel = new MasterChannel();
this.psg = new AY38910(mc1000Core);
this.psg.setMode(PsgDeviceChannel.MODE_SIGNED);
this.psg.setDevice(PsgDeviceChannel.DEVICE_AY_3_8910);
this.masterChannel.addChannel(this.psg);
this.filter = new BiquadFilterChannel();
this.looper = new AudioLooper(4096);
this.looper.setChannel(this.filter);
this.filter.setChannel(this.masterChannel);
}
return this.psg;
};
MC1000.prototype.mc1000CoreGetKeyboard = function(mc1000Core) {
if (this.keyboard == null) {
this.keyboard = new MC1000Keyboard(mc1000Core);
}
return this.keyboard;
};
MC1000.prototype.mc1000CoreGetRam = function() {
if (this.ram == null) {
if (this.delegate.getBuiltIn64kbRam()) {
this.ram = new Memory(65536, 0, 0xffff); // RAM: 64 KB.
} else {
this.ram = new Memory(16384, 0, 0x3fff); // RAM: 16 KB.
}
}
return this.ram;
};
MC1000.prototype.mc1000CoreGetVram = function() {
if (this.vram == null) {
if (this.delegate.getBuiltIn64kbRam()) {
this.vram = new Memory(8192, 0, 0x1fff); // VRAM: 8 KB.
} else {
this.vram = new Memory(6144, 0, 0x1fff); // VRAM: 6 KB.
}
}
return this.vram;
};
MC1000.prototype.mc1000CoreGetRom = function() {
if (this.rom == null) {
this.rom = new Memory(0, 0, 0x3fff);
this.rom.setArray(MC1000.ORIGINAL_ROM_ARRAY);
}
return this.rom;
};
MC1000.prototype.mc1000CoreGetRomCs = function() {
// Expansion port not implemented.
return true;
};
MC1000.prototype.mc1000CoreSetRomCe = function(romCe) {
// Expansion port not implemented.
};
MC1000.prototype.mc1000CoreGetDsb64 = function() {
// Expansion port not implemented.
return false;
};
MC1000.prototype.mc1000CoreGetBuiltIn64kbRam = function() {
return this.delegate.getBuiltIn64kbRam();
};
MC1000.prototype.mc1000CoreGetScreenLinesPerInterrupt = function() {
return this.delegate.getScreenLinesPerInterrupt();
};
MC1000.prototype.mc1000CoreGetKeyboardMapping = function() {
return this.delegate.getKeyboardMapping();
};
MC1000.prototype.mc1000CoreGetCanvas = function() {
return this.delegate.getCanvas();
};
MC1000.prototype.mc1000CoreReadMemory = function(address) {
// Expansion port not implemented.
return 0xff;
};
MC1000.prototype.mc1000CoreWriteMemory = function(address, data) {
// Expansion port not implemented.
};
MC1000.prototype.mc1000CoreReadIo = function(address) {
// Expansion port not implemented.
return 0xff;
};
MC1000.prototype.mc1000CoreWriteIo = function(address, data) {
// Expansion port not implemented.
};
MC1000.prototype.loadbiosrom = function(url, slot, canvasbiosrom) {
this.print("Reading bios rom " + url + "\n");
var biosrom = mc1000_loadurl(url);
this.print(biosrom.length+" bytes read\n");
if (biosrom != '') {
canvasbiosrom.width=256;
canvasbiosrom.height=biosrom.length/256;
//alert(biosrom.length+','+canvasbiosrom.width+','+canvasbiosrom.height);
var ctxbiosrom = canvasbiosrom.getContext("2d");
ctxbiosrom.fillStyle="rgb(0,0,0)";
ctxbiosrom.fillRect(0,0,canvasbiosrom.width,canvasbiosrom.height);
var imgdatabiosrom = undefined;
var dbr = undefined;
if (ctxbiosrom.getImageData) {
imgdatabiosrom = ctxbiosrom.getImageData(0,0,canvasbiosrom.width,canvasbiosrom.height);
dbr = imgdatabiosrom.data;
}
var biosromlength = biosrom.length;
// MimeType('application/octet-stream; charset=x-user-defined')
var charcode=0;
for (var i=0; i < biosromlength ; i++) {
charcode = biosrom.charCodeAt(i) & 0xff;
this.memoria[slot][i]=charcode;
if (dbr) {
dbr[i*4]=charcode;
dbr[i*4+1]=charcode;
dbr[i*4+2]=charcode;
} else {
ctxbiosrom.fillStyle="rgb("+charcode+","+charcode+","+charcode+")";
ctxbiosrom.fillRect(i%canvasbiosrom.width,Math.floor(i/canvasbiosrom.width),1,1);
}
}
if (ctxbiosrom.putImageData) {
ctxbiosrom.putImageData(imgdatabiosrom,0,0);
}
}
return biosrom;
};
MC1000.prototype.mc1000CoreLog = function(str) {
this.delegate.log(str);
};
MC1000.prototype.onkeydown = function(event) {
this.keyboard.keyPressed(event);
return false;
};
MC1000.prototype.onkeyup = function(event) {
this.keyboard.keyReleased(event);
return false;
};
MC1000.TOKENS = [
"END", "FOR", "NEXT", "DATA",
"EXIT", "INPUT", "DIM", "READ",
"LET", "GOTO", "RUN", "IF",
"RESTORE", "GOSUB", "RETURN", "REM",
"STOP", "OUT", "ON", "HOME",
"WAIT", "DEF", "POKE", "PRINT",
"PR#", "SOUND", "GR", "HGR",
"COLOR", "TEXT", "PLOT", "TRO",
"UNPLOT", "SET", "CALL", "DRAW",
"UNDRAW", "TEMPO", "WIDTH", "CONT",
"LIST", "CLEAR", "LOAD", "SAVE",
"NEW", "TLOAD", "COLUMN", "AUTO",
"FAST", "SLOW", "EDIT", "INVERSE",
"NORMAL", "DEBUG", "TAB(", "TO",
"FN", "SPC(", "THEN", "NOT",
"STEP", "VTAB(", "+", "-",
"*", "/", "^", "AND",
"OR", ">", "=", "<",
"SGN", "INT", "ABS", "USR",
"FRE", "INP", "POS", "SQR",
"RND", "LOG", "EXP", "COS",
"SIN", "TAN", "ATN", "PEEK",
"LEN", "STR$", "VAL", "ASC",
"CHR$", "LEFT$", "RIGHT$", "MID$"
];
MC1000.prototype.getBasicProgram = function() {
var me = this; // 'this' refers to 'window' in the state functions. Use 'me' to keep reference to MC1000 object.
var program = "";
var i, nl, b, c;
var state;
var stateToken = function() {
// Standard strategy.
if (b >= 128 && b - 128 < MC1000.TOKENS.length) {
// Token found: Output corresponding reserved word with padding spaces.
var detokenized = MC1000.TOKENS[b - 128];
program += " " + detokenized + " ";
// Some reserved words imply a change in strategy.
switch (detokenized) {
case "DATA":
state = stateDATA;
break;
case "REM":
case "SAVE":
case "LOAD" :
state = stateREM;
break;
}
} else {
switch (c) {
case " ":
// Space found: Output hexadecimal notation so it is not lost.
program += "~20";
break;
default:
stateStringOrChar();
}
}
};
var stateDATA = function() {
// Handles start of DATA instruction: Heading space.
switch(c) {
case " ":
// Space found: Output hexadecimal notation to mark start of actual data.
program += "~20";
state = stateDATA2;
break;
default:
(state = stateDATA2)();
}
};
var stateDATA2 = function() {
// Handles data item in DATA instruction: Spaces after any first character are output unescaped.
stateStringOrChar();
switch (c) {
case ":":
// End of DATA instruction.
state = stateToken;
break;
}
};
var stateREM = function() {
// Handles start of REM, SAVE or LOAD instructions: Heading space.
switch(c) {
case " ":
// Space found: Output hexadecimal notation to mark start of actual data.
program += "~20";
state = stateChar; // Output rest of line. Spaces after any first character are output unescaped.
break;
default:
(state = stateChar)(); // Output rest of line. Spaces after any first character are output unescaped.
}
};
var stateStringOrChar = function() {
// Identifies start of string.
stateChar();
switch (c) {
case '"':
// Start of string.
// Saves current strategy to resume when string ends.
stateBeforeString = state;
state = stateString;
break;
}
};
var stateString = function() {
// Handles string content until ending quotes are found.
stateChar();
switch (c) {
case '"':
// End of string.
state = stateBeforeString;
break;
}
};
var stateChar = function() {
// Handles characters.
if (b >= 32 && b < 96) {
// MC6847's ASCII character.
program += c;
} else if ((b ^ 0x80) >= 32 && (b ^ 0x80) < 96) {
// MC6847's ASCII character in INVERSE video.
// Output grave + normal character.
program += "`" + String.fromCharCode(b ^ 0x80);
} else {
// Other characters.
// Output as tilde + hexadecimal code.
program += "~" + (b < 0x10 ? "0" : "") + b.toString(16).toUpperCase();
}
};
// Get BASIC program start address at 0x349 (usually 0x3d5).
i = this.ram.read(0x349) | (this.ram.read(0x34a) << 8);
while (true) {
// Get address of next BASIC line.
nl = this.ram.read(i++) | (this.ram.read(i++) << 8);
// 0x000 signals end of program.
if (nl == 0) break;
// Print line number.
program += (this.ram.read(i++) | (this.ram.read(i++) << 8)) + " ";
// Initial state.
state = stateToken;
while (true) {
// Get next byte/character.
b = this.ram.read(i++);
c = String.fromCharCode(b);
// Expected end-of-line situation.
if (i >= nl && b == 0) break;
// Process byte/character.
state();
// Abnormal end-of-line situation.
if (i >= nl) break;
}
program += "\n";
i = nl;
}
return program;
};
MC1000.prototype.setBasicProgram = function(program) {
var me = this; // 'this' refers to 'window' in the state functions. Use 'me' to keep reference to MC1000 object.
var basicst = this.ram.read(0x349) | (this.ram.read(0x34a) << 8);
var lines, line;
var k, linest;
k = basicst;
var i, j;
var b, c;
var state;
var stateToken = function() {
// Default strategy: Discards spaces and tokenizes reserved words.
switch (c) {
case " ":
// Discards spaces.
k--;
break;
default:
// Token?
var tokenFound = false;
for (var l = 0; l < MC1000.TOKENS.length; l++) {
var token = MC1000.TOKENS[l];
if (line.substr(j, token.length) == token) {
tokenFound = true;
me.ram.write(k, l ^ 0x80);
j += token.length - 1;
break;
}
}
if (tokenFound) {
// Some reserved words imply a change in strategy.
switch (token) {
case "DATA":
state = stateDATA;
break;
case "REM":
case "SAVE":
case "LOAD":
state = stateREM;
break;
}
} else {
// Other characters.
stateStringOrChar();
}
}
};
var stateDATA = function() {
// Handles start of DATA instruction: Discards heading unescaped spaces, if any.
switch (c) {
case " ":
// Discards heading unescaped spaces after "DATA" word.
k--;
break;
default:
// Escaped spaces or any other character marks start of actual data.
(state = stateDATA2)();
break;
}
};
var stateDATA2 = function() {
// Handles data item in DATA instruction. Unescaped spaces after the first non-space character are output unescaped.
stateStringOrChar();
switch (c) {
case ":":
// End of DATA instruction.
state = stateToken;
break;
}
};
var stateREM = function() {
// Handles start of REM/SAVE/LOAD instruction: Discards heading unescaped spaces, if any.
switch (c) {
case " ":
// Discards first space after REM/SAVE/LOAD.
k--;
break;
default:
// Output rest of line.
(state = stateChar)();
break;
}
};
var stateStringOrChar = function() {
// Identifies start of string.
stateChar();
switch (c) {
case '"':
// Start of string.
// Saves current strategy to resume when string ends.
stateBeforeString = state;
state = stateString;
break;
}
};
var stateString = function() {
// Handles string content until quote is found.
stateChar();
switch (c) {
case '"':
// End of string.
state = stateBeforeString;
break;
}
};
var stateChar = function() {
// Handles characters.
switch (c) {
case "`":
// Inverse video character notation: `X.
if (j + 1 < line.length) {
me.ram.write(k, line.charCodeAt(++j) ^ 0x80);
}
break;
case "~":
// Hexadecimal notation: ~XX.
if (j + 2 < line.length) {
var hex = line.substr(j + 1, 2);
if (hex.match(/^[0-9a-fA-F]{2}$/)) {
me.ram.write(k, parseInt(hex, 16));
j += 2;
}
}
break;
}
};
lines = program.toUpperCase().split("\n");
for (i = 0; i < lines.length; i++) {
line = lines[i];
var match = line.match(/^\s*(\d*)\s*(\D.*?)?\s*$/);
if (match[1] || match[2]) {
// Tokenized line consists of:
// 2 bytes that point to the next line.
// + 2 bytes containing line number.
// + line content.
// + 1 byte 0 at end of line.
// Save line start position to be updated later with pointer to next line.
linest = k;
k += 2;
// Line number.
var lineno = parseInt(match[1]) || 0;
this.ram.write(k++, lineno & 0xff);
this.ram.write(k++, (lineno >> 8) & 0xff);
// Line content.
line = match[2] || "";
j = 0;
state = stateToken;
while (j < line.length) {
c = line.charAt(j);
b = c.charCodeAt(0);
this.ram.write(k, b);
state();
j++;
k++;
}
// Byte 0 at end of line.
this.ram.write(k++, 0);
// Update pointer to next line.
this.ram.write(linest, k & 0xff);
this.ram.write(linest + 1, (k >> 8) & 0xff);
}
}
// Output end of program.
this.ram.write(k++, 0);
this.ram.write(k++, 0);
// Update system variable that points to end of program.
this.ram.write(0x3b7, k & 0xff);
this.ram.write(0x3b8, (k >> 8) & 0xff);
};
MC1000.prototype.getTextScreen = function() {
var screen = "";
for(var i = 0; i < 512; i++) {
if((i & 31) == 0) {
if(i != 0) {
screen += "\n";
}
}
screen += String.fromCharCode(this.vram.read(i));
}
return screen;
};
MC1000.ORIGINAL_ROM_ARRAY = [
0xC3, 0x63, 0xC0, 0xC3, 0xD6, 0xCE, 0xC3, 0x1B,
0xC3, 0xC3, 0x47, 0xC3, 0xC3, 0x97, 0xC8, 0xC3,
0x62, 0xC1, 0xC3, 0xB7, 0xC4, 0xC3, 0x88, 0xC1,
0xC3, 0xDE, 0xC0, 0xC3, 0x54, 0xC1, 0xC3, 0xC9,
0xDA, 0xC3, 0xCE, 0xC7, 0xC3, 0x5F, 0xC5, 0xC3,
0x7F, 0xC3, 0xC3, 0x6E, 0xC4, 0xC3, 0x83, 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x04, 0x04, 0x04, 0x05,
0x54, 0x00, 0x40, 0x01, 0x40, 0x00, 0x40, 0x00,
0x40, 0x01, 0x50, 0x05, 0x54, 0x00, 0x04, 0x05,
0x54, 0x04, 0x00, 0x05, 0x54, 0x05, 0x54, 0x00,
0x04, 0x01, 0x54, 0x00, 0x04, 0x05, 0x54, 0x00,
0x50, 0x01, 0x10, 0x04, 0x10, 0x05, 0x54, 0x00,
0x10, 0x05, 0x54, 0x04, 0x00, 0x05, 0x54, 0x00,
0x04, 0x05, 0x54, 0x05, 0x54, 0x04, 0x00, 0x05,
0x54, 0x04, 0x04, 0x05, 0x54, 0x05, 0x54, 0x00,
0x04, 0x00, 0x10, 0x00, 0x40, 0x01, 0x00, 0x05,
0x54, 0x04, 0x04, 0x05, 0x54, 0x04, 0x04, 0x05,
0x54, 0x05, 0x54, 0x04, 0x04, 0x05, 0x54, 0x00,
0x04, 0x05, 0x54, 0x04, 0x00, 0x15, 0x55, 0x55,
0x55, 0x15, 0x55, 0x04, 0x00, 0x00, 0x10, 0x55,
0x54, 0x55, 0x55, 0x55, 0x54, 0x00, 0x10, 0x00,
0x01, 0x40, 0x04, 0x10, 0x10, 0x04, 0x40, 0x01,
0x00, 0x04, 0x04, 0x01, 0x10, 0x00, 0x40, 0x01,
0x10, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x88, 0xD3,
0x80, 0x01, 0x55, 0x55, 0xCD, 0x61, 0xCB, 0x3A,
0x57, 0x01, 0x21, 0x0B, 0x0A, 0xE5, 0x11, 0x20,
0x80, 0xCD, 0x8D, 0xCB, 0xE1, 0xE5, 0x44, 0x11,
0x28, 0x80, 0xCD, 0xAD, 0xCB, 0xE1, 0x45, 0x11,
0x34, 0x80, 0xCD, 0xAD, 0xCB, 0x21, 0x08, 0x87,
0x3E, 0x00, 0x06, 0x16, 0x77, 0x23, 0x05, 0xC2,
0xC4, 0xCD, 0x11, 0x2C, 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0xC2, 0x7F, 0xCE, 0x3A,
0x23, 0x01, 0x77, 0x23, 0x3A, 0x24, 0x01, 0x77,
0x23, 0x22, 0x09, 0x01, 0xC9, 0xCD, 0xBA, 0xCE,
0x32, 0x28, 0x01, 0x32, 0x57, 0x03, 0x32, 0x60,
0x03, 0x32, 0x58, 0x03, 0x32, 0x52, 0x03, 0x32,
0x61, 0x03, 0x3D, 0x32, 0x06, 0x01, 0x32, 0x53,
0x03, 0xCD, 0xCE, 0xC7, 0xCD, 0xFC, 0xC0, 0xC3,
0xD6, 0xCE, 0xAF, 0x32, 0x72, 0x01, 0x32, 0x78,
0x01, 0x32, 0x7E, 0x01, 0x32, 0x01, 0x00, 0x3E,
0x0B, 0xD3, 0x20, 0xAF, 0xD3, 0x60, 0x3E, 0x0C,
0xD3, 0x20, 0xAF, 0xD3, 0x60, 0xC9, 0x01, 0x4E,
0x00, 0x11, 0x00, 0x03, 0x21, 0x92, 0xD7, 0xED,
0xB0, 0xEB, 0xF9, 0xCD, 0xC7, 0xD9, 0xCD, 0xC7,
0xE0, 0x32, 0x8D, 0x03, 0x32, 0xD4, 0x03, 0x21,
0x38, 0x04, 0xCD, 0xFD, 0xC2, 0x11, 0x00, 0xFF,
0x19, 0x11, 0x2C, 0x03, 0xCD, 0x0B, 0xDC, 0xDA,
0x3E, 0xD8, 0x11, 0x00, 0xFE, 0x22, 0x92, 0x03,
0x19, 0x22, 0x45, 0x03, 0xCD, 0xA2, 0xD9, 0x2A,
0x45, 0x03, 0x11, 0xEF, 0xFF, 0x19, 0x11, 0xD4,
0x03, 0xAF, 0xED, 0x52, 0xE5, 0x21, 0x42, 0xD5,
0xCD, 0x34, 0xE7, 0xE1, 0xCD, 0x8B, 0xEE, 0x21,
0x38, 0xD5, 0xCD, 0x34, 0xE7, 0x31, 0x51, 0x03,
0xCD, 0xC7, 0xD9, 0xC3, 0x8D, 0xD8, 0x2B, 0xCD,
0x96, 0xE9, 0x32, 0x42, 0x03, 0x32, 0x43, 0x03,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xE5, 0xD5, 0xC5, 0xF5, 0xD1, 0xE5,
0xD5, 0xDD, 0xE5, 0xFD, 0xE5, 0x08, 0xD9, 0xE5,
0xD5, 0xC5, 0xF5, 0xD1, 0xE5, 0xD5, 0x08, 0xD9,
0x21, 0xD8, 0x00, 0xEB, 0x21, 0x1A, 0x00, 0x39,
0x06, 0x0C, 0xEB, 0x2B, 0x72, 0x2B, 0x73, 0xD1,
0x05, 0x20, 0xF8, 0xC1, 0x0B, 0xF9, 0x21, 0xF1,
0x00, 0x7E, 0x91, 0x23, 0x20, 0x04, 0x7E, 0x98,
0x28, 0x0C, 0x23, 0x23, 0x7E, 0x91, 0x23, 0x20,
0x04, 0x7E, 0x98, 0x28, 0x01, 0x03, 0x21, 0xEC,
0x00, 0x73, 0x23, 0x72, 0x2E, 0xEF, 0x71, 0x23,
0x70, 0xC5, 0xCD, 0x0F, 0xF4, 0x23, 0xE1, 0xCD,
0x77, 0xF4, 0x21, 0xF1, 0x00, 0x16, 0x02, 0x4E,
0xAF, 0x77, 0x23, 0x46, 0x77, 0x23, 0x79, 0xB0,
0x28, 0x02, 0x7E, 0x02, 0x23, 0x15, 0x20, 0xEF,
0xC3, 0x2A, 0xF2, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
];
| mit |
kkrolczyk/Schowek | app/src/main/java/org/kkrolczyk/schowek/modules/Notes/NoteDBAdapter.java | 3207 | package org.kkrolczyk.schowek.modules.Notes;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import org.kkrolczyk.schowek._AbstractDBAdapter;
import org.kkrolczyk.schowek.Utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class NoteDBAdapter extends _AbstractDBAdapter {
private static NoteConfig config;
private static List<NoteConfig> Configs_preparer(){
config = new NoteConfig();
return new ArrayList<NoteConfig>(Arrays.asList(config));
}
public NoteDBAdapter(Context ctx){
super(ctx, Configs_preparer());
};
//private NoteDBAdapter(){this.context = null;}; //prevent empty constructor
////////////////////////////////////////////////////////////////////////////////////////////////
public long insertItem(String timestamp, String note)
{
ContentValues initialValues = new ContentValues();
initialValues.put("timestamp", timestamp);
initialValues.put("note", note);
return db.insert(config.TABLE_NAME, null, initialValues);
}
public boolean deleteItem(long rowId)
{
return db.delete(config.TABLE_NAME, "_id = " + rowId, null) > 0;
}
public Cursor getAllItems(int... sort_order) throws SQLException
{
String order_by = null;
if (sort_order.length>0){
// TODO: WUT? Note to past me: do elaborate on that, srsly.
String order_dir = Arrays.toString(Utils.SORT_ORDER.values()).replaceAll("^.|.$", "").split(", ")[sort_order[0]].split("_")[1];
//Log.e(TAG,"Sort order 7:" + config.DATABASE_KEYS[sort_order[0] % config.DATABASE_KEYS.length]);
order_by = config.DATABASE_KEYS[sort_order[0] / 2] + " " + order_dir;
}
return db.query(config.TABLE_NAME, config.DATABASE_KEYS,
null,
null,
null,
null,
order_by);
}
public Cursor getAllItemsLike(String similar) throws SQLException
{
return db.query(config.TABLE_NAME, config.DATABASE_KEYS,
"note like '%" + similar + "%'",
null,
null,
null,
null);
// "CASE WHEN note like '" + similar.toString() + "%' THEN 0 ELSE 1 END, LAST_NAME" ??
}
public Cursor getItem(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, config.TABLE_NAME, config.DATABASE_KEYS,
"_id =" + rowId,
null,
null,
null,
null,
null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateItem(long rowId, String timestamp, String note)
{
ContentValues args = new ContentValues();
args.put("timestamp", timestamp);
args.put("note", note);
return db.update(config.TABLE_NAME, args,
"_id" + "=" + rowId, null) > 0;
}
}
| mit |
MBuffenoir/b4c | player/migrations/0003_remove_playerprofile_registration_ip.py | 367 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('player', '0002_auto_20151124_2241'),
]
operations = [
migrations.RemoveField(
model_name='playerprofile',
name='registration_ip',
),
]
| mit |
Picturelife/streamio-ffmpeg | lib/ffmpeg/movie.rb | 4308 | require 'time'
module FFMPEG
class Movie
attr_reader :path, :duration, :time, :bitrate, :rotation, :creation_time
attr_reader :video_stream, :video_codec, :video_bitrate, :colorspace, :resolution, :sar, :dar
attr_reader :audio_stream, :audio_codec, :audio_bitrate, :audio_sample_rate
attr_reader :container
def initialize(path)
raise Errno::ENOENT, "the file '#{path}' does not exist" unless File.exists?(path)
@path = path
# ffmpeg will output to stderr
command = "#{FFMPEG.ffmpeg_binary} -i #{Shellwords.escape(path)}"
output = Open3.popen3(command) { |stdin, stdout, stderr| stderr.read }
fix_encoding(output)
output[/Input \#\d+\,\s*(\S+),\s*from/]
@container = $1
output[/Duration: (\d{2}):(\d{2}):(\d{2}\.\d{2})/]
@duration = ($1.to_i*60*60) + ($2.to_i*60) + $3.to_f
output[/start: (\d*\.\d*)/]
@time = $1 ? $1.to_f : 0.0
@creation_time = begin
output[/creation_time {1,}: {1,}(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/]
$1 ? Time.parse("#{$1}") : nil
rescue ArgumentError
nil
end
output[/bitrate: (\d*)/]
@bitrate = $1 ? $1.to_i : nil
output[/rotate\ {1,}:\ {1,}(\d*)/]
@rotation = $1 ? $1.to_i : nil
output[/^\ +Stream.+Video:\ (?!none)(.*)/]
@video_stream = $1
output[/^\ +Stream.+Audio:\ (.*)/]
@audio_stream = $1
if video_stream
commas_except_in_parenthesis = /(?:\([^()]*\)|[^,])+/ # regexp to handle "yuv420p(tv, bt709)" colorspace etc from http://goo.gl/6oi645
@video_codec, @colorspace, resolution, video_bitrate = video_stream.scan(commas_except_in_parenthesis).map(&:strip)
@video_bitrate = video_bitrate =~ %r(\A(\d+) kb/s\Z) ? $1.to_i : nil
@resolution = resolution.split(" ").first rescue nil # get rid of [PAR 1:1 DAR 16:9]
@sar = $1 if video_stream[/SAR (\d+:\d+)/]
@dar = $1 if video_stream[/DAR (\d+:\d+)/]
end
if audio_stream
@audio_codec, audio_sample_rate, @audio_channels, unused, audio_bitrate = audio_stream.split(/\s?,\s?/)
@audio_bitrate = audio_bitrate =~ %r(\A(\d+) kb/s\Z) ? $1.to_i : nil
@audio_sample_rate = audio_sample_rate[/\d*/].to_i
end
@invalid = true if @video_stream.to_s.empty? && @audio_stream.to_s.empty?
@invalid = true if output.include?("is not supported")
@invalid = true if output.include?("could not find codec parameters")
end
def valid?
not @invalid
end
def width
resolution.split("x")[0].to_i rescue nil
end
def height
resolution.split("x")[1].to_i rescue nil
end
def calculated_aspect_ratio
aspect_from_dar || aspect_from_dimensions
end
def calculated_pixel_aspect_ratio
aspect_from_sar || 1
end
def size
File.size(@path)
end
def audio_channels
return nil unless @audio_channels
return @audio_channels[/\d*/].to_i if @audio_channels["channels"]
return 1 if @audio_channels["mono"]
return 2 if @audio_channels["stereo"]
return 6 if @audio_channels["5.1"]
end
def frame_rate
return nil unless video_stream
video_stream[/(\d*\.?\d*)\s?fps/] ? $1.to_f : nil
end
def transcode(output_file, options = EncodingOptions.new, transcoder_options = {}, &block)
Transcoder.new(self, output_file, options, transcoder_options).run &block
end
def screenshot(output_file, options = EncodingOptions.new, transcoder_options = {}, &block)
Transcoder.new(self, output_file, options.merge(screenshot: true), transcoder_options).run &block
end
protected
def aspect_from_dar
return nil unless dar
w, h = dar.split(":")
aspect = w.to_f / h.to_f
aspect.zero? ? nil : aspect
end
def aspect_from_sar
return nil unless sar
w, h = sar.split(":")
aspect = w.to_f / h.to_f
aspect.zero? ? nil : aspect
end
def aspect_from_dimensions
aspect = width.to_f / height.to_f
aspect.nan? ? nil : aspect
end
def fix_encoding(output)
output[/test/] # Running a regexp on the string throws error if it's not UTF-8
rescue ArgumentError
output.force_encoding("ISO-8859-1")
end
end
end
| mit |
CelineTo/new-repo | src/com/sudoku/data/model/User.java | 3188 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sudoku.data.model;
import java.util.List;
public class User implements Ruleable {
private int id;
private String pseudo;
private String salt;
private String birthdate;
private String profilePicturePath;
private String createDate;
private String updateDate;
private String ipAdress;
private List<ContactCategory> contactCategories;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the pseudo
*/
public String getPseudo() {
return pseudo;
}
/**
* @param pseudo the pseudo to set
*/
public void setPseudo(String pseudo) {
this.pseudo = pseudo;
}
/**
* @return the salt
*/
public String getSalt() {
return salt;
}
/**
* @param salt the salt to set
*/
public void setSalt(String salt) {
this.salt = salt;
}
/**
* @return the birthdate
*/
public String getBirthdate() {
return birthdate;
}
/**
* @param birthdate the birthdate to set
*/
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
/**
* @return the profilePicturePath
*/
public String getProfilePicturePath() {
return profilePicturePath;
}
/**
* @param profilePicturePath the profilePicturePath to set
*/
public void setProfilePicturePath(String profilePicturePath) {
this.profilePicturePath = profilePicturePath;
}
/**
* @return the createDate
*/
public String getCreateDate() {
return createDate;
}
/**
* @param createDate the createDate to set
*/
public void setCreateDate(String createDate) {
this.createDate = createDate;
}
/**
* @return the updateDate
*/
public String getUpdateDate() {
return updateDate;
}
/**
* @param updateDate the updateDate to set
*/
public void setUpdateDate(String updateDate) {
this.updateDate = updateDate;
}
/**
* @return the ipAdress
*/
public String getIpAdress() {
return ipAdress;
}
/**
* @param ipAdress the ipAdress to set
*/
public void setIpAdress(String ipAdress) {
this.ipAdress = ipAdress;
}
/**
* @return the contactCategories
*/
public List<ContactCategory> getContactCategories() {
return contactCategories;
}
/**
* @param contactCategories the contactCategories to set
*/
public void setContactCategories(List<ContactCategory> contactCategories) {
this.contactCategories = contactCategories;
}
@Override
public Boolean hasUser(User user) {
return this.equals(user);
}
@Override
public Boolean isUser(){
return true;
}
}
| mit |
jxzsxsp/gallery-by-react | src/config/dist.js | 205 | 'use strict';
import baseConfig from './base';
let config = {
appEnv: 'dist' // feel free to remove the appEnv property here
};
export default Object.freeze(Object.assign({}, baseConfig, config));
| mit |
rothomp3/weatherDjinni | java/jni/dataPoint.cpp | 9279 | // AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from weather.idl
#include "dataPoint.hpp" // my header
#include "Marshal.hpp"
namespace djinni_generated {
DataPoint::DataPoint() = default;
DataPoint::~DataPoint() = default;
auto DataPoint::fromCpp(JNIEnv* jniEnv, const CppType& c) -> ::djinni::LocalRef<JniType> {
const auto& data = ::djinni::JniClass<DataPoint>::get();
auto r = ::djinni::LocalRef<JniType>{jniEnv->NewObject(data.clazz.get(), data.jconstructor,
::djinni::I64::fromCpp(jniEnv, c.time),
::djinni::String::fromCpp(jniEnv, c.summary).get(),
::djinni::String::fromCpp(jniEnv, c.icon).get(),
::djinni::Optional<std::experimental::optional, ::djinni::I64>::fromCpp(jniEnv, c.sunriseTime).get(),
::djinni::Optional<std::experimental::optional, ::djinni::I64>::fromCpp(jniEnv, c.sunsetTime).get(),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::fromCpp(jniEnv, c.moonPhase).get(),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::fromCpp(jniEnv, c.nearestStormDistance).get(),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::fromCpp(jniEnv, c.nearestStormBearing).get(),
::djinni::F64::fromCpp(jniEnv, c.precipIntensity),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::fromCpp(jniEnv, c.precipIntensityMax).get(),
::djinni::Optional<std::experimental::optional, ::djinni::I64>::fromCpp(jniEnv, c.precipIntensityMaxTime).get(),
::djinni::F64::fromCpp(jniEnv, c.precipProbability),
::djinni::String::fromCpp(jniEnv, c.precipType).get(),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::fromCpp(jniEnv, c.precipAccumulation).get(),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::fromCpp(jniEnv, c.temperature).get(),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::fromCpp(jniEnv, c.temperatureMin).get(),
::djinni::Optional<std::experimental::optional, ::djinni::I64>::fromCpp(jniEnv, c.temperatureMinTime).get(),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::fromCpp(jniEnv, c.temperatureMax).get(),
::djinni::Optional<std::experimental::optional, ::djinni::I64>::fromCpp(jniEnv, c.temperatureMaxTime).get(),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::fromCpp(jniEnv, c.apparentTemperature).get(),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::fromCpp(jniEnv, c.apparentTemperatureMax).get(),
::djinni::Optional<std::experimental::optional, ::djinni::I64>::fromCpp(jniEnv, c.apparentTemperatureMaxTime).get(),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::fromCpp(jniEnv, c.apparentTemperatureMin).get(),
::djinni::Optional<std::experimental::optional, ::djinni::I64>::fromCpp(jniEnv, c.apparentTemperatureMinTime).get(),
::djinni::F64::fromCpp(jniEnv, c.dewPoint),
::djinni::F64::fromCpp(jniEnv, c.windSpeed),
::djinni::F64::fromCpp(jniEnv, c.windBearing),
::djinni::F64::fromCpp(jniEnv, c.cloudCover),
::djinni::F64::fromCpp(jniEnv, c.humidity),
::djinni::F64::fromCpp(jniEnv, c.pressure),
::djinni::F64::fromCpp(jniEnv, c.visibility),
::djinni::F64::fromCpp(jniEnv, c.ozone))};
::djinni::jniExceptionCheck(jniEnv);
return r;
}
auto DataPoint::toCpp(JNIEnv* jniEnv, JniType j) -> CppType {
::djinni::JniLocalScope jscope(jniEnv, 33);
assert(j != nullptr);
const auto& data = ::djinni::JniClass<DataPoint>::get();
return {::djinni::I64::toCpp(jniEnv, jniEnv->GetLongField(j, data.field_time)),
::djinni::String::toCpp(jniEnv, (jstring)jniEnv->GetObjectField(j, data.field_summary)),
::djinni::String::toCpp(jniEnv, (jstring)jniEnv->GetObjectField(j, data.field_icon)),
::djinni::Optional<std::experimental::optional, ::djinni::I64>::toCpp(jniEnv, jniEnv->GetObjectField(j, data.field_sunriseTime)),
::djinni::Optional<std::experimental::optional, ::djinni::I64>::toCpp(jniEnv, jniEnv->GetObjectField(j, data.field_sunsetTime)),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::toCpp(jniEnv, jniEnv->GetObjectField(j, data.field_moonPhase)),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::toCpp(jniEnv, jniEnv->GetObjectField(j, data.field_nearestStormDistance)),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::toCpp(jniEnv, jniEnv->GetObjectField(j, data.field_nearestStormBearing)),
::djinni::F64::toCpp(jniEnv, jniEnv->GetDoubleField(j, data.field_precipIntensity)),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::toCpp(jniEnv, jniEnv->GetObjectField(j, data.field_precipIntensityMax)),
::djinni::Optional<std::experimental::optional, ::djinni::I64>::toCpp(jniEnv, jniEnv->GetObjectField(j, data.field_precipIntensityMaxTime)),
::djinni::F64::toCpp(jniEnv, jniEnv->GetDoubleField(j, data.field_precipProbability)),
::djinni::String::toCpp(jniEnv, (jstring)jniEnv->GetObjectField(j, data.field_precipType)),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::toCpp(jniEnv, jniEnv->GetObjectField(j, data.field_precipAccumulation)),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::toCpp(jniEnv, jniEnv->GetObjectField(j, data.field_temperature)),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::toCpp(jniEnv, jniEnv->GetObjectField(j, data.field_temperatureMin)),
::djinni::Optional<std::experimental::optional, ::djinni::I64>::toCpp(jniEnv, jniEnv->GetObjectField(j, data.field_temperatureMinTime)),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::toCpp(jniEnv, jniEnv->GetObjectField(j, data.field_temperatureMax)),
::djinni::Optional<std::experimental::optional, ::djinni::I64>::toCpp(jniEnv, jniEnv->GetObjectField(j, data.field_temperatureMaxTime)),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::toCpp(jniEnv, jniEnv->GetObjectField(j, data.field_apparentTemperature)),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::toCpp(jniEnv, jniEnv->GetObjectField(j, data.field_apparentTemperatureMax)),
::djinni::Optional<std::experimental::optional, ::djinni::I64>::toCpp(jniEnv, jniEnv->GetObjectField(j, data.field_apparentTemperatureMaxTime)),
::djinni::Optional<std::experimental::optional, ::djinni::F64>::toCpp(jniEnv, jniEnv->GetObjectField(j, data.field_apparentTemperatureMin)),
::djinni::Optional<std::experimental::optional, ::djinni::I64>::toCpp(jniEnv, jniEnv->GetObjectField(j, data.field_apparentTemperatureMinTime)),
::djinni::F64::toCpp(jniEnv, jniEnv->GetDoubleField(j, data.field_dewPoint)),
::djinni::F64::toCpp(jniEnv, jniEnv->GetDoubleField(j, data.field_windSpeed)),
::djinni::F64::toCpp(jniEnv, jniEnv->GetDoubleField(j, data.field_windBearing)),
::djinni::F64::toCpp(jniEnv, jniEnv->GetDoubleField(j, data.field_cloudCover)),
::djinni::F64::toCpp(jniEnv, jniEnv->GetDoubleField(j, data.field_humidity)),
::djinni::F64::toCpp(jniEnv, jniEnv->GetDoubleField(j, data.field_pressure)),
::djinni::F64::toCpp(jniEnv, jniEnv->GetDoubleField(j, data.field_visibility)),
::djinni::F64::toCpp(jniEnv, jniEnv->GetDoubleField(j, data.field_ozone))};
}
} // namespace djinni_generated
| mit |
WicopeeDot/addons | scoreboard/lua/scoreboard/scoreboard.lua | 12435 |
local tag = "ReDreamScoreboard"
if IsValid(Scoreboard) then Scoreboard:Remove() end
scoreboard = {}
local Debug = false
local hostnameFont = {
font = "Roboto Bold",
size = ScreenScale(8),
antialias = true,
}
surface.CreateFont(tag .. "HostnameSmaller", hostnameFont)
hostnameFont.size = ScreenScale(12)
surface.CreateFont(tag .. "HostnameSmall", hostnameFont)
hostnameFont.size = ScreenScale(16)
surface.CreateFont(tag .. "HostnameBig", hostnameFont)
surface.CreateFont(tag .. "Option", {
font = "Roboto Condensed",
size = 16,
antialias = true,
})
function scoreboard:GetContentSize()
local w, h = 0, 0
local padding = { self:GetDockPadding() }
w = w + padding[1] + padding[3]
h = h + padding[2] + padding[4]
for _, pnl in next, self:GetChildren() do
if pnl:IsVisible() then
w = w + pnl:GetWide()
h = h + pnl:GetTall()
local margin = { pnl:GetDockMargin() }
w = w + margin[1] + margin[3]
h = h + margin[2] + margin[4]
end
end
return w, h
end
include("scoreboard/team_panel.lua")
include("scoreboard/player_panel.lua")
local wantsToClose = false
local activeFrame
local function OpenColorSelect()
if IsValid(activeFrame) then return end
local frame = vgui.Create("EditablePanel")
frame:SetSize(250, 175)
frame:SetPos(ScrW() * 0.5 - frame:GetWide() * 0.5, ScrH() * 0.75 - frame:GetTall() * 0.5)
frame:DockPadding(6, 6, 6, 6)
function frame:Paint(w, h)
local col = Color(77, 81, 96, 192)
surface.SetDrawColor(col)
surface.DrawRect(0, 0, w, h)
surface.SetDrawColor(Color(0, 0, 0, 80))
surface.DrawOutlinedRect(0, 0, w, h)
end
local top = frame:Add("EditablePanel")
top:Dock(TOP)
top:SetTall(20)
top:DockMargin(0, 0, 0, 4)
function top:Paint(w, h)
surface.SetFont(tag .. "Option")
local txt = "Header Color Selection"
local txtW, txtH = surface.GetTextSize(txt)
surface.SetTextPos(2, h * 0.5 - txtH * 0.5)
surface.SetTextColor(Color(255, 255, 255))
surface.DrawText(txt)
end
local close = top:Add("DButton")
close:Dock(RIGHT)
close:SetWide(20)
close:DockMargin(4, 0, 0, 0)
function close:Paint(w, h)
surface.SetDrawColor(Color(255, 96, 96, 192))
surface.DrawRect(0, 0, w, h)
surface.SetFont("marlett")
local txt = "r"
local txtW, txtH = surface.GetTextSize(txt)
surface.SetTextPos(w * 0.5 - txtW * 0.5, h * 0.5 - txtH * 0.5)
surface.SetTextColor(Color(0, 0, 0))
surface.DrawText(txt)
surface.SetDrawColor(Color(255, 255, 255, 20))
surface.DrawOutlinedRect(0, 0, w, h)
return true
end
function close:DoClick()
activeFrame:Remove()
if wantsToClose then
Scoreboard:Hide()
end
end
local reset = top:Add("DButton")
reset:Dock(RIGHT)
reset:SetWide(38)
function reset:Paint(w, h)
surface.SetDrawColor(Color(255, 96, 96, 192))
surface.DrawRect(0, 0, w, h)
surface.SetFont(tag .. "Option")
local txt = "Reset"
local txtW, txtH = surface.GetTextSize(txt)
surface.SetTextPos(w * 0.5 - txtW * 0.5, h * 0.5 - txtH * 0.5)
surface.SetTextColor(Color(0, 0, 0))
surface.DrawText(txt)
surface.SetDrawColor(Color(255, 255, 255, 20))
surface.DrawOutlinedRect(0, 0, w, h)
return true
end
function reset:DoClick()
Scoreboard.Config.Color = nil
Scoreboard:SaveConfig()
end
local mixer = frame:Add("DColorMixer")
mixer:Dock(FILL)
mixer:SetAlphaBar(false)
mixer:SetPalette(false)
local last = RealTime()
local changed = true
function mixer:ValueChanged(col)
last = RealTime() + 0.1
changed = false
end
function frame:Think()
if last < RealTime() and not changed then
Scoreboard.Config.Color = mixer:GetColor()
Scoreboard:SaveConfig()
changed = true
end
end
frame:MakePopup()
activeFrame = frame
end
local Options = {
Center = {
icon = Material("icon16/arrow_in.png"),
callback = function(self, option)
self.Config.Center = not self.Config.Center
self:SaveConfig()
self:InvalidateLayout()
end,
name = "Toggle Center",
type = "boolean",
w = 112
},
Color = {
icon = Material("icon16/palette.png"),
callback = function(self, option)
OpenColorSelect()
end,
name = "Change Header Color",
type = "table",
w = 144
}
}
local totype = {
boolean = tobool,
number = tonumber,
}
function scoreboard:LoadConfig()
self.Config = {}
local config = util.JSONToTable(file.Read(tag:lower() .. "_config.txt", "DATA") or "{}")
if not config then return end
for k, v in next, config do
if Options[k] then
local convert = totype[Options[k].type]
self.Config[k] = (Options[k].type and convert) and convert(v) or v
end
end
end
function scoreboard:SaveConfig()
file.Write(tag:lower() .. "_config.txt", util.TableToJSON(self.Config))
end
local maxH = ScrH() * 0.9
function scoreboard:Init()
local scoreboard = self
self:SetSize(ScrW() * 0.375, maxH)
self.Header = vgui.Create("DButton", self)
self.Header:Dock(TOP)
self.Header:SetTall(64)
self.Header:InvalidateLayout(true)
self.Header.lastTxt = ""
function self.Header:DoClick()
self.Expanded = not self.Expanded
self:SizeTo(self:GetWide(), self.Expanded and 112 or 64, 0.3)
end
function self.Header:PerformLayout()
self.Options:SetSize(self:GetWide(), 112 - 64)
end
function self.Header:Paint(w, h)
local col = scoreboard.Config.Color or Color(77, 81, 96)
col.a = 230
surface.SetDrawColor(col)
surface.DrawRect(0, 0, w, h)
local txt = GetHostName()
if txt ~= self.lastTxt then
self.lastTxt = txt
end
surface.SetFont(tag .. "HostnameBig")
local _txtW = surface.GetTextSize(txt)
if _txtW >= w - 32 then
surface.SetFont(tag .. "HostnameSmall")
local _txtW = surface.GetTextSize(txt)
if _txtW >= w - 32 then
surface.SetFont(tag .. "HostnameSmaller")
end
end
local txtW, txtH = surface.GetTextSize(txt)
local space = 3
surface.SetTextPos(w * 0.5 - txtW * 0.5 + space, 32 - txtH * 0.5 + space)
surface.SetTextColor(Color(0, 0, 0, 164))
surface.DrawText(txt)
surface.SetTextPos(w * 0.5 - txtW * 0.5, 32 - txtH * 0.5)
surface.SetTextColor(Color(255, 255, 255, 255))
surface.DrawText(txt)
surface.SetDrawColor(Color(255, 255, 255, 40))
surface.DrawOutlinedRect(0, 0, w, h)
surface.SetDrawColor(Color(255, 255, 255, 15))
surface.DrawOutlinedRect(1, 1, w - 2, h - 2)
if self:IsHovered() then
surface.SetDrawColor(Color(255, 255, 255, self.Depressed and 5 or 10))
surface.DrawRect(0, 0, w, h)
end
return true
end
self.Header.Options = vgui.Create("EditablePanel", self.Header)
self.Header.Options:SetPos(0, 64)
self.Header.Options:DockPadding(8, 8, 8, 8)
function self.Header.Options:Paint(w, h)
surface.SetDrawColor(Color(0, 0, 0, 90))
surface.DrawRect(0, 0, w, h)
end
for name, info in next, Options do
self.Header.Options[name] = vgui.Create("DButton", self.Header.Options)
local option = self.Header.Options[name]
option:Dock(LEFT)
option:DockMargin(0, 0, 4, 0)
option:SetWide(info.w or 64)
function option:Paint(w, h)
draw.RoundedBox(4, 0, 0, w, h, Color(0, 0, 0, 96))
surface.SetMaterial(info.icon)
surface.SetDrawColor(Color(255, 255, 255))
surface.DrawTexturedRect(8, h * 0.5 - 8, 16, 16)
local txt = info.name
surface.SetFont(tag .. "Option")
local txtW, txtH = surface.GetTextSize(txt)
surface.SetTextPos((w + 8 + 16) * 0.5 - txtW * 0.5 + 2, h * 0.5 - txtH * 0.5 + 2)
surface.SetTextColor(Color(0, 0, 0, 164))
surface.DrawText(txt)
surface.SetTextPos((w + 8 + 16) * 0.5 - txtW * 0.5, h * 0.5 - txtH * 0.5)
surface.SetTextColor(Color(255, 255, 255, 192))
surface.DrawText(txt)
if self:IsHovered() then
draw.RoundedBox(6, 0, 0, w, h, Color(255, 255, 255, self.Depressed and 2 or 4))
end
return true
end
function option:DoClick()
info.callback(scoreboard, self)
end
end
self.Teams = vgui.Create("PanelList", self)
self.Teams:Dock(TOP)
self.Teams:EnableVerticalScrollbar(true)
self.Teams:DockMargin(4, 0, 4, 0)
self.Teams:SetSpacing(0)
self.Teams:SetPadding(0)
self.Teams.GetContentSize = scoreboard.GetContentSize
self.Teams.pnlCanvas.GetContentSize = scoreboard.GetContentSize
self.Teams._PerformLayout = self.Teams.PerformLayout
function self.Teams:PerformLayout()
self:_PerformLayout()
local h = ({self.pnlCanvas:GetContentSize()})[2]
self.pnlCanvas:SetTall(h)
h = h > maxH and maxH - scoreboard.Header:GetTall() or h
self:SetTall(h)
end
function self.Teams:OnMouseWheeled(d)
if IsValid(self.VBar) and self.VBar.Enabled then
return self.VBar:AddVelocity(d)
end
end
function self.Teams:Paint()
return true
end
function self.Teams:GetTeams()
local teams = {}
for k, v in next, self:GetTable() do
if isnumber(k) then
teams[k] = v
end
end
return teams
end
if Debug then
self.Teams.isTeam = true
function self.Teams:PaintOver(w, h)
surface.SetDrawColor(Color(0, 255, 0))
surface.DrawOutlinedRect(0, 0, w, h)
end
end
self:MakePopup()
self:SetMouseInputEnabled(false)
self:SetKeyboardInputEnabled(false)
self:SetAlpha(255)
self:LoadConfig()
self:InvalidateLayout()
end
player.GetCount = player.GetCount or function()
return #player.GetAll()
end
function scoreboard:HandlePlayers()
local done = {}
for _, ply in next, player.GetAll() do
local id = ply:Team()
local pnl = self.Teams[id]
if (not self.Last or self.Last ~= player.GetCount()) and not done[id] then
self:RefreshPlayers(id)
done[id] = true
end
end
self.Last = player.GetCount()
local i = 0
for id, pnl in next, self.Teams:GetTeams() do
if IsValid(pnl) and pnl:IsVisible() then -- #team.GetPlayers(id) > 0 then
if pnl.Last ~= #team.GetPlayers(id) then
self:RefreshPlayers(id)
end
i = i + 1
end
end
for id, pnl in next, self.Teams:GetTeams() do
if pnl and pnl:IsVisible() then
pnl:SetLone(i < 2)
end
end
end
function scoreboard:RefreshPlayers(id)
if id then
local pnl = self.Teams[id]
if not pnl then
pnl = vgui.Create(tag .. "Team")
self.Teams:AddItem(pnl)
pnl.Team = id
pnl:SetTeam(id)
pnl:SetZPos(-id)
pnl:Dock(TOP)
pnl:DockMargin(0, 2, 0, 0)
self.Teams[id] = pnl
end
for _, ply in next, team.GetPlayers(id) do
local _pnl = pnl[ply:UserID()]
if not _pnl then
_pnl = vgui.Create(tag .. "Player", pnl)
_pnl.UserID = ply:UserID()
_pnl:SetPlayer(ply)
pnl[ply:UserID()] = _pnl
end
_pnl:Dock(TOP)
_pnl:DockMargin(8, 0, 8, 0)
_pnl:SetTall(36)
end
for _, _pnl in next, pnl:GetChildren() do
if not IsValid(_pnl.Player) or _pnl.Player:Team() ~= id then
pnl[_pnl.UserID] = nil
_pnl:SetVisible(false)
_pnl:SetParent() -- ugly hack to call PerformLayout
_pnl:Remove()
end
end
pnl.Last = #pnl:GetChildren()
if #pnl:GetChildren() < 1 then
pnl:SetVisible(false)
else
pnl:SetVisible(true)
end
end
end
function scoreboard:Think()
self:HandlePlayers()
end
function scoreboard:Show()
wantsToClose = false
self:SetVisible(true)
end
function scoreboard:Hide()
wantsToClose = true
if IsValid(activeFrame) then return end
CloseDermaMenus()
self:SetVisible(false)
if self.Popup then
self:SetMouseInputEnabled(false)
self.Popup = false
end
end
function scoreboard:PerformLayout()
self:SizeToContentsY()
if self:GetTall() > maxH then
self:SetTall(maxH)
end
if self.Config.Center then
self:Center()
else
local y = ScrH() * 0.2 - (ScrH() * 0.1 * (self:GetTall() / maxH))
self:SetPos(ScrW() * 0.5 - self:GetWide() * 0.5, y)
end
end
if Debug then
function scoreboard:Paint(w, h)
surface.SetDrawColor(Color(255, 0, 0))
surface.DrawOutlinedRect(0, 0, w, h)
end
end
vgui.Register(tag, scoreboard, "EditablePanel")
local redream_scoreboard_enable = CreateClientConVar("redream_scoreboard_enable", "1")
hook.Add("PlayerBindPress", tag, function(ply, bind, pressed)
if not redream_scoreboard_enable:GetBool() then return end
if not IsValid(Scoreboard) then return end
if bind:lower():match("+attack2") and pressed and Scoreboard:IsVisible() and not Scoreboard.Popup then
Scoreboard:SetMouseInputEnabled(true)
Scoreboard.Popup = true
return true
end
end)
hook.Add("ScoreboardShow", tag, function()
if not redream_scoreboard_enable:GetBool() then return end
if not IsValid(Scoreboard) then
Scoreboard = vgui.Create(tag)
end
Scoreboard:Show()
return true
end)
hook.Add("ScoreboardHide", tag, function()
if not redream_scoreboard_enable:GetBool() then return end
if not IsValid(Scoreboard) then
Scoreboard = vgui.Create(tag)
end
Scoreboard:Hide()
return true
end)
| mit |
feliposz/learning-stuff | java/tutorial/LearnJava/src/my/learnjava/DataOnly.java | 733 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package my.learnjava;
/**
*
* @author Felipo
*/
public class DataOnly {
int i;
float f;
boolean b;
int storage(String s) {
return s.length() * 2;
}
public static void main(String[] args) {
DataOnly d = new DataOnly();
d.i = 47;
d.f = 1.1f;
d.b = false;
System.out.println("Data stored in the object:");
System.out.format("d.i = %d%nd.f = %f%nd.b = %b%n", d.i, d.f, d.b);
String s = "Felipo Soranz";
System.out.println("Content of string s is: " + s);
System.out.println("Return of storage(s) is: " + d.storage(s));
}
}
| mit |
fluentribbon/Fluent.Ribbon | Fluent.Ribbon/Automation/Peers/RibbonControlDataAutomationPeer.cs | 2243 | namespace Fluent.Automation.Peers
{
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
/// <summary>
/// Automation peer for ribbon control items.
/// </summary>
public class RibbonControlDataAutomationPeer : ItemAutomationPeer
{
/// <summary>
/// Creates a new instance.
/// </summary>
public RibbonControlDataAutomationPeer(object item, ItemsControlAutomationPeer itemsControlPeer)
: base(item, itemsControlPeer)
{
}
/// <inheritdoc />
protected override AutomationControlType GetAutomationControlTypeCore()
{
return AutomationControlType.ListItem;
}
/// <inheritdoc />
protected override string GetClassNameCore()
{
var wrapperPeer = this.GetWrapperPeer();
return wrapperPeer?.GetClassName() ?? string.Empty;
}
/// <inheritdoc />
public override object GetPattern(PatternInterface patternInterface)
{
// Doesnt implement any patterns of its own, so just forward to the wrapper peer.
var wrapperPeer = this.GetWrapperPeer();
return wrapperPeer?.GetPattern(patternInterface) ?? base.GetPattern(patternInterface);
}
private UIElement? GetWrapper()
{
var itemsControlAutomationPeer = this.ItemsControlAutomationPeer;
var owner = (ItemsControl?)itemsControlAutomationPeer?.Owner;
return owner?.ItemContainerGenerator.ContainerFromItem(this.Item) as UIElement;
}
private AutomationPeer? GetWrapperPeer()
{
var wrapper = this.GetWrapper();
if (wrapper is null)
{
return null;
}
var wrapperPeer = UIElementAutomationPeer.CreatePeerForElement(wrapper);
if (wrapperPeer is not null)
{
return wrapperPeer;
}
if (wrapper is FrameworkElement element)
{
return new FrameworkElementAutomationPeer(element);
}
return new UIElementAutomationPeer(wrapper);
}
}
} | mit |
Bladrak/ecommerce | src/Sonata/ProductBundle/Controller/ProductController.php | 5288 | <?php
/*
* This file is part of the Sonata package.
*
* (c) Thomas Rabaix <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\ProductBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Form\FormView;
use Symfony\Component\HttpFoundation\Response;
use Sonata\Component\Basket\BasketElementInterface;
use Sonata\Component\Basket\BasketInterface;
class ProductController extends Controller
{
/**
* @param $productId
* @param $slug
*
* @throws NotFoundHttpException
*
* @return Response
*/
public function viewAction($productId, $slug)
{
$product = is_object($productId) ? $productId : $this->get('sonata.product.set.manager')->findEnabledFromIdAndSlug($productId, $slug);
if (!$product) {
throw new NotFoundHttpException(sprintf('Unable to find the product with id=%d', $productId));
}
if ($product->hasVariations() && !$product->hasEnabledVariations()) {
throw new NotFoundHttpException('Product has no activated variation');
}
$provider = $this->get('sonata.product.pool')->getProvider($product);
$action = sprintf('%s:view', $provider->getBaseControllerName());
$response = $this->forward($action, array(
'product' => $product
));
if ($this->get('kernel')->isDebug()) {
$response->setContent(sprintf("\n<!-- [Sonata] Product code: %s, id: %s, action: %s -->\n%s\n<!-- [Sonata] end product -->\n",
$this->get('sonata.product.pool')->getProductCode($product),
$product->getId(),
$action,
$response->getContent()
));
}
return $response;
}
/**
* @param \Symfony\Component\Form\FormView $formView
* @param \Sonata\Component\Basket\BasketElementInterface $basketElement
* @param \Sonata\Component\Basket\BasketInterface $basket
*
* @return Response
*/
public function renderFormBasketElementAction(FormView $formView, BasketElementInterface $basketElement, BasketInterface $basket)
{
$action = sprintf('%s:renderFormBasketElement', $basketElement->getProductProvider()->getBaseControllerName()) ;
$response = $this->forward($action, array(
'formView' => $formView,
'basketElement' => $basketElement,
'basket' => $basket
));
if ($this->get('kernel')->isDebug()) {
$response->setContent(sprintf("\n<!-- [Sonata] Product code: %s, id: %s, action: %s -->\n%s\n<!-- [Sonata] end product -->\n",
$basketElement->getProductCode(),
$basketElement->getProductId(),
$action,
$response->getContent()
));
}
return $response;
}
/**
* @param \Sonata\Component\Basket\BasketElementInterface $basketElement
* @param \Sonata\Component\Basket\BasketInterface $basket
*
* @return Response
*/
public function renderFinalReviewBasketElementAction(BasketElementInterface $basketElement, BasketInterface $basket)
{
$action = sprintf('%s:renderFinalReviewBasketElement', $basketElement->getProductProvider()->getBaseControllerName()) ;
$response = $this->forward($action, array(
'basketElement' => $basketElement,
'basket' => $basket
));
if ($this->get('kernel')->isDebug()) {
$response->setContent(sprintf("\n<!-- [Sonata] Product code: %s, id: %s, action: %s -->\n%s\n<!-- [Sonata] end product -->\n",
$basketElement->getProductCode(),
$basketElement->getProductId(),
$action,
$response->getContent()
));
}
return $response;
}
/**
* @param $productId
* @param $slug
*
* @throws NotFoundHttpException
*
* @return Response
*/
public function viewVariationsAction($productId, $slug)
{
$product = is_object($productId) ? $productId : $this->get('sonata.product.set.manager')->findEnabledFromIdAndSlug($productId, $slug);
if (!$product) {
throw new NotFoundHttpException(sprintf('Unable to find the product with id=%d', $productId));
}
$provider = $this->get('sonata.product.pool')->getProvider($product);
$action = sprintf('%s:viewVariations', $provider->getBaseControllerName());
$response = $this->forward($action, array(
'product' => $product
));
if ($this->get('kernel')->isDebug()) {
$response->setContent(sprintf("\n<!-- [Sonata] Product code: %s, id: %s, action: %s -->\n%s\n<!-- [Sonata] end product -->\n",
$this->get('sonata.product.pool')->getProductCode($product),
$product->getId(),
$action,
$response->getContent()
));
}
return $response;
}
}
| mit |
oydang/CS4701-pokemon-AI | Tracer-VisualboyAdvance1.7.1/Tracer-VisualboyAdvance1.7.1/source/src/expr.cpp | 27160 |
* A Bison parser, made from expr.y
by GNU Bison version 1.28 */
#define YYBISON 1 /* Identify Bison output. */
#define TOKEN_IDENTIFIER 257
#define TOKEN_DOT 258
#define TOKEN_STAR 259
#define TOKEN_ARROW 260
#define TOKEN_ADDR 261
#define TOKEN_SIZEOF 262
#define TOKEN_NUMBER 263
#line 1 "expr.y"
namespace std {
#include <stdio.h>
#include <memory.h>
#include <stdlib.h>
#include <string.h>
}
using namespace std;
#include "System.h"
#include "elf.h"
#include "exprNode.h"
extern int yyerror(char *);
extern int yylex();
extern char *yytext;
//#define YYERROR_VERBOSE 1
//#define YYDEBUG 1
Node *result = NULL;
#ifndef YYSTYPE
#define YYSTYPE int
#endif
#include <stdio.h>
#ifndef __cplusplus
#ifndef __STDC__
#define const
#endif
#endif
#define YYFINAL 26
#define YYFLAG -32768
#define YYNTBASE 14
#define YYTRANSLATE(x) ((unsigned)(x) <= 263 ? yytranslate[x] : 19)
static const char yytranslate[] = { 0,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 11,
12, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
10, 2, 13, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 1, 3, 4, 5, 6,
7, 8, 9
};
#if YYDEBUG != 0
static const short yyprhs[] = { 0,
0, 2, 4, 8, 12, 16, 21, 23, 26, 29,
34, 36
};
static const short yyrhs[] = { 15,
0, 16, 0, 11, 15, 12, 0, 15, 4, 18,
0, 15, 6, 18, 0, 15, 10, 17, 13, 0,
18, 0, 5, 15, 0, 7, 15, 0, 8, 11,
15, 12, 0, 9, 0, 3, 0
};
#endif
#if YYDEBUG != 0
static const short yyrline[] = { 0,
32, 35, 36, 37, 38, 39, 42, 43, 44, 45,
49, 53
};
#endif
#if YYDEBUG != 0 || defined (YYERROR_VERBOSE)
static const char * const yytname[] = { "$","error","$undefined.","TOKEN_IDENTIFIER",
"TOKEN_DOT","TOKEN_STAR","TOKEN_ARROW","TOKEN_ADDR","TOKEN_SIZEOF","TOKEN_NUMBER",
"'['","'('","')'","']'","final","expression","simple_expression","number","ident", NULL
};
#endif
static const short yyr1[] = { 0,
14, 15, 15, 15, 15, 15, 16, 16, 16, 16,
17, 18
};
static const short yyr2[] = { 0,
1, 1, 3, 3, 3, 4, 1, 2, 2, 4,
1, 1
};
static const short yydefact[] = { 0,
12, 0, 0, 0, 0, 1, 2, 7, 8, 9,
0, 0, 0, 0, 0, 0, 3, 4, 5, 11,
0, 10, 6, 0, 0, 0
};
static const short yydefgoto[] = { 24,
6, 7, 21, 8
};
static const short yypact[] = { -1,
-32768, -1, -1, -6, -1, 17,-32768,-32768, 17, 17,
-1, 7, 5, 5, 13, 8,-32768,-32768,-32768,-32768,
11,-32768,-32768, 25, 26,-32768
};
static const short yypgoto[] = {-32768,
-2,-32768,-32768, 2
};
#define YYLAST 27
static const short yytable[] = { 9,
10, 1, 12, 2, 11, 3, 4, 1, 16, 5,
13, 13, 14, 14, 18, 19, 15, 15, 17, 22,
13, 20, 14, 23, 25, 26, 15
};
static const short yycheck[] = { 2,
3, 3, 5, 5, 11, 7, 8, 3, 11, 11,
4, 4, 6, 6, 13, 14, 10, 10, 12, 12,
4, 9, 6, 13, 0, 0, 10
};
/* -*-C-*- Note some compilers choke on comments on `#line' lines. */
#line 3 "/usr/lib/bison.simple"
/* This file comes from bison-1.28. */
/* Skeleton output parser for bison,
Copyright (C) 1984, 1989, 1990 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA. */
/* As a special exception, when this file is copied by Bison into a
Bison output file, you may use that output file without restriction.
This special exception was added by the Free Software Foundation
in version 1.24 of Bison. */
/* This is the parser code that is written into each bison parser
when the %semantic_parser declaration is not specified in the grammar.
It was written by Richard Stallman by simplifying the hairy parser
used when %semantic_parser is specified. */
#ifndef YYSTACK_USE_ALLOCA
#ifdef alloca
#define YYSTACK_USE_ALLOCA
#else /* alloca not defined */
#ifdef __GNUC__
#define YYSTACK_USE_ALLOCA
#define alloca __builtin_alloca
#else /* not GNU C. */
#if (!defined (__STDC__) && defined (sparc)) || defined (__sparc__) || defined (__sparc) || defined (__sgi) || (defined (__sun) && defined (__i386))
#define YYSTACK_USE_ALLOCA
#include <alloca.h>
#else /* not sparc */
/* We think this test detects Watcom and Microsoft C. */
/* This used to test MSDOS, but that is a bad idea
since that symbol is in the user namespace. */
#if (defined (_MSDOS) || defined (_MSDOS_)) && !defined (__TURBOC__)
#if 0 /* No need for malloc.h, which pollutes the namespace;
instead, just don't use alloca. */
#include <malloc.h>
#endif
#else /* not MSDOS, or __TURBOC__ */
#if defined(_AIX)
/* I don't know what this was needed for, but it pollutes the namespace.
So I turned it off. rms, 2 May 1997. */
/* #include <malloc.h> */
#pragma alloca
#define YYSTACK_USE_ALLOCA
#else /* not MSDOS, or __TURBOC__, or _AIX */
#if 0
#ifdef __hpux /* [email protected] says this works for HPUX 9.05 and up,
and on HPUX 10. Eventually we can turn this on. */
#define YYSTACK_USE_ALLOCA
#define alloca __builtin_alloca
#endif /* __hpux */
#endif
#endif /* not _AIX */
#endif /* not MSDOS, or __TURBOC__ */
#endif /* not sparc */
#endif /* not GNU C */
#endif /* alloca not defined */
#endif /* YYSTACK_USE_ALLOCA not defined */
#ifdef YYSTACK_USE_ALLOCA
#define YYSTACK_ALLOC alloca
#else
#define YYSTACK_ALLOC malloc
#endif
/* Note: there must be only one dollar sign in this file.
It is replaced by the list of actions, each action
as one case of the switch. */
#define yyerrok (yyerrstatus = 0)
#define yyclearin (yychar = YYEMPTY)
#define YYEMPTY -2
#define YYEOF 0
#define YYACCEPT goto yyacceptlab
#define YYABORT goto yyabortlab
#define YYERROR goto yyerrlab1
/* Like YYERROR except do call yyerror.
This remains here temporarily to ease the
transition to the new meaning of YYERROR, for GCC.
Once GCC version 2 has supplanted version 1, this can go. */
#define YYFAIL goto yyerrlab
#define YYRECOVERING() (!!yyerrstatus)
#define YYBACKUP(token, value) \
do \
if (yychar == YYEMPTY && yylen == 1) \
{ yychar = (token), yylval = (value); \
yychar1 = YYTRANSLATE (yychar); \
YYPOPSTACK; \
goto yybackup; \
} \
else \
{ yyerror ("syntax error: cannot back up"); YYERROR; } \
while (0)
#define YYTERROR 1
#define YYERRCODE 256
#ifndef YYPURE
#define YYLEX yylex()
#endif
#ifdef YYPURE
#ifdef YYLSP_NEEDED
#ifdef YYLEX_PARAM
#define YYLEX yylex(&yylval, &yylloc, YYLEX_PARAM)
#else
#define YYLEX yylex(&yylval, &yylloc)
#endif
#else /* not YYLSP_NEEDED */
#ifdef YYLEX_PARAM
#define YYLEX yylex(&yylval, YYLEX_PARAM)
#else
#define YYLEX yylex(&yylval)
#endif
#endif /* not YYLSP_NEEDED */
#endif
/* If nonreentrant, generate the variables here */
#ifndef YYPURE
int yychar; /* the lookahead symbol */
YYSTYPE yylval; /* the semantic value of the */
/* lookahead symbol */
#ifdef YYLSP_NEEDED
YYLTYPE yylloc; /* location data for the lookahead */
/* symbol */
#endif
int yynerrs; /* number of parse errors so far */
#endif /* not YYPURE */
#if YYDEBUG != 0
int yydebug; /* nonzero means print parse trace */
/* Since this is uninitialized, it does not stop multiple parsers
from coexisting. */
#endif
/* YYINITDEPTH indicates the initial size of the parser's stacks */
#ifndef YYINITDEPTH
#define YYINITDEPTH 200
#endif
/* YYMAXDEPTH is the maximum size the stacks can grow to
(effective only if the built-in stack extension method is used). */
#if YYMAXDEPTH == 0
#undef YYMAXDEPTH
#endif
#ifndef YYMAXDEPTH
#define YYMAXDEPTH 10000
#endif
/* Define __yy_memcpy. Note that the size argument
should be passed with type unsigned int, because that is what the non-GCC
definitions require. With GCC, __builtin_memcpy takes an arg
of type size_t, but it can handle unsigned int. */
#if __GNUC__ > 1 /* GNU C and GNU C++ define this. */
#define __yy_memcpy(TO,FROM,COUNT) __builtin_memcpy(TO,FROM,COUNT)
#else /* not GNU C or C++ */
#ifndef __cplusplus
/* This is the most reliable way to avoid incompatibilities
in available built-in functions on various systems. */
static void
__yy_memcpy (to, from, count)
char *to;
char *from;
unsigned int count;
{
register char *f = from;
register char *t = to;
register int i = count;
while (i-- > 0)
*t++ = *f++;
}
#else /* __cplusplus */
/* This is the most reliable way to avoid incompatibilities
in available built-in functions on various systems. */
static void
__yy_memcpy (char *to, char *from, unsigned int count)
{
register char *t = to;
register char *f = from;
register int i = count;
while (i-- > 0)
*t++ = *f++;
}
#endif
#endif
#line 217 "/usr/lib/bison.simple"
/* The user can define YYPARSE_PARAM as the name of an argument to be passed
into yyparse. The argument should have type void *.
It should actually point to an object.
Grammar actions can access the variable by casting it
to the proper pointer type. */
#ifdef YYPARSE_PARAM
#ifdef __cplusplus
#define YYPARSE_PARAM_ARG void *YYPARSE_PARAM
#define YYPARSE_PARAM_DECL
#else /* not __cplusplus */
#define YYPARSE_PARAM_ARG YYPARSE_PARAM
#define YYPARSE_PARAM_DECL void *YYPARSE_PARAM;
#endif /* not __cplusplus */
#else /* not YYPARSE_PARAM */
#define YYPARSE_PARAM_ARG
#define YYPARSE_PARAM_DECL
#endif /* not YYPARSE_PARAM */
/* Prevent warning if -Wstrict-prototypes. */
#ifdef __GNUC__
#ifdef YYPARSE_PARAM
int yyparse (void *);
#else
int yyparse (void);
#endif
#endif
int
yyparse(YYPARSE_PARAM_ARG)
YYPARSE_PARAM_DECL
{
register int yystate;
register int yyn;
register short *yyssp;
register YYSTYPE *yyvsp;
int yyerrstatus; /* number of tokens to shift before error messages enabled */
int yychar1 = 0; /* lookahead token as an internal (translated) token number */
short yyssa[YYINITDEPTH]; /* the state stack */
YYSTYPE yyvsa[YYINITDEPTH]; /* the semantic value stack */
short *yyss = yyssa; /* refer to the stacks thru separate pointers */
YYSTYPE *yyvs = yyvsa; /* to allow yyoverflow to reallocate them elsewhere */
#ifdef YYLSP_NEEDED
YYLTYPE yylsa[YYINITDEPTH]; /* the location stack */
YYLTYPE *yyls = yylsa;
YYLTYPE *yylsp;
#define YYPOPSTACK (yyvsp--, yyssp--, yylsp--)
#else
#define YYPOPSTACK (yyvsp--, yyssp--)
#endif
int yystacksize = YYINITDEPTH;
int yyfree_stacks = 0;
#ifdef YYPURE
int yychar;
YYSTYPE yylval;
int yynerrs;
#ifdef YYLSP_NEEDED
YYLTYPE yylloc;
#endif
#endif
YYSTYPE yyval; /* the variable used to return */
/* semantic values from the action */
/* routines */
int yylen;
#if YYDEBUG != 0
if (yydebug)
fprintf(stderr, "Starting parse\n");
#endif
yystate = 0;
yyerrstatus = 0;
yynerrs = 0;
yychar = YYEMPTY; /* Cause a token to be read. */
/* Initialize stack pointers.
Waste one element of value and location stack
so that they stay on the same level as the state stack.
The wasted elements are never initialized. */
yyssp = yyss - 1;
yyvsp = yyvs;
#ifdef YYLSP_NEEDED
yylsp = yyls;
#endif
/* Push a new state, which is found in yystate . */
/* In all cases, when you get here, the value and location stacks
have just been pushed. so pushing a state here evens the stacks. */
yynewstate:
*++yyssp = yystate;
if (yyssp >= yyss + yystacksize - 1)
{
/* Give user a chance to reallocate the stack */
/* Use copies of these so that the &'s don't force the real ones into memory. */
YYSTYPE *yyvs1 = yyvs;
short *yyss1 = yyss;
#ifdef YYLSP_NEEDED
YYLTYPE *yyls1 = yyls;
#endif
/* Get the current used size of the three stacks, in elements. */
int size = yyssp - yyss + 1;
#ifdef yyoverflow
/* Each stack pointer address is followed by the size of
the data in use in that stack, in bytes. */
#ifdef YYLSP_NEEDED
/* This used to be a conditional around just the two extra args,
but that might be undefined if yyoverflow is a macro. */
yyoverflow("parser stack overflow",
&yyss1, size * sizeof (*yyssp),
&yyvs1, size * sizeof (*yyvsp),
&yyls1, size * sizeof (*yylsp),
&yystacksize);
#else
yyoverflow("parser stack overflow",
&yyss1, size * sizeof (*yyssp),
&yyvs1, size * sizeof (*yyvsp),
&yystacksize);
#endif
yyss = yyss1; yyvs = yyvs1;
#ifdef YYLSP_NEEDED
yyls = yyls1;
#endif
#else /* no yyoverflow */
/* Extend the stack our own way. */
if (yystacksize >= YYMAXDEPTH)
{
yyerror("parser stack overflow");
if (yyfree_stacks)
{
free (yyss);
free (yyvs);
#ifdef YYLSP_NEEDED
free (yyls);
#endif
}
return 2;
}
yystacksize *= 2;
if (yystacksize > YYMAXDEPTH)
yystacksize = YYMAXDEPTH;
#ifndef YYSTACK_USE_ALLOCA
yyfree_stacks = 1;
#endif
yyss = (short *) YYSTACK_ALLOC (yystacksize * sizeof (*yyssp));
__yy_memcpy ((char *)yyss, (char *)yyss1,
size * (unsigned int) sizeof (*yyssp));
yyvs = (YYSTYPE *) YYSTACK_ALLOC (yystacksize * sizeof (*yyvsp));
__yy_memcpy ((char *)yyvs, (char *)yyvs1,
size * (unsigned int) sizeof (*yyvsp));
#ifdef YYLSP_NEEDED
yyls = (YYLTYPE *) YYSTACK_ALLOC (yystacksize * sizeof (*yylsp));
__yy_memcpy ((char *)yyls, (char *)yyls1,
size * (unsigned int) sizeof (*yylsp));
#endif
#endif /* no yyoverflow */
yyssp = yyss + size - 1;
yyvsp = yyvs + size - 1;
#ifdef YYLSP_NEEDED
yylsp = yyls + size - 1;
#endif
#if YYDEBUG != 0
if (yydebug)
fprintf(stderr, "Stack size increased to %d\n", yystacksize);
#endif
if (yyssp >= yyss + yystacksize - 1)
YYABORT;
}
#if YYDEBUG != 0
if (yydebug)
fprintf(stderr, "Entering state %d\n", yystate);
#endif
goto yybackup;
yybackup:
/* Do appropriate processing given the current state. */
/* Read a lookahead token if we need one and don't already have one. */
/* yyresume: */
/* First try to decide what to do without reference to lookahead token. */
yyn = yypact[yystate];
if (yyn == YYFLAG)
goto yydefault;
/* Not known => get a lookahead token if don't already have one. */
/* yychar is either YYEMPTY or YYEOF
or a valid token in external form. */
if (yychar == YYEMPTY)
{
#if YYDEBUG != 0
if (yydebug)
fprintf(stderr, "Reading a token: ");
#endif
yychar = YYLEX;
}
/* Convert token to internal form (in yychar1) for indexing tables with */
if (yychar <= 0) /* This means end of input. */
{
yychar1 = 0;
yychar = YYEOF; /* Don't call YYLEX any more */
#if YYDEBUG != 0
if (yydebug)
fprintf(stderr, "Now at end of input.\n");
#endif
}
else
{
yychar1 = YYTRANSLATE(yychar);
#if YYDEBUG != 0
if (yydebug)
{
fprintf (stderr, "Next token is %d (%s", yychar, yytname[yychar1]);
/* Give the individual parser a way to print the precise meaning
of a token, for further debugging info. */
#ifdef YYPRINT
YYPRINT (stderr, yychar, yylval);
#endif
fprintf (stderr, ")\n");
}
#endif
}
yyn += yychar1;
if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != yychar1)
goto yydefault;
yyn = yytable[yyn];
/* yyn is what to do for this token type in this state.
Negative => reduce, -yyn is rule number.
Positive => shift, yyn is new state.
New state is final state => don't bother to shift,
just return success.
0, or most negative number => error. */
if (yyn < 0)
{
if (yyn == YYFLAG)
goto yyerrlab;
yyn = -yyn;
goto yyreduce;
}
else if (yyn == 0)
goto yyerrlab;
if (yyn == YYFINAL)
YYACCEPT;
/* Shift the lookahead token. */
#if YYDEBUG != 0
if (yydebug)
fprintf(stderr, "Shifting token %d (%s), ", yychar, yytname[yychar1]);
#endif
/* Discard the token being shifted unless it is eof. */
if (yychar != YYEOF)
yychar = YYEMPTY;
*++yyvsp = yylval;
#ifdef YYLSP_NEEDED
*++yylsp = yylloc;
#endif
/* count tokens shifted since error; after three, turn off error status. */
if (yyerrstatus) yyerrstatus--;
yystate = yyn;
goto yynewstate;
/* Do the default action for the current state. */
yydefault:
yyn = yydefact[yystate];
if (yyn == 0)
goto yyerrlab;
/* Do a reduction. yyn is the number of a rule to reduce with. */
yyreduce:
yylen = yyr2[yyn];
if (yylen > 0)
yyval = yyvsp[1-yylen]; /* implement default value of the action */
#if YYDEBUG != 0
if (yydebug)
{
int i;
fprintf (stderr, "Reducing via rule %d (line %d), ",
yyn, yyrline[yyn]);
/* Print the symbols being reduced, and their result. */
for (i = yyprhs[yyn]; yyrhs[i] > 0; i++)
fprintf (stderr, "%s ", yytname[yyrhs[i]]);
fprintf (stderr, " -> %s\n", yytname[yyr1[yyn]]);
}
#endif
switch (yyn) {
case 1:
#line 32 "expr.y"
{ result = yyvsp[0]; ;
break;}
case 2:
#line 36 "expr.y"
{ yyval = yyvsp[0]; ;
break;}
case 3:
#line 37 "expr.y"
{ yyval = yyvsp[-1]; ;
break;}
case 4:
#line 38 "expr.y"
{ yyval = exprNodeDot(yyvsp[-2], yyvsp[0]); ;
break;}
case 5:
#line 39 "expr.y"
{ yyval = exprNodeArrow(yyvsp[-2], yyvsp[0]); ;
break;}
case 6:
#line 40 "expr.y"
{ yyval = exprNodeArray(yyvsp[-3], yyvsp[-1]); ;
break;}
case 7:
#line 43 "expr.y"
{ yyval = yyvsp[0]; ;
break;}
case 8:
#line 44 "expr.y"
{ yyval = exprNodeStar(yyvsp[0]); ;
break;}
case 9:
#line 45 "expr.y"
{ yyval = exprNodeAddr(yyvsp[0]); ;
break;}
case 10:
#line 46 "expr.y"
{ yyval = exprNodeSizeof(yyvsp[-1]); ;
break;}
case 11:
#line 50 "expr.y"
{ yyval = exprNodeNumber(); ;
break;}
case 12:
#line 54 "expr.y"
{yyval = exprNodeIdentifier(); ;
break;}
}
/* the action file gets copied in in place of this dollarsign */
#line 543 "/usr/lib/bison.simple"
yyvsp -= yylen;
yyssp -= yylen;
#ifdef YYLSP_NEEDED
yylsp -= yylen;
#endif
#if YYDEBUG != 0
if (yydebug)
{
short *ssp1 = yyss - 1;
fprintf (stderr, "state stack now");
while (ssp1 != yyssp)
fprintf (stderr, " %d", *++ssp1);
fprintf (stderr, "\n");
}
#endif
*++yyvsp = yyval;
#ifdef YYLSP_NEEDED
yylsp++;
if (yylen == 0)
{
yylsp->first_line = yylloc.first_line;
yylsp->first_column = yylloc.first_column;
yylsp->last_line = (yylsp-1)->last_line;
yylsp->last_column = (yylsp-1)->last_column;
yylsp->text = 0;
}
else
{
yylsp->last_line = (yylsp+yylen-1)->last_line;
yylsp->last_column = (yylsp+yylen-1)->last_column;
}
#endif
/* Now "shift" the result of the reduction.
Determine what state that goes to,
based on the state we popped back to
and the rule number reduced by. */
yyn = yyr1[yyn];
yystate = yypgoto[yyn - YYNTBASE] + *yyssp;
if (yystate >= 0 && yystate <= YYLAST && yycheck[yystate] == *yyssp)
yystate = yytable[yystate];
else
yystate = yydefgoto[yyn - YYNTBASE];
goto yynewstate;
yyerrlab: /* here on detecting error */
if (! yyerrstatus)
/* If not already recovering from an error, report this error. */
{
++yynerrs;
#ifdef YYERROR_VERBOSE
yyn = yypact[yystate];
if (yyn > YYFLAG && yyn < YYLAST)
{
int size = 0;
char *msg;
int x, count;
count = 0;
/* Start X at -yyn if nec to avoid negative indexes in yycheck. */
for (x = (yyn < 0 ? -yyn : 0);
x < (sizeof(yytname) / sizeof(char *)); x++)
if (yycheck[x + yyn] == x)
size += strlen(yytname[x]) + 15, count++;
msg = (char *) malloc(size + 15);
if (msg != 0)
{
strcpy(msg, "parse error");
if (count < 5)
{
count = 0;
for (x = (yyn < 0 ? -yyn : 0);
x < (sizeof(yytname) / sizeof(char *)); x++)
if (yycheck[x + yyn] == x)
{
strcat(msg, count == 0 ? ", expecting `" : " or `");
strcat(msg, yytname[x]);
strcat(msg, "'");
count++;
}
}
yyerror(msg);
free(msg);
}
else
yyerror ("parse error; also virtual memory exceeded");
}
else
#endif /* YYERROR_VERBOSE */
yyerror("parse error");
}
goto yyerrlab1;
yyerrlab1: /* here on error raised explicitly by an action */
if (yyerrstatus == 3)
{
/* if just tried and failed to reuse lookahead token after an error, discard it. */
/* return failure if at end of input */
if (yychar == YYEOF)
YYABORT;
#if YYDEBUG != 0
if (yydebug)
fprintf(stderr, "Discarding token %d (%s).\n", yychar, yytname[yychar1]);
#endif
yychar = YYEMPTY;
}
/* Else will try to reuse lookahead token
after shifting the error token. */
yyerrstatus = 3; /* Each real token shifted decrements this */
goto yyerrhandle;
yyerrdefault: /* current state does not do anything special for the error token. */
#if 0
/* This is wrong; only states that explicitly want error tokens
should shift them. */
yyn = yydefact[yystate]; /* If its default is to accept any token, ok. Otherwise pop it.*/
if (yyn) goto yydefault;
#endif
yyerrpop: /* pop the current state because it cannot handle the error token */
if (yyssp == yyss) YYABORT;
yyvsp--;
yystate = *--yyssp;
#ifdef YYLSP_NEEDED
yylsp--;
#endif
#if YYDEBUG != 0
if (yydebug)
{
short *ssp1 = yyss - 1;
fprintf (stderr, "Error: state stack now");
while (ssp1 != yyssp)
fprintf (stderr, " %d", *++ssp1);
fprintf (stderr, "\n");
}
#endif
yyerrhandle:
yyn = yypact[yystate];
if (yyn == YYFLAG)
goto yyerrdefault;
yyn += YYTERROR;
if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != YYTERROR)
goto yyerrdefault;
yyn = yytable[yyn];
if (yyn < 0)
{
if (yyn == YYFLAG)
goto yyerrpop;
yyn = -yyn;
goto yyreduce;
}
else if (yyn == 0)
goto yyerrpop;
if (yyn == YYFINAL)
YYACCEPT;
#if YYDEBUG != 0
if (yydebug)
fprintf(stderr, "Shifting error token, ");
#endif
*++yyvsp = yylval;
#ifdef YYLSP_NEEDED
*++yylsp = yylloc;
#endif
yystate = yyn;
goto yynewstate;
yyacceptlab:
/* YYACCEPT comes here. */
if (yyfree_stacks)
{
free (yyss);
free (yyvs);
#ifdef YYLSP_NEEDED
free (yyls);
#endif
}
return 0;
yyabortlab:
/* YYABORT comes here. */
if (yyfree_stacks)
{
free (yyss);
free (yyvs);
#ifdef YYLSP_NEEDED
free (yyls);
#endif
}
return 1;
}
#line 57 "expr.y"
int yyerror(char *s)
{
return 0;
}
#ifndef SDL
extern FILE *yyin;
int main(int argc, char **argv)
{
// yydebug = 1;
++argv, --argc;
if(argc > 0)
yyin = fopen(argv[0], "r");
else
yyin = stdin;
if(!yyparse())
result->print();
}
#endif
| mit |
vladvelici/game-of-skate | protected/views/site/index.php | 531 | <?php $this->pageTitle=Yii::app()->name; ?>
<div style="float:right;width:300px;">
<h2>1. Film your tricks</h2>
It's enough to film your tricks in just one stance.
<h2>2. Upload and validate</h2>
Upload the video with the trick and then you'll be able to do that trick in the game.
<h2>3. Play Game of Skate online with others.</h2>
Show off your skateboarding skills online.
</div>
<h1>Welcome to <?php echo CHtml::encode(Yii::app()->name); ?></h1>
<img src='/images/home.png' alt="film, upload, play" align="center" /><br />
| mit |
pipa/MultiBundleBrowserify | static/src/js/modules/global.js | 129 | // Test Class ===================================
export default class Global {
foo() {
console.log('bar');
}
}
| mit |
ReneFGJr/CentroIntegradoPesquisa | system/Database/MySQLi/Forge.php | 5534 | <?php
/**
* This file is part of the CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CodeIgniter\Database\MySQLi;
use CodeIgniter\Database\Forge as BaseForge;
/**
* Forge for MySQLi
*/
class Forge extends BaseForge
{
/**
* CREATE DATABASE statement
*
* @var string
*/
protected $createDatabaseStr = 'CREATE DATABASE %s CHARACTER SET %s COLLATE %s';
/**
* CREATE DATABASE IF statement
*
* @var string
*/
protected $createDatabaseIfStr = 'CREATE DATABASE IF NOT EXISTS %s CHARACTER SET %s COLLATE %s';
/**
* DROP CONSTRAINT statement
*
* @var string
*/
protected $dropConstraintStr = 'ALTER TABLE %s DROP FOREIGN KEY %s';
/**
* CREATE TABLE keys flag
*
* Whether table keys are created from within the
* CREATE TABLE statement.
*
* @var boolean
*/
protected $createTableKeys = true;
/**
* UNSIGNED support
*
* @var array
*/
protected $_unsigned = [
'TINYINT',
'SMALLINT',
'MEDIUMINT',
'INT',
'INTEGER',
'BIGINT',
'REAL',
'DOUBLE',
'DOUBLE PRECISION',
'FLOAT',
'DECIMAL',
'NUMERIC',
];
/**
* Table Options list which required to be quoted
*
* @var array
*/
protected $_quoted_table_options = [
'COMMENT',
'COMPRESSION',
'CONNECTION',
'DATA DIRECTORY',
'INDEX DIRECTORY',
'ENCRYPTION',
'PASSWORD',
];
/**
* NULL value representation in CREATE/ALTER TABLE statements
*
* @var string
*
* @internal
*/
protected $null = 'NULL';
//--------------------------------------------------------------------
/**
* CREATE TABLE attributes
*
* @param array $attributes Associative array of table attributes
* @return string
*/
protected function _createTableAttributes(array $attributes): string
{
$sql = '';
foreach (array_keys($attributes) as $key)
{
if (is_string($key))
{
$sql .= ' ' . strtoupper($key) . ' = ';
if (in_array(strtoupper($key), $this->_quoted_table_options, true))
{
$sql .= $this->db->escape($attributes[$key]);
}
else
{
$sql .= $this->db->escapeString($attributes[$key]);
}
}
}
if (! empty($this->db->charset) && ! strpos($sql, 'CHARACTER SET') && ! strpos($sql, 'CHARSET'))
{
$sql .= ' DEFAULT CHARACTER SET = ' . $this->db->escapeString($this->db->charset);
}
if (! empty($this->db->DBCollat) && ! strpos($sql, 'COLLATE'))
{
$sql .= ' COLLATE = ' . $this->db->escapeString($this->db->DBCollat);
}
return $sql;
}
//--------------------------------------------------------------------
/**
* ALTER TABLE
*
* @param string $alterType ALTER type
* @param string $table Table name
* @param mixed $field Column definition
* @return string|string[]
*/
protected function _alterTable(string $alterType, string $table, $field)
{
if ($alterType === 'DROP')
{
return parent::_alterTable($alterType, $table, $field);
}
$sql = 'ALTER TABLE ' . $this->db->escapeIdentifiers($table);
foreach ($field as $i => $data)
{
if ($data['_literal'] !== false)
{
$field[$i] = ($alterType === 'ADD') ? "\n\tADD " . $data['_literal'] : "\n\tMODIFY " . $data['_literal'];
}
else
{
if ($alterType === 'ADD')
{
$field[$i]['_literal'] = "\n\tADD ";
}
else
{
$field[$i]['_literal'] = empty($data['new_name']) ? "\n\tMODIFY " : "\n\tCHANGE ";
}
$field[$i] = $field[$i]['_literal'] . $this->_processColumn($field[$i]);
}
}
return [$sql . implode(',', $field)];
}
//--------------------------------------------------------------------
/**
* Process column
*
* @param array $field
* @return string
*/
protected function _processColumn(array $field): string
{
$extraClause = isset($field['after']) ? ' AFTER ' . $this->db->escapeIdentifiers($field['after']) : '';
if (empty($extraClause) && isset($field['first']) && $field['first'] === true)
{
$extraClause = ' FIRST';
}
return $this->db->escapeIdentifiers($field['name'])
. (empty($field['new_name']) ? '' : ' ' . $this->db->escapeIdentifiers($field['new_name']))
. ' ' . $field['type'] . $field['length']
. $field['unsigned']
. $field['null']
. $field['default']
. $field['auto_increment']
. $field['unique']
. (empty($field['comment']) ? '' : ' COMMENT ' . $field['comment'])
. $extraClause;
}
//--------------------------------------------------------------------
/**
* Process indexes
*
* @param string $table (ignored)
* @return string
*/
protected function _processIndexes(string $table): string
{
$sql = '';
for ($i = 0, $c = count($this->keys); $i < $c; $i ++)
{
if (is_array($this->keys[$i]))
{
for ($i2 = 0, $c2 = count($this->keys[$i]); $i2 < $c2; $i2 ++)
{
if (! isset($this->fields[$this->keys[$i][$i2]]))
{
unset($this->keys[$i][$i2]);
continue;
}
}
}
elseif (! isset($this->fields[$this->keys[$i]]))
{
unset($this->keys[$i]);
continue;
}
if (! is_array($this->keys[$i]))
{
$this->keys[$i] = [$this->keys[$i]];
}
$unique = in_array($i, $this->uniqueKeys, true) ? 'UNIQUE ' : '';
$sql .= ",\n\t{$unique}KEY " . $this->db->escapeIdentifiers(implode('_', $this->keys[$i]))
. ' (' . implode(', ', $this->db->escapeIdentifiers($this->keys[$i])) . ')';
}
$this->keys = [];
return $sql;
}
}
| mit |
flav-io/flavio | flavio/physics/common.py | 1464 | """Common functions for physics."""
from collections import Counter
def conjugate_par(par_dict):
"""Given a dictionary of parameter values, return the dictionary where
all CP-odd parameters have flipped sign.
This assumes that the only CP-odd parameters are `gamma` or `delta` (the
CKM phase in the Wolfenstein or standard parametrization)."""
cp_odd = ['gamma', 'delta']
return {k: -v if k in cp_odd else v for k, v in par_dict.items()}
def conjugate_wc(wc_dict):
"""Given a dictionary of Wilson coefficients, return the dictionary where
all coefficients are CP conjugated (which simply amounts to complex
conjugation)."""
return {k: v.conjugate() for k, v in wc_dict.items()}
def add_dict(dicts):
"""Add dictionaries.
This will add the two dictionaries
`A = {'a':1, 'b':2, 'c':3}`
`B = {'b':3, 'c':4, 'd':5}`
into
`A + B {'a':1, 'b':5, 'c':7, 'd':5}`
but works for an arbitrary number of dictionaries."""
# start with the first dict
res = Counter(dicts[0])
# successively add all other dicts
for d in dicts[1:]: res.update(Counter(d))
return res
def lambda_K(a, b, c):
r"""Källén function $\lambda$.
$\lambda(a,b,c) = a^2 + b^2 + c^2 - 2 (ab + bc + ac)$
"""
z = a**2 + b**2 + c**2 - 2 * (a * b + b * c + a * c)
if z < 0:
# to avoid sqrt(-1e-16) type errors due to numerical inaccuracies
return 0
else:
return z
| mit |
MrPIvanov/SoftUni | 02-Progr Fundamentals/04-C# Basic Syntax - Exercises/04-BasicSyntaxMore/07-trainHall/Properties/AssemblyInfo.cs | 1395 | 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("07-trainHall")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("07-trainHall")]
[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("8e916d8e-2d70-4a6e-861d-670cde001aae")]
// 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 |
CCEM/nlp-heroku-app | reddex/setup.py | 1510 | """Setup for server/web page of reddex extension."""
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.txt')) as f:
README = f.read()
with open(os.path.join(here, 'CHANGES.txt')) as f:
CHANGES = f.read()
requires = [
'pyramid',
'pyramid_jinja2',
'pyramid_debugtoolbar',
'pyramid_tm',
'SQLAlchemy',
'transaction',
'zope.sqlalchemy',
'waitress',
'psycopg2',
'nltk'
]
tests_require = [
'WebTest >= 1.3.1',
'pytest',
'pytest-cov',
'tox',
]
setup(
name='reddex',
version='0.0',
description='Reddex',
long_description=README + '\n\n' + CHANGES,
classifiers=[
'Programming Language :: Python',
'Framework :: Pyramid',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
],
author='Carlos Cadena, Chris Hudson, Ely Paysinger, Morgan Numura',
author_email='[email protected], [email protected], [email protected], [email protected]',
url='https://github.com/CCEM',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
extras_require={
'testing': tests_require,
},
install_requires=requires,
entry_points={
'paste.app_factory': [
'main = reddex:main',
],
'console_scripts': [
'initdb = reddex.scripts.initializedb:main',
],
},
)
| mit |
EdwGx/AeroplaneChess | config/routes.rb | 1651 | Rails.application.routes.draw do
root 'games#index'
get 'd' => 'games#destroy'
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
| mit |
mdomlad85/foirun | FOIRun/database/src/main/java/hr/foi/air/database/entities/Aktivnost.java | 4478 | package hr.foi.air.database.entities;
import com.raizlabs.android.dbflow.annotation.Column;
import com.raizlabs.android.dbflow.annotation.ForeignKey;
import com.raizlabs.android.dbflow.annotation.ForeignKeyReference;
import com.raizlabs.android.dbflow.annotation.PrimaryKey;
import com.raizlabs.android.dbflow.annotation.Table;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.raizlabs.android.dbflow.sql.language.Select;
import com.raizlabs.android.dbflow.structure.BaseModel;
import java.util.List;
import hr.foi.air.database.FoiDatabase;
@Table(database = FoiDatabase.class)
public class Aktivnost extends BaseModel {
@PrimaryKey(autoincrement = true)
@Column int id;
@Column long start_time;
@Column double distance;
@Column long time;
@Column String name;
@Column String comment;
@Column double avg_hr;
@Column int max_hr;
@Column double avg_cadence;
@Column boolean deleted;
@Column int type_id;
@Column int user_id;
@Column(defaultValue = "0") boolean is_exercise;
public Aktivnost(long start_time, double distance, long time, String name, String comment,
int type_id, int avg_hr, int max_hr, double avg_cadence, boolean deleted) {
this.start_time = start_time;
this.distance = distance;
this.time = time;
this.name = name;
this.comment = comment;
this.type_id = type_id;
this.avg_hr = avg_hr;
this.max_hr = max_hr;
this.avg_cadence = avg_cadence;
this.deleted = deleted;
}
public Aktivnost() {
}
public static List<Aktivnost> getAll(){
return SQLite.select().from(Aktivnost.class).queryList();
}
public static List<Aktivnost> getExercises() {
return new Select().from(Aktivnost.class)
.where(Aktivnost_Table.is_exercise.eq(true))
.queryList();
}
List<Location> locationList;
public List<Location> getLocationList(){
if(locationList == null || locationList.isEmpty()){
locationList = new Select().from(Location.class)
.where(Location_Table.activity_id.eq(id))
.queryList();
}
return locationList;
}
public static List<Aktivnost> getByUserId(int uid) {
return new Select().from(Aktivnost.class)
.where(Aktivnost_Table.user_id.eq(uid))
.queryList();
}
public int getId() {
return id;
}
public long getStart_time() {
return start_time;
}
public void setStart_time(long start_time) {
this.start_time = start_time;
}
public double getDistance() {
return distance;
}
public void setDistance(double distance) {
this.distance = distance;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public double getAvg_hr() {
return avg_hr;
}
public void setAvg_hr(double avg_hr) {
this.avg_hr = avg_hr;
}
public int getMax_hr() {
return max_hr;
}
public void setMax_hr(int max_hr) {
this.max_hr = max_hr;
}
public double getAvg_cadence() {
return avg_cadence;
}
public void setAvg_cadence(double avg_cadence) {
this.avg_cadence = avg_cadence;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public int getType_id() {
return type_id;
}
public void setType_id(int type_id) {
this.type_id = type_id;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public boolean is_exercise() {
return is_exercise;
}
public void setIs_exercise(boolean is_exercise) {
this.is_exercise = is_exercise;
}
}
| mit |
VENIEGAMES/LocalDataSaver-Unity | Assets/Scripts/LocalDataSaver.cs | 1190 | using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
using System.Text;
public static class LocalDataSaver
{
private static string SavePath = Application.persistentDataPath + "/LocalData/";
public static void Save<T>(T serializableObject) where T : new()
{
if(!Directory.Exists(SavePath)){
Directory.CreateDirectory(SavePath);
}
string json = JsonUtility.ToJson(serializableObject);
File.WriteAllText(GetSaveDataPath<T>(), json);
}
public static T Load<T>() where T : new()
{
T deserializedObject = new T();
if (File.Exists (SavePath + (new T()).GetType().FullName)) {
try
{
deserializedObject = JsonUtility.FromJson<T>(File.ReadAllText(GetSaveDataPath<T>()));
}
catch
{
Debug.Log(string.Format("{0}の定義が変更された可能性があるため読み込めませんでした。", (GetSaveDataPath<T>())));
}
}
return deserializedObject;
}
public static void Delete<T>() where T : new()
{
File.Delete(GetSaveDataPath<T>());
}
private static string GetSaveDataPath<T>() where T : new()
{
return SavePath + (new T()).GetType().FullName;
}
}
| mit |
LegalizeAdulthood/cimple | src/providers/Upcall/module.cpp | 2319 | //==============================================================================
//
// PLEASE DO NOT EDIT; THIS FILE WAS AUTOMATICALLY GENERATED BY GENMOD 2.0.5
//
//==============================================================================
/* NOCHKSRC */
#include <cimple/cimple.h>
#include "Upcall_Provider.h"
using namespace cimple;
static int __cimple_Upcall_Provider_proc(
const Registration* registration,
int operation,
void* arg0,
void* arg1,
void* arg2,
void* arg3,
void* arg4,
void* arg5,
void* arg6,
void* arg7)
{
typedef Upcall Class;
typedef Upcall_Provider Provider;
if (operation != OPERATION_INVOKE_METHOD)
return Instance_Provider_Proc_T<Provider>::proc(registration,
operation, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
Provider* provider = (Provider*)arg0;
const Class* self = (const Class*)arg1;
const char* meth_name = ((Instance*)arg2)->meta_class->name;
if (strcasecmp(meth_name, "StartTest") == 0)
{
typedef Upcall_StartTest_method Method;
Method* method = (Method*)arg2;
return provider->StartTest(
method->count,
method->delay,
method->return_value);
}
if (strcasecmp(meth_name, "StopTest") == 0)
{
typedef Upcall_StopTest_method Method;
Method* method = (Method*)arg2;
return provider->StopTest(
method->return_value);
}
return -1;
}
CIMPLE_MODULE(Upcall_Module);
CIMPLE_INSTANCE_PROVIDER(Upcall_Provider);
#ifdef CIMPLE_PEGASUS_MODULE
CIMPLE_PEGASUS_PROVIDER_ENTRY_POINT;
# define __CIMPLE_FOUND_ENTRY_POINT
#endif
#ifdef CIMPLE_CMPI_MODULE
CIMPLE_CMPI_INSTANCE_PROVIDER(Upcall_Provider);
CIMPLE_CMPI_INSTANCE_PROVIDER2(Upcall_Provider, Upcall);
# define __CIMPLE_FOUND_ENTRY_POINT
#endif
#ifdef CIMPLE_OPENWBEM_MODULE
CIMPLE_OPENWBEM_PROVIDER(Upcall_Module);
# define __CIMPLE_FOUND_ENTRY_POINT
#endif
#ifdef CIMPLE_WMI_MODULE
# include "guid.h"
CIMPLE_WMI_PROVIDER_ENTRY_POINTS(CLSID_Upcall_Module)
# define __CIMPLE_FOUND_ENTRY_POINT
#endif
#ifndef __CIMPLE_FOUND_ENTRY_POINT
# error "No provider entry point found. Please define one of the following: CIMPLE_PEGASUS_MODULE, CIMPLE_CMPI_MODULE, CIMPLE_OPENWBEM_MODULE, CIMPLE_WMI_MODULE"
#endif
| mit |
fushouhai/flask_11_28 | app/api_1_0/errors.py | 775 | from . import api
from flask import jsonify
from ..exceptions import ValidationError
def bad_request(message):
response = jsonify({'error':'Bad request', 'message':message})
response.status_code = 400
return response
@api.errorhandler(ValidationError)
def validation_error(e):
return bad_request(e.args[0])
def forbidden(message):
response = jsonify({'error': 'forbidden', 'message':message})
response.status_code = 403
return response
def unauthorized(message):
response = jsonify({'error': 'Unauthorized', 'message':message})
response.status_code = 401
return response
def methodNotAllowed(message):
response = jsonify({'error': 'Method not allowed', 'message':message})
response.status_code = 405
return response
| mit |
romainneutron/PHPExiftool | lib/PHPExiftool/Driver/Tag/XMPIptcExt/LocationCreated.php | 927 | <?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\XMPIptcExt;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class LocationCreated extends AbstractTag
{
protected $Id = 'LocationCreated';
protected $Name = 'LocationCreated';
protected $FullName = 'XMP::iptcExt';
protected $GroupName = 'XMP-iptcExt';
protected $g0 = 'XMP';
protected $g1 = 'XMP-iptcExt';
protected $g2 = 'Author';
protected $Type = 'struct';
protected $Writable = true;
protected $Description = 'Location Created';
protected $local_g2 = 'Location';
protected $flag_List = true;
protected $flag_Bag = true;
}
| mit |
euroteamoutreach/euroteamoutreach.org | spec/features/doctrine_spec.rb | 192 | describe "Doctrine page", type: :feature do
before do
visit "/doctrine"
end
it "displays the correct heading" do
expect(page).to have_selector("h1", text: "Doctrine")
end
end
| mit |
dannyvankooten/laravel-vat | src/VatServiceProvider.php | 2000 | <?php
namespace DvK\Laravel\Vat;
use Illuminate\Contracts\Container\Container;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator as LaravelValidator;
use DvK\Laravel\Vat\Facades\Validator as VatValidator;
use DvK\Laravel\Vat\Rules;
use DvK\Vat\Countries;
use DvK\Vat\Rates\Rates;
use DvK\Vat\Validator;
class VatServiceProvider extends ServiceProvider
{
/**
* Boot the service provider.
*
* @return void
*/
public function boot()
{
/**
* Register the "vat_number" validation rule.
*/
LaravelValidator::extend('vat_number', function ($attribute, $value, $parameters, $validator) {
$rule = new Rules\VatNumber;
return $rule->passes($attribute, $value);
});
/**
* Register the "country_code" validation rule.
*/
LaravelValidator::extend('country_code', function ($attribute, $value, $parameters, $validator) {
$rule = new Rules\Country;
return $rule->passes($attribute, $value);
});
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton( Countries::class, function (Container $app) {
return new Countries();
});
$this->app->singleton( Validator::class, function (Container $app) {
return new Validator();
});
$this->app->singleton( Rates::class, function (Container $app) {
$defaultCacheDriver = $app['cache']->getDefaultDriver();
$cacheDriver = $app['cache']->driver( $defaultCacheDriver );
return new Rates( null, $cacheDriver );
});
}
/**
* Get the services provided by the provider.
*
* @return string[]
*/
public function provides()
{
return [
Validator::class,
Rates::class,
Countries::class,
];
}
}
| mit |
KnpLabs/ConsoleServiceProvider | Knp/Provider/ConsoleServiceProvider.php | 3137 | <?php
namespace Knp\Provider;
use Knp\Command\Twig\DebugCommand;
use Knp\Command\Twig\LintCommand;
use Knp\Console\Application as ConsoleApplication;
use Knp\Console\ConsoleEvent;
use Knp\Console\ConsoleEvents;
use Pimple\Container;
use Pimple\ServiceProviderInterface;
use Symfony\Bridge\Twig\Command\DebugCommand as TwigBridgeDebugCommand;
use Symfony\Component\Yaml\Command\LintCommand as LintYamlCommand;
/**
* Symfony Console service provider for Silex.
*/
class ConsoleServiceProvider implements ServiceProviderInterface
{
/**
* Registers the service provider.
*
* @param Container $app The Pimple container
*/
public function register(Container $app)
{
$app['console.name'] = 'Silex console';
$app['console.version'] = 'UNKNOWN';
// Assume we are in vendor/knplabs/console-service-provider/Knp/Provider
$app['console.project_directory'] = __DIR__.'/../../../../..';
$app['console.class'] = ConsoleApplication::class;
// List of command service ids indexed by command name (i.e: array('my:command' => 'my.command.service.id'))
$app['console.command.ids'] = [];
// Maintain BC with projects that depend on the old behavior (application gets booted from console constructor)
$app['console.boot_in_constructor'] = false;
$app['console'] = function () use ($app) {
/** @var ConsoleApplication $console */
$console = new $app['console.class'](
$app,
$app['console.project_directory'],
$app['console.name'],
$app['console.version']
);
$console->setDispatcher($app['dispatcher']);
foreach ($app['console.command.ids'] as $id) {
$console->add($app[$id]);
}
if ($app['dispatcher']->hasListeners(ConsoleEvents::INIT)) {
@trigger_error('Listening to the Knp\Console\ConsoleEvents::INIT event is deprecated and will be removed in v3 of the service provider. You should extend the console service instead.', E_USER_DEPRECATED);
$app['dispatcher']->dispatch(ConsoleEvents::INIT, new ConsoleEvent($console));
}
return $console;
};
$commands = [];
if (isset($app['twig']) && class_exists(TwigBridgeDebugCommand::class)) {
$app['console.command.twig.debug'] = function (Container $container) {
return new DebugCommand($container);
};
$app['console.command.twig.lint'] = function (Container $container) {
return new LintCommand($container);
};
$commands['debug:twig'] = 'console.command.twig.debug';
$commands['lint:twig'] = 'console.command.twig.lint';
}
if (class_exists(LintYamlCommand::class)) {
$app['console.command.yaml.lint'] = function () {
return new LintYamlCommand();
};
$commands['lint:yaml'] = 'console.command.yaml.lint';
}
$app['console.command.ids'] = $commands;
}
}
| mit |
wgcrouch/scrum-board | scripts/fos-mongo-migrate.js | 297 | db.users.find().forEach(function(user) {
user.username = user.usernameCanonical = user.email.match(/^(.*)@/)[1];
user.enabled = true;
user.expired = false;
user.locked = false;
user.emailCanonical = user.email;
user.roles = user.roles || {};
db.users.save(user);
});
| mit |
nodkz/react-relay-network-layer | src/__tests__/mutation.test.js | 1960 | /* @flow */
import fetchMock from 'fetch-mock';
import { RelayNetworkLayer } from '..';
import { mockReq } from '../__mocks__/mockReq';
describe('Mutation tests', () => {
const middlewares = [];
const rnl = new RelayNetworkLayer(middlewares);
beforeEach(() => {
fetchMock.restore();
});
it('should make a successfull mutation', async () => {
fetchMock.post('/graphql', { data: { ok: 1 } });
const req = mockReq();
await rnl.sendMutation(req);
expect(req.payload).toEqual({ response: { ok: 1 } });
});
it('should fail correctly on network failure', async () => {
fetchMock.mock({
matcher: '/graphql',
response: {
throws: new Error('Network connection error'),
},
method: 'POST',
});
const req1 = mockReq();
expect.assertions(2);
try {
await rnl.sendMutation(req1).catch(() => {});
} catch (e) {
expect(e instanceof Error).toBeTruthy();
expect(e.toString()).toMatch('Network connection error');
}
});
it('should handle error response', async () => {
fetchMock.mock({
matcher: '/graphql',
response: {
status: 200,
body: {
errors: [{ location: 1, message: 'major error' }],
},
},
method: 'POST',
});
const req1 = mockReq(1);
await rnl.sendMutation(req1).catch(() => {});
expect(req1.error instanceof Error).toBeTruthy();
});
it('should handle server non-2xx errors', async () => {
fetchMock.mock({
matcher: '/graphql',
response: {
status: 500,
body: 'Something went completely wrong.',
},
method: 'POST',
});
const req1 = mockReq(1);
await rnl.sendMutation(req1).catch(() => {});
const error: any = req1.error;
expect(error instanceof Error).toBeTruthy();
expect(error.message).toEqual('Something went completely wrong.');
expect(error.fetchResponse.status).toEqual(500);
});
});
| mit |
pkorenev/cms | lib/cms/banners/activerecord_helpers.rb | 3010 | module Cms
module Banners
module ActiveRecordExtensions
module ClassMethods
def acts_as_banner options = {}
class_variable_set(:@@acts_as_banner_options, options)
if mod = options[:base_articles]
self.send(:extend, mod)
end
self.attr_accessible *attribute_names
initialize_all_attachments = options[:initialize_all_attachments]
initialize_all_attachments ||= false
attachment_names = normalize_banner_columns(options).keep_if{|k, v| v == :attachment }.keys
if attachment_names.try(&:any?)
attachment_names.each do |attachment_name|
has_attached_file attachment_name
do_not_validate_attachment_file_type attachment_name if respond_to?(:do_not_validate_attachment_file_type)
attr_accessible attachment_name
allow_delete_attachment attachment_name
end
end
belongs_to :attachable, polymorphic: true
scope :published, -> { where(published: 't') }
scope :sort_by_sorting_position, ->{ order("sorting_position asc") }
return unless self.table_exists?
if Cms.config.use_translations
initialize_banner_translation
end
end
def normalize_banner_columns(options = {})
default_columns = {
attachable_type: :string,
attachable_id: :integer,
attachable_field_name: :string,
published: :boolean,
sorting_position: :integer,
name: :string,
image: :attachment
}
additional_columns = {
description: :text,
icon: :attachment
}
Utils.normalize_columns(default_columns: default_columns, additional_columns: additional_columns)
end
def normalize_banner_translation_columns(options = {})
defaults = {
default_translation_columns: {
name: :string
},
additional_translation_columns: {
description: :text
}
}
Utils.normalize_translation_columns(defaults.merge(options))
end
def initialize_banner_translation
Utils.initialize_translation(self, normalize_banner_translation_columns)
end
def acts_as_banner_options
opts = class_variable_defined?(:@@acts_as_banner_options) ? class_variable_get(:@@acts_as_banner_options) : {}
end
def attachment_names
[:image]
end
end
module InstanceMethods
def set_default_title_html_tag
self.title_html_tag = "div" if self.title_html_tag.blank?
end
end
end
end
end
ActiveRecord::Base.send(:extend, Cms::Banners::ActiveRecordExtensions::ClassMethods)
ActiveRecord::Base.send(:include, Cms::Banners::ActiveRecordExtensions::InstanceMethods) | mit |
freesamael/npu-moboapp-programming-fall-2015 | b2g-dist-win32-20151125/defaults/autoconfig/prefcalls.js | 5838 | /* -*- tab-width: 4; indent-tabs-mode: nil; js-indent-level: 4 -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const nsILDAPURL = Components.interfaces.nsILDAPURL;
const LDAPURLContractID = "@mozilla.org/network/ldap-url;1";
const nsILDAPSyncQuery = Components.interfaces.nsILDAPSyncQuery;
const LDAPSyncQueryContractID = "@mozilla.org/ldapsyncquery;1";
const nsIPrefService = Components.interfaces.nsIPrefService;
const PrefServiceContractID = "@mozilla.org/preferences-service;1";
var gVersion;
function getPrefBranch() {
var prefService = Components.classes[PrefServiceContractID]
.getService(nsIPrefService);
return prefService.getBranch(null);
}
function pref(prefName, value) {
try {
var prefBranch = getPrefBranch();
if (typeof value == "string") {
prefBranch.setCharPref(prefName, value);
}
else if (typeof value == "number") {
prefBranch.setIntPref(prefName, value);
}
else if (typeof value == "boolean") {
prefBranch.setBoolPref(prefName, value);
}
}
catch(e) {
displayError("pref", e);
}
}
function defaultPref(prefName, value) {
try {
var prefService = Components.classes[PrefServiceContractID]
.getService(nsIPrefService);
var prefBranch = prefService.getDefaultBranch(null);
if (typeof value == "string") {
prefBranch.setCharPref(prefName, value);
}
else if (typeof value == "number") {
prefBranch.setIntPref(prefName, value);
}
else if (typeof value == "boolean") {
prefBranch.setBoolPref(prefName, value);
}
}
catch(e) {
displayError("defaultPref", e);
}
}
function lockPref(prefName, value) {
try {
var prefBranch = getPrefBranch();
if (prefBranch.prefIsLocked(prefName))
prefBranch.unlockPref(prefName);
defaultPref(prefName, value);
prefBranch.lockPref(prefName);
}
catch(e) {
displayError("lockPref", e);
}
}
function unlockPref(prefName) {
try {
var prefBranch = getPrefBranch();
prefBranch.unlockPref(prefName);
}
catch(e) {
displayError("unlockPref", e);
}
}
function getPref(prefName) {
try {
var prefBranch = getPrefBranch();
switch (prefBranch.getPrefType(prefName)) {
case prefBranch.PREF_STRING:
return prefBranch.getCharPref(prefName);
case prefBranch.PREF_INT:
return prefBranch.getIntPref(prefName);
case prefBranch.PREF_BOOL:
return prefBranch.getBoolPref(prefName);
default:
return null;
}
}
catch(e) {
displayError("getPref", e);
}
}
function clearPref(prefName) {
try {
var prefBranch = getPrefBranch();
prefBranch.clearUserPref(prefName);
}
catch(e) {
}
}
function setLDAPVersion(version) {
gVersion = version;
}
function getLDAPAttributes(host, base, filter, attribs) {
try {
var urlSpec = "ldap://" + host + "/" + base + "?" + attribs + "?sub?" +
filter;
var url = Components.classes["@mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService)
.newURI(urlSpec, null, null)
.QueryInterface(Components.interfaces.nsILDAPURL);
var ldapquery = Components.classes[LDAPSyncQueryContractID]
.createInstance(nsILDAPSyncQuery);
// default to LDAP v3
if (!gVersion)
gVersion = Components.interfaces.nsILDAPConnection.VERSION3
// user supplied method
processLDAPValues(ldapquery.getQueryResults(url, gVersion));
}
catch(e) {
displayError("getLDAPAttibutes", e);
}
}
function getLDAPValue(str, key) {
try {
if (str == null || key == null)
return null;
var search_key = "\n" + key + "=";
var start_pos = str.indexOf(search_key);
if (start_pos == -1)
return null;
start_pos += search_key.length;
var end_pos = str.indexOf("\n", start_pos);
if (end_pos == -1)
end_pos = str.length;
return str.substring(start_pos, end_pos);
}
catch(e) {
displayError("getLDAPValue", e);
}
}
function displayError(funcname, message) {
try {
var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Components.interfaces.nsIPromptService);
var bundle = Components.classes["@mozilla.org/intl/stringbundle;1"]
.getService(Components.interfaces.nsIStringBundleService)
.createBundle("chrome://autoconfig/locale/autoconfig.properties");
var title = bundle.GetStringFromName("autoConfigTitle");
var msg = bundle.formatStringFromName("autoConfigMsg", [funcname], 1);
promptService.alert(null, title, msg + " " + message);
}
catch(e) { }
}
function getenv(name) {
try {
var environment = Components.classes["@mozilla.org/process/environment;1"].
getService(Components.interfaces.nsIEnvironment);
return environment.get(name);
}
catch(e) {
displayError("getEnvironment", e);
}
}
| mit |
modularcode/modular-starter-react | src/server/router.js | 270 | const path = require('path');
const express = require('express');
const router = express.Router();
router.get("/*", function(req, res) {
return res.set('Content-Type', 'text/html')
.sendFile(path.resolve(PUBLIC_DIR, 'index.html'));
});
module.exports = router;
| mit |
cryogen/throneteki | server/game/cards/12-KotI/ReturnToTheFields.js | 1301 | const PlotCard = require('../../plotcard');
const TextHelper = require('../../TextHelper');
const GameActions = require('../../GameActions');
class ReturnToTheFields extends PlotCard {
setupCardAbilities() {
this.whenRevealed({
target: {
type: 'select',
mode: 'upTo',
numCards: 3,
cardCondition: (card, context) => card.getType() === 'character' && card.location === 'play area' && card.controller === context.player,
gameAction: 'sacrifice'
},
handler: (context) => {
this.game.resolveGameAction(
GameActions.simultaneously(
context.target.map(card => GameActions.sacrificeCard({ card }))
)
);
let cardsDrawn = context.player.drawCardsToHand(context.target.length).length;
let goldGained = this.game.addGold(context.player, context.target.length);
this.game.addMessage('{0} uses {1} to sacrifice {2}, draw {3}, and gain {4} gold', context.player, this, context.target, TextHelper.count(cardsDrawn, 'card'), goldGained);
}
});
}
}
ReturnToTheFields.code = '12047';
module.exports = ReturnToTheFields;
| mit |
ecbypi/guise | lib/guise/syntax.rb | 5854 | require 'active_support/concern'
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/hash/indifferent_access'
require 'active_support/core_ext/string/inflections'
module Guise
module Syntax
# Setup the model's `guises` association. Given the following setup:
#
# ```ruby
# class User < ActiveRecord::Base
# has_guises :DeskWorker, :MailForwarder, association: :roles, attribute: :value
# end
# ```
#
# The following is configured:
#
# * `has_many` association named according to the `:association` option.
# * `User.desk_workers` and `User.mail_forwarders` model scopes.
# * `User#has_guise?` that checks if a user is a particular type.
# * `User#desk_worker?`, `User#mail_forwarder?` that proxy to `User#has_guise?`.
# * `User#has_guises?` that checks if a user has records for all the types
# supplied. This is aliased to `User#has_roles?`.
# * `User#has_any_guises?` that checks if a user has records for any of the
# types supplied. This is aliased to `User#has_any_roles?`.
# * If the association name is not `:guises`:
# * Aliases the association methods to equivalent methods for `guises`
# (i.e. `guises=` to `roles=`).
# * Aliases the introspection methods (i.e. `has_guise?` to `has_role?`
# and `has_any_guises?` to `has_any_roles?`
#
# @overload has_guises(*guises, options)
# @param [Array<Symbol, String>] *guises names of guises that should be
# allowed
# @param [Hash] options options to configure the association
# @option options [Symbol] :association name of the association to define.
# This option is required.
# @option options [Symbol] :attribute name of the association's column
# where the value of which guise is being represented is stored. This
# option is required.
def has_guises(*guises)
include Introspection
Guise.register_source(self, *guises)
end
# Specifies that the model is a subclass of a model configured with
# {#has_guises} specified by `class_name`.
#
# Configures the caller with the correct `default_scope`. Given the
# following definition with `has_guises`:
#
# ```ruby
# class User < ActiveRecord::Base
# has_guises :DeskWorker, :MailForwarder, association: :roles, attribute: :title
# end
# ```
#
# The following call to `guise_of`:
#
# class DeskWorker < User
# guise_of :User
# end
# ```
#
# Is equivalent to:
#
# ```ruby
# class DeskWorker < User
# default_scope -> { desk_workers }
#
# after_initialize do
# self.guises.build(title: 'DeskWorker')
# end
#
# after_create do
# self.guises.create(title: 'DeskWorker')
# end
# end
# ```
#
# @param [String, Symbol] source_class_name name of the superclass
# configured with {#has_guises}.
def guise_of(source_class_name)
options = Guise.registry[source_class_name]
default_scope GuiseOfScope.new(name, options)
after_initialize SourceCallback.new(name, options.attribute)
end
# Configures the other end of the association defined by {#has_guises}.
# Defines equivalent scopes defined on the model configured with
# {#has_guises}.
#
# Given the following configuring of `has_guises`:
#
# ```ruby
# class User < ActiveRecord::Base
# has_guises :DeskWorker, :MailForwarder, association: :roles, attribute: :title
# end
# ```
#
# The following call to `guise_for`:
#
# ```ruby
# class Role < ActiveRecord::Base
# guise_for :User
# end
# ```
#
# Is equivalent to:
#
# ```ruby
# class Role < ActiveRecord::Base
# belongs_to :user
#
# validates :title, presence: true, uniqueness: { scope: :user_id }, inclusion: { in: %w( DeskWorker MailForwarder ) }
#
# scope :desk_workers, -> { where(title: "DeskWorker") }
# scope :mail_forwarder, -> { where(title: "MailForwarder") }
# end
# ```
#
# @param [Symbol, String] source_class_name name of the class configured
# with {#has_guises}
# @param [Hash] options options to configure the `belongs_to` association.
# @option options [false] :validate specify `false` to skip
# validations for the `:attribute` specified in {#has_guises}
# @option options [Symbol] :foreign_key foreign key used to build the
# association.
def guise_for(source_class_name, options = {})
Guise.register_association(self, source_class_name, options)
end
# Specifies that the model is a subclass of a model configured with
# {#guise_for} specified by `class_name`. The name of the calling class must
# be `<value|parent_class_name>`.
#
# Given the following configuration with `guise_for`:
#
# ```ruby
# class Role < ActiveRecord::Base
# guise_for :User
# end
# ```
#
# The following call to `scoped_guise_for`:
#
# ```ruby
# class DeskWorkerRole < Role
# scoped_guise_for :Role
# end
# ```
#
# Is equivalent to:
#
# ```ruby
# class DeskWorkerRole < Role
# default_scope -> { desk_workers }
#
# after_initialize do
# self.title = "DeskWorker"
# end
# end
# ```
#
# @param [Symbol, String] association_class_name name of the superclass
# configured with {#guise_for}.
def scoped_guise_for(association_class_name)
options = Guise.registry[association_class_name]
value = name.chomp(options.association_class.name)
default_scope options.scope(value, :guise_for)
after_initialize AssociationCallback.new(value, options.attribute)
end
end
end
| mit |
sygic-travel/js-sdk | src/Pdf/MapGenerator.test.ts | 6018 | import * as chai from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import { cloneDeep } from '../Util';
import { sandbox as sinonSandbox, SinonSandbox, SinonStub } from 'sinon';
import { Bounds } from '../Geo';
import { Place } from '../Places';
import { setEnvironment } from '../Settings/';
import { placeDetailedEiffelTowerWithoutMedia as placeMock } from '../TestData/PlacesExpectedResults';
import * as Dao from './DataAccess';
import { calculateMapGrid, generateDestinationMainMap, generateDestinationSecondaryMaps } from './MapGenerator';
import { PdfQuery, PdfStaticMap, PdfStaticMapSector, PlaceSource } from './PdfData';
let sandbox: SinonSandbox;
chai.use(chaiAsPromised);
describe('MapGeneratorController', () => {
const place1: Place = cloneDeep(placeMock);
place1.id = 'poi:1';
place1.location = {
lat: 30,
lng: 10
};
const place2: Place = cloneDeep(placeMock);
place2.id = 'poi:2';
place2.location = {
lat: 30,
lng: 30
};
const place3: Place = cloneDeep(placeMock);
place3.id = 'poi:3';
place3.location = {
lat: 10,
lng: 10
};
const place4: Place = cloneDeep(placeMock);
place4.id = 'poi:4';
place4.location = {
lat: 10,
lng: 30
};
const destinationPlaces: Place[] = [place1, place2, place3, place4];
const query: PdfQuery = {
tripId: 'x',
mainMapWidth: 1000,
mainMapHeight: 1000,
gridRowsCount: 2,
gridColumnsCount: 2,
secondaryMapWidth: 100,
secondaryMapHeight: 100
};
before((done) => {
setEnvironment({ stApiUrl: 'api', integratorApiKey: '987654321' });
done();
});
beforeEach(() => {
sandbox = sinonSandbox.create();
});
afterEach(() => {
sandbox.restore();
});
describe('#generateDestinationMainMap', () => {
it('should generate main static map', async () => {
sandbox.stub(Dao, 'getStaticMap').returns({
id: 'main',
url: 'some_url',
bounds: {
south: 0,
west: 0,
north: 40,
east: 40
} as Bounds,
sectors: []
});
const map: PdfStaticMap = await generateDestinationMainMap(destinationPlaces, new Map<string, PlaceSource>(), query);
chai.expect(map.sectors.length).to.be.eq(4);
const sectorA0: PdfStaticMapSector | undefined = map.sectors.find((s: PdfStaticMapSector) => s.id === 'A0');
const sectorA1: PdfStaticMapSector | undefined = map.sectors.find((s: PdfStaticMapSector) => s.id === 'A1');
const sectorB0: PdfStaticMapSector | undefined = map.sectors.find((s: PdfStaticMapSector) => s.id === 'B0');
const sectorB1: PdfStaticMapSector | undefined = map.sectors.find((s: PdfStaticMapSector) => s.id === 'B1');
chai.expect(sectorA0!.bounds).to.be.deep.eq({
south: 20,
west: 0,
north: 40,
east: 20
});
chai.expect(sectorA1!.bounds).to.be.deep.eq({
south: 20,
west: 20,
north: 40,
east: 40
});
chai.expect(sectorB0!.bounds).to.be.deep.eq({
south: 0,
west: 0,
north: 20,
east: 20
});
chai.expect(sectorB1!.bounds).to.be.deep.eq({
south: 0,
west: 20,
north: 20,
east: 40
});
chai.expect(sectorA0!.places[0]).to.be.deep.eq(place1);
chai.expect(sectorA1!.places[0]).to.be.deep.eq(place2);
chai.expect(sectorB0!.places[0]).to.be.deep.eq(place3);
chai.expect(sectorB1!.places[0]).to.be.deep.eq(place4);
});
});
describe('#generateDestinationSecondaryMaps', () => {
it('should generate secondary static maps', async () => {
const stub: SinonStub = sandbox.stub(Dao, 'getStaticMap');
stub.onCall(0).returns({
id: 'A0',
url: 'some_url',
bounds: {
south: 0,
west: 0,
north: 0,
east: 0
} as Bounds,
sectors: []
});
stub.onCall(1).returns({
id: 'A1',
url: 'some_url',
bounds: {
south: 0,
west: 0,
north: 0,
east: 0
} as Bounds,
sectors: []
});
stub.onCall(2).returns({
id: 'B0',
url: 'some_url',
bounds: {
south: 0,
west: 0,
north: 0,
east: 0
} as Bounds,
sectors: []
});
stub.onCall(3).returns({
id: 'B1',
url: 'some_url',
bounds: {
south: 0,
west: 0,
north: 0,
east: 0
} as Bounds,
sectors: []
});
const mainMapSectors: PdfStaticMapSector[] = [{
id: 'A0',
places: [place1],
bounds: {
south: 20,
west: 0,
north: 40,
east: 20
}
}, {
id: 'A1',
places: [place2],
bounds: {
south: 20,
west: 20,
north: 40,
east: 40
}
}, {
id: 'B0',
places: [place3],
bounds: {
south: 0,
west: 0,
north: 20,
east: 20
}
}, {
id: 'B1',
places: [place4],
bounds: {
south: 0,
west: 20,
north: 20,
east: 40
}
}];
const secondaryMaps: PdfStaticMap[] = await generateDestinationSecondaryMaps(
destinationPlaces,
query,
mainMapSectors,
new Map<string, PlaceSource>()
);
chai.expect(secondaryMaps.length).to.be.eq(4);
chai.expect(secondaryMaps[0]).to.haveOwnProperty('id', 'A0');
chai.expect(secondaryMaps[1]).to.haveOwnProperty('id', 'A1');
chai.expect(secondaryMaps[2]).to.haveOwnProperty('id', 'B0');
chai.expect(secondaryMaps[3]).to.haveOwnProperty('id', 'B1');
});
});
describe('#calculateMapGrid', () => {
it('should calculate grid based on bounds and # of rows and columns', () => {
const bounds: Bounds = {
south: 2,
west: 2,
north: 4,
east: 4
};
const result: PdfStaticMapSector[] = [{
id: 'A0',
bounds: {
south: 3,
west: 2,
north: 4,
east: 3
},
places: []
}, {
id: 'A1',
bounds: {
south: 3,
west: 3,
north: 4,
east: 4
},
places: []
}, {
id: 'B0',
bounds: {
south: 2,
west: 2,
north: 3,
east: 3
},
places: []
}, {
id: 'B1',
bounds: {
south: 2,
west: 3,
north: 3,
east: 4
},
places: []
}];
chai.expect(calculateMapGrid(
bounds,
2,
2
)).to.deep.equal(result);
});
});
});
| mit |
imbo/behat-api-extension | src/ArrayContainsComparator/Matcher/LessThan.php | 1063 | <?php declare(strict_types=1);
namespace Imbo\BehatApiExtension\ArrayContainsComparator\Matcher;
use InvalidArgumentException;
/**
* Check if a numeric value is less than another value
*/
class LessThan
{
/**
* Match a numeric value
*
* @param mixed $number A variable
* @param mixed $max The max value of $number
* @throws InvalidArgumentException
*/
public function __invoke($number, $max): bool
{
if (!is_numeric($number)) {
throw new InvalidArgumentException(sprintf(
'"%s" is not numeric.',
(string) $number,
));
}
if (!is_numeric($max)) {
throw new InvalidArgumentException(sprintf(
'"%s" is not numeric.',
(string) $max,
));
}
if ($number >= $max) {
throw new InvalidArgumentException(sprintf(
'"%s" is not less than "%s".',
$number,
$max,
));
}
return true;
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.