code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
import time
import json
import redis
import subprocess
from subprocess import Popen, check_output
import shlex
import os
from py_cf_new_py3.chain_flow_py3 import CF_Base_Interpreter
from redis_graph_py3 import farm_template_py3
class Process_Control(object ):
def __init__(self):
pass
def run_process_to_completion(self,command_string, shell_flag = False, timeout_value = None):
try:
command_parameters = shlex.split(command_string)
return_value = check_output(command_parameters, stderr=subprocess.STDOUT , shell = shell_flag, timeout = timeout_value)
return [0,return_value.decode()]
except subprocess.CalledProcessError as cp:
return [ cp.returncode , cp.output.decode() ]
except :
return [-1,""]
def launch_process(self,command_string,stderr=None,shell=True):
command_parameters = shlex.split(command_string)
try:
process_handle = Popen(command_parameters, stderr=open(self.error_file,'w' ))
return [ True, process_handle ]
except:
return [False, None]
def monitor_process(self, process_handle):
returncode = process_handle.poll()
if returncode == None:
return [ True, 0]
else:
del process_handle
return [ False, returncode ]
def kill_process(self,process_handle):
try:
process_handle.kill()
process_handle.wait()
del process_handle
except:
pass
class Manage_A_Python_Process(Process_Control):
def __init__(self,command_string, restart_flag = True, error_directory = "/tmp"):
super(Process_Control,self)
self.restart_flag = restart_flag
command_string = "python3 "+command_string
self.command_string = command_string
command_list= shlex.split(command_string)
script_file_list = command_list[1].split("/")
self.script_file_name = script_file_list[-1].split(".")[0]
temp = error_directory + "/"+self.script_file_name
self.error_file = temp+".err"
self.error_file_rollover = temp +".errr"
self.error = False
self.enabled = True
self.active = False
def get_script(self):
return self.script_file_name
def launch(self):
if( (self.enabled == True) and (self.active == False )):
temp = self.launch_process(self.command_string, stderr=self.error_file)
return_value = temp[0]
self.handle = temp[1]
self.active = return_value
if self.active == False:
self.rollover()
self.error = True
else:
self.error = False
def monitor(self):
if self.enabled == True:
if self.active == True:
return_value = self.monitor_process(self.handle)
if return_value[0] == True:
return True
self.active = False
self.rollover()
if self.restart_flag == True:
self.launch()
return False
def rollover(self):
os.system("mv "+self.error_file+" " +self.error_file_rollover)
def kill(self):
self.active = False
self.error = False
self.enabled = False
self.kill_process(self.handle)
self.rollover()
class System_Control(object):
def __init__(self,
redis_handle,
error_queue_key,
web_command_queue_key,
web_process_data_key,
web_display_list_key,
command_string_list ):
self.redis_handle = redis_handle
self.error_queue_key = error_queue_key
self.web_command_queue_key = web_command_queue_key
self.web_process_data_key = web_process_data_key
self.web_display_list_key = web_display_list_key
self.command_string_list = command_string_list
self.startup_list = []
self.process_hash = {}
self.process_state = {}
for command_string in command_string_list:
temp_class = Manage_A_Python_Process( command_string )
python_script = temp_class.get_script()
self.startup_list.append(python_script)
self.process_hash[python_script] = temp_class
self.redis_handle.set(self.web_display_list_key,json.dumps(self.startup_list))
self.update_web_display()
def launch_processes( self,*unused ):
for script in self.startup_list:
temp = self.process_hash[script]
temp.launch()
if temp.error == True:
return_data = json.dumps({ "script": script, "error_file" : temp.temp.error_file_rollover})
self.redis_handle.publish(self.error_queue_key,return_data)
temp.error = False
def monitor( self, *unused ):
for script in self.startup_list:
temp = self.process_hash[script]
temp.monitor()
if temp.error == True:
return_data = json.dumps({ "script": script, "error_file" : temp.temp.error_file_rollover})
self.redis_handle.publish(self.error_queue_key,return_data)
temp.error = False
self.update_web_display()
def process_web_queue( self, *unused ):
if self.redis_handle.llen(self.web_command_queue_key) > 0 :
data_json = redis_handle.lpop(self.web_command_queue_key)
self.redis_handle.ltrim(self.web_command_queue_key,0,-1) # empty redis queue
data = json.loads(data_json)
print("made it here")
for script,item in data.items():
temp = self.process_hash[script]
try:
if item["enabled"] == True:
if temp.enabled == False:
temp.enabled = True
temp.active = False
#print(script,"---------------------------launch")
temp.launch()
else:
if temp.enabled == True:
temp.enabled = False
#print(script,"----------------------------kill")
temp.kill()
except:
pass
print(self.process_hash[script].active)
print(self.process_hash[script].enabled)
self.update_web_display()
def update_web_display(self):
process_state = {}
for script in self.startup_list:
temp = self.process_hash[script]
process_state[script] = {"name":script,"enabled":temp.enabled,"active":temp.active,"error":temp.error}
self.redis_handle.set(self.web_process_data_key,json.dumps(process_state))
def add_chains(self,cf):
cf.define_chain("initialization",True)
cf.insert.one_step(self.launch_processes)
cf.insert.enable_chains( ["monitor_web_command_queue","monitor_active_processes"] )
cf.insert.terminate()
cf.define_chain("monitor_web_command_queue", False)
cf.insert.wait_event_count( event = "TIME_TICK", count = 1)
cf.insert.one_step(self.process_web_queue)
cf.insert.reset()
cf.define_chain("monitor_active_processes",False)
cf.insert.wait_event_count( event = "TIME_TICK",count = 10)
cf.insert.one_step(self.monitor)
cf.insert.reset()
if __name__ == "__main__":
cf = CF_Base_Interpreter()
gm = farm_template_py3.Graph_Management(
"PI_1", "main_remote", "LaCima_DataStore")
process_data = gm.match_terminal_relationship("PROCESS_CONTROL")[0]
redis_data = process_data["redis"]
redis_handle = redis.StrictRedis(
host=redis_data["ip"], port=redis_data["port"], db=redis_data["db"], decode_responses=True)
web_command_queue_key =process_data['web_command_key']
error_queue_key = process_data['error_queue_key']
command_string_list = process_data["command_string_list"]
web_process_data_key = process_data["web_process_data"]
web_display_list_key = process_data["web_display_list"]
print(web_process_data_key,web_display_list_key)
system_control = System_Control( redis_handle = redis_handle,
error_queue_key = error_queue_key,
web_command_queue_key = web_command_queue_key,
web_process_data_key = web_process_data_key,
web_display_list_key = web_display_list_key,
command_string_list = command_string_list )
system_control.add_chains(cf)
cf.execute()
| glenn-edgar/local_controller_3 | process_control_py3.py | Python | mit | 9,357 |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ISpliceable } from 'vs/base/common/sequence';
import { Iterator, ISequence } from 'vs/base/common/iterator';
import { Emitter, Event, EventBufferer } from 'vs/base/common/event';
import { tail2 } from 'vs/base/common/arrays';
import { ITreeFilterDataResult, TreeVisibility, ITreeFilter, ITreeModel, ITreeNode, ITreeElement } from 'vs/base/browser/ui/tree/tree';
interface IMutableTreeNode<T, TFilterData> extends ITreeNode<T, TFilterData> {
readonly parent: IMutableTreeNode<T, TFilterData> | undefined;
readonly children: IMutableTreeNode<T, TFilterData>[];
collapsible: boolean;
collapsed: boolean;
renderNodeCount: number;
visible: boolean;
filterData: TFilterData | undefined;
}
function isFilterResult<T>(obj: any): obj is ITreeFilterDataResult<T> {
return typeof obj === 'object' && 'visibility' in obj && 'data' in obj;
}
function treeNodeToElement<T>(node: IMutableTreeNode<T, any>): ITreeElement<T> {
const { element, collapsed } = node;
const children = Iterator.map(Iterator.fromArray(node.children), treeNodeToElement);
return { element, children, collapsed };
}
function getVisibleState(visibility: boolean | TreeVisibility): TreeVisibility {
switch (visibility) {
case true: return TreeVisibility.Visible;
case false: return TreeVisibility.Hidden;
default: return visibility;
}
}
export interface IIndexTreeModelOptions<T, TFilterData> {
collapseByDefault?: boolean; // defaults to false
filter?: ITreeFilter<T, TFilterData>;
}
export class IndexTreeModel<T extends Exclude<any, undefined>, TFilterData = void> implements ITreeModel<T, TFilterData, number[]> {
private root: IMutableTreeNode<T, TFilterData>;
private eventBufferer = new EventBufferer();
private _onDidChangeCollapseState = new Emitter<ITreeNode<T, TFilterData>>();
readonly onDidChangeCollapseState: Event<ITreeNode<T, TFilterData>> = this.eventBufferer.wrapEvent(this._onDidChangeCollapseState.event);
private _onDidChangeRenderNodeCount = new Emitter<ITreeNode<T, TFilterData>>();
readonly onDidChangeRenderNodeCount: Event<ITreeNode<T, TFilterData>> = this.eventBufferer.wrapEvent(this._onDidChangeRenderNodeCount.event);
private collapseByDefault: boolean;
private filter?: ITreeFilter<T, TFilterData>;
constructor(private list: ISpliceable<ITreeNode<T, TFilterData>>, rootElement: T, options: IIndexTreeModelOptions<T, TFilterData> = {}) {
this.collapseByDefault = typeof options.collapseByDefault === 'undefined' ? false : options.collapseByDefault;
this.filter = options.filter;
this.root = {
parent: undefined,
element: rootElement,
children: [],
depth: 0,
collapsible: false,
collapsed: false,
renderNodeCount: 0,
visible: true,
filterData: undefined
};
}
splice(
location: number[],
deleteCount: number,
toInsert?: ISequence<ITreeElement<T>>,
onDidCreateNode?: (node: ITreeNode<T, TFilterData>) => void,
onDidDeleteNode?: (node: ITreeNode<T, TFilterData>) => void
): Iterator<ITreeElement<T>> {
if (location.length === 0) {
throw new Error('Invalid tree location');
}
const { parentNode, listIndex, revealed } = this.getParentNodeWithListIndex(location);
const treeListElementsToInsert: ITreeNode<T, TFilterData>[] = [];
const nodesToInsertIterator = Iterator.map(Iterator.from(toInsert), el => this.createTreeNode(el, parentNode, parentNode.visible ? TreeVisibility.Visible : TreeVisibility.Hidden, revealed, treeListElementsToInsert, onDidCreateNode));
const nodesToInsert: IMutableTreeNode<T, TFilterData>[] = [];
let renderNodeCount = 0;
Iterator.forEach(nodesToInsertIterator, node => {
nodesToInsert.push(node);
renderNodeCount += node.renderNodeCount;
});
const lastIndex = location[location.length - 1];
const deletedNodes = parentNode.children.splice(lastIndex, deleteCount, ...nodesToInsert);
if (revealed) {
const visibleDeleteCount = deletedNodes.reduce((r, node) => r + node.renderNodeCount, 0);
this._updateAncestorsRenderNodeCount(parentNode, renderNodeCount - visibleDeleteCount);
this.list.splice(listIndex, visibleDeleteCount, treeListElementsToInsert);
}
if (deletedNodes.length > 0 && onDidDeleteNode) {
const visit = (node: ITreeNode<T, TFilterData>) => {
onDidDeleteNode(node);
node.children.forEach(visit);
};
deletedNodes.forEach(visit);
}
return Iterator.map(Iterator.fromArray(deletedNodes), treeNodeToElement);
}
getListIndex(location: number[]): number {
return this.getTreeNodeWithListIndex(location).listIndex;
}
setCollapsed(location: number[], collapsed: boolean): boolean {
const { node, listIndex, revealed } = this.getTreeNodeWithListIndex(location);
return this.eventBufferer.bufferEvents(() => this._setCollapsed(node, listIndex, revealed, collapsed));
}
toggleCollapsed(location: number[]): void {
const { node, listIndex, revealed } = this.getTreeNodeWithListIndex(location);
this.eventBufferer.bufferEvents(() => this._setCollapsed(node, listIndex, revealed));
}
collapseAll(): void {
const queue = [...this.root.children];
let listIndex = 0;
this.eventBufferer.bufferEvents(() => {
while (queue.length > 0) {
const node = queue.shift()!;
const revealed = listIndex < this.root.children.length;
this._setCollapsed(node, listIndex, revealed, true);
queue.push(...node.children);
listIndex++;
}
});
}
isCollapsed(location: number[]): boolean {
return this.getTreeNode(location).collapsed;
}
refilter(): void {
const previousRenderNodeCount = this.root.renderNodeCount;
const toInsert = this.updateNodeAfterFilterChange(this.root);
this.list.splice(0, previousRenderNodeCount, toInsert);
}
private _setCollapsed(node: IMutableTreeNode<T, TFilterData>, listIndex: number, revealed: boolean, collapsed?: boolean | undefined): boolean {
if (!node.collapsible) {
return false;
}
if (typeof collapsed === 'undefined') {
collapsed = !node.collapsed;
}
if (node.collapsed === collapsed) {
return false;
}
node.collapsed = collapsed;
if (revealed) {
const previousRenderNodeCount = node.renderNodeCount;
const toInsert = this.updateNodeAfterCollapseChange(node);
this.list.splice(listIndex + 1, previousRenderNodeCount - 1, toInsert.slice(1));
this._onDidChangeCollapseState.fire(node);
}
return true;
}
private createTreeNode(
treeElement: ITreeElement<T>,
parent: IMutableTreeNode<T, TFilterData>,
parentVisibility: TreeVisibility,
revealed: boolean,
treeListElements: ITreeNode<T, TFilterData>[],
onDidCreateNode?: (node: ITreeNode<T, TFilterData>) => void
): IMutableTreeNode<T, TFilterData> {
const node: IMutableTreeNode<T, TFilterData> = {
parent,
element: treeElement.element,
children: [],
depth: parent.depth + 1,
collapsible: typeof treeElement.collapsible === 'boolean' ? treeElement.collapsible : (typeof treeElement.collapsed !== 'undefined'),
collapsed: typeof treeElement.collapsed === 'undefined' ? this.collapseByDefault : treeElement.collapsed,
renderNodeCount: 1,
visible: true,
filterData: undefined
};
const visibility = this._filterNode(node, parentVisibility);
if (revealed) {
treeListElements.push(node);
}
const childElements = Iterator.from(treeElement.children);
const childRevealed = revealed && visibility !== TreeVisibility.Hidden && !node.collapsed;
const childNodes = Iterator.map(childElements, el => this.createTreeNode(el, node, visibility, childRevealed, treeListElements, onDidCreateNode));
let hasVisibleDescendants = false;
let renderNodeCount = 1;
Iterator.forEach(childNodes, child => {
node.children.push(child);
hasVisibleDescendants = hasVisibleDescendants || child.visible;
renderNodeCount += child.renderNodeCount;
});
node.collapsible = node.collapsible || node.children.length > 0;
node.visible = visibility === TreeVisibility.Recurse ? hasVisibleDescendants : (visibility === TreeVisibility.Visible);
if (!node.visible) {
node.renderNodeCount = 0;
if (revealed) {
treeListElements.pop();
}
} else if (!node.collapsed) {
node.renderNodeCount = renderNodeCount;
}
if (onDidCreateNode) {
onDidCreateNode(node);
}
return node;
}
private updateNodeAfterCollapseChange(node: IMutableTreeNode<T, TFilterData>): ITreeNode<T, TFilterData>[] {
const previousRenderNodeCount = node.renderNodeCount;
const result: ITreeNode<T, TFilterData>[] = [];
this._updateNodeAfterCollapseChange(node, result);
this._updateAncestorsRenderNodeCount(node.parent, result.length - previousRenderNodeCount);
return result;
}
private _updateNodeAfterCollapseChange(node: IMutableTreeNode<T, TFilterData>, result: ITreeNode<T, TFilterData>[]): number {
if (node.visible === false) {
return 0;
}
result.push(node);
node.renderNodeCount = 1;
if (!node.collapsed) {
for (const child of node.children) {
node.renderNodeCount += this._updateNodeAfterCollapseChange(child, result);
}
}
this._onDidChangeRenderNodeCount.fire(node);
return node.renderNodeCount;
}
private updateNodeAfterFilterChange(node: IMutableTreeNode<T, TFilterData>): ITreeNode<T, TFilterData>[] {
const previousRenderNodeCount = node.renderNodeCount;
const result: ITreeNode<T, TFilterData>[] = [];
this._updateNodeAfterFilterChange(node, node.visible ? TreeVisibility.Visible : TreeVisibility.Hidden, result);
this._updateAncestorsRenderNodeCount(node.parent, result.length - previousRenderNodeCount);
return result;
}
private _updateNodeAfterFilterChange(node: IMutableTreeNode<T, TFilterData>, parentVisibility: TreeVisibility, result: ITreeNode<T, TFilterData>[], revealed = true): boolean {
let visibility: TreeVisibility;
if (node !== this.root) {
visibility = this._filterNode(node, parentVisibility);
if (visibility === TreeVisibility.Hidden) {
node.visible = false;
return false;
}
if (revealed) {
result.push(node);
}
}
const resultStartLength = result.length;
node.renderNodeCount = node === this.root ? 0 : 1;
let hasVisibleDescendants = false;
if (!node.collapsed || visibility! !== TreeVisibility.Hidden) {
for (const child of node.children) {
hasVisibleDescendants = this._updateNodeAfterFilterChange(child, visibility!, result, revealed && !node.collapsed) || hasVisibleDescendants;
}
}
if (node !== this.root) {
node.visible = visibility! === TreeVisibility.Recurse ? hasVisibleDescendants : (visibility! === TreeVisibility.Visible);
}
if (!node.visible) {
node.renderNodeCount = 0;
if (revealed) {
result.pop();
}
} else if (!node.collapsed) {
node.renderNodeCount += result.length - resultStartLength;
}
this._onDidChangeRenderNodeCount.fire(node);
return node.visible;
}
private _updateAncestorsRenderNodeCount(node: IMutableTreeNode<T, TFilterData> | undefined, diff: number): void {
if (diff === 0) {
return;
}
while (node) {
node.renderNodeCount += diff;
this._onDidChangeRenderNodeCount.fire(node);
node = node.parent;
}
}
private _filterNode(node: IMutableTreeNode<T, TFilterData>, parentVisibility: TreeVisibility): TreeVisibility {
const result = this.filter ? this.filter.filter(node.element, parentVisibility) : TreeVisibility.Visible;
if (typeof result === 'boolean') {
node.filterData = undefined;
return result ? TreeVisibility.Visible : TreeVisibility.Hidden;
} else if (isFilterResult<TFilterData>(result)) {
node.filterData = result.data;
return getVisibleState(result.visibility);
} else {
node.filterData = undefined;
return getVisibleState(result);
}
}
// cheap
private getTreeNode(location: number[], node: IMutableTreeNode<T, TFilterData> = this.root): IMutableTreeNode<T, TFilterData> {
if (!location || location.length === 0) {
return node;
}
const [index, ...rest] = location;
if (index < 0 || index > node.children.length) {
throw new Error('Invalid tree location');
}
return this.getTreeNode(rest, node.children[index]);
}
// expensive
private getTreeNodeWithListIndex(location: number[]): { node: IMutableTreeNode<T, TFilterData>, listIndex: number, revealed: boolean } {
const { parentNode, listIndex, revealed } = this.getParentNodeWithListIndex(location);
const index = location[location.length - 1];
if (index < 0 || index > parentNode.children.length) {
throw new Error('Invalid tree location');
}
const node = parentNode.children[index];
return { node, listIndex, revealed };
}
private getParentNodeWithListIndex(location: number[], node: IMutableTreeNode<T, TFilterData> = this.root, listIndex: number = 0, revealed = true): { parentNode: IMutableTreeNode<T, TFilterData>; listIndex: number; revealed: boolean; } {
const [index, ...rest] = location;
if (index < 0 || index > node.children.length) {
throw new Error('Invalid tree location');
}
// TODO@joao perf!
for (let i = 0; i < index; i++) {
listIndex += node.children[i].renderNodeCount;
}
revealed = revealed && !node.collapsed;
if (rest.length === 0) {
return { parentNode: node, listIndex, revealed };
}
return this.getParentNodeWithListIndex(rest, node.children[index], listIndex + 1, revealed);
}
getNode(location: number[] = []): ITreeNode<T, TFilterData> {
return this.getTreeNode(location);
}
// TODO@joao perf!
getNodeLocation(node: ITreeNode<T, TFilterData>): number[] {
const location: number[] = [];
while (node.parent) {
location.push(node.parent.children.indexOf(node));
node = node.parent;
}
return location.reverse();
}
getParentNodeLocation(location: number[]): number[] {
if (location.length <= 1) {
return [];
}
return tail2(location)[0];
}
getParentElement(location: number[]): T {
const parentLocation = this.getParentNodeLocation(location);
const node = this.getTreeNode(parentLocation);
return node.element;
}
getFirstElementChild(location: number[]): T | undefined {
const node = this.getTreeNode(location);
if (node.children.length === 0) {
return undefined;
}
return node.children[0].element;
}
getLastElementAncestor(location: number[] = []): T | undefined {
const node = this.getTreeNode(location);
if (node.children.length === 0) {
return undefined;
}
return this._getLastElementAncestor(node);
}
private _getLastElementAncestor(node: ITreeNode<T, TFilterData>): T {
if (node.children.length === 0) {
return node.element;
}
return this._getLastElementAncestor(node.children[node.children.length - 1]);
}
} | DustinCampbell/vscode | src/vs/base/browser/ui/tree/indexTreeModel.ts | TypeScript | mit | 14,919 |
<?php
declare(strict_types=1);
/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\AdminBundle\Tests\Action;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Sonata\AdminBundle\Action\GetShortObjectDescriptionAction;
use Sonata\AdminBundle\Action\SetObjectFieldValueAction;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Admin\FieldDescriptionInterface;
use Sonata\AdminBundle\Admin\Pool;
use Sonata\AdminBundle\Model\ModelManagerInterface;
use Sonata\AdminBundle\Templating\TemplateRegistryInterface;
use Sonata\AdminBundle\Twig\Extension\SonataAdminExtension;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Environment;
use Twig\Loader\ArrayLoader;
final class SetObjectFieldValueActionTest extends TestCase
{
/**
* @var Pool
*/
private $pool;
/**
* @var Environment
*/
private $twig;
/**
* @var GetShortObjectDescriptionAction
*/
private $action;
/**
* @var AbstractAdmin
*/
private $admin;
/**
* @var ValidatorInterface
*/
private $validator;
protected function setUp(): void
{
$this->twig = new Environment(new ArrayLoader([
'admin_template' => 'renderedTemplate',
'field_template' => 'renderedTemplate',
]));
$this->pool = $this->prophesize(Pool::class);
$this->admin = $this->prophesize(AbstractAdmin::class);
$this->pool->getInstance(Argument::any())->willReturn($this->admin->reveal());
$this->admin->setRequest(Argument::type(Request::class))->shouldBeCalled();
$this->validator = $this->prophesize(ValidatorInterface::class);
$this->action = new SetObjectFieldValueAction(
$this->twig,
$this->pool->reveal(),
$this->validator->reveal()
);
}
public function testSetObjectFieldValueAction(): void
{
$object = new Foo();
$request = new Request([
'code' => 'sonata.post.admin',
'objectId' => 42,
'field' => 'enabled',
'value' => 1,
'context' => 'list',
], [], [], [], [], ['REQUEST_METHOD' => Request::METHOD_POST, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);
$fieldDescription = $this->prophesize(FieldDescriptionInterface::class);
$pool = $this->prophesize(Pool::class);
$translator = $this->prophesize(TranslatorInterface::class);
$propertyAccessor = new PropertyAccessor();
$templateRegistry = $this->prophesize(TemplateRegistryInterface::class);
$container = $this->prophesize(ContainerInterface::class);
$this->admin->getObject(42)->willReturn($object);
$this->admin->getCode()->willReturn('sonata.post.admin');
$this->admin->hasAccess('edit', $object)->willReturn(true);
$this->admin->getListFieldDescription('enabled')->willReturn($fieldDescription->reveal());
$this->admin->update($object)->shouldBeCalled();
$templateRegistry->getTemplate('base_list_field')->willReturn('admin_template');
$container->get('sonata.post.admin.template_registry')->willReturn($templateRegistry->reveal());
$this->pool->getPropertyAccessor()->willReturn($propertyAccessor);
$this->twig->addExtension(new SonataAdminExtension(
$pool->reveal(),
$translator->reveal(),
$container->reveal()
));
$fieldDescription->getOption('editable')->willReturn(true);
$fieldDescription->getAdmin()->willReturn($this->admin->reveal());
$fieldDescription->getType()->willReturn('boolean');
$fieldDescription->getTemplate()->willReturn('field_template');
$fieldDescription->getValue(Argument::cetera())->willReturn('some value');
$this->validator->validate($object)->willReturn(new ConstraintViolationList([]));
$response = ($this->action)($request);
$this->assertSame(Response::HTTP_OK, $response->getStatusCode());
}
public function getTimeZones(): iterable
{
$default = new \DateTimeZone(date_default_timezone_get());
$custom = new \DateTimeZone('Europe/Rome');
return [
'empty timezone' => [null, $default],
'disabled timezone' => [false, $default],
'default timezone by name' => [$default->getName(), $default],
'default timezone by object' => [$default, $default],
'custom timezone by name' => [$custom->getName(), $custom],
'custom timezone by object' => [$custom, $custom],
];
}
/**
* @dataProvider getTimeZones
*/
public function testSetObjectFieldValueActionWithDate($timezone, \DateTimeZone $expectedTimezone): void
{
$object = new Bafoo();
$request = new Request([
'code' => 'sonata.post.admin',
'objectId' => 42,
'field' => 'dateProp',
'value' => '2020-12-12',
'context' => 'list',
], [], [], [], [], ['REQUEST_METHOD' => Request::METHOD_POST, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);
$fieldDescription = $this->prophesize(FieldDescriptionInterface::class);
$pool = $this->prophesize(Pool::class);
$translator = $this->prophesize(TranslatorInterface::class);
$propertyAccessor = new PropertyAccessor();
$templateRegistry = $this->prophesize(TemplateRegistryInterface::class);
$container = $this->prophesize(ContainerInterface::class);
$this->admin->getObject(42)->willReturn($object);
$this->admin->getCode()->willReturn('sonata.post.admin');
$this->admin->hasAccess('edit', $object)->willReturn(true);
$this->admin->getListFieldDescription('dateProp')->willReturn($fieldDescription->reveal());
$this->admin->update($object)->shouldBeCalled();
$templateRegistry->getTemplate('base_list_field')->willReturn('admin_template');
$container->get('sonata.post.admin.template_registry')->willReturn($templateRegistry->reveal());
$this->pool->getPropertyAccessor()->willReturn($propertyAccessor);
$this->twig->addExtension(new SonataAdminExtension(
$pool->reveal(),
$translator->reveal(),
$container->reveal()
));
$fieldDescription->getOption('editable')->willReturn(true);
$fieldDescription->getOption('timezone')->willReturn($timezone);
$fieldDescription->getAdmin()->willReturn($this->admin->reveal());
$fieldDescription->getType()->willReturn('date');
$fieldDescription->getTemplate()->willReturn('field_template');
$fieldDescription->getValue(Argument::cetera())->willReturn('some value');
$this->validator->validate($object)->willReturn(new ConstraintViolationList([]));
$response = ($this->action)($request);
$this->assertSame(Response::HTTP_OK, $response->getStatusCode());
$defaultTimezone = new \DateTimeZone(date_default_timezone_get());
$expectedDate = new \DateTime($request->query->get('value'), $expectedTimezone);
$expectedDate->setTimezone($defaultTimezone);
$this->assertInstanceOf(\DateTime::class, $object->getDateProp());
$this->assertSame($expectedDate->format('Y-m-d'), $object->getDateProp()->format('Y-m-d'));
$this->assertSame($defaultTimezone->getName(), $object->getDateProp()->getTimezone()->getName());
}
public function testSetObjectFieldValueActionOnARelationField(): void
{
$object = new Baz();
$associationObject = new Bar();
$request = new Request([
'code' => 'sonata.post.admin',
'objectId' => 42,
'field' => 'bar',
'value' => 1,
'context' => 'list',
], [], [], [], [], ['REQUEST_METHOD' => Request::METHOD_POST, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);
$fieldDescription = $this->prophesize(FieldDescriptionInterface::class);
$modelManager = $this->prophesize(ModelManagerInterface::class);
$translator = $this->prophesize(TranslatorInterface::class);
$propertyAccessor = new PropertyAccessor();
$templateRegistry = $this->prophesize(TemplateRegistryInterface::class);
$container = $this->prophesize(ContainerInterface::class);
$this->admin->getObject(42)->willReturn($object);
$this->admin->getCode()->willReturn('sonata.post.admin');
$this->admin->hasAccess('edit', $object)->willReturn(true);
$this->admin->getListFieldDescription('bar')->willReturn($fieldDescription->reveal());
$this->admin->getClass()->willReturn(\get_class($object));
$this->admin->update($object)->shouldBeCalled();
$container->get('sonata.post.admin.template_registry')->willReturn($templateRegistry->reveal());
$templateRegistry->getTemplate('base_list_field')->willReturn('admin_template');
$this->admin->getModelManager()->willReturn($modelManager->reveal());
$this->twig->addExtension(new SonataAdminExtension(
$this->pool->reveal(),
$translator->reveal(),
$container->reveal()
));
$this->pool->getPropertyAccessor()->willReturn($propertyAccessor);
$fieldDescription->getType()->willReturn('choice');
$fieldDescription->getOption('editable')->willReturn(true);
$fieldDescription->getOption('class')->willReturn(Bar::class);
$fieldDescription->getTargetModel()->willReturn(Bar::class);
$fieldDescription->getAdmin()->willReturn($this->admin->reveal());
$fieldDescription->getTemplate()->willReturn('field_template');
$fieldDescription->getValue(Argument::cetera())->willReturn('some value');
$modelManager->find(\get_class($associationObject), 1)->willReturn($associationObject);
$this->validator->validate($object)->willReturn(new ConstraintViolationList([]));
$response = ($this->action)($request);
$this->assertSame(Response::HTTP_OK, $response->getStatusCode());
}
public function testSetObjectFieldValueActionWithViolations(): void
{
$bar = new Bar();
$object = new Baz();
$object->setBar($bar);
$request = new Request([
'code' => 'sonata.post.admin',
'objectId' => 42,
'field' => 'bar.enabled',
'value' => 1,
'context' => 'list',
], [], [], [], [], ['REQUEST_METHOD' => Request::METHOD_POST, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);
$fieldDescription = $this->prophesize(FieldDescriptionInterface::class);
$propertyAccessor = new PropertyAccessor();
$this->pool->getPropertyAccessor()->willReturn($propertyAccessor);
$this->admin->getObject(42)->willReturn($object);
$this->admin->hasAccess('edit', $object)->willReturn(true);
$this->admin->getListFieldDescription('bar.enabled')->willReturn($fieldDescription->reveal());
$this->validator->validate($bar)->willReturn(new ConstraintViolationList([
new ConstraintViolation('error1', null, [], null, 'enabled', null),
new ConstraintViolation('error2', null, [], null, 'enabled', null),
]));
$fieldDescription->getOption('editable')->willReturn(true);
$fieldDescription->getType()->willReturn('boolean');
$response = ($this->action)($request);
$this->assertSame(Response::HTTP_BAD_REQUEST, $response->getStatusCode());
$this->assertSame(json_encode("error1\nerror2"), $response->getContent());
}
public function testSetObjectFieldEditableMultipleValue(): void
{
$object = new StatusMultiple();
$request = new Request([
'code' => 'sonata.post.admin',
'objectId' => 42,
'field' => 'status',
'value' => [1, 2],
'context' => 'list',
], [], [], [], [], ['REQUEST_METHOD' => Request::METHOD_POST, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);
$fieldDescription = $this->prophesize(FieldDescriptionInterface::class);
$pool = $this->prophesize(Pool::class);
$template = $this->prophesize(Template::class);
$translator = $this->prophesize(TranslatorInterface::class);
$propertyAccessor = new PropertyAccessor();
$templateRegistry = $this->prophesize(TemplateRegistryInterface::class);
$container = $this->prophesize(ContainerInterface::class);
$this->admin->getObject(42)->willReturn($object);
$this->admin->getCode()->willReturn('sonata.post.admin');
$this->admin->hasAccess('edit', $object)->willReturn(true);
$this->admin->getListFieldDescription('status')->willReturn($fieldDescription->reveal());
$this->admin->update($object)->shouldBeCalled();
$templateRegistry->getTemplate('base_list_field')->willReturn('admin_template');
$container->get('sonata.post.admin.template_registry')->willReturn($templateRegistry->reveal());
$this->pool->getPropertyAccessor()->willReturn($propertyAccessor);
$this->twig->addExtension(new SonataAdminExtension(
$pool->reveal(),
$translator->reveal(),
$container->reveal()
));
$fieldDescription->getOption('editable')->willReturn(true);
$fieldDescription->getOption('multiple')->willReturn(true);
$fieldDescription->getAdmin()->willReturn($this->admin->reveal());
$fieldDescription->getType()->willReturn('boolean');
$fieldDescription->getTemplate()->willReturn('field_template');
$fieldDescription->getValue(Argument::cetera())->willReturn(['some value']);
$this->validator->validate($object)->willReturn(new ConstraintViolationList([]));
$response = ($this->action)($request);
$this->assertSame(Response::HTTP_OK, $response->getStatusCode());
}
}
| jordisala1991/SonataAdminBundle | tests/Action/SetObjectFieldValueActionTest.php | PHP | mit | 14,552 |
module.exports={
"file":1, // fname, mode, contents
"filedelete":2, // fname
"checkout":3, // fname
"checkin":4, // fname
"ping":5, // -
"pong":6, // -
"edit":{
"open":100, // fname
"close":101, // fname
"open_ok":102, // fname
"open_err":103, // fname
"close_ok":104, // fname
"close_err":105 // fname
}
};
| tomsmeding/gvajnez | msgtype.js | JavaScript | mit | 329 |
package com.mines.main;
import com.mines.domain.enums.BoardSize;
import com.mines.domain.enums.Difficulty;
public class MineField{
private int[][] field;
private BoardSize size;
private Difficulty diff;
private int nrMines = 0;
public MineField(){
diff = Difficulty.EASY;
size = BoardSize.MEDIUM;
neww();
}
public MineField(Difficulty d, BoardSize s){
diff = d;
size = s;
neww();
}
public void neww(String...args){
if (args.length == 2){
size = BoardSize.valueOf(args[0].toUpperCase());
diff = Difficulty.valueOf(args[1].toUpperCase());
}
nrMines = 0;
generateMines();
setSafeSpots();
}
public int[][] getField(){
return field;
}
public int getSize(){
return size.getSize();
}
public int getNrMines(){
return nrMines;
}
/** PRIVATE **/
private void generateMines(){
int sizeInt = size.getSize();
field = new int[sizeInt][sizeInt];
for(int i=0; i < sizeInt; i++){
for(int j=0; j < sizeInt; j++){
field[i][j] = randBoolByDifficulty() ? -1 : 0;
}
}
}
private void setSafeSpots(){
int sizeInt = size.getSize();
for(int i=0; i < sizeInt; i++){
for(int j=0; j < sizeInt; j++){
if(field[i][j] != -1) field[i][j] = getNeighbors(i,j);
}
}
}
private boolean randBoolByDifficulty(){
if ((Math.random() * (size.getSize() * diff.getDiff())) < size.getSize()){
nrMines++; return true;
}
else return false;
}
private int getNeighbors(int i, int j){
int val = 0;
for (int k = i-1; k <= i+1; k++){
for (int l = j-1; l <= j+1; l++){
try{
if(field[k][l] == -1) val++;
}catch(ArrayIndexOutOfBoundsException e){}
}
}
return val;
}
}
| tonycatapano/JMinesField | src/main/java/com/mines/main/MineField.java | Java | mit | 1,804 |
// Decompiled with JetBrains decompiler
// Type: System.Fabric.Management.ServiceModel.ApplicationPoliciesType
// Assembly: System.Fabric.Management.ServiceModel, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
// MVID: C6D32D4D-966E-4EA3-BD3A-F4CF14D36DBC
// Assembly location: C:\Git\ServiceFabricSdkContrib\ServiceFabricSdkContrib.MsBuild\bin\Debug\netstandard2.0\publish\runtimes\win\lib\netstandard2.0\System.Fabric.Management.ServiceModel.dll
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Xml.Serialization;
namespace System.Fabric.Management.ServiceModel
{
[GeneratedCode("xsd", "4.0.30319.17929")]
[DebuggerStepThrough]
[XmlType(Namespace = "http://schemas.microsoft.com/2011/01/fabric")]
public class ApplicationPoliciesType
{
private ApplicationPoliciesTypeLogCollectionPolicies logCollectionPoliciesField;
private ApplicationPoliciesTypeDefaultRunAsPolicy defaultRunAsPolicyField;
private ApplicationHealthPolicyType healthPolicyField;
private ApplicationPoliciesTypeSecurityAccessPolicies securityAccessPoliciesField;
public ApplicationPoliciesTypeLogCollectionPolicies LogCollectionPolicies
{
get
{
return this.logCollectionPoliciesField;
}
set
{
this.logCollectionPoliciesField = value;
}
}
public ApplicationPoliciesTypeDefaultRunAsPolicy DefaultRunAsPolicy
{
get
{
return this.defaultRunAsPolicyField;
}
set
{
this.defaultRunAsPolicyField = value;
}
}
public ApplicationHealthPolicyType HealthPolicy
{
get
{
return this.healthPolicyField;
}
set
{
this.healthPolicyField = value;
}
}
public ApplicationPoliciesTypeSecurityAccessPolicies SecurityAccessPolicies
{
get
{
return this.securityAccessPoliciesField;
}
set
{
this.securityAccessPoliciesField = value;
}
}
}
}
| aL3891/ServiceFabricSdkContrib | System.Fabric.Management.ServiceModel/ApplicationPoliciesType.cs | C# | mit | 2,017 |
# Django settings for obi project.
from os.path import abspath, dirname
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
# Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'ENGINE': 'django.db.backends.',
# Or path to database file if using sqlite3.
'NAME': '',
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
# Empty for localhost through domain sockets or '127.0.0.1'
# for localhost through TCP.
'HOST': '',
# Set to empty string for default.
'PORT': '',
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/New_York'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = dirname(dirname(abspath(__file__))) + '/static'
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '6(5f^qra2a%%(iok=0ktz)xnhx(-f7df3q(tuva4*0dz3c^ug4'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
)
ROOT_URLCONF = 'obi.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'obi.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or
# "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.humanize',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'south',
'ui',
)
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
# Be sure to create your own 'local_settings.py' file as described in README
try:
from local_settings import *
except ImportError:
pass
| adityadharne/TestObento | obi/obi/settings.py | Python | mit | 6,014 |
var Cheerleaders = angular.module('Cheerleaders', [ 'ngRoute', 'ngDragDrop', 'angularjs-dropdown-multiselect']);
Cheerleaders.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'partials/index.html',
controller: 'routineIndexController',
access: {restricted: true}
})
.when('/login', {
templateUrl: 'partials/login.html',
controller: 'loginController',
access: {restricted: false}
})
.when('/logout', {
controller: 'logoutController',
access: {restricted: true}
})
.when('/register', {
templateUrl: 'partials/register.html',
controller: 'registerController',
access: {restricted: false}
}).when('/routine/:id', {
templateUrl: 'partials/routineViewer.html',
controller: 'routineController',
access: {restricted: true}
}).when('/config', {
templateUrl : 'partials/config.html',
controller: 'routineController',
access: {restricted: true}
})
.otherwise({
redirectTo: '/'
});
});
Cheerleaders.run(function ($rootScope, $location, $route, AuthService) {
//console.log($rootScope);
//console.log($location);
//console.log($route);
//console.log(AuthService);
$rootScope.$on('$routeChangeStart',
function (event, next, current) {
AuthService.getUserStatus()
.then(function(){
if (next.access.restricted && !AuthService.isLoggedIn()){
$location.path('/login');
$route.reload();
}
});
});
}); | richard-mack/cheer-planner | client/app.js | JavaScript | mit | 1,525 |
require 'cocaine'
require 'English'
require 'time'
require_relative 'result'
require_relative 'error'
class LittleneckClamAV
class Clam
def engine
version[:engine] if available?
end
def database_version
version[:database_version].to_i if available?
end
def database_date
Time.parse(version[:database_date]) if available?
end
def available?
version[:success]
end
def scan(path)
check_scan! path
opts = { swallow_stderr: true, expected_outcodes: [0, 1] }
params = ['--no-summary', %("#{path}")].join(' ')
output = Cocaine::CommandLine.new(command, params, opts).run
parse_result path, output, $CHILD_STATUS.exitstatus
end
def command
'clamscan'
end
private
def version
@version ||= begin
opts = { swallow_stderr: true }
params = '--version'
output = Cocaine::CommandLine.new(command, params, opts).run.strip
parse_output(output)
rescue Cocaine::ExitStatusError, Cocaine::CommandNotFoundError => e
{ error: e.message, success: false }
end
end
def parse_output(output)
engine, db_version, db_date = output.sub(/^ClamAV /, '').split('/', 3)
success = !(db_version && db_date).nil?
{
output: output,
engine: engine,
database_version: db_version,
database_date: db_date,
success: success
}
end
def parse_result(path, output, _code)
clean = $CHILD_STATUS.exitstatus == 0
description = output.split(':').last.strip
description.sub! ' FOUND', ''
Result.new path: path, clean: clean, description: description
end
def check_scan!(path)
exists = File.exist? path
if !exists
fail Error, "the path #{path} does not exist"
elsif !available?
message = "#{self.class} is not available"
message << "because #{version[:message]}" if version[:message]
fail Error, message
end
end
end
end
| theozaurus/littleneck_clamav | lib/littleneck_clamav/clam.rb | Ruby | mit | 2,029 |
using System;
using System.Threading.Tasks;
using work.bacome.async;
using work.bacome.imapclient.support;
using work.bacome.trace;
namespace work.bacome.imapclient
{
public partial class cIMAPClient
{
internal cMessageHandleList SetUnseenCount(iMailboxHandle pMailboxHandle)
{
var lContext = mRootContext.NewMethod(nameof(cIMAPClient), nameof(Messages));
var lTask = ZSetUnseenCountAsync(pMailboxHandle, lContext);
mSynchroniser.Wait(lTask, lContext);
return lTask.Result;
}
internal Task<cMessageHandleList> SetUnseenCountAsync(iMailboxHandle pMailboxHandle)
{
var lContext = mRootContext.NewMethod(nameof(cIMAPClient), nameof(MessagesAsync));
return ZSetUnseenCountAsync(pMailboxHandle, lContext);
}
private async Task<cMessageHandleList> ZSetUnseenCountAsync(iMailboxHandle pMailboxHandle, cTrace.cContext pParentContext)
{
var lContext = pParentContext.NewMethod(nameof(cIMAPClient), nameof(ZMessagesAsync), pMailboxHandle);
if (mDisposed) throw new ObjectDisposedException(nameof(cIMAPClient));
var lSession = mSession;
if (lSession == null || lSession.ConnectionState != eConnectionState.selected) throw new InvalidOperationException(kInvalidOperationExceptionMessage.NotSelected);
if (pMailboxHandle == null) throw new ArgumentNullException(nameof(pMailboxHandle));
var lCapabilities = lSession.Capabilities;
using (var lToken = mCancellationManager.GetToken(lContext))
{
var lMC = new cMethodControl(mTimeout, lToken.CancellationToken);
if (lCapabilities.ESearch) return await lSession.SetUnseenCountExtendedAsync(lMC, pMailboxHandle, lContext).ConfigureAwait(false);
else return await lSession.SetUnseenCountAsync(lMC, pMailboxHandle, lContext).ConfigureAwait(false);
}
}
}
} | bacome/imapclient | imapclient/imapclient/client/setunseencount.cs | C# | mit | 2,008 |
import assert from "assert";
import BufSamples from "../../../src/scapi/units/BufSamples";
describe("scapi/units/BufSamples", () => {
it(".kr should create control rate node", () => {
const node = BufSamples.kr(1);
assert.deepEqual(node, {
type: "BufSamples", rate: "control", props: [ 1 ]
});
});
it(".ir should create scalar rate node", () => {
const node = BufSamples.ir(1);
assert.deepEqual(node, {
type: "BufSamples", rate: "scalar", props: [ 1 ]
});
});
it("default rate is control", () => {
const node = BufSamples();
assert.deepEqual(node, {
type: "BufSamples", rate: "control", props: [ 0 ]
});
});
});
| mohayonao/neume | test/scapi/units/BufSamples.js | JavaScript | mit | 684 |
<?php
namespace AerialShip\SteelMqBundle\Entity;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* @ORM\Entity(repositoryClass="AerialShip\SteelMqBundle\Entity\Repository\UserRepository")
* @ORM\Table(name="smq_user")
*/
class User implements UserInterface, \Serializable
{
const ROLE_USER = 'ROLE_USER';
const ROLE_ADMIN = 'ROLE_ADMIN';
const ROLE_SUPER_ADMIN = 'ROLE_SUPER_ADMIN';
const ROLE_DEFAULT = self::ROLE_USER;
private static $allRoles = array(
self::ROLE_USER => 1,
self::ROLE_ADMIN => 1,
self::ROLE_SUPER_ADMIN => 1,
);
/**
* @param string $role
*
* @return bool
*/
public static function isValidRole($role)
{
return isset(self::$allRoles[$role]);
}
/**
* @var int
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
protected $id;
/**
* @var string
* @ORM\Column(type="string", length=100, unique=true)
*/
protected $email;
/**
* @var string
* @ORM\Column(type="string", length=100)
*/
protected $name;
/**
* @var \DateTime
* @ORM\Column(type="datetime")
*/
protected $createdAt;
/**
* @var \DateTime|null
* @ORM\Column(type="datetime", nullable=true)
*/
protected $lastLogin;
/**
* @var string|null
*/
protected $plainPassword;
/**
* @var string
* @ORM\Column(type="text")
*/
protected $salt;
/**
* @var string
* @ORM\Column(type="text")
*/
protected $password;
/**
* @var array
* @ORM\Column(type="array")
*/
protected $roles = array();
/**
* @var string
* @ORM\Column(type="string", length=64)
*/
protected $accessToken;
/**
* @var string|null
* @ORM\Column(type="string", length=64, nullable=true)
*/
protected $passwordToken;
/**
* @var \DateTime|null
* @ORM\Column(type="datetime", nullable=true)
*/
protected $passwordRequestAt;
/**
* @var string
* @ORM\Column(type="string", length=16)
*/
protected $locale = 'en';
/**
* @var string
* @ORM\Column(type="string", length=32)
*/
protected $timezone = 'Europe/Oslo';
/**
* @var string
* @ORM\Column(type="string", length=200, nullable=true)
*/
protected $pictureUrl;
/**
* @var ProjectRole[]|ArrayCollection
* @ORM\OneToMany(
* targetEntity="ProjectRole",
* mappedBy="user",
* orphanRemoval=true,
* cascade={"remove"},
* fetch="EXTRA_LAZY"
* )
*/
protected $projectRoles;
/**
*
*/
public function __construct()
{
$this->createdAt = new \DateTime();
$this->projectRoles = new ArrayCollection();
$this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
}
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @return string
*/
public function getLocale()
{
return $this->locale;
}
/**
* @param string $locale
* @return $this|User
*/
public function setLocale($locale)
{
$this->locale = $locale;
return $this;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
* @return $this|User
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* @param string $email
* @return $this|User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @param \DateTime $createdAt
* @return $this|User
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* @return \DateTime|null
*/
public function getLastLogin()
{
return $this->lastLogin;
}
/**
* @param \DateTime|null $lastLogin
* @return $this|User
*/
public function setLastLogin($lastLogin)
{
$this->lastLogin = $lastLogin;
return $this;
}
/**
* @return null|string
*/
public function getPlainPassword()
{
return $this->plainPassword;
}
/**
* @param null|string $plainPassword
* @return $this|User
*/
public function setPlainPassword($plainPassword)
{
$this->plainPassword = $plainPassword;
return $this;
}
/**
* @return string
*/
public function getTimezone()
{
return $this->timezone;
}
/**
* @param string $timezone
* @return $this|User
*/
public function setTimezone($timezone)
{
$this->timezone = $timezone;
return $this;
}
/**
* @return string
*/
public function getPictureUrl()
{
return $this->pictureUrl;
}
/**
* @param string $pictureUrl
* @return $this|User
*/
public function setPictureUrl($pictureUrl)
{
$this->pictureUrl = $pictureUrl;
return $this;
}
/**
* @return null|string
*/
public function getAccessToken()
{
return $this->accessToken;
}
/**
* @param string $accessToken
* @return $this|User
*/
public function setAccessToken($accessToken)
{
$this->accessToken = $accessToken;
return $this;
}
/**
* @return \DateTime|null
*/
public function getPasswordRequestAt()
{
return $this->passwordRequestAt;
}
/**
* @param \DateTime|null $passwordRequestAt
* @return $this|User
*/
public function setPasswordRequestAt(\DateTime $passwordRequestAt = null)
{
$this->passwordRequestAt = $passwordRequestAt;
return $this;
}
/**
* @return null|string
*/
public function getPasswordToken()
{
return $this->passwordToken;
}
/**
* @param null|string $passwordToken
* @return $this|User
*/
public function setPasswordToken($passwordToken)
{
$this->passwordToken = $passwordToken;
return $this;
}
/**
* @return ProjectRole[]|ArrayCollection
*/
public function getProjectRoles()
{
return $this->projectRoles;
}
/**
* @param string $role
* @return User|$this
*/
public function addRole($role)
{
$role = strtoupper($role);
if ($role === self::ROLE_DEFAULT) {
return $this;
}
if (false == in_array($role, $this->roles, true)) {
$this->roles[] = $role;
}
return $this;
}
/**
* @param string $role
* @return User|$this
*/
public function removeRole($role)
{
if (false !== $key = array_search(strtoupper($role), $this->roles, true)) {
unset($this->roles[$key]);
$this->roles = array_values($this->roles);
}
return $this;
}
/**
* @param array $roles
* @return $this|User
*/
public function setRoles(array $roles)
{
$this->roles = $roles;
return $this;
}
/**
* @param string $password
* @return $this|User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* @param string $salt
* @return $this|User
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
// UserInterface ------------------------------------------------------------
/**
* Returns the roles granted to the user.
*
* <code>
* public function getRoles()
* {
* return array('ROLE_USER');
* }
* </code>
*
* Alternatively, the roles might be stored on a ``roles`` property,
* and populated in any number of different ways when the user object
* is created.
*
* @return Role[] The user roles
*/
public function getRoles()
{
$roles = $this->roles;
// we need to make sure to have at least one role
$roles[] = self::ROLE_DEFAULT;
return array_unique($roles);
}
/**
* Returns the password used to authenticate the user.
*
* This should be the encoded password. On authentication, a plain-text
* password will be salted, encoded, and then compared to this value.
*
* @return string The password
*/
public function getPassword()
{
return $this->password;
}
/**
* Returns the salt that was originally used to encode the password.
*
* This can return null if the password was not encoded using a salt.
*
* @return string|null The salt
*/
public function getSalt()
{
return $this->salt;
}
/**
* Returns the username used to authenticate the user.
*
* @return string The username
*/
public function getUsername()
{
return $this->email;
}
/**
* Removes sensitive data from the user.
*
* This is important if, at any given point, sensitive information like
* the plain-text password is stored on this object.
*/
public function eraseCredentials()
{
$this->plainPassword = null;
}
// Serializable ----------------------------------------------------------------------
/**
* (PHP 5 >= 5.1.0)<br/>
* String representation of object
* @link http://php.net/manual/en/serializable.serialize.php
* @return string the string representation of the object or null
*/
public function serialize()
{
return serialize(array(
$this->id,
$this->email,
$this->name,
$this->locale,
$this->timezone,
$this->pictureUrl,
$this->roles,
));
}
/**
* (PHP 5 >= 5.1.0)<br/>
* Constructs the object
* @link http://php.net/manual/en/serializable.unserialize.php
* @param string $serialized <p>
* The string representation of the object.
* </p>
* @return void
*/
public function unserialize($serialized)
{
$data = unserialize($serialized);
// add a few extra elements in the array to ensure that we have enough keys when unserializing
// older data which does not include all properties.
$data = array_merge($data, array_fill(0, 2, null));
list(
$this->id,
$this->email,
$this->name,
$this->locale,
$this->timezone,
$this->pictureUrl,
$this->roles
) = $data;
}
}
| aerialship/steel-mq | src/AerialShip/SteelMqBundle/Entity/User.php | PHP | mit | 11,457 |
<?php
namespace GuildWars2\Api\Entity;
use GuildWars2\Api\SetEntityBase;
abstract class ItemInfoBase extends SetEntityBase
{
private $_itemId;
private $_amount;
private $_skinId;
private $_upgradeIds;
private $_infusionIds;
private $_bindType;
private $_boundCharacterName;
protected function init()
{
$this->_itemId = null;
$this->_amount = null;
$this->_skinId = null;
$this->_upgradeIds = [];
$this->_infusionIds = [];
$this->_bindType = null;
$this->_boundCharacterName = null;
}
/**
* @return mixed
*/
public function getItemId()
{
return $this->_itemId;
}
/**
* @return Item
*/
public function getItem()
{
return $this->getApi()->items->getOne($this->_itemId);
}
/**
* @return mixed
*/
public function getAmount()
{
return $this->_amount;
}
/**
* @return mixed
*/
public function getSkinId()
{
return $this->_skinId;
}
/**
* @return mixed
*/
public function getUpgradeIds()
{
return $this->_upgradeIds;
}
/**
* @return mixed
*/
public function getInfusionIds()
{
return $this->_infusionIds;
}
/**
* @return mixed
*/
public function getBindType()
{
return $this->_bindType;
}
/**
* @return mixed
*/
public function getBoundCharacterName()
{
return $this->_boundCharacterName;
}
protected function set($key, $value)
{
switch ($key) {
case 'id':
$this->_itemId = intval($value);
break;
case 'count':
$this->_amount = $value;
break;
case 'skin':
$this->_skinId = $value;
break;
case 'upgrades':
$this->_upgradeIds = array_map('intval', $value);
break;
case 'infusions':
$this->_infusionIds = array_map('intval', $value);
break;
case 'binding':
$this->_bindType = $value;
break;
case 'bound_to':
$this->_boundCharacterName = $value;
break;
}
}
} | TorbenKoehn/gw2-php | Api/Entity/ItemInfoBase.php | PHP | mit | 2,373 |
#pragma once
/* LightedMaterial.hpp
*
* Copyright (C) 2017 Dynamic Reflectance
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
//std
#include <string>
#include <vector>
namespace core {
namespace utils {
std::vector<std::string> tokenize(const std::string& a_data,
const std::vector<char>& a_white_spaces,
const std::vector<char>& a_separators);
} // namespace utils
} // namespace core | dynamicreflectance/core | utils/source/Tokenizer.hpp | C++ | mit | 558 |
import { combineReducers } from 'redux';
import { routerReducer as routing } from 'react-router-redux';
import account from '../reducers/account';
import authentication from '../reducers/authentication';
import user from '../reducers/user';
import modelPortfolio from '../reducers/modelPortfolio';
import portfolio from '../reducers/portfolio';
import investmentAmount from '../reducers/investmentAmount';
import message from '../reducers/message';
import rebalancing from '../reducers/rebalancing';
import view from '../reducers/view';
import * as types from '../types';
const isFetching = (state = false, action) => {
switch (action.type) {
case types.CREATE_REQUEST:
return true;
case types.REQUEST_SUCCESS:
case types.REQUEST_FAILURE:
return false;
default:
return state;
}
};
const rootReducer = combineReducers({
isFetching,
authentication,
account,
modelPortfolio,
portfolio,
user,
investmentAmount,
message,
rebalancing,
view,
routing,
});
export default rootReducer;
| AlexisDeschamps/portfolio-rebalancer | app/reducers/index.js | JavaScript | mit | 1,039 |
var mongo = require('mongodb');
var fs = require('fs');
var path = require("path");
var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('vivudb', server);
function getExtPart(str){
var n=str.split(".");
return n[n.length - 1];
}
function getNamePart(str){
var n=str.split(".");
return n[0];
}
function removeSubstring(str,strrm){
var newstr = str.replace(strrm,"");
return newstr;
}
exports.uploadAudio = function(req, res){
var addInbox = function(inbox) {
console.log("Starting add Inbox: ");
console.log(inbox);
console.log(inbox.UserID);
var gcm = new GLOBAL.GCMessage;
var saveInbox = function( ){
db.collection('inboxs', function(err, collection) {
collection.insert(inbox, {safe:true}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred'});
}
else{
console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
}); // end Inbox collection
}
var findDeviceByUserIdAndSend = function (id) {
console.log("findDeviceByUserIdAndSend");
console.log('Retrieving all devices by user id: ' + id);
// get all device by userId
db.collection('devices', function(err, collection) {
collection.find({'UserID':id.toString()}).toArray(function(err, items) {
var ltsDevicesIds = [];
for(var i = 0;i <items.length;i++){
ltsDevicesIds.push(items[i].DeviceID);
}
gcm.addRegIdList(ltsDevicesIds);
gcm.addMessageData("inbox",inbox);
gcm.send( );
saveInbox( );
}); // end device collection
});
}
// step 2.1
var increaseNoInbox = function (noCfs) {
// increase Inbox Id
console.log("increaseNoInbox");
inbox.InboxID = ++noCfs;
findDeviceByUserIdAndSend(inbox.UserID);
}
// step 2.2
var userUnknown = function( ) {
console.log("userUnknown");
res.send({'unknown':'There are no user in this system'});
}
// step 1
var getNoCfsByUserId = function(userid){
try{
console.log("getNoCfsByUserId: "+ userid);
db.collection('users', function(err, users) {
users.findOne({'UserID':userid}, function(err, item) {
if(item != null){
item.noCfs++;
users.save(item);
increaseNoInbox(item.noCfs);
}
else{
userUnknown();
}
});
});
}
catch(e){
console.log("Error at getNoCfsByUserId");
}
}
getNoCfsByUserId(inbox.UserID);
}// end add inbox function
var inbox = JSON.parse(req.body.json);
console.log("json: ");
console.log(inbox);
//update Inbox
var updateInbox = function(seqNo){
try{
var link = GLOBAL.HOSTNAME + "/cfs/audio/"+seqNo;
inbox.ContentVoice = link;
addInbox(inbox);
}
catch(e){
console.log("error in updateInbox in uploadAudio ");
res.send({error:"Error from server"});
}
}
var saveAudio = function(seqNo){
console.log('Adding New Audio');
staticDir = removeSubstring(GLOBAL.__dirname,"/vivuserver/trunk");
//var audioDir = GLOBAL.__dirname + "/public/audio/";
var audioDir = staticDir + "/staticserver/public/audio/";
console.log("audio Dir: "+audioDir);
//var fileName = req.files.source.name;
var fileName = seqNo+"."+getExtPart(req.files.source.name);
console.log("source: "+req.files.source.path);
console.log("dest: "+audioDir + fileName);
fs.rename(req.files.source.path,
audioDir + fileName,
function(err){
if(err != null){
console.log("Server cant rename");
console.log(err);
res.send({error:"Error from server"});
}
else{
console.log("Success rename");
var soundlib = new GLOBAL.Sound;
var sourcepart = getNamePart(fileName);
soundlib.convertWavToMp3(audioDir + fileName,audioDir + sourcepart+".mp3",function( ){
fs.unlink(audioDir + fileName,function(err){
console.log("Error delete file: " + err);
});
});
updateInbox(seqNo);
res.send("Ok");
}
}
);
}
var insertSequence = function( ){
var sequences = {sequenceNo:1};
db.collection('sequences', function(err, collection) {
collection.insert(sequences, {safe:true}, function(err, result) {
if (err) {
console.log("Error when insert first sequence");
res.send({'error':'An error has occurred'});
}
else {
console.log('Success: ' + JSON.stringify(result[0]));
saveAudio(result[0].sequenceNo);
}
});
});
}
var updateSequence = function( ){
db.collection('sequences', function(err, sequences) {
sequences.findOne({}, function(err, item) {
item.sequenceNo++;
sequences.save(item);
saveAudio(item.sequenceNo);
});
});
}
db.collection('sequences', function(err, sequences) {
sequences.find().toArray(function(err, items) {
if(items.length == 0){
insertSequence( );
}
else{
updateSequence( );
}
});
});
} | tonycaovn/vivuserver | services/audio.js | JavaScript | mit | 5,449 |
var gulp = require('gulp');
var connect = require('gulp-connect');
var wiredep = require('wiredep').stream;
var $ = require('gulp-load-plugins')();
var del = require('del');
var jsReporter = require('jshint-stylish');
var annotateAdfPlugin = require('ng-annotate-adf-plugin');
var pkg = require('./package.json');
var annotateOptions = {
plugin: [
annotateAdfPlugin
]
};
var templateOptions = {
root: '{widgetsPath}/deviceInventory/src',
module: 'adf.widget.deviceInventory'
};
/** lint **/
gulp.task('csslint', function(){
gulp.src('src/**/*.css')
.pipe($.csslint())
.pipe($.csslint.reporter());
});
gulp.task('jslint', function(){
gulp.src('src/**/*.js')
.pipe($.jshint())
.pipe($.jshint.reporter(jsReporter));
});
gulp.task('lint', ['csslint', 'jslint']);
/** serve **/
gulp.task('templates', function(){
return gulp.src('src/**/*.html')
.pipe($.angularTemplatecache('templates.tpl.js', templateOptions))
.pipe(gulp.dest('.tmp/dist'));
});
gulp.task('sample', ['templates'], function(){
var files = gulp.src(['src/**/*.js', 'src/**/*.css', 'src/**/*.less', '.tmp/dist/*.js'])
.pipe($.if('*.js', $.angularFilesort()));
gulp.src('sample/index.html')
.pipe(wiredep({
directory: './components/',
bowerJson: require('./bower.json'),
devDependencies: true,
dependencies: true
}))
.pipe($.inject(files))
.pipe(gulp.dest('.tmp/dist'))
.pipe(connect.reload());
});
gulp.task('watch', function(){
gulp.watch(['src/**'], ['sample']);
});
gulp.task('serve', ['watch', 'sample'], function(){
connect.server({
root: ['.tmp/dist', '.'],
livereload: true,
port: 9002
});
});
/** build **/
gulp.task('css', function(){
gulp.src(['src/**/*.css', 'src/**/*.less'])
.pipe($.if('*.less', $.less()))
.pipe($.concat(pkg.name + '.css'))
.pipe(gulp.dest('dist'))
.pipe($.rename(pkg.name + '.min.css'))
.pipe($.minifyCss())
.pipe(gulp.dest('dist'));
});
gulp.task('js', function() {
gulp.src(['src/**/*.js', 'src/**/*.html'])
.pipe($.if('*.html', $.minifyHtml()))
.pipe($.if('*.html', $.angularTemplatecache(pkg.name + '.tpl.js', templateOptions)))
.pipe($.angularFilesort())
.pipe($.if('*.js', $.replace(/'use strict';/g, '')))
.pipe($.concat(pkg.name + '.js'))
.pipe($.headerfooter('(function(window, undefined) {\'use strict\';\n', '})(window);'))
.pipe($.ngAnnotate(annotateOptions))
.pipe(gulp.dest('dist'))
.pipe($.rename(pkg.name + '.min.js'))
.pipe($.uglify())
.pipe(gulp.dest('dist'));
});
/** clean **/
gulp.task('clean', function(cb){
del(['dist', '.tmp'], cb);
});
gulp.task('default', ['css', 'js']);
| reshak/angular-dashboard-framework | sample/widgets/deviceInventory/gulpfile.js | JavaScript | mit | 2,787 |
from rest_framework import serializers
from rest_auth.serializers import UserDetailsSerializer
class UserSerializer(UserDetailsSerializer):
website = serializers.URLField(source="userprofile.website", allow_blank=True, required=False)
about = serializers.CharField(source="userprofile.about", allow_blank=True, required=False)
class Meta(UserDetailsSerializer.Meta):
fields = UserDetailsSerializer.Meta.fields + ('website', 'about')
def update(self, instance, validated_data):
profile_data = validated_data.pop('userprofile', {})
website = profile_data.get('website')
about = profile_data.get('about')
instance = super(UserSerializer, self).update(instance, validated_data)
# get and update user profile
profile = instance.userprofile
if profile_data:
if website:
profile.website = website
if about:
profile.about = about
profile.save()
return instance
| ZachLiuGIS/reactjs-auth-django-rest | django_backend/user_profile/serializers.py | Python | mit | 1,016 |
/** @license React vundefined
* react.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.React = {}));
}(this, (function (exports) { 'use strict';
var ReactVersion = '18.0.0-bdd6d5064-20211001';
// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var REACT_ELEMENT_TYPE = 0xeac7;
var REACT_PORTAL_TYPE = 0xeaca;
exports.Fragment = 0xeacb;
exports.StrictMode = 0xeacc;
exports.Profiler = 0xead2;
var REACT_PROVIDER_TYPE = 0xeacd;
var REACT_CONTEXT_TYPE = 0xeace;
var REACT_FORWARD_REF_TYPE = 0xead0;
exports.Suspense = 0xead1;
exports.SuspenseList = 0xead8;
var REACT_MEMO_TYPE = 0xead3;
var REACT_LAZY_TYPE = 0xead4;
var REACT_SCOPE_TYPE = 0xead7;
var REACT_OPAQUE_ID_TYPE = 0xeae0;
var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1;
var REACT_OFFSCREEN_TYPE = 0xeae2;
var REACT_LEGACY_HIDDEN_TYPE = 0xeae3;
var REACT_CACHE_TYPE = 0xeae4;
if (typeof Symbol === 'function' && Symbol.for) {
var symbolFor = Symbol.for;
REACT_ELEMENT_TYPE = symbolFor('react.element');
REACT_PORTAL_TYPE = symbolFor('react.portal');
exports.Fragment = symbolFor('react.fragment');
exports.StrictMode = symbolFor('react.strict_mode');
exports.Profiler = symbolFor('react.profiler');
REACT_PROVIDER_TYPE = symbolFor('react.provider');
REACT_CONTEXT_TYPE = symbolFor('react.context');
REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref');
exports.Suspense = symbolFor('react.suspense');
exports.SuspenseList = symbolFor('react.suspense_list');
REACT_MEMO_TYPE = symbolFor('react.memo');
REACT_LAZY_TYPE = symbolFor('react.lazy');
REACT_SCOPE_TYPE = symbolFor('react.scope');
REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id');
REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode');
REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen');
REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden');
REACT_CACHE_TYPE = symbolFor('react.cache');
}
var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator';
function getIteratorFn(maybeIterable) {
if (maybeIterable === null || typeof maybeIterable !== 'object') {
return null;
}
var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
if (typeof maybeIterator === 'function') {
return maybeIterator;
}
return null;
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
var _assign = function (to, from) {
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
};
var assign = Object.assign || function (target, sources) {
if (target == null) {
throw new TypeError('Object.assign target cannot be null or undefined');
}
var to = Object(target);
for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) {
var nextSource = arguments[nextIndex];
if (nextSource != null) {
_assign(to, Object(nextSource));
}
}
return to;
};
/**
* Keeps track of the current dispatcher.
*/
var ReactCurrentDispatcher = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
/**
* Keeps track of the current batch's configuration such as how long an update
* should suspend for if it needs to.
*/
var ReactCurrentBatchConfig = {
transition: 0
};
{
ReactCurrentBatchConfig._updatedFibers = new Set();
}
var ReactCurrentActQueue = {
current: null,
// Our internal tests use a custom implementation of `act` that works by
// mocking the Scheduler package. Use this field to disable the `act` warning.
// TODO: Maybe the warning should be disabled by default, and then turned
// on at the testing frameworks layer? Instead of what we do now, which
// is check if a `jest` global is defined.
disableActWarning: false,
// Used to reproduce behavior of `batchedUpdates` in legacy mode.
isBatchingLegacy: false,
didScheduleLegacyUpdate: false
};
/**
* Keeps track of the current owner.
*
* The current owner is the component who should own any components that are
* currently being constructed.
*/
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
var ReactDebugCurrentFrame = {};
var currentExtraStackFrame = null;
function setExtraStackFrame(stack) {
{
currentExtraStackFrame = stack;
}
}
{
ReactDebugCurrentFrame.setExtraStackFrame = function (stack) {
{
currentExtraStackFrame = stack;
}
}; // Stack implementation injected by the current renderer.
ReactDebugCurrentFrame.getCurrentStack = null;
ReactDebugCurrentFrame.getStackAddendum = function () {
var stack = ''; // Add an extra top frame while an element is being validated
if (currentExtraStackFrame) {
stack += currentExtraStackFrame;
} // Delegate to the injected renderer-specific implementation
var impl = ReactDebugCurrentFrame.getCurrentStack;
if (impl) {
stack += impl() || '';
}
return stack;
};
}
var ReactSharedInternals = {
ReactCurrentDispatcher: ReactCurrentDispatcher,
ReactCurrentBatchConfig: ReactCurrentBatchConfig,
ReactCurrentOwner: ReactCurrentOwner,
// Used by renderers to avoid bundling object-assign twice in UMD bundles:
assign: assign
};
{
ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue;
}
// by calls to these methods by a Babel plugin.
//
// In PROD (or in packages without access to React internals),
// they are left as they are instead.
function warn(format) {
{
{
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
printWarning('warn', format, args);
}
}
}
function error(format) {
{
{
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
printWarning('error', format, args);
}
}
}
function printWarning(level, format, args) {
// When changing this logic, you might want to also
// update consoleWithStackDev.www.js as well.
{
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
var stack = ReactDebugCurrentFrame.getStackAddendum();
if (stack !== '') {
format += '%s';
args = args.concat([stack]);
} // eslint-disable-next-line react-internal/safe-string-coercion
var argsWithFormat = args.map(function (item) {
return String(item);
}); // Careful: RN currently depends on this prefix
argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
// breaks IE9: https://github.com/facebook/react/issues/13610
// eslint-disable-next-line react-internal/no-production-logging
Function.prototype.apply.call(console[level], console, argsWithFormat);
}
}
var didWarnStateUpdateForUnmountedComponent = {};
function warnNoop(publicInstance, callerName) {
{
var _constructor = publicInstance.constructor;
var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass';
var warningKey = componentName + "." + callerName;
if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
return;
}
error("Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName);
didWarnStateUpdateForUnmountedComponent[warningKey] = true;
}
}
/**
* This is the abstract API for an update queue.
*/
var ReactNoopUpdateQueue = {
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function (publicInstance) {
return false;
},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {?function} callback Called after component is updated.
* @param {?string} callerName name of the calling function in the public API.
* @internal
*/
enqueueForceUpdate: function (publicInstance, callback, callerName) {
warnNoop(publicInstance, 'forceUpdate');
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @param {?function} callback Called after component is updated.
* @param {?string} callerName name of the calling function in the public API.
* @internal
*/
enqueueReplaceState: function (publicInstance, completeState, callback, callerName) {
warnNoop(publicInstance, 'replaceState');
},
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @param {?function} callback Called after component is updated.
* @param {?string} Name of the calling function in the public API.
* @internal
*/
enqueueSetState: function (publicInstance, partialState, callback, callerName) {
warnNoop(publicInstance, 'setState');
}
};
var emptyObject = {};
{
Object.freeze(emptyObject);
}
/**
* Base class helpers for the updating state of a component.
*/
function Component(props, context, updater) {
this.props = props;
this.context = context; // If a component has string refs, we will assign a different object later.
this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
}
Component.prototype.isReactComponent = {};
/**
* Sets a subset of the state. Always use this to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* When a function is provided to setState, it will be called at some point in
* the future (not synchronously). It will be called with the up to date
* component arguments (state, props, context). These values can be different
* from this.* because your function may be called after receiveProps but before
* shouldComponentUpdate, and this new state, props, and context will not yet be
* assigned to this.
*
* @param {object|function} partialState Next partial state or function to
* produce next partial state to be merged with current state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
Component.prototype.setState = function (partialState, callback) {
if (typeof partialState !== 'object' && typeof partialState !== 'function' && partialState != null) {
throw Error( 'setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.' );
}
this.updater.enqueueSetState(this, partialState, callback, 'setState');
};
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
Component.prototype.forceUpdate = function (callback) {
this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};
/**
* Deprecated APIs. These APIs used to exist on classic React classes but since
* we would like to deprecate them, we're not going to move them over to this
* modern base class. Instead, we define a getter that warns if it's accessed.
*/
{
var deprecatedAPIs = {
isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']
};
var defineDeprecationWarning = function (methodName, info) {
Object.defineProperty(Component.prototype, methodName, {
get: function () {
warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);
return undefined;
}
});
};
for (var fnName in deprecatedAPIs) {
if (deprecatedAPIs.hasOwnProperty(fnName)) {
defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
}
}
}
function ComponentDummy() {}
ComponentDummy.prototype = Component.prototype;
/**
* Convenience component with default shallow equality check for sCU.
*/
function PureComponent(props, context, updater) {
this.props = props;
this.context = context; // If a component has string refs, we will assign a different object later.
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
}
var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods.
assign(pureComponentPrototype, Component.prototype);
pureComponentPrototype.isPureReactComponent = true;
// an immutable object with a single mutable value
function createRef() {
var refObject = {
current: null
};
{
Object.seal(refObject);
}
return refObject;
}
var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
function isArray(a) {
return isArrayImpl(a);
}
/*
* The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
* and Temporal.* types. See https://github.com/facebook/react/pull/22064.
*
* The functions in this module will throw an easier-to-understand,
* easier-to-debug exception with a clear errors message message explaining the
* problem. (Instead of a confusing exception thrown inside the implementation
* of the `value` object).
*/
// $FlowFixMe only called in DEV, so void return is not possible.
function typeName(value) {
{
// toStringTag is needed for namespaced types like Temporal.Instant
var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
return type;
}
} // $FlowFixMe only called in DEV, so void return is not possible.
function willCoercionThrow(value) {
{
if (value !== null && typeof value === 'object' && value.$$typeof === REACT_OPAQUE_ID_TYPE) {
// OpaqueID type is expected to throw, so React will handle it. Not sure if
// it's expected that string coercion will throw, but we'll assume it's OK.
// See https://github.com/facebook/react/issues/20127.
return;
}
try {
testStringCoercion(value);
return false;
} catch (e) {
return true;
}
}
}
function testStringCoercion(value) {
// If you ended up here by following an exception call stack, here's what's
// happened: you supplied an object or symbol value to React (as a prop, key,
// DOM attribute, CSS property, string ref, etc.) and when React tried to
// coerce it to a string using `'' + value`, an exception was thrown.
//
// The most common types that will cause this exception are `Symbol` instances
// and Temporal objects like `Temporal.Instant`. But any object that has a
// `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
// exception. (Library authors do this to prevent users from using built-in
// numeric operators like `+` or comparison operators like `>=` because custom
// methods are needed to perform accurate arithmetic or comparison.)
//
// To fix the problem, coerce this object or symbol value to a string before
// passing it to React. The most reliable way is usually `String(value)`.
//
// To find which value is throwing, check the browser or debugger console.
// Before this exception was thrown, there should be `console.error` output
// that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
// problem and how that type was used: key, atrribute, input value prop, etc.
// In most cases, this console output also shows the component and its
// ancestor components where the exception happened.
//
// eslint-disable-next-line react-internal/safe-string-coercion
return '' + value;
}
function checkKeyStringCoercion(value) {
{
if (willCoercionThrow(value)) {
error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));
return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
}
}
}
function getWrappedName(outerType, innerType, wrapperName) {
var displayName = outerType.displayName;
if (displayName) {
return displayName;
}
var functionName = innerType.displayName || innerType.name || '';
return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
} // Keep in sync with react-reconciler/getComponentNameFromFiber
function getContextName(type) {
return type.displayName || 'Context';
} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.
function getComponentNameFromType(type) {
if (type == null) {
// Host root, text node or just invalid type.
return null;
}
{
if (typeof type.tag === 'number') {
error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
}
}
if (typeof type === 'function') {
return type.displayName || type.name || null;
}
if (typeof type === 'string') {
return type;
}
switch (type) {
case exports.Fragment:
return 'Fragment';
case REACT_PORTAL_TYPE:
return 'Portal';
case exports.Profiler:
return 'Profiler';
case exports.StrictMode:
return 'StrictMode';
case exports.Suspense:
return 'Suspense';
case exports.SuspenseList:
return 'SuspenseList';
case REACT_CACHE_TYPE:
return 'Cache';
}
if (typeof type === 'object') {
switch (type.$$typeof) {
case REACT_CONTEXT_TYPE:
var context = type;
return getContextName(context) + '.Consumer';
case REACT_PROVIDER_TYPE:
var provider = type;
return getContextName(provider._context) + '.Provider';
case REACT_FORWARD_REF_TYPE:
return getWrappedName(type, type.render, 'ForwardRef');
case REACT_MEMO_TYPE:
var outerName = type.displayName || null;
if (outerName !== null) {
return outerName;
}
return getComponentNameFromType(type.type) || 'Memo';
case REACT_LAZY_TYPE:
{
var lazyComponent = type;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
try {
return getComponentNameFromType(init(payload));
} catch (x) {
return null;
}
}
}
}
return null;
}
var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
var RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true
};
var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;
{
didWarnAboutStringRefs = {};
}
function hasValidRef(config) {
{
if (hasOwnProperty$1.call(config, 'ref')) {
var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.ref !== undefined;
}
function hasValidKey(config) {
{
if (hasOwnProperty$1.call(config, 'key')) {
var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.key !== undefined;
}
function defineKeyPropWarningGetter(props, displayName) {
var warnAboutAccessingKey = function () {
{
if (!specialPropKeyWarningShown) {
specialPropKeyWarningShown = true;
error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
}
}
};
warnAboutAccessingKey.isReactWarning = true;
Object.defineProperty(props, 'key', {
get: warnAboutAccessingKey,
configurable: true
});
}
function defineRefPropWarningGetter(props, displayName) {
var warnAboutAccessingRef = function () {
{
if (!specialPropRefWarningShown) {
specialPropRefWarningShown = true;
error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
}
}
};
warnAboutAccessingRef.isReactWarning = true;
Object.defineProperty(props, 'ref', {
get: warnAboutAccessingRef,
configurable: true
});
}
function warnIfStringRefCannotBeAutoConverted(config) {
{
if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {
var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);
if (!didWarnAboutStringRefs[componentName]) {
error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref);
didWarnAboutStringRefs[componentName] = true;
}
}
}
}
/**
* Factory method to create a new React element. This no longer adheres to
* the class pattern, so do not use new to call it. Also, instanceof check
* will not work. Instead test $$typeof field against Symbol.for('react.element') to check
* if something is a React Element.
*
* @param {*} type
* @param {*} props
* @param {*} key
* @param {string|object} ref
* @param {*} owner
* @param {*} self A *temporary* helper to detect places where `this` is
* different from the `owner` when React.createElement is called, so that we
* can warn. We want to get rid of owner and replace string `ref`s with arrow
* functions, and as long as `this` and owner are the same, there will be no
* change in behavior.
* @param {*} source An annotation object (added by a transpiler or otherwise)
* indicating filename, line number, and/or other information.
* @internal
*/
var ReactElement = function (type, key, ref, self, source, owner, props) {
var element = {
// This tag allows us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner
};
{
// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
Object.defineProperty(element._store, 'validated', {
configurable: false,
enumerable: false,
writable: true,
value: false
}); // self and source are DEV only properties.
Object.defineProperty(element, '_self', {
configurable: false,
enumerable: false,
writable: false,
value: self
}); // Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, '_source', {
configurable: false,
enumerable: false,
writable: false,
value: source
});
if (Object.freeze) {
Object.freeze(element.props);
Object.freeze(element);
}
}
return element;
};
/**
* Create and return a new ReactElement of the given type.
* See https://reactjs.org/docs/react-api.html#createelement
*/
function createElement(type, config, children) {
var propName; // Reserved names are extracted
var props = {};
var key = null;
var ref = null;
var self = null;
var source = null;
if (config != null) {
if (hasValidRef(config)) {
ref = config.ref;
{
warnIfStringRefCannotBeAutoConverted(config);
}
}
if (hasValidKey(config)) {
{
checkKeyStringCoercion(config.key);
}
key = '' + config.key;
}
self = config.__self === undefined ? null : config.__self;
source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object
for (propName in config) {
if (hasOwnProperty$1.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
} // Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
{
if (Object.freeze) {
Object.freeze(childArray);
}
}
props.children = childArray;
} // Resolve default props
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
}
{
if (key || ref) {
var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
if (key) {
defineKeyPropWarningGetter(props, displayName);
}
if (ref) {
defineRefPropWarningGetter(props, displayName);
}
}
}
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
}
function cloneAndReplaceKey(oldElement, newKey) {
var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
return newElement;
}
/**
* Clone and return a new ReactElement using element as the starting point.
* See https://reactjs.org/docs/react-api.html#cloneelement
*/
function cloneElement(element, config, children) {
if (element === null || element === undefined) {
throw Error( "React.cloneElement(...): The argument must be a React element, but you passed " + element + "." );
}
var propName; // Original props are copied
var props = assign({}, element.props); // Reserved names are extracted
var key = element.key;
var ref = element.ref; // Self is preserved since the owner is preserved.
var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a
// transpiler, and the original source is probably a better indicator of the
// true owner.
var source = element._source; // Owner will be preserved, unless ref is overridden
var owner = element._owner;
if (config != null) {
if (hasValidRef(config)) {
// Silently steal the ref from the parent.
ref = config.ref;
owner = ReactCurrentOwner.current;
}
if (hasValidKey(config)) {
{
checkKeyStringCoercion(config.key);
}
key = '' + config.key;
} // Remaining properties override existing props
var defaultProps;
if (element.type && element.type.defaultProps) {
defaultProps = element.type.defaultProps;
}
for (propName in config) {
if (hasOwnProperty$1.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
if (config[propName] === undefined && defaultProps !== undefined) {
// Resolve default props
props[propName] = defaultProps[propName];
} else {
props[propName] = config[propName];
}
}
}
} // Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
return ReactElement(element.type, key, ref, self, source, owner, props);
}
/**
* Verifies the object is a ReactElement.
* See https://reactjs.org/docs/react-api.html#isvalidelement
* @param {?object} object
* @return {boolean} True if `object` is a ReactElement.
* @final
*/
function isValidElement(object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
var SEPARATOR = '.';
var SUBSEPARATOR = ':';
/**
* Escape and wrap key so it is safe to use as a reactid
*
* @param {string} key to be escaped.
* @return {string} the escaped key.
*/
function escape(key) {
var escapeRegex = /[=:]/g;
var escaperLookup = {
'=': '=0',
':': '=2'
};
var escapedString = key.replace(escapeRegex, function (match) {
return escaperLookup[match];
});
return '$' + escapedString;
}
/**
* TODO: Test that a single child and an array with one item have the same key
* pattern.
*/
var didWarnAboutMaps = false;
var userProvidedKeyEscapeRegex = /\/+/g;
function escapeUserProvidedKey(text) {
return text.replace(userProvidedKeyEscapeRegex, '$&/');
}
/**
* Generate a key string that identifies a element within a set.
*
* @param {*} element A element that could contain a manual key.
* @param {number} index Index that is used if a manual key is not provided.
* @return {string}
*/
function getElementKey(element, index) {
// Do some typechecking here since we call this blindly. We want to ensure
// that we don't block potential future ES APIs.
if (typeof element === 'object' && element !== null && element.key != null) {
// Explicit key
{
checkKeyStringCoercion(element.key);
}
return escape('' + element.key);
} // Implicit key determined by the index in the set
return index.toString(36);
}
function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
var type = typeof children;
if (type === 'undefined' || type === 'boolean') {
// All of the above are perceived as null.
children = null;
}
var invokeCallback = false;
if (children === null) {
invokeCallback = true;
} else {
switch (type) {
case 'string':
case 'number':
invokeCallback = true;
break;
case 'object':
switch (children.$$typeof) {
case REACT_ELEMENT_TYPE:
case REACT_PORTAL_TYPE:
invokeCallback = true;
}
}
}
if (invokeCallback) {
var _child = children;
var mappedChild = callback(_child); // If it's the only child, treat the name as if it was wrapped in an array
// so that it's consistent if the number of children grows:
var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar;
if (isArray(mappedChild)) {
var escapedChildKey = '';
if (childKey != null) {
escapedChildKey = escapeUserProvidedKey(childKey) + '/';
}
mapIntoArray(mappedChild, array, escapedChildKey, '', function (c) {
return c;
});
} else if (mappedChild != null) {
if (isValidElement(mappedChild)) {
{
// The `if` statement here prevents auto-disabling of the safe
// coercion ESLint rule, so we must manually disable it below.
// $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) {
checkKeyStringCoercion(mappedChild.key);
}
}
mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as
// traverseAllChildren used to do for objects as children
escapedPrefix + ( // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
mappedChild.key && (!_child || _child.key !== mappedChild.key) ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number
// eslint-disable-next-line react-internal/safe-string-coercion
escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey);
}
array.push(mappedChild);
}
return 1;
}
var child;
var nextName;
var subtreeCount = 0; // Count of children found in the current subtree.
var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
if (isArray(children)) {
for (var i = 0; i < children.length; i++) {
child = children[i];
nextName = nextNamePrefix + getElementKey(child, i);
subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
}
} else {
var iteratorFn = getIteratorFn(children);
if (typeof iteratorFn === 'function') {
var iterableChildren = children;
{
// Warn about using Maps as children
if (iteratorFn === iterableChildren.entries) {
if (!didWarnAboutMaps) {
warn('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
}
didWarnAboutMaps = true;
}
}
var iterator = iteratorFn.call(iterableChildren);
var step;
var ii = 0;
while (!(step = iterator.next()).done) {
child = step.value;
nextName = nextNamePrefix + getElementKey(child, ii++);
subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
}
} else if (type === 'object') {
// eslint-disable-next-line react-internal/safe-string-coercion
var childrenString = String(children);
throw Error( "Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.' );
}
}
return subtreeCount;
}
/**
* Maps children that are typically specified as `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenmap
*
* The provided mapFunction(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func The map function.
* @param {*} context Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var result = [];
var count = 0;
mapIntoArray(children, result, '', '', function (child) {
return func.call(context, child, count++);
});
return result;
}
/**
* Count the number of children that are typically specified as
* `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrencount
*
* @param {?*} children Children tree container.
* @return {number} The number of children.
*/
function countChildren(children) {
var n = 0;
mapChildren(children, function () {
n++; // Don't return anything
});
return n;
}
/**
* Iterates through children that are typically specified as `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenforeach
*
* The provided forEachFunc(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc
* @param {*} forEachContext Context for forEachContext.
*/
function forEachChildren(children, forEachFunc, forEachContext) {
mapChildren(children, function () {
forEachFunc.apply(this, arguments); // Don't return anything.
}, forEachContext);
}
/**
* Flatten a children object (typically specified as `props.children`) and
* return an array with appropriately re-keyed children.
*
* See https://reactjs.org/docs/react-api.html#reactchildrentoarray
*/
function toArray(children) {
return mapChildren(children, function (child) {
return child;
}) || [];
}
/**
* Returns the first child in a collection of children and verifies that there
* is only one child in the collection.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenonly
*
* The current implementation of this function assumes that a single child gets
* passed without a wrapper, but the purpose of this helper function is to
* abstract away the particular structure of children.
*
* @param {?object} children Child collection structure.
* @return {ReactElement} The first and only `ReactElement` contained in the
* structure.
*/
function onlyChild(children) {
if (!isValidElement(children)) {
throw Error( 'React.Children.only expected to receive a single React element child.' );
}
return children;
}
function createContext(defaultValue) {
// TODO: Second argument used to be an optional `calculateChangedBits`
// function. Warn to reserve for future use?
var context = {
$$typeof: REACT_CONTEXT_TYPE,
// As a workaround to support multiple concurrent renderers, we categorize
// some renderers as primary and others as secondary. We only expect
// there to be two concurrent renderers at most: React Native (primary) and
// Fabric (secondary); React DOM (primary) and React ART (secondary).
// Secondary renderers store their context values on separate fields.
_currentValue: defaultValue,
_currentValue2: defaultValue,
// Used to track how many concurrent renderers this context currently
// supports within in a single renderer. Such as parallel server rendering.
_threadCount: 0,
// These are circular
Provider: null,
Consumer: null
};
context.Provider = {
$$typeof: REACT_PROVIDER_TYPE,
_context: context
};
var hasWarnedAboutUsingNestedContextConsumers = false;
var hasWarnedAboutUsingConsumerProvider = false;
var hasWarnedAboutDisplayNameOnConsumer = false;
{
// A separate object, but proxies back to the original context object for
// backwards compatibility. It has a different $$typeof, so we can properly
// warn for the incorrect usage of Context as a Consumer.
var Consumer = {
$$typeof: REACT_CONTEXT_TYPE,
_context: context
}; // $FlowFixMe: Flow complains about not setting a value, which is intentional here
Object.defineProperties(Consumer, {
Provider: {
get: function () {
if (!hasWarnedAboutUsingConsumerProvider) {
hasWarnedAboutUsingConsumerProvider = true;
error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?');
}
return context.Provider;
},
set: function (_Provider) {
context.Provider = _Provider;
}
},
_currentValue: {
get: function () {
return context._currentValue;
},
set: function (_currentValue) {
context._currentValue = _currentValue;
}
},
_currentValue2: {
get: function () {
return context._currentValue2;
},
set: function (_currentValue2) {
context._currentValue2 = _currentValue2;
}
},
_threadCount: {
get: function () {
return context._threadCount;
},
set: function (_threadCount) {
context._threadCount = _threadCount;
}
},
Consumer: {
get: function () {
if (!hasWarnedAboutUsingNestedContextConsumers) {
hasWarnedAboutUsingNestedContextConsumers = true;
error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
}
return context.Consumer;
}
},
displayName: {
get: function () {
return context.displayName;
},
set: function (displayName) {
if (!hasWarnedAboutDisplayNameOnConsumer) {
warn('Setting `displayName` on Context.Consumer has no effect. ' + "You should set it directly on the context with Context.displayName = '%s'.", displayName);
hasWarnedAboutDisplayNameOnConsumer = true;
}
}
}
}); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty
context.Consumer = Consumer;
}
{
context._currentRenderer = null;
context._currentRenderer2 = null;
}
return context;
}
var Uninitialized = -1;
var Pending = 0;
var Resolved = 1;
var Rejected = 2;
function lazyInitializer(payload) {
if (payload._status === Uninitialized) {
var ctor = payload._result;
var thenable = ctor(); // Transition to the next state.
// This might throw either because it's missing or throws. If so, we treat it
// as still uninitialized and try again next time. Which is the same as what
// happens if the ctor or any wrappers processing the ctor throws. This might
// end up fixing it if the resolution was a concurrency bug.
thenable.then(function (moduleObject) {
if (payload._status === Pending || payload._status === Uninitialized) {
// Transition to the next state.
var resolved = payload;
resolved._status = Resolved;
resolved._result = moduleObject;
}
}, function (error) {
if (payload._status === Pending || payload._status === Uninitialized) {
// Transition to the next state.
var rejected = payload;
rejected._status = Rejected;
rejected._result = error;
}
});
if (payload._status === Uninitialized) {
// In case, we're still uninitialized, then we're waiting for the thenable
// to resolve. Set it as pending in the meantime.
var pending = payload;
pending._status = Pending;
pending._result = thenable;
}
}
if (payload._status === Resolved) {
var moduleObject = payload._result;
{
if (moduleObject === undefined) {
error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies.
'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))\n\n" + 'Did you accidentally put curly braces around the import?', moduleObject);
}
}
{
if (!('default' in moduleObject)) {
error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies.
'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))", moduleObject);
}
}
return moduleObject.default;
} else {
throw payload._result;
}
}
function lazy(ctor) {
var payload = {
// We use these fields to store the result.
_status: Uninitialized,
_result: ctor
};
var lazyType = {
$$typeof: REACT_LAZY_TYPE,
_payload: payload,
_init: lazyInitializer
};
{
// In production, this would just set it on the object.
var defaultProps;
var propTypes; // $FlowFixMe
Object.defineProperties(lazyType, {
defaultProps: {
configurable: true,
get: function () {
return defaultProps;
},
set: function (newDefaultProps) {
error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
defaultProps = newDefaultProps; // Match production behavior more closely:
// $FlowFixMe
Object.defineProperty(lazyType, 'defaultProps', {
enumerable: true
});
}
},
propTypes: {
configurable: true,
get: function () {
return propTypes;
},
set: function (newPropTypes) {
error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
propTypes = newPropTypes; // Match production behavior more closely:
// $FlowFixMe
Object.defineProperty(lazyType, 'propTypes', {
enumerable: true
});
}
}
});
}
return lazyType;
}
function forwardRef(render) {
{
if (render != null && render.$$typeof === REACT_MEMO_TYPE) {
error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).');
} else if (typeof render !== 'function') {
error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render);
} else {
if (render.length !== 0 && render.length !== 2) {
error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.');
}
}
if (render != null) {
if (render.defaultProps != null || render.propTypes != null) {
error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?');
}
}
}
var elementType = {
$$typeof: REACT_FORWARD_REF_TYPE,
render: render
};
{
var ownName;
Object.defineProperty(elementType, 'displayName', {
enumerable: false,
configurable: true,
get: function () {
return ownName;
},
set: function (name) {
ownName = name; // The inner component shouldn't inherit this display name in most cases,
// because the component may be used elsewhere.
// But it's nice for anonymous functions to inherit the name,
// so that our component-stack generation logic will display their frames.
// An anonymous function generally suggests a pattern like:
// React.forwardRef((props, ref) => {...});
// This kind of inner function is not used elsewhere so the side effect is okay.
if (!render.name && !render.displayName) {
render.displayName = name;
}
}
});
}
return elementType;
}
// Filter certain DOM attributes (e.g. src, href) if their values are empty strings.
var enableCache = false; // Only used in www builds.
var enableScopeAPI = false; // Experimental Create Event Handle API.
var warnOnSubscriptionInsideStartTransition = false;
var REACT_MODULE_REFERENCE = 0;
if (typeof Symbol === 'function') {
REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
}
function isValidElementType(type) {
if (typeof type === 'string' || typeof type === 'function') {
return true;
} // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
if (type === exports.Fragment || type === exports.Profiler || type === REACT_DEBUG_TRACING_MODE_TYPE || type === exports.StrictMode || type === exports.Suspense || type === exports.SuspenseList || type === REACT_LEGACY_HIDDEN_TYPE || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCache ) {
return true;
}
if (typeof type === 'object' && type !== null) {
if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
// types supported by any Flight configuration anywhere since
// we don't know which Flight build this will end up being used
// with.
type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
return true;
}
}
return false;
}
function memo(type, compare) {
{
if (!isValidElementType(type)) {
error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type);
}
}
var elementType = {
$$typeof: REACT_MEMO_TYPE,
type: type,
compare: compare === undefined ? null : compare
};
{
var ownName;
Object.defineProperty(elementType, 'displayName', {
enumerable: false,
configurable: true,
get: function () {
return ownName;
},
set: function (name) {
ownName = name; // The inner component shouldn't inherit this display name in most cases,
// because the component may be used elsewhere.
// But it's nice for anonymous functions to inherit the name,
// so that our component-stack generation logic will display their frames.
// An anonymous function generally suggests a pattern like:
// React.memo((props) => {...});
// This kind of inner function is not used elsewhere so the side effect is okay.
if (!type.name && !type.displayName) {
type.displayName = name;
}
}
});
}
return elementType;
}
function resolveDispatcher() {
var dispatcher = ReactCurrentDispatcher.current;
{
if (dispatcher === null) {
error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');
}
} // Will result in a null access error if accessed outside render phase. We
// intentionally don't throw our own error because this is in a hot path.
// Also helps ensure this is inlined.
return dispatcher;
}
function useContext(Context) {
var dispatcher = resolveDispatcher();
{
// TODO: add a more generic warning for invalid values.
if (Context._context !== undefined) {
var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs
// and nobody should be using this in existing code.
if (realContext.Consumer === Context) {
error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?');
} else if (realContext.Provider === Context) {
error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?');
}
}
}
return dispatcher.useContext(Context);
}
function useState(initialState) {
var dispatcher = resolveDispatcher();
return dispatcher.useState(initialState);
}
function useReducer(reducer, initialArg, init) {
var dispatcher = resolveDispatcher();
return dispatcher.useReducer(reducer, initialArg, init);
}
function useRef(initialValue) {
var dispatcher = resolveDispatcher();
return dispatcher.useRef(initialValue);
}
function useEffect(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useEffect(create, deps);
}
function useLayoutEffect(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useLayoutEffect(create, deps);
}
function useCallback(callback, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useCallback(callback, deps);
}
function useMemo(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useMemo(create, deps);
}
function useImperativeHandle(ref, create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useImperativeHandle(ref, create, deps);
}
function useDebugValue(value, formatterFn) {
{
var dispatcher = resolveDispatcher();
return dispatcher.useDebugValue(value, formatterFn);
}
}
function useTransition() {
var dispatcher = resolveDispatcher();
return dispatcher.useTransition();
}
function useDeferredValue(value) {
var dispatcher = resolveDispatcher();
return dispatcher.useDeferredValue(value);
}
function useOpaqueIdentifier() {
var dispatcher = resolveDispatcher();
return dispatcher.useOpaqueIdentifier();
}
function useMutableSource(source, getSnapshot, subscribe) {
var dispatcher = resolveDispatcher();
return dispatcher.useMutableSource(source, getSnapshot, subscribe);
}
// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.
var disabledDepth = 0;
var prevLog;
var prevInfo;
var prevWarn;
var prevError;
var prevGroup;
var prevGroupCollapsed;
var prevGroupEnd;
function disabledLog() {}
disabledLog.__reactDisabledLog = true;
function disableLogs() {
{
if (disabledDepth === 0) {
/* eslint-disable react-internal/no-production-logging */
prevLog = console.log;
prevInfo = console.info;
prevWarn = console.warn;
prevError = console.error;
prevGroup = console.group;
prevGroupCollapsed = console.groupCollapsed;
prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
var props = {
configurable: true,
enumerable: true,
value: disabledLog,
writable: true
}; // $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console, {
info: props,
log: props,
warn: props,
error: props,
group: props,
groupCollapsed: props,
groupEnd: props
});
/* eslint-enable react-internal/no-production-logging */
}
disabledDepth++;
}
}
function reenableLogs() {
{
disabledDepth--;
if (disabledDepth === 0) {
/* eslint-disable react-internal/no-production-logging */
var props = {
configurable: true,
enumerable: true,
writable: true
}; // $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console, {
log: assign({}, props, {
value: prevLog
}),
info: assign({}, props, {
value: prevInfo
}),
warn: assign({}, props, {
value: prevWarn
}),
error: assign({}, props, {
value: prevError
}),
group: assign({}, props, {
value: prevGroup
}),
groupCollapsed: assign({}, props, {
value: prevGroupCollapsed
}),
groupEnd: assign({}, props, {
value: prevGroupEnd
})
});
/* eslint-enable react-internal/no-production-logging */
}
if (disabledDepth < 0) {
error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
}
}
}
var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
var prefix;
function describeBuiltInComponentFrame(name, source, ownerFn) {
{
if (prefix === undefined) {
// Extract the VM specific prefix used by each line.
try {
throw Error();
} catch (x) {
var match = x.stack.trim().match(/\n( *(at )?)/);
prefix = match && match[1] || '';
}
} // We use the prefix to ensure our stacks line up with native stack frames.
return '\n' + prefix + name;
}
}
var reentry = false;
var componentFrameCache;
{
var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
componentFrameCache = new PossiblyWeakMap();
}
function describeNativeComponentFrame(fn, construct) {
// If something asked for a stack inside a fake render, it should get ignored.
if ( !fn || reentry) {
return '';
}
{
var frame = componentFrameCache.get(fn);
if (frame !== undefined) {
return frame;
}
}
var control;
reentry = true;
var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
Error.prepareStackTrace = undefined;
var previousDispatcher;
{
previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function
// for warnings.
ReactCurrentDispatcher$1.current = null;
disableLogs();
}
try {
// This should throw.
if (construct) {
// Something should be setting the props in the constructor.
var Fake = function () {
throw Error();
}; // $FlowFixMe
Object.defineProperty(Fake.prototype, 'props', {
set: function () {
// We use a throwing setter instead of frozen or non-writable props
// because that won't throw in a non-strict mode function.
throw Error();
}
});
if (typeof Reflect === 'object' && Reflect.construct) {
// We construct a different control for this case to include any extra
// frames added by the construct call.
try {
Reflect.construct(Fake, []);
} catch (x) {
control = x;
}
Reflect.construct(fn, [], Fake);
} else {
try {
Fake.call();
} catch (x) {
control = x;
}
fn.call(Fake.prototype);
}
} else {
try {
throw Error();
} catch (x) {
control = x;
}
fn();
}
} catch (sample) {
// This is inlined manually because closure doesn't do it for us.
if (sample && control && typeof sample.stack === 'string') {
// This extracts the first frame from the sample that isn't also in the control.
// Skipping one frame that we assume is the frame that calls the two.
var sampleLines = sample.stack.split('\n');
var controlLines = control.stack.split('\n');
var s = sampleLines.length - 1;
var c = controlLines.length - 1;
while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
// We expect at least one stack frame to be shared.
// Typically this will be the root most one. However, stack frames may be
// cut off due to maximum stack limits. In this case, one maybe cut off
// earlier than the other. We assume that the sample is longer or the same
// and there for cut off earlier. So we should find the root most frame in
// the sample somewhere in the control.
c--;
}
for (; s >= 1 && c >= 0; s--, c--) {
// Next we find the first one that isn't the same which should be the
// frame that called our sample function and the control.
if (sampleLines[s] !== controlLines[c]) {
// In V8, the first line is describing the message but other VMs don't.
// If we're about to return the first line, and the control is also on the same
// line, that's a pretty good indicator that our sample threw at same line as
// the control. I.e. before we entered the sample frame. So we ignore this result.
// This can happen if you passed a class to function component, or non-function.
if (s !== 1 || c !== 1) {
do {
s--;
c--; // We may still have similar intermediate frames from the construct call.
// The next one that isn't the same should be our match though.
if (c < 0 || sampleLines[s] !== controlLines[c]) {
// V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
var _frame = '\n' + sampleLines[s].replace(' at new ', ' at ');
{
if (typeof fn === 'function') {
componentFrameCache.set(fn, _frame);
}
} // Return the line we found.
return _frame;
}
} while (s >= 1 && c >= 0);
}
break;
}
}
}
} finally {
reentry = false;
{
ReactCurrentDispatcher$1.current = previousDispatcher;
reenableLogs();
}
Error.prepareStackTrace = previousPrepareStackTrace;
} // Fallback to just using the name if we couldn't make it throw.
var name = fn ? fn.displayName || fn.name : '';
var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
{
if (typeof fn === 'function') {
componentFrameCache.set(fn, syntheticFrame);
}
}
return syntheticFrame;
}
function describeFunctionComponentFrame(fn, source, ownerFn) {
{
return describeNativeComponentFrame(fn, false);
}
}
function shouldConstruct(Component) {
var prototype = Component.prototype;
return !!(prototype && prototype.isReactComponent);
}
function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
if (type == null) {
return '';
}
if (typeof type === 'function') {
{
return describeNativeComponentFrame(type, shouldConstruct(type));
}
}
if (typeof type === 'string') {
return describeBuiltInComponentFrame(type);
}
switch (type) {
case exports.Suspense:
return describeBuiltInComponentFrame('Suspense');
case exports.SuspenseList:
return describeBuiltInComponentFrame('SuspenseList');
}
if (typeof type === 'object') {
switch (type.$$typeof) {
case REACT_FORWARD_REF_TYPE:
return describeFunctionComponentFrame(type.render);
case REACT_MEMO_TYPE:
// Memo may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
case REACT_LAZY_TYPE:
{
var lazyComponent = type;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
try {
// Lazy may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
} catch (x) {}
}
}
}
return '';
}
var loggedTypeFailures = {};
var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
function setCurrentlyValidatingElement(element) {
{
if (element) {
var owner = element._owner;
var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
} else {
ReactDebugCurrentFrame$1.setExtraStackFrame(null);
}
}
}
function checkPropTypes(typeSpecs, values, location, componentName, element) {
{
// $FlowFixMe This is okay but Flow doesn't know it.
var has = Function.call.bind(hasOwnProperty$1);
for (var typeSpecName in typeSpecs) {
if (has(typeSpecs, typeSpecName)) {
var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if (typeof typeSpecs[typeSpecName] !== 'function') {
// eslint-disable-next-line react-internal/prod-error-codes
var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
err.name = 'Invariant Violation';
throw err;
}
error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
} catch (ex) {
error$1 = ex;
}
if (error$1 && !(error$1 instanceof Error)) {
setCurrentlyValidatingElement(element);
error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);
setCurrentlyValidatingElement(null);
}
if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error$1.message] = true;
setCurrentlyValidatingElement(element);
error('Failed %s type: %s', location, error$1.message);
setCurrentlyValidatingElement(null);
}
}
}
}
}
function setCurrentlyValidatingElement$1(element) {
{
if (element) {
var owner = element._owner;
var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
setExtraStackFrame(stack);
} else {
setExtraStackFrame(null);
}
}
}
var propTypesMisspellWarningShown;
{
propTypesMisspellWarningShown = false;
}
function getDeclarationErrorAddendum() {
if (ReactCurrentOwner.current) {
var name = getComponentNameFromType(ReactCurrentOwner.current.type);
if (name) {
return '\n\nCheck the render method of `' + name + '`.';
}
}
return '';
}
function getSourceInfoErrorAddendum(source) {
if (source !== undefined) {
var fileName = source.fileName.replace(/^.*[\\\/]/, '');
var lineNumber = source.lineNumber;
return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
}
return '';
}
function getSourceInfoErrorAddendumForProps(elementProps) {
if (elementProps !== null && elementProps !== undefined) {
return getSourceInfoErrorAddendum(elementProps.__source);
}
return '';
}
/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/
var ownerHasKeyUseWarning = {};
function getCurrentComponentErrorInfo(parentType) {
var info = getDeclarationErrorAddendum();
if (!info) {
var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
if (parentName) {
info = "\n\nCheck the top-level render call using <" + parentName + ">.";
}
}
return info;
}
/**
* Warn if the element doesn't have an explicit key assigned to it.
* This element is in an array. The array could grow and shrink or be
* reordered. All children that haven't already been validated are required to
* have a "key" property assigned to it. Error statuses are cached so a warning
* will only be shown once.
*
* @internal
* @param {ReactElement} element Element that requires a key.
* @param {*} parentType element's parent's type.
*/
function validateExplicitKey(element, parentType) {
if (!element._store || element._store.validated || element.key != null) {
return;
}
element._store.validated = true;
var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
return;
}
ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
var childOwner = '';
if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
// Give the component that originally created this child.
childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
}
{
setCurrentlyValidatingElement$1(element);
error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
setCurrentlyValidatingElement$1(null);
}
}
/**
* Ensure that every element either is passed in a static location, in an
* array with an explicit keys property defined, or in an object literal
* with valid key property.
*
* @internal
* @param {ReactNode} node Statically passed child of any type.
* @param {*} parentType node's parent's type.
*/
function validateChildKeys(node, parentType) {
if (typeof node !== 'object') {
return;
}
if (isArray(node)) {
for (var i = 0; i < node.length; i++) {
var child = node[i];
if (isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (isValidElement(node)) {
// This element was passed in a valid location.
if (node._store) {
node._store.validated = true;
}
} else if (node) {
var iteratorFn = getIteratorFn(node);
if (typeof iteratorFn === 'function') {
// Entry iterators used to provide implicit keys,
// but now we print a separate warning for them later.
if (iteratorFn !== node.entries) {
var iterator = iteratorFn.call(node);
var step;
while (!(step = iterator.next()).done) {
if (isValidElement(step.value)) {
validateExplicitKey(step.value, parentType);
}
}
}
}
}
}
/**
* Given an element, validate that its props follow the propTypes definition,
* provided by the type.
*
* @param {ReactElement} element
*/
function validatePropTypes(element) {
{
var type = element.type;
if (type === null || type === undefined || typeof type === 'string') {
return;
}
var propTypes;
if (typeof type === 'function') {
propTypes = type.propTypes;
} else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
// Inner props are checked in the reconciler.
type.$$typeof === REACT_MEMO_TYPE)) {
propTypes = type.propTypes;
} else {
return;
}
if (propTypes) {
// Intentionally inside to avoid triggering lazy initializers:
var name = getComponentNameFromType(type);
checkPropTypes(propTypes, element.props, 'prop', name, element);
} else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:
var _name = getComponentNameFromType(type);
error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
}
if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
}
}
}
/**
* Given a fragment, validate that it can only be provided with fragment props
* @param {ReactElement} fragment
*/
function validateFragmentProps(fragment) {
{
var keys = Object.keys(fragment.props);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (key !== 'children' && key !== 'key') {
setCurrentlyValidatingElement$1(fragment);
error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
setCurrentlyValidatingElement$1(null);
break;
}
}
if (fragment.ref !== null) {
setCurrentlyValidatingElement$1(fragment);
error('Invalid attribute `ref` supplied to `React.Fragment`.');
setCurrentlyValidatingElement$1(null);
}
}
}
function createElementWithValidation(type, props, children) {
var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
// succeed and there will likely be errors in render.
if (!validType) {
var info = '';
if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
}
var sourceInfo = getSourceInfoErrorAddendumForProps(props);
if (sourceInfo) {
info += sourceInfo;
} else {
info += getDeclarationErrorAddendum();
}
var typeString;
if (type === null) {
typeString = 'null';
} else if (isArray(type)) {
typeString = 'array';
} else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
info = ' Did you accidentally export a JSX literal instead of a component?';
} else {
typeString = typeof type;
}
{
error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
}
}
var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if (element == null) {
return element;
} // Skip key warning if the type isn't valid since our key validation logic
// doesn't expect a non-string/function type and can throw confusing errors.
// We don't want exception behavior to differ between dev and prod.
// (Rendering will throw with a helpful message and as soon as the type is
// fixed, the key warnings will appear.)
if (validType) {
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], type);
}
}
if (type === exports.Fragment) {
validateFragmentProps(element);
} else {
validatePropTypes(element);
}
return element;
}
var didWarnAboutDeprecatedCreateFactory = false;
function createFactoryWithValidation(type) {
var validatedFactory = createElementWithValidation.bind(null, type);
validatedFactory.type = type;
{
if (!didWarnAboutDeprecatedCreateFactory) {
didWarnAboutDeprecatedCreateFactory = true;
warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.');
} // Legacy hook: remove it
Object.defineProperty(validatedFactory, 'type', {
enumerable: false,
get: function () {
warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.');
Object.defineProperty(this, 'type', {
value: type
});
return type;
}
});
}
return validatedFactory;
}
function cloneElementWithValidation(element, props, children) {
var newElement = cloneElement.apply(this, arguments);
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], newElement.type);
}
validatePropTypes(newElement);
return newElement;
}
function createMutableSource(source, getVersion) {
var mutableSource = {
_getVersion: getVersion,
_source: source,
_workInProgressVersionPrimary: null,
_workInProgressVersionSecondary: null
};
{
mutableSource._currentPrimaryRenderer = null;
mutableSource._currentSecondaryRenderer = null; // Used to detect side effects that update a mutable source during render.
// See https://github.com/facebook/react/issues/19948
mutableSource._currentlyRenderingFiber = null;
mutableSource._initialVersionAsOfFirstRender = null;
}
return mutableSource;
}
var enableSchedulerDebugging = false;
var enableProfiling = false;
var frameYieldMs = 5;
function push(heap, node) {
var index = heap.length;
heap.push(node);
siftUp(heap, node, index);
}
function peek(heap) {
return heap.length === 0 ? null : heap[0];
}
function pop(heap) {
if (heap.length === 0) {
return null;
}
var first = heap[0];
var last = heap.pop();
if (last !== first) {
heap[0] = last;
siftDown(heap, last, 0);
}
return first;
}
function siftUp(heap, node, i) {
var index = i;
while (index > 0) {
var parentIndex = index - 1 >>> 1;
var parent = heap[parentIndex];
if (compare(parent, node) > 0) {
// The parent is larger. Swap positions.
heap[parentIndex] = node;
heap[index] = parent;
index = parentIndex;
} else {
// The parent is smaller. Exit.
return;
}
}
}
function siftDown(heap, node, i) {
var index = i;
var length = heap.length;
var halfLength = length >>> 1;
while (index < halfLength) {
var leftIndex = (index + 1) * 2 - 1;
var left = heap[leftIndex];
var rightIndex = leftIndex + 1;
var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those.
if (compare(left, node) < 0) {
if (rightIndex < length && compare(right, left) < 0) {
heap[index] = right;
heap[rightIndex] = node;
index = rightIndex;
} else {
heap[index] = left;
heap[leftIndex] = node;
index = leftIndex;
}
} else if (rightIndex < length && compare(right, node) < 0) {
heap[index] = right;
heap[rightIndex] = node;
index = rightIndex;
} else {
// Neither child is smaller. Exit.
return;
}
}
}
function compare(a, b) {
// Compare sort index first, then task id.
var diff = a.sortIndex - b.sortIndex;
return diff !== 0 ? diff : a.id - b.id;
}
// TODO: Use symbols?
var ImmediatePriority = 1;
var UserBlockingPriority = 2;
var NormalPriority = 3;
var LowPriority = 4;
var IdlePriority = 5;
function markTaskErrored(task, ms) {
}
/* eslint-disable no-var */
var getCurrentTime;
var hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function';
if (hasPerformanceNow) {
var localPerformance = performance;
getCurrentTime = function () {
return localPerformance.now();
};
} else {
var localDate = Date;
var initialTime = localDate.now();
getCurrentTime = function () {
return localDate.now() - initialTime;
};
} // Max 31 bit integer. The max integer size in V8 for 32-bit systems.
// Math.pow(2, 30) - 1
// 0b111111111111111111111111111111
var maxSigned31BitInt = 1073741823; // Times out immediately
var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out
var USER_BLOCKING_PRIORITY_TIMEOUT = 250;
var NORMAL_PRIORITY_TIMEOUT = 5000;
var LOW_PRIORITY_TIMEOUT = 10000; // Never times out
var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap
var taskQueue = [];
var timerQueue = []; // Incrementing id counter. Used to maintain insertion order.
var taskIdCounter = 1; // Pausing the scheduler is useful for debugging.
var currentTask = null;
var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance.
var isPerformingWork = false;
var isHostCallbackScheduled = false;
var isHostTimeoutScheduled = false; // Capture local references to native APIs, in case a polyfill overrides them.
var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : null;
var localClearTimeout = typeof clearTimeout === 'function' ? clearTimeout : null;
var localSetImmediate = typeof setImmediate !== 'undefined' ? setImmediate : null; // IE and Node.js + jsdom
var isInputPending = typeof navigator !== 'undefined' && navigator.scheduling !== undefined && navigator.scheduling.isInputPending !== undefined ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null;
function advanceTimers(currentTime) {
// Check for tasks that are no longer delayed and add them to the queue.
var timer = peek(timerQueue);
while (timer !== null) {
if (timer.callback === null) {
// Timer was cancelled.
pop(timerQueue);
} else if (timer.startTime <= currentTime) {
// Timer fired. Transfer to the task queue.
pop(timerQueue);
timer.sortIndex = timer.expirationTime;
push(taskQueue, timer);
} else {
// Remaining timers are pending.
return;
}
timer = peek(timerQueue);
}
}
function handleTimeout(currentTime) {
isHostTimeoutScheduled = false;
advanceTimers(currentTime);
if (!isHostCallbackScheduled) {
if (peek(taskQueue) !== null) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
} else {
var firstTimer = peek(timerQueue);
if (firstTimer !== null) {
requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
}
}
}
}
function flushWork(hasTimeRemaining, initialTime) {
isHostCallbackScheduled = false;
if (isHostTimeoutScheduled) {
// We scheduled a timeout but it's no longer needed. Cancel it.
isHostTimeoutScheduled = false;
cancelHostTimeout();
}
isPerformingWork = true;
var previousPriorityLevel = currentPriorityLevel;
try {
if (enableProfiling) {
try {
return workLoop(hasTimeRemaining, initialTime);
} catch (error) {
if (currentTask !== null) {
var currentTime = getCurrentTime();
markTaskErrored(currentTask, currentTime);
currentTask.isQueued = false;
}
throw error;
}
} else {
// No catch in prod code path.
return workLoop(hasTimeRemaining, initialTime);
}
} finally {
currentTask = null;
currentPriorityLevel = previousPriorityLevel;
isPerformingWork = false;
}
}
function workLoop(hasTimeRemaining, initialTime) {
var currentTime = initialTime;
advanceTimers(currentTime);
currentTask = peek(taskQueue);
while (currentTask !== null && !(enableSchedulerDebugging )) {
if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) {
// This currentTask hasn't expired, and we've reached the deadline.
break;
}
var callback = currentTask.callback;
if (typeof callback === 'function') {
currentTask.callback = null;
currentPriorityLevel = currentTask.priorityLevel;
var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
var continuationCallback = callback(didUserCallbackTimeout);
currentTime = getCurrentTime();
if (typeof continuationCallback === 'function') {
currentTask.callback = continuationCallback;
} else {
if (currentTask === peek(taskQueue)) {
pop(taskQueue);
}
}
advanceTimers(currentTime);
} else {
pop(taskQueue);
}
currentTask = peek(taskQueue);
} // Return whether there's additional work
if (currentTask !== null) {
return true;
} else {
var firstTimer = peek(timerQueue);
if (firstTimer !== null) {
requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
}
return false;
}
}
function unstable_runWithPriority(priorityLevel, eventHandler) {
switch (priorityLevel) {
case ImmediatePriority:
case UserBlockingPriority:
case NormalPriority:
case LowPriority:
case IdlePriority:
break;
default:
priorityLevel = NormalPriority;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
}
function unstable_next(eventHandler) {
var priorityLevel;
switch (currentPriorityLevel) {
case ImmediatePriority:
case UserBlockingPriority:
case NormalPriority:
// Shift down to normal priority
priorityLevel = NormalPriority;
break;
default:
// Anything lower than normal priority should remain at the current level.
priorityLevel = currentPriorityLevel;
break;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
}
function unstable_wrapCallback(callback) {
var parentPriorityLevel = currentPriorityLevel;
return function () {
// This is a fork of runWithPriority, inlined for performance.
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = parentPriorityLevel;
try {
return callback.apply(this, arguments);
} finally {
currentPriorityLevel = previousPriorityLevel;
}
};
}
function unstable_scheduleCallback(priorityLevel, callback, options) {
var currentTime = getCurrentTime();
var startTime;
if (typeof options === 'object' && options !== null) {
var delay = options.delay;
if (typeof delay === 'number' && delay > 0) {
startTime = currentTime + delay;
} else {
startTime = currentTime;
}
} else {
startTime = currentTime;
}
var timeout;
switch (priorityLevel) {
case ImmediatePriority:
timeout = IMMEDIATE_PRIORITY_TIMEOUT;
break;
case UserBlockingPriority:
timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
break;
case IdlePriority:
timeout = IDLE_PRIORITY_TIMEOUT;
break;
case LowPriority:
timeout = LOW_PRIORITY_TIMEOUT;
break;
case NormalPriority:
default:
timeout = NORMAL_PRIORITY_TIMEOUT;
break;
}
var expirationTime = startTime + timeout;
var newTask = {
id: taskIdCounter++,
callback: callback,
priorityLevel: priorityLevel,
startTime: startTime,
expirationTime: expirationTime,
sortIndex: -1
};
if (startTime > currentTime) {
// This is a delayed task.
newTask.sortIndex = startTime;
push(timerQueue, newTask);
if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
// All tasks are delayed, and this is the task with the earliest delay.
if (isHostTimeoutScheduled) {
// Cancel an existing timeout.
cancelHostTimeout();
} else {
isHostTimeoutScheduled = true;
} // Schedule a timeout.
requestHostTimeout(handleTimeout, startTime - currentTime);
}
} else {
newTask.sortIndex = expirationTime;
push(taskQueue, newTask);
// wait until the next time we yield.
if (!isHostCallbackScheduled && !isPerformingWork) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
}
}
return newTask;
}
function unstable_pauseExecution() {
}
function unstable_continueExecution() {
if (!isHostCallbackScheduled && !isPerformingWork) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
}
}
function unstable_getFirstCallbackNode() {
return peek(taskQueue);
}
function unstable_cancelCallback(task) {
// remove from the queue because you can't remove arbitrary nodes from an
// array based heap, only the first one.)
task.callback = null;
}
function unstable_getCurrentPriorityLevel() {
return currentPriorityLevel;
}
var isMessageLoopRunning = false;
var scheduledHostCallback = null;
var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main
// thread, like user events. By default, it yields multiple times per frame.
// It does not attempt to align with frame boundaries, since most tasks don't
// need to be frame aligned; for those that do, use requestAnimationFrame.
var frameInterval = frameYieldMs;
var startTime = -1;
function shouldYieldToHost() {
var timeElapsed = getCurrentTime() - startTime;
if (timeElapsed < frameInterval) {
// The main thread has only been blocked for a really short amount of time;
// smaller than a single frame. Don't yield yet.
return false;
} // The main thread has been blocked for a non-negligible amount of time. We
return true;
}
function requestPaint() {
}
function forceFrameRate(fps) {
if (fps < 0 || fps > 125) {
// Using console['error'] to evade Babel and ESLint
console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported');
return;
}
if (fps > 0) {
frameInterval = Math.floor(1000 / fps);
} else {
// reset the framerate
frameInterval = frameYieldMs;
}
}
var performWorkUntilDeadline = function () {
if (scheduledHostCallback !== null) {
var currentTime = getCurrentTime(); // Keep track of the start time so we can measure how long the main thread
// has been blocked.
startTime = currentTime;
var hasTimeRemaining = true; // If a scheduler task throws, exit the current browser task so the
// error can be observed.
//
// Intentionally not using a try-catch, since that makes some debugging
// techniques harder. Instead, if `scheduledHostCallback` errors, then
// `hasMoreWork` will remain true, and we'll continue the work loop.
var hasMoreWork = true;
try {
hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
} finally {
if (hasMoreWork) {
// If there's more work, schedule the next message event at the end
// of the preceding one.
schedulePerformWorkUntilDeadline();
} else {
isMessageLoopRunning = false;
scheduledHostCallback = null;
}
}
} else {
isMessageLoopRunning = false;
} // Yielding to the browser will give it a chance to paint, so we can
};
var schedulePerformWorkUntilDeadline;
if (typeof localSetImmediate === 'function') {
// Node.js and old IE.
// There's a few reasons for why we prefer setImmediate.
//
// Unlike MessageChannel, it doesn't prevent a Node.js process from exiting.
// (Even though this is a DOM fork of the Scheduler, you could get here
// with a mix of Node.js 15+, which has a MessageChannel, and jsdom.)
// https://github.com/facebook/react/issues/20756
//
// But also, it runs earlier which is the semantic we want.
// If other browsers ever implement it, it's better to use it.
// Although both of these would be inferior to native scheduling.
schedulePerformWorkUntilDeadline = function () {
localSetImmediate(performWorkUntilDeadline);
};
} else if (typeof MessageChannel !== 'undefined') {
// DOM and Worker environments.
// We prefer MessageChannel because of the 4ms setTimeout clamping.
var channel = new MessageChannel();
var port = channel.port2;
channel.port1.onmessage = performWorkUntilDeadline;
schedulePerformWorkUntilDeadline = function () {
port.postMessage(null);
};
} else {
// We should only fallback here in non-browser environments.
schedulePerformWorkUntilDeadline = function () {
localSetTimeout(performWorkUntilDeadline, 0);
};
}
function requestHostCallback(callback) {
scheduledHostCallback = callback;
if (!isMessageLoopRunning) {
isMessageLoopRunning = true;
schedulePerformWorkUntilDeadline();
}
}
function requestHostTimeout(callback, ms) {
taskTimeoutID = localSetTimeout(function () {
callback(getCurrentTime());
}, ms);
}
function cancelHostTimeout() {
localClearTimeout(taskTimeoutID);
taskTimeoutID = -1;
}
var unstable_requestPaint = requestPaint;
var unstable_Profiling = null;
var Scheduler = /*#__PURE__*/Object.freeze({
__proto__: null,
unstable_ImmediatePriority: ImmediatePriority,
unstable_UserBlockingPriority: UserBlockingPriority,
unstable_NormalPriority: NormalPriority,
unstable_IdlePriority: IdlePriority,
unstable_LowPriority: LowPriority,
unstable_runWithPriority: unstable_runWithPriority,
unstable_next: unstable_next,
unstable_scheduleCallback: unstable_scheduleCallback,
unstable_cancelCallback: unstable_cancelCallback,
unstable_wrapCallback: unstable_wrapCallback,
unstable_getCurrentPriorityLevel: unstable_getCurrentPriorityLevel,
unstable_shouldYield: shouldYieldToHost,
unstable_requestPaint: unstable_requestPaint,
unstable_continueExecution: unstable_continueExecution,
unstable_pauseExecution: unstable_pauseExecution,
unstable_getFirstCallbackNode: unstable_getFirstCallbackNode,
get unstable_now () { return getCurrentTime; },
unstable_forceFrameRate: forceFrameRate,
unstable_Profiling: unstable_Profiling
});
var ReactSharedInternals$1 = {
ReactCurrentDispatcher: ReactCurrentDispatcher,
ReactCurrentOwner: ReactCurrentOwner,
ReactCurrentBatchConfig: ReactCurrentBatchConfig,
// Used by renderers to avoid bundling object-assign twice in UMD bundles:
assign: assign,
// Re-export the schedule API(s) for UMD bundles.
// This avoids introducing a dependency on a new UMD global in a minor update,
// Since that would be a breaking change (e.g. for all existing CodeSandboxes).
// This re-export is only required for UMD bundles;
// CJS bundles use the shared NPM package.
Scheduler: Scheduler
};
{
ReactSharedInternals$1.ReactCurrentActQueue = ReactCurrentActQueue;
ReactSharedInternals$1.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
}
function startTransition(scope) {
var prevTransition = ReactCurrentBatchConfig.transition;
ReactCurrentBatchConfig.transition = 1;
try {
scope();
} finally {
ReactCurrentBatchConfig.transition = prevTransition;
{
if (prevTransition !== 1 && warnOnSubscriptionInsideStartTransition && ReactCurrentBatchConfig._updatedFibers) {
var updatedFibersCount = ReactCurrentBatchConfig._updatedFibers.size;
if (updatedFibersCount > 10) {
warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.');
}
ReactCurrentBatchConfig._updatedFibers.clear();
}
}
}
}
var didWarnAboutMessageChannel = false;
var enqueueTaskImpl = null;
function enqueueTask(task) {
if (enqueueTaskImpl === null) {
try {
// read require off the module object to get around the bundlers.
// we don't want them to detect a require and bundle a Node polyfill.
var requireString = ('require' + Math.random()).slice(0, 7);
var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's
// version of setImmediate, bypassing fake timers if any.
enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate;
} catch (_err) {
// we're in a browser
// we can't use regular timers because they may still be faked
// so we try MessageChannel+postMessage instead
enqueueTaskImpl = function (callback) {
{
if (didWarnAboutMessageChannel === false) {
didWarnAboutMessageChannel = true;
if (typeof MessageChannel === 'undefined') {
error('This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.');
}
}
}
var channel = new MessageChannel();
channel.port1.onmessage = callback;
channel.port2.postMessage(undefined);
};
}
}
return enqueueTaskImpl(task);
}
var actScopeDepth = 0;
var didWarnNoAwaitAct = false;
function act(callback) {
{
// `act` calls can be nested, so we track the depth. This represents the
// number of `act` scopes on the stack.
var prevActScopeDepth = actScopeDepth;
actScopeDepth++;
if (ReactCurrentActQueue.current === null) {
// This is the outermost `act` scope. Initialize the queue. The reconciler
// will detect the queue and use it instead of Scheduler.
ReactCurrentActQueue.current = [];
}
var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy;
var result;
try {
// Used to reproduce behavior of `batchedUpdates` in legacy mode. Only
// set to `true` while the given callback is executed, not for updates
// triggered during an async event, because this is how the legacy
// implementation of `act` behaved.
ReactCurrentActQueue.isBatchingLegacy = true;
result = callback(); // Replicate behavior of original `act` implementation in legacy mode,
// which flushed updates immediately after the scope function exits, even
// if it's an async function.
if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) {
var queue = ReactCurrentActQueue.current;
if (queue !== null) {
ReactCurrentActQueue.didScheduleLegacyUpdate = false;
flushActQueue(queue);
}
}
} catch (error) {
popActScope(prevActScopeDepth);
throw error;
} finally {
ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy;
}
if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
var thenableResult = result; // The callback is an async function (i.e. returned a promise). Wait
// for it to resolve before exiting the current scope.
var wasAwaited = false;
var thenable = {
then: function (resolve, reject) {
wasAwaited = true;
thenableResult.then(function (returnValue) {
popActScope(prevActScopeDepth);
if (actScopeDepth === 0) {
// We've exited the outermost act scope. Recursively flush the
// queue until there's no remaining work.
recursivelyFlushAsyncActWork(returnValue, resolve, reject);
} else {
resolve(returnValue);
}
}, function (error) {
// The callback threw an error.
popActScope(prevActScopeDepth);
reject(error);
});
}
};
{
if (!didWarnNoAwaitAct && typeof Promise !== 'undefined') {
// eslint-disable-next-line no-undef
Promise.resolve().then(function () {}).then(function () {
if (!wasAwaited) {
didWarnNoAwaitAct = true;
error('You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, ' + 'interleaving multiple act calls and mixing their ' + 'scopes. ' + 'You should - await act(async () => ...);');
}
});
}
}
return thenable;
} else {
var returnValue = result; // The callback is not an async function. Exit the current scope
// immediately, without awaiting.
popActScope(prevActScopeDepth);
if (actScopeDepth === 0) {
// Exiting the outermost act scope. Flush the queue.
var _queue = ReactCurrentActQueue.current;
if (_queue !== null) {
flushActQueue(_queue);
ReactCurrentActQueue.current = null;
} // Return a thenable. If the user awaits it, we'll flush again in
// case additional work was scheduled by a microtask.
var _thenable = {
then: function (resolve, reject) {
// Confirm we haven't re-entered another `act` scope, in case
// the user does something weird like await the thenable
// multiple times.
if (ReactCurrentActQueue.current === null) {
// Recursively flush the queue until there's no remaining work.
ReactCurrentActQueue.current = [];
recursivelyFlushAsyncActWork(returnValue, resolve, reject);
} else {
resolve(returnValue);
}
}
};
return _thenable;
} else {
// Since we're inside a nested `act` scope, the returned thenable
// immediately resolves. The outer scope will flush the queue.
var _thenable2 = {
then: function (resolve, reject) {
resolve(returnValue);
}
};
return _thenable2;
}
}
}
}
function popActScope(prevActScopeDepth) {
{
if (prevActScopeDepth !== actScopeDepth - 1) {
error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. ');
}
actScopeDepth = prevActScopeDepth;
}
}
function recursivelyFlushAsyncActWork(returnValue, resolve, reject) {
{
var queue = ReactCurrentActQueue.current;
if (queue !== null) {
try {
flushActQueue(queue);
enqueueTask(function () {
if (queue.length === 0) {
// No additional work was scheduled. Finish.
ReactCurrentActQueue.current = null;
resolve(returnValue);
} else {
// Keep flushing work until there's none left.
recursivelyFlushAsyncActWork(returnValue, resolve, reject);
}
});
} catch (error) {
reject(error);
}
} else {
resolve(returnValue);
}
}
}
var isFlushing = false;
function flushActQueue(queue) {
{
if (!isFlushing) {
// Prevent re-entrance.
isFlushing = true;
var i = 0;
try {
for (; i < queue.length; i++) {
var callback = queue[i];
do {
callback = callback(true);
} while (callback !== null);
}
queue.length = 0;
} catch (error) {
// If something throws, leave the remaining callbacks on the queue.
queue = queue.slice(i + 1);
throw error;
} finally {
isFlushing = false;
}
}
}
}
var createElement$1 = createElementWithValidation ;
var cloneElement$1 = cloneElementWithValidation ;
var createFactory = createFactoryWithValidation ;
var Children = {
map: mapChildren,
forEach: forEachChildren,
count: countChildren,
toArray: toArray,
only: onlyChild
};
exports.Children = Children;
exports.Component = Component;
exports.PureComponent = PureComponent;
exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals$1;
exports.cloneElement = cloneElement$1;
exports.createContext = createContext;
exports.createElement = createElement$1;
exports.createFactory = createFactory;
exports.createRef = createRef;
exports.forwardRef = forwardRef;
exports.isValidElement = isValidElement;
exports.lazy = lazy;
exports.memo = memo;
exports.startTransition = startTransition;
exports.unstable_act = act;
exports.unstable_createMutableSource = createMutableSource;
exports.unstable_useMutableSource = useMutableSource;
exports.unstable_useOpaqueIdentifier = useOpaqueIdentifier;
exports.useCallback = useCallback;
exports.useContext = useContext;
exports.useDebugValue = useDebugValue;
exports.useDeferredValue = useDeferredValue;
exports.useEffect = useEffect;
exports.useImperativeHandle = useImperativeHandle;
exports.useLayoutEffect = useLayoutEffect;
exports.useMemo = useMemo;
exports.useReducer = useReducer;
exports.useRef = useRef;
exports.useState = useState;
exports.useTransition = useTransition;
exports.version = ReactVersion;
})));
| cdnjs/cdnjs | ajax/libs/react/18.0.0-alpha-bdd6d5064-20211001/umd/react.development.js | JavaScript | mit | 112,128 |
<?
$prefix = $_SERVER['DOCUMENT_ROOT'];
require_once($prefix . '/common/markdown.php');
require_once($prefix . '/common/smartypants.php');
// Connect to Database
include('common/dbconnect.php');
// Only items that have been published
// (No posts scheduled for the future)
$post_cutoff_time = time();
// Number of Posts
$num_of_posts = 14;
// Troubleshoot?
$troubleshoot = FALSE;
// Last Updated
$last_updated_query = "SELECT MAX(published_time) AS last_update FROM blog WHERE published_time<$post_cutoff_time";
$last_updated_result = $mysqli->query($last_updated_query);
$last_updated_array = $last_updated_result->fetch_array(MYSQLI_ASSOC);
$last_updated_timestamp = $last_updated_array['last_update'];
$last_updated = date('c', $last_updated_timestamp);
// Preamble
if(!$troubleshoot){
echo '<?xml version="1.0" encoding="utf-8"?>' . "\n";
echo '<feed xmlns="http://www.w3.org/2005/Atom">' . "\n";
}
echo '<title>MEK Studios</title>' . "\n";
echo '<id>tag:www.mekstudios.com,2013-02-10:/notional/20130210055031443</id>' . "\n";
echo '<subtitle type="html">Critical thinking to start your day.<br>A blog of ideas, thoughts, and concepts for consideration.</subtitle>' . "\n";
echo '<link rel="alternate" type="text/html" hreflang="en" href="https://www.mekstudios.com/"/>' . "\n";
echo '<link rel="self" type="application/atom+xml" href="https://www.mekstudios.com/feed/"/>' . "\n";
echo '<rights>Copyright (c) 2013 Michael E. Kirkpatrick</rights>' . "\n";
echo '<updated>' . $last_updated . '</updated>' . "\n";
echo '<author>' . "\n";
echo ' <name>Michael E. Kirkpatrick</name>' . "\n";
echo ' <uri>http://www.mekstudios.com</uri>' . "\n";
echo ' <email>michael@mekstudios.com</email>' . "\n";
echo '</author>' . "\n";
// Cycle through posts
$article_query = "SELECT url, link, title, author, published_time, published_month, published_year, updated_time, text, atom_id FROM blog WHERE published_time<$post_cutoff_time ORDER BY published_time DESC LIMIT $num_of_posts";
$article_result = $mysqli->query($article_query);
while($article_array = $article_result->fetch_array(MYSQLI_ASSOC)){
echo '<entry>' . "\n";
//echo ' <title type="html">' . htmlspecialchars(html_entity_decode($article_array['title'], ENT_QUOTES | ENT_HTML5, "UTF-8")) . '</title>' . "\n";
echo ' <title type="html">' . htmlspecialchars(SmartyPants($article_array['title'], ENT_QUOTES | ENT_HTML5, "UTF-8")) . '</title>' . "\n";
echo ' <id>' . $article_array['atom_id'] . '</id>' . "\n";
if($article_array['link'] != ''){echo ' <link href="' . htmlspecialchars($article_array['link']) . '" rel="via" type="text/html" />' . "\n";}
echo ' <link href="http://www.mekstudios.com/' . $article_array['published_year'] . '/' . $article_array['published_month'] . '/' . $article_array['url'] . '" rel="alternate" type="text/html" />' . "\n";
echo ' <published>' . date('c', $article_array['published_time']) . '</published>' . "\n";
# If Updated
if($article_array['updated_time'] != ''){
echo ' <updated>' . date('c', $article_array['updated_time']) . '</updated>' . "\n";
}else{
echo ' <updated>' . date('c', $article_array['published_time']) . '</updated>' . "\n";
}
echo ' <author>' . "\n";
echo ' <name>' . $article_array['author'] . '</name>' . "\n";
echo ' </author>' . "\n";
$text_display = SmartyPants(Markdown($article_array['text']));
//$text_display = html_entity_decode($article_array['text'], ENT_QUOTES | ENT_HTML5, "UTF-8");
//$text_display = str_replace('\r\n', '', $text_display);
$find = array('&', '<');
$replace = array('&', '<');
$text_display = str_replace($find, $replace, $text_display);
echo ' <content type="html">' . $text_display . '</content>' . "\n";
echo '</entry>' . "\n";
}
// End of Feed
echo '</feed>' . "\n";
?> | mk14/Long-Beach | atom-feed.php | PHP | mit | 3,777 |
angular.module('ExampleCtrl', []).controller('ExampleCtrl', ['$scope',
function($scope) {
$scope.createItems = function() {
$scope.items = [];
for (var i = 0; i < 100; i++) {
$scope.items[i] = {
ratio: Math.max(0.4, Math.random() * 2),
color: '#' + ('000000' + Math.floor(Math.random()*16777215).toString(16)).slice(-6)
};
}
};
$scope.createItems();
}
]);
angular.module('ExampleApp', ['hj.columnify', 'ExampleCtrl']).config(function() {}); | homerjam/angular-columnify | example/app.js | JavaScript | mit | 557 |
package model.expression;
/**
* The type Operation.
*/
public class Operation
{
/**
* The constant ADD.
*/
public static final int ADD = 1;
/**
* The constant SUBTRACT.
*/
public static final int SUBTRACT = 2;
/**
* The constant MULTIPLY.
*/
public static final int MULTIPLY = 3;
/**
* The constant DIVIDE.
*/
public static final int DIVIDE = 4;
/**
* Operation to string.
*
* @param op the op
* @return the string
*/
public static String operationToString(int op)
{
switch (op)
{
case ADD:
return "+";
case SUBTRACT:
return "-";
case MULTIPLY:
return "*";
case DIVIDE:
return "/";
default:
return "";
}
}
} | leyyin/university | advanced-programming-methods/labs/toy-interpreter-java/src/model/expression/Operation.java | Java | mit | 895 |
var _ = require('lodash'),
EventEmitter = require('events').EventEmitter,
config = require('./config'),
Channel = require('./channel'),
Connection = require('./connection'),
Bus = require('./bus'),
API = require('./utils');
var subscribedChannels;
function Gusher (applicationKey, options) {
options || (options = {});
subscribedChannels = {};
this.options = options;
this.bus = new Bus();
this.connection = new Connection(this.bus);
}
Gusher.prototype.subscribe = function (channelName) {
var channel = new Channel(channelName, this.bus);
subscribedChannels[channelName] = channel;
return channel;
};
Gusher.prototype.unsubscribe = function (channelName) {
};
Gusher.prototype.allChannels = function () {
return _.values(subscribedChannels);
};
Gusher.prototype.disconnect = function () {
this.connection.disconnect();
//TODO actually unsubscribe from each channel
};
module.exports = {
gusher: Gusher,
api: API
};
| dobrite/gusher | src/javascripts/gusher.js | JavaScript | mit | 1,015 |
var less = require('less');
var lessStr = '.class { width: (1+1)}';
less.render(lessStr, function(e, output) {
console.log(output.css);
});
console.log(less.render(lessStr)); | escray/besike-nodejs-harp | lessExample.js | JavaScript | mit | 177 |
namespace LibMinecraft
{
public struct Vector3
{
public static Vector3 Zero
{
get { return new Vector3(0, 0, 0); }
}
public static Vector3 UpX
{
get { return new Vector3(1, 0, 0); }
}
public static Vector3 UpY
{
get { return new Vector3(0, 1, 0); }
}
public static Vector3 UpZ
{
get { return new Vector3(0, 0, 1); }
}
public double X;
public double Y;
public double Z;
public Vector3(double x, double y, double z)
{
X = x;
Y = y;
Z = z;
}
public static Vector3 operator +(Vector3 a, Vector3 b)
{
return new Vector3(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
}
public static Vector3 operator -(Vector3 a, Vector3 b)
{
return new Vector3(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
}
public static Vector3 operator *(Vector3 a, Vector3 b)
{
return new Vector3(a.X * b.X, a.Y * b.Y, a.Z * b.Z);
}
public static Vector3 operator /(Vector3 a, Vector3 b)
{
return new Vector3(a.X / b.X, a.Y / b.Y, a.Z / b.Z);
}
}
} | inku25253/MineProtocol.net | LibMinecraft/Vector3.cs | C# | mit | 996 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TheCode
{
public class Customer
{
public string Id { get; set; }
public string Name { get; set; }
public bool Pro { get; set; }
}
}
| chadmichel/UnitTest | TheCode/Customer.cs | C# | mit | 298 |
<?php
$ISO_3166_2 = array();
$ISO_3166_2['01'] = "Adana";
$ISO_3166_2['02'] = "Adiyaman";
$ISO_3166_2['03'] = "Afyonkarahisar";
$ISO_3166_2['04'] = "Agri";
$ISO_3166_2['68'] = "Aksaray";
$ISO_3166_2['05'] = "Amasya";
$ISO_3166_2['06'] = "Ankara";
$ISO_3166_2['07'] = "Antalya";
$ISO_3166_2['75'] = "Ardahan";
$ISO_3166_2['08'] = "Artvin";
$ISO_3166_2['09'] = "Aydin";
$ISO_3166_2['10'] = "Balikesir";
$ISO_3166_2['74'] = "Bartin";
$ISO_3166_2['72'] = "Batman";
$ISO_3166_2['69'] = "Bayburt";
$ISO_3166_2['11'] = "Bilecik";
$ISO_3166_2['12'] = "Bingöl";
$ISO_3166_2['13'] = "Bitlis";
$ISO_3166_2['14'] = "Bolu";
$ISO_3166_2['15'] = "Burdur";
$ISO_3166_2['16'] = "Bursa";
$ISO_3166_2['20'] = "Denizli";
$ISO_3166_2['21'] = "Diyarbakir";
$ISO_3166_2['81'] = "Düzce";
$ISO_3166_2['22'] = "Edirne";
$ISO_3166_2['23'] = "Elazig";
$ISO_3166_2['24'] = "Erzincan";
$ISO_3166_2['25'] = "Erzurum";
$ISO_3166_2['26'] = "Eskisehir";
$ISO_3166_2['27'] = "Gaziantep";
$ISO_3166_2['28'] = "Giresun";
$ISO_3166_2['29'] = "Gümüshane";
$ISO_3166_2['30'] = "Hakkâri";
$ISO_3166_2['31'] = "Hatay";
$ISO_3166_2['76'] = "Igdir";
$ISO_3166_2['32'] = "Isparta";
$ISO_3166_2['34'] = "Istanbul";
$ISO_3166_2['35'] = "Izmir";
$ISO_3166_2['46'] = "Kahramanmaras";
$ISO_3166_2['78'] = "Karabük";
$ISO_3166_2['70'] = "Karaman";
$ISO_3166_2['36'] = "Kars";
$ISO_3166_2['37'] = "Kastamonu";
$ISO_3166_2['38'] = "Kayseri";
$ISO_3166_2['79'] = "Kilis";
$ISO_3166_2['71'] = "Kirikkale";
$ISO_3166_2['39'] = "Kirklareli";
$ISO_3166_2['40'] = "Kirsehir";
$ISO_3166_2['41'] = "Kocaeli";
$ISO_3166_2['42'] = "Konya";
$ISO_3166_2['43'] = "Kütahya";
$ISO_3166_2['44'] = "Malatya";
$ISO_3166_2['45'] = "Manisa";
$ISO_3166_2['47'] = "Mardin";
$ISO_3166_2['33'] = "Mersin";
$ISO_3166_2['48'] = "Mugla";
$ISO_3166_2['49'] = "Mus";
$ISO_3166_2['50'] = "Nevsehir";
$ISO_3166_2['51'] = "Nigde";
$ISO_3166_2['52'] = "Ordu";
$ISO_3166_2['80'] = "Osmaniye";
$ISO_3166_2['53'] = "Rize";
$ISO_3166_2['54'] = "Sakarya";
$ISO_3166_2['55'] = "Samsun";
$ISO_3166_2['63'] = "Sanliurfa";
$ISO_3166_2['56'] = "Siirt";
$ISO_3166_2['57'] = "Sinop";
$ISO_3166_2['73'] = "Sirnak";
$ISO_3166_2['58'] = "Sivas";
$ISO_3166_2['59'] = "Tekirdag";
$ISO_3166_2['60'] = "Tokat";
$ISO_3166_2['61'] = "Trabzon";
$ISO_3166_2['62'] = "Tunceli";
$ISO_3166_2['64'] = "Usak";
$ISO_3166_2['65'] = "Van";
$ISO_3166_2['77'] = "Yalova";
$ISO_3166_2['66'] = "Yozgat";
$ISO_3166_2['67'] = "Zonguldak";
$ISO_3166_2['17'] = "Çanakkale";
$ISO_3166_2['18'] = "Çankiri";
$ISO_3166_2['19'] = "Çorum";
?>
| Yarduddles/ISO-3166 | PHP/ISO-3166-2-TR.php | PHP | mit | 2,522 |
<?php
require_once(__DIR__ . "/../model/config.php");
//takes and stores exp - exp4
//$exp = filter_input(INPUT_POST, "exp", FILTER_SANITIZE_STRING);
//$exp1 = filter_input(INPUT_POST, "exp1", FILTER_SANITIZE_STRING);
//$exp2 = filter_input(INPUT_POST, "exp2", FILTER_SANITIZE_STRING);
//$exp3 = filter_input(INPUT_POST, "exp3", FILTER_SANITIZE_STRING);
//$exp4 = filter_input(INPUT_POST, "exp4", FILTER_SANITIZE_STRING);
//
//
//$query = $_SESSION["connection"]->query("UPDATE users SET "
// . "exp = $exp, "
// . "exp1 = $exp1, "
// . "exp2 = $exp2, "
// . "exp3 = $exp3, "
// . "exp4 = $exp4 WHERE username = \"" . $_SESSION["name"]. "\"");
//
if($query) {
//need for Ajax
echo "true";
}
else {
echo "<p>" . $_SESSION["connection"]->error . "</p>";
} | SimonAnna/final | Php/controller/save-user.php | PHP | mit | 815 |
import React from "react";
import { SelectAddressModal } from "../ImportAccount";
import { roundingNumber } from "../../utils/converter"
import PathSelector from "../../containers/CommonElements/PathSelector";
const ImportByDeviceView = (props) => {
function choosePath(dpath) {
let inputPath = document.getElementById('form-input-custom-path');
let selectedPath = dpath.value;
if (!selectedPath) {
selectedPath = inputPath.value;
dpath = { value: selectedPath, desc: 'Your Custom Path' };
}
props.choosePath(dpath);
props.analytics.callTrack("trackChoosePathColdWallet", selectedPath);
}
function getAddress(formAddress) {
let data = {
address: formAddress.addressString,
type: props.walletType,
path: props.currentDPath.value + '/' + formAddress.index,
};
if (props.currentDPath.bip44) {
data.path = `${props.currentDPath.value}/${formAddress.index}'/0/0`;
}
props.getAddress(data);
}
function getCurrentList() {
let currentListHtml = props.currentAddresses.map((address) => {
return (
<div className={"address-item"} key={address.addressString}>
<div className="address-item__address">
<div class="name text-lowercase theme__text-6">
<label class="mb-0">
<span class="hash">{address.addressString.slice(0, 12)}...{address.addressString.slice(-8)}</span>
</label>
</div>
</div>
<div class="address-item__import">
<div class="balance theme__text-6 common__flexbox-normal" title={address.balance}>
{address.balance == '-1' ?
<img src={require(`../../../assets/img/${props.theme === 'dark' ? 'waiting-black' : 'waiting-white'}.svg`)}/>
: roundingNumber(address.balance)
} ETH
</div>
<div class="import" onClick={() => getAddress(address)}>
{props.translate("import.import") || "Import"}
</div>
</div>
</div>
)
})
return currentListHtml;
}
function getListPathHtml() {
return (
<PathSelector
listItem={props.allDPaths}
choosePath={choosePath}
walletType={props.walletType}
currentDPath={props.currentDPath}
analytics={props.analytics}
/>
)
}
function getSelectAddressHtml() {
return (
<div className={"import-modal"}>
<div class="import-modal__header cold-wallet">
<div className="import-modal__header--title">
{props.translate(`modal.select_${props.walletType}_address`) || 'Select address'}
</div>
<div class="x" onClick={props.onRequestClose}>×</div>
</div>
<div class="import-modal__body">
<div class="cold-wallet__path">
<div class="cold-wallet__path--title">
{props.translate("modal.select_hd_path") || "Select HD derivation path"}
</div>
<div className="cold-wallet__path--choose-path theme__background-44">
{getListPathHtml()}
</div>
</div>
{props.isLoading && (
<div className="text-center">
<img src={require(`../../../assets/img/${props.theme === 'dark' ? 'waiting-black' : 'waiting-white'}.svg`)}/>
</div>
)}
{!props.isLoading && (
<div className="cold-wallet__address theme__text-6">
<div className="cold-wallet__address--title">
{props.translate("modal.select_address") || "Select the address you would like to interact with"}
</div>
<div className="address-list animated fadeIn">
{getCurrentList()}
</div>
</div>
)}
</div>
<div className={"import-modal__footer import-modal__footer--cold-wallet theme__background-2"}>
<div className={'address-button address-button-previous ' + (props.isFirstList ? 'disabled' : '')}
onClick={props.getPreAddress}>
<div className={"address-arrow address-arrow-left theme__arrow-icon"}/>
</div>
<div className="address-button address-button-next" onClick={props.getMoreAddress}>
<div className={"address-arrow address-arrow-right theme__arrow-icon"}/>
</div>
</div>
</div>
)
}
return ([
<div key='coldwallet'>{props.content}</div>,
<SelectAddressModal
key="modal"
isOpen={props.modalOpen}
onRequestClose={props.onRequestClose}
content={getSelectAddressHtml()}
translate={props.translate}
walletType={props.walletType}
/>
])
}
export default ImportByDeviceView
| KyberNetwork/KyberWallet | src/js/components/ImportAccount/ImportByDeviceView.js | JavaScript | mit | 4,782 |
// Copyright (c) 2014 The Bitcoin Core developers
// Copyright (c) 2014-2015 The Singularity developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/transaction.h"
#include "main.h"
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(main_tests)
BOOST_AUTO_TEST_CASE(subsidy_limit_test)
{
CAmount nSum = 0;
for (int nHeight = 0; nHeight < 14000000; nHeight += 1000) {
/* @TODO fix subsidity, add nBits */
CAmount nSubsidy = GetBlockValue(0, nHeight, 0);
BOOST_CHECK(nSubsidy <= 25 * COIN);
nSum += nSubsidy * 1000;
BOOST_CHECK(MoneyRange(nSum));
}
BOOST_CHECK(nSum == 1350824726649000ULL);
}
BOOST_AUTO_TEST_SUITE_END()
| grumpydevelop/singularity | src/test/main_tests.cpp | C++ | mit | 806 |
class FixColumnName < ActiveRecord::Migration
def change
rename_column :posts, :user, :username
rename_column :tagged_posts, :user, :username
add_column :posts, :likes, :integer
add_column :tagged_posts, :likes, :integer
end
end
| joannangx/visionaria_app | db/migrate/20161029100010_fix_column_name.rb | Ruby | mit | 254 |
package iso20022
// Details of the securities trade.
type SecuritiesTradeDetails54 struct {
// Reference assigned to the trade by the investor or the trading party. This reference will be used throughout the trade life cycle to access/update the trade details.
TradeIdentification []*Max35Text `xml:"TradId,omitempty"`
// Unambiguous identification of a collateral transaction as assigned by the instructing party.
CollateralTransactionIdentification []*Max35Text `xml:"CollTxId,omitempty"`
// Identification of an account owner transaction that could potentially match with the allegement notified.
AccountOwnerTransactionIdentification []*Max35Text `xml:"AcctOwnrTxId,omitempty"`
// Identification of the transaction assigned by the processor of the instruction other than the account owner the account servicer and the market infrastructure.
ProcessorTransactionIdentification *Max35Text `xml:"PrcrTxId,omitempty"`
// Market in which a trade transaction has been executed.
PlaceOfTrade *PlaceOfTradeIdentification1 `xml:"PlcOfTrad,omitempty"`
// Infrastructure which may be a component of a clearing house and which facilitates clearing and settlement for its members by standing between the buyer and the seller. It may net transactions and it substitutes itself as settlement counterparty for each position.
PlaceOfClearing *PlaceOfClearingIdentification1 `xml:"PlcOfClr,omitempty"`
// Specifies the date/time on which the trade was executed.
TradeDate *TradeDate5Choice `xml:"TradDt,omitempty"`
// Date and time at which the securities are to be delivered or received.
SettlementDate *SettlementDate9Choice `xml:"SttlmDt"`
// Specifies the price of the traded financial instrument.
// This is the deal price of the individual trade transaction.
// If there is only one trade transaction for the execution of the trade, then the deal price could equal the executed trade price (unless, for example, the price includes commissions or rounding, or some other factor has been applied to the deal price or the executed trade price, or both).
DealPrice *Price2 `xml:"DealPric,omitempty"`
// Number of days on which the interest rate accrues (daily accrual note).
NumberOfDaysAccrued *Max3Number `xml:"NbOfDaysAcrd,omitempty"`
// Indicates the conditions under which the order/trade is to be/was executed.
TradeTransactionCondition []*TradeTransactionCondition5Choice `xml:"TradTxCond,omitempty"`
// Specifies the type of price and information about the price.
TypeOfPrice *TypeOfPrice29Choice `xml:"TpOfPric,omitempty"`
}
func (s *SecuritiesTradeDetails54) AddTradeIdentification(value string) {
s.TradeIdentification = append(s.TradeIdentification, (*Max35Text)(&value))
}
func (s *SecuritiesTradeDetails54) AddCollateralTransactionIdentification(value string) {
s.CollateralTransactionIdentification = append(s.CollateralTransactionIdentification, (*Max35Text)(&value))
}
func (s *SecuritiesTradeDetails54) AddAccountOwnerTransactionIdentification(value string) {
s.AccountOwnerTransactionIdentification = append(s.AccountOwnerTransactionIdentification, (*Max35Text)(&value))
}
func (s *SecuritiesTradeDetails54) SetProcessorTransactionIdentification(value string) {
s.ProcessorTransactionIdentification = (*Max35Text)(&value)
}
func (s *SecuritiesTradeDetails54) AddPlaceOfTrade() *PlaceOfTradeIdentification1 {
s.PlaceOfTrade = new(PlaceOfTradeIdentification1)
return s.PlaceOfTrade
}
func (s *SecuritiesTradeDetails54) AddPlaceOfClearing() *PlaceOfClearingIdentification1 {
s.PlaceOfClearing = new(PlaceOfClearingIdentification1)
return s.PlaceOfClearing
}
func (s *SecuritiesTradeDetails54) AddTradeDate() *TradeDate5Choice {
s.TradeDate = new(TradeDate5Choice)
return s.TradeDate
}
func (s *SecuritiesTradeDetails54) AddSettlementDate() *SettlementDate9Choice {
s.SettlementDate = new(SettlementDate9Choice)
return s.SettlementDate
}
func (s *SecuritiesTradeDetails54) AddDealPrice() *Price2 {
s.DealPrice = new(Price2)
return s.DealPrice
}
func (s *SecuritiesTradeDetails54) SetNumberOfDaysAccrued(value string) {
s.NumberOfDaysAccrued = (*Max3Number)(&value)
}
func (s *SecuritiesTradeDetails54) AddTradeTransactionCondition() *TradeTransactionCondition5Choice {
newValue := new(TradeTransactionCondition5Choice)
s.TradeTransactionCondition = append(s.TradeTransactionCondition, newValue)
return newValue
}
func (s *SecuritiesTradeDetails54) AddTypeOfPrice() *TypeOfPrice29Choice {
s.TypeOfPrice = new(TypeOfPrice29Choice)
return s.TypeOfPrice
}
| fgrid/iso20022 | SecuritiesTradeDetails54.go | GO | mit | 4,526 |
const Discord = require('discord.js');
const client = new Discord.Client({
forceFetchUsers: true,
autoReconnect: true,
disableEveryone: true,
});
const settings = require('./auth.json');
const chalk = require('chalk');
const fs = require('fs');
const moment = require('moment');
require('./util/eventLoader')(client);
client.on('message', function (message)
{
if (message.channel.isPrivate) {
return;
}
if (message.everyoneMentioned) {
return;
}
if (message.type === 'dm') {
return;
}
});
const log = message => {
console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] ${message}`);
};
client.commands = new Discord.Collection();
client.aliases = new Discord.Collection();
fs.readdir('./commands/', (err, files) => {
if (err) console.error(err);
log(`Loading a total of ${files.length} commands.`);
files.forEach(f => {
let props = require(`./commands/${f}`);
log(`Loading Command: ${props.help.name}. ✔️`);
client.commands.set(props.help.name, props);
props.conf.aliases.forEach(alias => {
client.aliases.set(alias, props.help.name);
});
});
});
client.reload = command => {
return new Promise((resolve, reject) => {
try {
delete require.cache[require.resolve(`./commands/${command}`)];
let cmd = require(`./commands/${command}`);
client.commands.delete(command);
client.aliases.forEach((cmd, alias) => {
if (cmd === command) client.aliases.delete(alias);
});
client.commands.set(command, cmd);
cmd.conf.aliases.forEach(alias => {
client.aliases.set(alias, cmd.help.name);
});
resolve();
} catch (e) {
reject(e);
}
});
};
client.elevation = message => {
/* This function should resolve to an ELEVATION level which
is then sent to the command handler for verification*/
if(!message.guild) return;
let permlvl = 0;
let follower = message.guild.roles.find('name', settings.followerrolename);
if (follower && message.member.roles.has(follower.id)) permlvl = 1;
let player = message.guild.roles.find('name', settings.playerrolename);
if (player && message.member.roles.has(player.id)) permlvl = 2;
let overseer = message.guild.roles.find('name', settings.overseerrolename);
if (overseer && message.member.roles.has(overseer.id)) permlvl = 3;
let trusted = message.guild.roles.find('name', settings.trustedrolename);
if (trusted && message.member.roles.has(trusted.id)) permlvl = 4;
let overlord = message.guild.roles.find('name', settings.overlordrolename);
if (overlord && message.member.roles.has(overlord.id)) permlvl = 5;
if (message.author.id === settings.ownerid) permlvl = 5;
return permlvl;
};
// var regToken = /[\w\d]{24}\.[\w\d]{6}\.[\w\d-_]{27}/g;
//
// client.on('warn', e => {
// console.log(chalk.bgYellow(e.replace(regToken, 'that was redacted')));
// });
//
// client.on('error', e => {
// console.log(chalk.bgRed(e.replace(regToken, 'that was redacted')));
// });
client.login(settings.token);
| Ryahn/SoEBot | bot.js | JavaScript | mit | 2,929 |
class TokyoMetro::App::Renderer::RealTimeInfos::EachRailwayLine < TokyoMetro::Factory::Decorate::MetaClass
TRAIN_OPERATION_STATUS_FOR_TEST = ::YAML.load_file( "#{ ::TokyoMetro::DICTIONARY_DIR }/view/train_operation_status_for_test.yaml" )
def initialize( request , railway_line , http_client , test_mode )
super( request )
@railway_line = railway_line
get_train_operation_info( http_client , test_mode )
get_train_location_infos( http_client , test_mode )
set_max_delay
end
attr_reader :railway_line
attr_reader :train_operation_info
attr_reader :train_location_infos
def render_train_operation_info( controller )
@train_operation_info.decorate( request , @railway_line , @max_delay , controller , no_train? ).render
end
def render_train_location_infos
if @train_location_infos.present?
@train_location_infos.decorate( request , @railway_line ).render
end
end
def update_train_operation_text_in_db
if @train_operation_info.instance_of?( ::TokyoMetro::Api::TrainOperation::Info )
@train_operation_info.update_train_operation_text_in_db
end
end
private
def get_train_operation_info( http_client , test_mode )
case test_mode
when nil
begin
train_operation_infos = ::TokyoMetro::Api::TrainOperation.get( http_client , railway_line: @railway_line.same_as , parse_json: true , generate_instance: true )
if train_operation_infos.length > 1
raise "Error"
end
@train_operation_info = train_operation_infos.first
rescue ::SocketError
@train_operation_info = ::TokyoMetro::Api::TrainOperation::Info::NetworkError.instance
rescue ::JSON::ParserError
@train_operation_info = ::TokyoMetro::Api::TrainOperation::Info::JsonParserError.instance
ensure
sleep( 0.2 )
end
when :network_error
@train_operation_info = ::TokyoMetro::Api::TrainOperation::Info::NetworkError.instance
when :json_parser_error
@train_operation_info = ::TokyoMetro::Api::TrainOperation::Info::JsonParserError.instance
else
raise
end
end
def get_train_location_infos( http_client , test_mode )
case test_mode
when nil
begin
@train_location_infos = ::TokyoMetro::Api::TrainLocation.get( http_client , @railway_line.same_as , parse_json: true , generate_instance: true )
rescue ::SocketError
@train_operation_info = ::TokyoMetro::Api::TrainOperation::Info::NetworkError.instance
@train_location_infos = nil
rescue ::JSON::ParserError
@train_operation_info = ::TokyoMetro::Api::TrainOperation::Info::JsonParserError.instance
@train_location_infos = nil
ensure
sleep( 0.2 )
end
when :network_error , :json_parser_error
@train_location_infos = nil
else
raise
end
end
def set_max_delay
@max_delay = @train_location_infos.try( :max_delay )
end
def no_train?
@train_location_infos.blank?
end
end
__END__
Started GET "/train_location/fukutoshin_line" for 127.0.0.1 at 2015-06-11 07:05:07 +0900
Processing by TrainLocationController#action_for_railway_line_page as HTML
Parameters: {"railway_line"=>"fukutoshin_line"}
Completed 500 Internal Server Error in 2543ms (ActiveRecord: 0.0ms)
JSON::ParserError - A JSON text must at least contain two octets!:
json (1.8.3) lib/json/common.rb:155:in `parse'
tokyo_metro (0.6.2) lib/tokyo_metro/factory/get/api/meta_class/fundamental.rb:103:in `parsed_json'
tokyo_metro (0.6.2) lib/tokyo_metro/factory/get/api/meta_class/fundamental.rb:81:in `process_response'
tokyo_metro (0.6.2) lib/tokyo_metro/factory/get/api/meta_class/fundamental.rb:51:in `get_data'
tokyo_metro (0.6.2) lib/tokyo_metro/factory/get/api/data_search/train_location.rb:64:in `process'
tokyo_metro (0.6.2) lib/tokyo_metro/api/train_location.rb:38:in `get'
tokyo_metro (0.6.2) lib/tokyo_metro/app/renderer/real_time_infos/each_railway_line.rb:43:in `get_train_location_infos'
tokyo_metro (0.6.2) lib/tokyo_metro/app/renderer/real_time_infos/each_railway_line.rb:9:in `initialize'
tokyo_metro (0.6.2) lib/tokyo_metro/app/renderer/real_time_infos.rb:143:in `block in set_infos_of_each_railway_line'
tokyo_metro (0.6.2) lib/tokyo_metro/app/renderer/real_time_infos.rb:142:in `set_infos_of_each_railway_line'
tokyo_metro (0.6.2) lib/tokyo_metro/app/renderer/real_time_infos.rb:9:in `initialize'
app/controllers/concerns/real_time_info_processor.rb:6:in `set_real_time_info_processor'
app/controllers/train_location_controller.rb:21:in `block in action_for_railway_line_page'
app/controllers/concerns/action_base_for_railway_line_page.rb:7:in `action_base_for_railway_line_page'
app/controllers/train_location_controller.rb:19:in `action_for_railway_line_page'
#--------
SocketError - getaddrinfo: ���̂悤�ȃz�X�g�͕s���ł��B (https://api.tokyometroapp.jp:443):
httpclient (2.6.0.1) lib/httpclient/session.rb:799:in `create_socket'
httpclient (2.6.0.1) lib/httpclient/session.rb:747:in `block in connect'
C:/Ruby21/lib/ruby/2.1.0/timeout.rb:91:in `block in timeout'
C:/Ruby21/lib/ruby/2.1.0/timeout.rb:101:in `timeout'
C:/Ruby21/lib/ruby/2.1.0/timeout.rb:127:in `timeout'
httpclient (2.6.0.1) lib/httpclient/session.rb:746:in `connect'
httpclient (2.6.0.1) lib/httpclient/session.rb:612:in `query'
httpclient (2.6.0.1) lib/httpclient/session.rb:164:in `query'
httpclient (2.6.0.1) lib/httpclient.rb:1191:in `do_get_block'
httpclient (2.6.0.1) lib/httpclient.rb:974:in `block in do_request'
httpclient (2.6.0.1) lib/httpclient.rb:1082:in `protect_keep_alive_disconnected'
httpclient (2.6.0.1) lib/httpclient.rb:969:in `do_request'
httpclient (2.6.0.1) lib/httpclient.rb:822:in `request'
httpclient (2.6.0.1) lib/httpclient.rb:713:in `get'
tokyo_metro (0.6.3) lib/tokyo_metro/factory/get/api/meta_class/fundamental.rb:71:in `response_from_api'
tokyo_metro (0.6.3) lib/tokyo_metro/factory/get/api/meta_class/fundamental.rb:44:in `get_data'
tokyo_metro (0.6.3) lib/tokyo_metro/factory/get/api/data_search/train_operation.rb:44:in `process'
tokyo_metro (0.6.3) lib/tokyo_metro/api/train_operation.rb:28:in `get'
tokyo_metro (0.6.3) lib/tokyo_metro/app/renderer/real_time_infos/each_railway_line.rb:29:in `get_train_operation_info'
tokyo_metro (0.6.3) lib/tokyo_metro/app/renderer/real_time_infos/each_railway_line.rb:8:in `initialize'
tokyo_metro (0.6.3) lib/tokyo_metro/app/renderer/real_time_infos.rb:143:in `block in set_infos_of_each_railway_line'
C:0:in `map'
tokyo_metro (0.6.3) lib/tokyo_metro/app/renderer/real_time_infos.rb:142:in `set_infos_of_each_railway_line'
tokyo_metro (0.6.3) lib/tokyo_metro/app/renderer/real_time_infos.rb:9:in `initialize'
app/controllers/concerns/real_time_info_processor.rb:7:in `set_real_time_info_processor'
app/controllers/station_facility_controller.rb:30:in `block in action_for_station_page'
app/controllers/concerns/action_base_for_station_page.rb:8:in `action_base_for_station_page'
app/controllers/station_facility_controller.rb:24:in `action_for_station_page'
actionpack (4.2.1) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
| osorubeki-fujita/odpt_tokyo_metro | lib/tokyo_metro/app/renderer/real_time_infos/each_railway_line.rb | Ruby | mit | 7,218 |
# -*- coding: utf-8 -*-
"""
flask_via.examples.basic
========================
A simple ``Flask-Via`` example Flask application.
"""
from flask import Flask
from flask.ext.via import Via
from flask.ext.via.routers.default import Functional
app = Flask(__name__)
def foo(bar=None):
return 'Functional Foo View!'
routes = [
Functional('/foo', foo),
Functional('/foo/<bar>', foo, endpoint='foo2'),
]
via = Via()
via.init_app(app, routes_module='flask_via.examples.basic')
if __name__ == "__main__":
app.run(debug=True)
| thisissoon/Flask-Via | flask_via/examples/basic.py | Python | mit | 542 |
<?php
use App\Match;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;
class CreateMatchesTable extends Migration
{
public function up()
{
Schema::create('matches', function(Blueprint $table) {
$table->increments('id');
$table->integer('tournamentId')->unsigned();
$table->integer('homeTournamentTeamId')->unsigned();
$table->integer('awayTournamentTeamId')->unsigned();
$table->tinyInteger('homeScore')->unsigned();
$table->tinyInteger('awayScore')->unsigned();
$table->tinyInteger('homePenaltyScore')->unsigned();
$table->tinyInteger('awayPenaltyScore')->unsigned();
$table->enum('gameType', Match::getAvailableGameTypes());
$table->enum('resultType', Match::getAvailableResultTypes());
$table->enum('status', Match::getAvailableStatuses())->default(Match::STATUS_NOT_STARTED);
$table->timestamps();
});
Schema::table('matches', function(Blueprint $table) {
$table->foreign('homeTournamentTeamId')->references('id')->on('tournament_teams')
->onDelete('restrict')
->onUpdate('restrict');
$table->foreign('awayTournamentTeamId')->references('id')->on('tournament_teams')
->onDelete('restrict')
->onUpdate('restrict');
});
}
public function down()
{
Schema::drop('matches');
}
}
| nixsolutions/ggf | database/migrations/2015_07_07_144512_create_matches_table.php | PHP | mit | 1,556 |
require('server.babel'); // babel registration (runtime transpilation for node)
const path = require('path');
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const autoprefixer = require('autoprefixer');
const webpack = require('webpack');
const webpackIsomorphicToolsConfig = require('./webpack-isomorphic-tools');
const WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
const webpackIsomorphicTools = new WebpackIsomorphicToolsPlugin(
webpackIsomorphicToolsConfig
);
module.exports = {
performance: {
hints: false,
},
context: path.resolve('./'),
entry: {
main: [
'src/less/styles.less', // entry point for styles
'src/js/client.jsx', // entry point for js
],
},
output: {
path: path.resolve('public/assets'),
filename: '[name]-[hash].js',
chunkFilename: '[name]-[chunkhash].js',
publicPath: '/assets/',
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: true,
// disable babel sourcemaps to see the transpiled code when debugging
sourceMap: false,
plugins: ['lodash'],
},
},
],
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
sourceMap: false,
importLoaders: 1,
},
},
{
loader: 'postcss-loader',
options: {
sourceMap: false,
plugins() {
return [autoprefixer];
},
},
},
],
}),
},
{
test: /\.less$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
sourceMap: false,
minimize: true,
importLoaders: 2,
},
},
{
loader: 'postcss-loader',
options: {
sourceMap: false,
plugins() {
return [autoprefixer];
},
},
},
{
loader: 'less-loader',
options: {
sourceMap: false,
},
},
],
}),
},
{
test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/font-woff',
},
},
// loader: 'url?limit=10000&mimetype=application/font-woff',
},
{
test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/font-woff',
},
},
// loader: 'url?limit=10000&mimetype=application/font-woff',
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/octet-stream',
},
},
// loader: 'url?limit=10000&mimetype=application/octet-stream',
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/vnd.ms-fontobject',
},
},
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'image/svg+xml',
},
},
},
{
test: /\.otf(\?v=\d+\.\d+\.\d+)?$/,
use: ['file-loader'],
},
{
test: webpackIsomorphicTools.regular_expression('images'),
use: {
loader: 'url-loader',
options: {
limit: 10240,
},
},
// loader: 'url-loader?limit=10240',
},
],
},
resolve: {
modules: ['./', 'node_modules'],
extensions: ['.json', '.js', '.jsx'],
},
plugins: [
new ExtractTextPlugin({
filename: '[name]-[chunkhash].css',
allChunks: true,
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"',
},
__CLIENT__: true,
__DEVTOOLS__: false,
}),
new LodashModuleReplacementPlugin({
// collections: true,
// shorthands: true
}),
// ignore dev config
new webpack.IgnorePlugin(/\.\/dev/, /\/config$/),
// optimizations
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
sourceMap: false,
}),
webpackIsomorphicTools,
],
};
| sankalplakhina/isomorphic-universal-react-redux-boilerplate-seed | webpack/prod.config.js | JavaScript | mit | 5,226 |
using System.ComponentModel.DataAnnotations;
namespace OptionsWebSite.ViewModels.Account
{
public class ExternalLoginConfirmationViewModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
}
}
| FriendlyNPC/MVC6_Mac | OptionsWebsite/ViewModels/Account/ExternalLoginConfirmationViewModel.cs | C# | mit | 253 |
package com.dev.lambda.demo;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.junit.BeforeClass;
import org.junit.Test;
import com.amazonaws.services.lambda.runtime.Context;
import com.dev.lambda.demo.model.Input;
/**
* A simple test harness for locally invoking your Lambda function handler.
*/
public class LambdaFunctionHandlerTest {
private static Input input;
@BeforeClass
public static void createInput() throws IOException {
// TODO: set up your sample input object here.
input = new Input();
}
private Context createContext() {
TestContext ctx = new TestContext();
// TODO: customize your context here if needed.
ctx.setFunctionName("Your Function Name");
return ctx;
}
@Test
public void testLambdaFunctionHandler() {
LambdaFunctionHandler handler = new LambdaFunctionHandler();
Context ctx = createContext();
String output = handler.handleRequest(input, ctx);
// TODO: validate output here if needed.
//Assert.assertEquals("Hello from Lambda!", output);
}
}
| kaulavinash/berryme | src/test/java/com/dev/lambda/demo/LambdaFunctionHandlerTest.java | Java | mit | 1,143 |
/*****************************************************************************
* *
* OpenNI 2.x Alpha *
* Copyright (C) 2012 PrimeSense Ltd. *
* *
* This file is part of OpenNI. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* *
*****************************************************************************/
package org.openni.android.tools.niviewer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.Toast;
import org.openni.Device;
import org.openni.DeviceInfo;
import org.openni.OpenNI;
import org.openni.Recorder;
import org.openni.android.OpenNIHelper;
import org.openni.android.tools.niviewer.StreamView;
public class NiViewerActivity
extends Activity
implements OpenNIHelper.DeviceOpenListener {
private Installation installation;
private static final String TAG = "NiViewer";
private OpenNIHelper mOpenNIHelper;
private boolean mDeviceOpenPending = false;
private Device mDevice;
private Recorder mRecorder;
private String mRecordingName;
private String mRecording;
private LinearLayout mStreamsContainer;
private int mActiveDeviceID = -1;
private void toast(String message) {
Toast toast = Toast.makeText(getApplicationContext(),
message, Toast.LENGTH_SHORT);
toast.show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
MyToaster.setContext(this);
Log.d(TAG, "onCreate");
installation = new Installation();
if (installation.execute()) {
Log.d(TAG, "ROOT commands executed.");
} else {
toast("Not running as ROOT.");
Log.d(TAG, "Not running as ROOT.");
}
MyNetworkManager nm = new MyNetworkManager(this);
nm.startup();
mOpenNIHelper = new OpenNIHelper(this);
//OpenNI.setLogAndroidOutput(true);
//OpenNI.setLogMinSeverity(0);
OpenNI.initialize();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_niviewer);
mStreamsContainer = (LinearLayout)findViewById(R.id.streams_container);
onConfigurationChanged(getResources().getConfiguration());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.niviewer_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.record:
toggleRecording(item);
return true;
case R.id.add_stream:
addStream();
return true;
case R.id.device:
switchDevice();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy");
super.onDestroy();
mOpenNIHelper.shutdown();
OpenNI.shutdown();
}
@Override
protected void onStart() {
Log.d(TAG, "onStart");
super.onStart();
final android.content.Intent intent = getIntent ();
if (intent != null) {
final android.net.Uri data = intent.getData ();
if (data != null) {
mRecording = data.getEncodedPath ();
Log.d(TAG, "Will open file " + mRecording);
}
}
}
@Override
protected void onResume() {
Log.d(TAG, "onResume");
super.onResume();
// onResume() is called after the USB permission dialog is closed, in which case, we don't want
// to request device permissions again
if (mDeviceOpenPending) {
return;
}
// Request opening the first OpenNI-compliant device found
String uri;
if (mRecording != null) {
uri = mRecording;
} else {
List<DeviceInfo> devices = OpenNI.enumerateDevices();
if (devices.isEmpty()) {
showAlertAndExit("No OpenNI-compliant device found.");
return;
}
uri = devices.get(devices.size() - 1).getUri();
}
mDeviceOpenPending = true;
mOpenNIHelper.requestDeviceOpen(uri, this);
}
@Override
public void onConfigurationChanged(Configuration config) {
Log.d(TAG, "onConfigurationChanged");
if (Configuration.ORIENTATION_PORTRAIT == config.orientation) {
mStreamsContainer.setOrientation(LinearLayout.VERTICAL);
} else {
mStreamsContainer.setOrientation(LinearLayout.HORIZONTAL);
}
//Re-insert each view to force correct display (forceLayout() doesn't work)
for (StreamView streamView : getStreamViews()) {
mStreamsContainer.removeView(streamView);
setStreamViewLayout(streamView, config);
mStreamsContainer.addView(streamView);
}
super.onConfigurationChanged(config);
}
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message);
builder.show();
}
private void showAlertAndExit(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message);
builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.show();
}
@Override
public void onDeviceOpened(Device aDevice) {
Log.d(TAG, "Permission granted for device " + aDevice.getDeviceInfo().getUri());
mDeviceOpenPending = false;
mDevice = aDevice;
//Find device ID
List<DeviceInfo> devices = OpenNI.enumerateDevices();
for(int i=0; i < devices.size(); i++)
{
if(devices.get(i).getUri().equals(mDevice.getDeviceInfo().getUri())){
mActiveDeviceID = i;
break;
}
}
for (StreamView streamView : getStreamViews()) {
streamView.setDevice(mDevice);
}
mStreamsContainer.requestLayout();
addStream();
}
private void setStreamViewLayout(StreamView streamView, Configuration config) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
if (config.orientation == Configuration.ORIENTATION_PORTRAIT) {
params.width = LayoutParams.WRAP_CONTENT;
params.height = 0;
} else {
params.width = 0;
params.height = LayoutParams.WRAP_CONTENT;
}
params.weight = 1;
params.gravity = Gravity.CENTER;
streamView.setLayoutParams(params);
}
private void addStream() {
StreamView streamView = new StreamView(this);
setStreamViewLayout(streamView, getResources().getConfiguration());
streamView.setDevice(mDevice);
mStreamsContainer.addView(streamView);
mStreamsContainer.requestLayout();
}
@SuppressLint("SimpleDateFormat")
private void toggleRecording(MenuItem item) {
if (mRecorder == null) {
mRecordingName = Environment.getExternalStorageDirectory().getPath() +
"/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".oni";
try {
mRecorder = Recorder.create(mRecordingName);
for (StreamView streamView : getStreamViews()) {
mRecorder.addStream(streamView.getStream(), true);
}
mRecorder.start();
} catch (RuntimeException ex) {
mRecorder = null;
showAlert("Failed to start recording: " + ex.getMessage());
return;
}
item.setTitle(R.string.stop_record);
} else {
stopRecording();
item.setTitle(R.string.start_record);
}
}
private void stopRecording() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.destroy();
mRecorder = null;
showAlert("Recording saved to: " + mRecordingName);
mRecordingName = null;
}
}
private void switchDevice() {
List<DeviceInfo> devices = OpenNI.enumerateDevices();
if (devices.isEmpty()) {
showAlertAndExit("No OpenNI-compliant device found.");
return;
}
new DeviceSelectDialog().showDialog(devices, mActiveDeviceID, this);
}
public void openDevice(String deviceURI) {
if (mDeviceOpenPending) {
return;
}
stopRecording();
for (StreamView streamView : getStreamViews()) {
streamView.stop();
mStreamsContainer.removeView(streamView);
}
if (mDevice != null) {
mDevice.close();
}
mDeviceOpenPending = true;
mOpenNIHelper.requestDeviceOpen(deviceURI, this);
}
@Override
public void onDeviceOpenFailed(String uri) {
Log.e(TAG, "Failed to open device " + uri);
mDeviceOpenPending = false;
showAlertAndExit("Failed to open device");
}
@Override
protected void onPause() {
Log.d(TAG, "onPause");
super.onPause();
// onPause() is called just before the USB permission dialog is opened, in which case, we don't
// want to shutdown OpenNI
if (mDeviceOpenPending)
return;
stopRecording();
for (StreamView streamView : getStreamViews()) {
streamView.stop();
}
if (mDevice != null) {
mDevice.close();
mDevice = null;
}
}
private List<StreamView> getStreamViews() {
int count = mStreamsContainer.getChildCount();
ArrayList<StreamView> list = new ArrayList<StreamView>(count);
for (int i = 0; i < count; ++i) {
StreamView view = (StreamView)mStreamsContainer.getChildAt(i);
list.add(view);
}
return list;
}
}
| Windowsfreak/NIStreamer | Android/NiViewer.Android/src/org/openni/android/tools/niviewer/NiViewerActivity.java | Java | mit | 10,505 |
<?php
namespace Vision\DependencyInjection;
use Psr\Container\NotFoundExceptionInterface;
use RuntimeException;
class NotFoundException extends RuntimeException implements NotFoundExceptionInterface
{
}
| Trainmaster/Vision | src/DependencyInjection/NotFoundException.php | PHP | mit | 206 |
<?php defined('KOHANASYSPATH') or die('No direct script access.');
/**
* UTF8::from_unicode
*
* @package Kohana
* @author Kohana Team
* @copyright (c) 2007-2011 Kohana Team
* @copyright (c) 2005 Harry Fuecks
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt
*/
function _from_unicode($arr)
{
ob_start();
$keys = array_keys($arr);
foreach ($keys as $k)
{
// ASCII range (including control chars)
if (($arr[$k] >= 0) AND ($arr[$k] <= 0x007f))
{
echo chr($arr[$k]);
}
// 2 byte sequence
elseif ($arr[$k] <= 0x07ff)
{
echo chr(0xc0 | ($arr[$k] >> 6));
echo chr(0x80 | ($arr[$k] & 0x003f));
}
// Byte order mark (skip)
elseif ($arr[$k] == 0xFEFF)
{
// nop -- zap the BOM
}
// Test for illegal surrogates
elseif ($arr[$k] >= 0xD800 AND $arr[$k] <= 0xDFFF)
{
// Found a surrogate
trigger_error('UTF8::from_unicode: Illegal surrogate at index: '.$k.', value: '.$arr[$k], E_USER_WARNING);
return FALSE;
}
// 3 byte sequence
elseif ($arr[$k] <= 0xffff)
{
echo chr(0xe0 | ($arr[$k] >> 12));
echo chr(0x80 | (($arr[$k] >> 6) & 0x003f));
echo chr(0x80 | ($arr[$k] & 0x003f));
}
// 4 byte sequence
elseif ($arr[$k] <= 0x10ffff)
{
echo chr(0xf0 | ($arr[$k] >> 18));
echo chr(0x80 | (($arr[$k] >> 12) & 0x3f));
echo chr(0x80 | (($arr[$k] >> 6) & 0x3f));
echo chr(0x80 | ($arr[$k] & 0x3f));
}
// Out of range
else
{
trigger_error('UTF8::from_unicode: Codepoint out of Unicode range at index: '.$k.', value: '.$arr[$k], E_USER_WARNING);
return FALSE;
}
}
$result = ob_get_contents();
ob_end_clean();
return $result;
}
| ivantcholakov/codeigniter-utf8 | application/third_party/kohana/utf8/from_unicode.php | PHP | mit | 1,718 |
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jms.connection;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.TransactionInProgressException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.transaction.support.ResourceHolderSupport;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils;
/**
* JMS resource holder, wrapping a JMS Connection and a JMS Session.
* JmsTransactionManager binds instances of this class to the thread,
* for a given JMS ConnectionFactory.
*
* <p>Note: This is an SPI class, not intended to be used by applications.
*
* @author Juergen Hoeller
* @since 1.1
* @see JmsTransactionManager
* @see org.springframework.jms.core.JmsTemplate
*/
public class JmsResourceHolder extends ResourceHolderSupport {
private static final Log logger = LogFactory.getLog(JmsResourceHolder.class);
private ConnectionFactory connectionFactory;
private boolean frozen = false;
private final List<Connection> connections = new LinkedList<>();
private final List<Session> sessions = new LinkedList<>();
private final Map<Connection, List<Session>> sessionsPerConnection =
new HashMap<>();
/**
* Create a new JmsResourceHolder that is open for resources to be added.
* @see #addConnection
* @see #addSession
*/
public JmsResourceHolder() {
}
/**
* Create a new JmsResourceHolder that is open for resources to be added.
* @param connectionFactory the JMS ConnectionFactory that this
* resource holder is associated with (may be {@code null})
*/
public JmsResourceHolder(ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
/**
* Create a new JmsResourceHolder for the given JMS Session.
* @param session the JMS Session
*/
public JmsResourceHolder(Session session) {
addSession(session);
this.frozen = true;
}
/**
* Create a new JmsResourceHolder for the given JMS resources.
* @param connection the JMS Connection
* @param session the JMS Session
*/
public JmsResourceHolder(Connection connection, Session session) {
addConnection(connection);
addSession(session, connection);
this.frozen = true;
}
/**
* Create a new JmsResourceHolder for the given JMS resources.
* @param connectionFactory the JMS ConnectionFactory that this
* resource holder is associated with (may be {@code null})
* @param connection the JMS Connection
* @param session the JMS Session
*/
public JmsResourceHolder(ConnectionFactory connectionFactory, Connection connection, Session session) {
this.connectionFactory = connectionFactory;
addConnection(connection);
addSession(session, connection);
this.frozen = true;
}
public final boolean isFrozen() {
return this.frozen;
}
public final void addConnection(Connection connection) {
Assert.isTrue(!this.frozen, "Cannot add Connection because JmsResourceHolder is frozen");
Assert.notNull(connection, "Connection must not be null");
if (!this.connections.contains(connection)) {
this.connections.add(connection);
}
}
public final void addSession(Session session) {
addSession(session, null);
}
public final void addSession(Session session, Connection connection) {
Assert.isTrue(!this.frozen, "Cannot add Session because JmsResourceHolder is frozen");
Assert.notNull(session, "Session must not be null");
if (!this.sessions.contains(session)) {
this.sessions.add(session);
if (connection != null) {
List<Session> sessions = this.sessionsPerConnection.get(connection);
if (sessions == null) {
sessions = new LinkedList<>();
this.sessionsPerConnection.put(connection, sessions);
}
sessions.add(session);
}
}
}
public boolean containsSession(Session session) {
return this.sessions.contains(session);
}
public Connection getConnection() {
return (!this.connections.isEmpty() ? this.connections.get(0) : null);
}
public Connection getConnection(Class<? extends Connection> connectionType) {
return CollectionUtils.findValueOfType(this.connections, connectionType);
}
public Session getSession() {
return (!this.sessions.isEmpty() ? this.sessions.get(0) : null);
}
public Session getSession(Class<? extends Session> sessionType) {
return getSession(sessionType, null);
}
public Session getSession(Class<? extends Session> sessionType, Connection connection) {
List<Session> sessions = this.sessions;
if (connection != null) {
sessions = this.sessionsPerConnection.get(connection);
}
return CollectionUtils.findValueOfType(sessions, sessionType);
}
public void commitAll() throws JMSException {
for (Session session : this.sessions) {
try {
session.commit();
}
catch (TransactionInProgressException ex) {
// Ignore -> can only happen in case of a JTA transaction.
}
catch (javax.jms.IllegalStateException ex) {
if (this.connectionFactory != null) {
try {
Method getDataSourceMethod = this.connectionFactory.getClass().getMethod("getDataSource");
Object ds = ReflectionUtils.invokeMethod(getDataSourceMethod, this.connectionFactory);
while (ds != null) {
if (TransactionSynchronizationManager.hasResource(ds)) {
// IllegalStateException from sharing the underlying JDBC Connection
// which typically gets committed first, e.g. with Oracle AQ --> ignore
return;
}
try {
// Check for decorated DataSource a la Spring's DelegatingDataSource
Method getTargetDataSourceMethod = ds.getClass().getMethod("getTargetDataSource");
ds = ReflectionUtils.invokeMethod(getTargetDataSourceMethod, ds);
}
catch (NoSuchMethodException nsme) {
ds = null;
}
}
}
catch (Throwable ex2) {
if (logger.isDebugEnabled()) {
logger.debug("No working getDataSource method found on ConnectionFactory: " + ex2);
}
// No working getDataSource method - cannot perform DataSource transaction check
}
}
throw ex;
}
}
}
public void closeAll() {
for (Session session : this.sessions) {
try {
session.close();
}
catch (Throwable ex) {
logger.debug("Could not close synchronized JMS Session after transaction", ex);
}
}
for (Connection con : this.connections) {
ConnectionFactoryUtils.releaseConnection(con, this.connectionFactory, true);
}
this.connections.clear();
this.sessions.clear();
this.sessionsPerConnection.clear();
}
}
| boggad/jdk9-sample | sample-catalog/spring-jdk9/src/spring.jms/org/springframework/jms/connection/JmsResourceHolder.java | Java | mit | 7,474 |
<?php
namespace GRT\MainBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class GRTMainBundle extends Bundle
{
}
| mwd410/GRT-Interview | src/GRT/MainBundle/GRTMainBundle.php | PHP | mit | 122 |
import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from './auth.service';
import { IToastr, TOASTR_TOKEN } from '../common/toastr.service';
@Component({
templateUrl: 'app/user/profile.component.html',
styles: [
`
em {float:right;color:#e05c65;padding-left:10px;}
.error input{background-color:#e3c3c5;}
.error ::-webkit-input-placeholder {color:#999;}
.error ::-moz-placeholder {color:#999;}
.error :-ms-input-placeholder {color:#999;}
`,
],
})
export class ProfileComponent implements OnInit {
profileForm: FormGroup;
private firstName: FormControl;
private lastName: FormControl;
constructor(
private authService: AuthService,
private router: Router,
@Inject(TOASTR_TOKEN) private toastr: IToastr) { }
ngOnInit() {
this.firstName = new FormControl(
this.authService.currentUser.firstName, [Validators.required, Validators.pattern('[a-zA-Z].*')]);
this.lastName = new FormControl(this.authService.currentUser.lastName, Validators.required);
this.profileForm = new FormGroup({
firstName: this.firstName,
lastName: this.lastName,
});
}
cancel() {
this.router.navigate(['events'])
}
saveProfile(formValues) {
if (this.profileForm.valid) {
this.authService.updateCurrentUser(formValues.firstName, formValues.lastName)
.subscribe(() => {
this.toastr.success('Profile saved successfully!');
});
// this.router.navigate(['events'])
}
}
validateFirstName() {
return this.firstName.valid || this.firstName.untouched;
}
validateLastName() {
return this.lastName.valid || this.lastName.untouched;
}
logout(){
this.authService.logout().subscribe(()=> {
this.router.navigate(['/user/login']);
});
}
}
| AdamNagy/FrontendTryouts | Angular/EventManager/app/user/profile.component.ts | TypeScript | mit | 1,870 |
require('dotenv').config();
import http from 'http';
import https from 'https';
import Koa from 'koa';
import Io from 'socket.io';
import KoaBody from 'koa-body';
import cors from 'kcors';
import Router from 'koa-router';
import Socket from './socket';
import crypto from 'crypto';
import mailer from './utils/mailer';
import koaStatic from 'koa-static';
import koaSend from 'koa-send';
import { pollForInactiveRooms } from './inactive_rooms';
import getStore from './store';
const env = process.env.NODE_ENV || 'development';
const app = new Koa();
const PORT = process.env.PORT || 3001;
const router = new Router();
const koaBody = new KoaBody();
const appName = process.env.HEROKU_APP_NAME;
const isReviewApp = /-pr-/.test(appName);
const siteURL = process.env.SITE_URL;
const store = getStore();
if ((siteURL || env === 'development') && !isReviewApp) {
app.use(
cors({
origin: env === 'development' ? '*' : siteURL,
allowMethods: ['GET', 'HEAD', 'POST'],
credentials: true,
}),
);
}
router.post('/abuse/:roomId', koaBody, async ctx => {
let { roomId } = ctx.params;
roomId = roomId.trim();
if (process.env.ABUSE_FROM_EMAIL_ADDRESS && process.env.ABUSE_TO_EMAIL_ADDRESS) {
const abuseForRoomExists = await store.get('abuse', roomId);
if (!abuseForRoomExists) {
mailer.send({
from: process.env.ABUSE_FROM_EMAIL_ADDRESS,
to: process.env.ABUSE_TO_EMAIL_ADDRESS,
subject: 'Darkwire Abuse Notification',
text: `Room ID: ${roomId}`,
});
}
}
await store.inc('abuse', roomId);
ctx.status = 200;
});
app.use(router.routes());
const apiHost = process.env.API_HOST;
const cspDefaultSrc = `'self'${apiHost ? ` https://${apiHost} wss://${apiHost}` : ''}`;
function setStaticFileHeaders(ctx) {
ctx.set({
'strict-transport-security': 'max-age=31536000',
'Content-Security-Policy': `default-src ${cspDefaultSrc} 'unsafe-inline'; img-src 'self' data:;`,
'X-Frame-Options': 'deny',
'X-XSS-Protection': '1; mode=block',
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'no-referrer',
'Feature-Policy': "geolocation 'none'; vr 'none'; payment 'none'; microphone 'none'",
});
}
const clientDistDirectory = process.env.CLIENT_DIST_DIRECTORY;
if (clientDistDirectory) {
app.use(async (ctx, next) => {
setStaticFileHeaders(ctx);
await koaStatic(clientDistDirectory, {
maxage: ctx.req.url === '/' ? 60 * 1000 : 365 * 24 * 60 * 60 * 1000, // one minute in ms for html doc, one year for css, js, etc
})(ctx, next);
});
app.use(async ctx => {
setStaticFileHeaders(ctx);
await koaSend(ctx, 'index.html', { root: clientDistDirectory });
});
} else {
app.use(async ctx => {
ctx.body = { ready: true };
});
}
const protocol = (process.env.PROTOCOL || 'http') === 'http' ? http : https;
const server = protocol.createServer(app.callback());
const io = Io(server, {
pingInterval: 20000,
pingTimeout: 5000,
});
// Only use socket adapter if store has one
if (store.hasSocketAdapter) {
io.adapter(store.getSocketAdapter());
}
const roomHashSecret = process.env.ROOM_HASH_SECRET;
const getRoomIdHash = id => {
if (env === 'development') {
return id;
}
if (roomHashSecret) {
return crypto.createHmac('sha256', roomHashSecret).update(id).digest('hex');
}
return crypto.createHash('sha256').update(id).digest('hex');
};
export const getIO = () => io;
io.on('connection', async socket => {
const roomId = socket.handshake.query.roomId;
const roomIdHash = getRoomIdHash(roomId);
let room = await store.get('rooms', roomIdHash);
room = JSON.parse(room || '{}');
new Socket({
roomIdOriginal: roomId,
roomId: roomIdHash,
socket,
room,
});
});
const init = async () => {
server.listen(PORT, () => {
console.log(`Darkwire is online at port ${PORT}`);
});
pollForInactiveRooms();
};
init();
| seripap/darkwire.io | server/src/index.js | JavaScript | mit | 3,919 |
# -*- coding: utf-8 -*-
"""Functions for manipulating FGONG files. These are provided through
the **FGONG** object and a module function to read an **FGONG** object
from a file.
"""
import numpy as np
import warnings
from .adipls import fgong_to_amdl
from .constants import G_DEFAULT
from .utils import integrate, tomso_open, regularize
from .utils import FullStellarModel
def load_fgong(filename, fmt='ivers', return_comment=False,
return_object=True, G=None):
"""Given an FGONG file, returns NumPy arrays ``glob`` and ``var`` that
correspond to the scalar and point-wise variables, as specified
in the `FGONG format`_.
.. _FGONG format: https://www.astro.up.pt/corot/ntools/docs/CoRoT_ESTA_Files.pdf
Also returns the first four lines of the file as a `comment`, if
desired.
The version number ``ivers`` is used to infer the format of floats
if ``fmt='ivers'``.
If ``return_object`` is ``True``, instead returns an :py:class:`FGONG`
object. This is the default behaviour as of v0.0.12. The old
behaviour will be dropped completely from v0.1.0.
Parameters
----------
filename: str
Name of the FGONG file to read.
fmt: str, optional
Format string for floats in `glob` and `var`. If ``'ivers'``,
uses ``%16.9E`` if the file's ``ivers < 1000`` or ``%26.18E3` if
``ivers >= 1000``. If ``'auto'``, tries to guess the size of each
float. (default: 'ivers')
return_comment: bool, optional
If ``True``, return the first four lines of the FGONG file.
These are comments that are not used in any calculations.
Returns
-------
glob: NumPy array
The scalar (or global) variables for the stellar model
var: NumPy array
The point-wise variables for the stellar model. i.e. things
that vary through the star like temperature, density, etc.
comment: list of strs, optional
The first four lines of the FGONG file. These are comments
that are not used in any calculations. Only returned if
``return_comment=True``.
"""
with tomso_open(filename, 'rb') as f:
comment = [f.readline().decode('utf-8').strip() for i in range(4)]
nn, iconst, ivar, ivers = [int(i) for i in f.readline().decode('utf-8').split()]
# lines = f.readlines()
lines = [line.decode('utf-8').lower().replace('d', 'e')
for line in f.readlines()]
tmp = []
if fmt == 'ivers':
if ivers < 1000:
N = 16
else:
N = 27
# try to guess the length of each float in the data
elif fmt == 'auto':
N = len(lines[0])//5
else:
N = len(fmt % -1.111)
for line in lines:
for i in range(len(line)//N):
s = line[i*N:i*N+N]
# print(s)
if s[-9:] == '-Infinity':
s = '-Inf'
elif s[-9:] == ' Infinity':
s = 'Inf'
elif s.lower().endswith('nan'):
s = 'nan'
elif 'd' in s.lower():
s = s.lower().replace('d','e')
tmp.append(float(s))
glob = np.array(tmp[:iconst])
var = np.array(tmp[iconst:]).reshape((-1, ivar))
if return_object:
return FGONG(glob, var, ivers=ivers, G=G,
description=comment)
else:
warnings.warn("From tomso 0.1.0+, `fgong.load_fgong` will only "
"return an `FGONG` object: use `return_object=True` "
"to mimic future behaviour",
FutureWarning)
if return_comment:
return glob, var, comment
else:
return glob, var
def save_fgong(filename, glob, var, ivers=1300, comment=['','','',''],
float_formatter='ivers'):
"""Given data for an FGONG file in the format returned by
:py:meth:`~tomso.fgong.load_fgong` (i.e. two NumPy arrays and a
possible header), writes the data to a file.
This function will be dropped from v0.1.0 in favour of the `to_file`
function of the :py:class:`FGONG` object.
Parameters
----------
filename: str
Filename to which FGONG data is written.
glob: NumPy array
The global variables for the stellar model.
var: NumPy array
The point-wise variables for the stellar model. i.e. things
that vary through the star like temperature, density, etc.
ivers: int, optional
The integer indicating the version number of the file.
(default=1300)
comment: list of strs, optional
The first four lines of the FGONG file, which usually contain
notes about the stellar model.
float_formatter: str or function
Determines how floating point numbers are formatted. If
``'ivers'`` (the default), use the standard formats ``%16.9E``
if ``ivers < 1000`` or ``%26.18E3`` if ``ivers >= 1000``. If
a Python format specifier (e.g. ``'%16.9E'``), pass floats
into that like ``float_formatter % float``. Otherwise, must
be a function that takes a float as an argument and returns a
string. In most circumstances you'll want to control the
output by changing the value of ``'ivers'``.
"""
nn, ivar = var.shape
iconst = len(glob)
if float_formatter == 'ivers':
if ivers < 1000:
def ff(x):
if not np.isfinite(x):
return '%16s' % x
s = np.format_float_scientific(x, precision=9, unique=False, exp_digits=2, sign=True)
if s[0] == '+':
s = ' ' + s[1:]
return s
else:
def ff(x):
if not np.isfinite(x):
return '%27s' % x
s = np.format_float_scientific(x, precision=18, unique=False, exp_digits=3, sign=True)
if s[0] == '+':
s = ' ' + s[1:]
return ' ' + s
else:
try:
float_formatter % 1.111
ff = lambda x: float_formatter % x
except TypeError:
ff = float_formatter
with open(filename, 'wt') as f:
f.write('\n'.join(comment) + '\n')
line = '%10i'*4 % (nn, iconst, ivar, ivers) + '\n'
f.write(line)
for i, val in enumerate(glob):
f.write(ff(val))
if i % 5 == 4:
f.write('\n')
if i % 5 != 4:
f.write('\n')
for row in var:
for i, val in enumerate(row):
f.write(ff(val))
if i % 5 == 4:
f.write('\n')
if i % 5 != 4:
f.write('\n')
def fgong_get(key_or_keys, glob, var, reverse=False, G=G_DEFAULT):
"""Retrieves physical properties of a FGONG model from the ``glob`` and
``var`` arrays.
This function will be dropped from v0.1.0 in favour of the
attributes of the :py:class:`FGONG` object.
Parameters
----------
key_or_keys: str or list of strs
The desired variable or a list of desired variables. Current
options are:
- ``M``: total mass (float)
- ``R``: photospheric radius (float)
- ``L``: total luminosity (float)
- ``r``: radius (array)
- ``x``: fractional radius (array)
- ``m``: mass co-ordinate (array)
- ``q``: fractional mass co-ordinate (array)
- ``g``: gravity (array)
- ``rho``: density (array)
- ``P``: pressure (array)
- ``AA``: Ledoux discriminant (array)
- ``Hp``: pressure scale height (array)
- ``Hrho``: density scale height (array)
- ``G1``: first adiabatic index (array)
- ``T``: temperature (array)
- ``X``: hydrogen abundance (array)
- ``L_r``: luminosity at radius ``r`` (array)
- ``kappa``: opacity (array)
- ``epsilon``: specific energy generation rate (array)
- ``cp``: specific heat capacity (array)
- ``cs2``: sound speed squared (array)
- ``cs``: sound speed (array)
- ``tau``: acoustic depth (array)
For example, if ``glob`` and ``var`` have been returned from
:py:meth:`~tomso.fgong.load_fgong`, you could use
>>> M, m = fgong.fgong_get(['M', 'm'], glob, var)
to get the total mass and mass co-ordinate. If you only want
one variable, you don't need to use a list. The return type
is just the one corresponding float or array. So, to get a
single variable you could use either
>>> x, = fgong.fgong_get(['x'], glob, var)
or
>>> x = fgong.fgong_get('x', glob, var)
glob: NumPy array
The scalar (or global) variables for the stellar model
var: NumPy array
The point-wise variables for the stellar model. i.e. things
that vary through the star like temperature, density, etc.
reverse: bool (optional)
If ``True``, reverse the arrays so that the first element is
the centre.
G: float (optional)
Value of the gravitational constant.
Returns
-------
output: list of floats and arrays
A list returning the floats or arrays in the order requested
by the parameter ``keys``.
"""
M, R, L = glob[:3]
r, lnq, T, P, rho, X, L_r, kappa, epsilon, G1 = var[:,:10].T
cp = var[:,12]
AA = var[:,14]
x = r/R
q = np.exp(lnq)
m = q*M
g = G*m/r**2
Hp = P/(rho*g)
Hrho = 1/(1/G1/Hp + AA/r)
cs2 = G1*P/rho # square of the sound speed
cs = np.sqrt(cs2)
if np.all(np.diff(x) < 0):
tau = -integrate(1./cs, r) # acoustic depth
else:
tau = integrate(1./cs[::-1], r[::-1])[::-1]
tau = np.max(tau)-tau
if type(key_or_keys) == str:
keys = [key_or_keys]
just_one = True
else:
keys = key_or_keys
just_one = False
I = np.arange(len(var), dtype=int)
if reverse:
I = I[::-1]
output = []
for key in keys:
if key == 'M': output.append(M)
elif key == 'R': output.append(R)
elif key == 'L': output.append(L)
elif key == 'r': output.append(r[I])
elif key == 'x': output.append(x[I])
elif key == 'm': output.append(m[I])
elif key == 'q': output.append(q[I])
elif key == 'g': output.append(g[I])
elif key == 'rho': output.append(rho[I])
elif key == 'P': output.append(P[I])
elif key == 'AA': output.append(AA[I])
elif key == 'Hp': output.append(Hp[I])
elif key == 'Hrho': output.append(Hrho[I])
elif key == 'G1': output.append(G1[I])
elif key == 'T': output.append(T[I])
elif key == 'X': output.append(X[I])
elif key == 'L_r': output.append(L_r[I])
elif key == 'kappa': output.append(kappa[I])
elif key == 'epsilon': output.append(epsilon[I])
elif key == 'cp': output.append(cp[I])
elif key == 'cs2': output.append(cs2[I])
elif key == 'cs': output.append(cs[I])
elif key == 'tau': output.append(tau[I])
else: raise ValueError('%s is not a valid key for fgong.fgong_get' % key)
if just_one:
assert(len(output) == 1)
return output[0]
else:
return output
class FGONG(FullStellarModel):
"""A class that contains and allows one to manipulate the data in a
stellar model stored in the `FGONG format`_.
.. _FGONG format: https://www.astro.up.pt/corot/ntools/docs/CoRoT_ESTA_Files.pdf
The main attributes are the **glob** and **var** arrays, which
follow the definitions in the FGONG standard. The data in these
arrays can be accessed via the attributes with more
physically-meaningful names (e.g. the radius is ``FGONG.r``).
Some of these values can also be set via the attributes if doing
so is unambiguous. For example, the fractional radius **x** is not a
member of the **var** array but setting **x** will assign the actual
radius **r**, which is the first column of **var**. Values that are
settable are indicated in the list of parameters.
Parameters
----------
glob: NumPy array
The global variables for the stellar model.
var: NumPy array
The point-wise variables for the stellar model. i.e. things
that vary through the star like temperature, density, etc.
ivers: int, optional
The integer indicating the version number of the file.
(default=0)
G: float, optional
Value for the gravitational constant. If not given (which is
the default behaviour), we use ``glob[14]`` if it exists and
is close to the module-wide default value. Otherwise, we use
the module-wide default value.
description: list of 4 strs, optional
The first four lines of the FGONG file, which usually contain
notes about the stellar model.
Attributes
----------
iconst: int
number of global data entries (i.e. length of **glob**)
nn: int
number of points in stellar model (i.e. number of rows in **var**)
ivar: int
number of variables recorded at each point in stellar model
(i.e. number of columns in **var**)
M: float, settable
total mass
R: float, settable
photospheric radius
L: float, settable
total luminosity
Teff: float
effective temperature, derived from luminosity and radius
r: NumPy array, settable
radius co-ordinate
lnq: NumPy array, settable
natural logarithm of the fractional mass co-ordinate
T: NumPy array, settable
temperature
P: NumPy array, settable
pressure
rho: NumPy array, settable
density
X: NumPy array, settable
fractional hydrogen abundance (by mass)
L_r: NumPy array, settable
luminosity at radius **r**
kappa: NumPy array, settable
Rosseland mean opacity
epsilon: NumPy array, settable
specific energy generation rate
Gamma_1: NumPy array, settable
first adiabatic index, aliased by **G1**
G1: NumPy array, settable
first adiabatic index, alias of **Gamma_1**
cp: NumPy array, settable
specific heat capacity
AA: NumPy array, settable
Ledoux discriminant
Z: NumPy array, settable
metal abundance
x: NumPy array, settable
fractional radius co-ordinate
q: NumPy array, settable
fractional mass co-ordinate
m: NumPy array, settable
mass co-ordinate
g: NumPy array
local gravitational acceleration
Hp: NumPy array
pressure scale height
Hrho: NumPy array
density scale height
N2: NumPy array
squared Brunt–Väisälä (angular) frequency
cs2: NumPy array
squared adiabatic sound speed
cs: NumPy array
adiabatic sound speed
U: NumPy array
homology invariant *dlnm/dlnr*
V: NumPy array
homology invariant *dlnP/dlnr*
Vg: NumPy array
homology invariant *V/Gamma_1*
tau: NumPy array
acoustic depth
"""
def __init__(self, glob, var, ivers=300, G=None,
description=['', '', '', '']):
self.ivers = ivers
self.glob = glob
self.var = var
self.description = description
# if G is None, use glob[14] if it exists and looks like a
# reasonable value of G
if G is None:
if len(glob) >= 14 and np.isclose(glob[14], G_DEFAULT,
rtol=1e-3, atol=0.01e-8):
self.G = glob[14]
else:
self.G = G_DEFAULT
else:
self.G = G
def __len__(self):
return len(self.var)
def __repr__(self):
with np.printoptions(threshold=10):
return('FGONG(\nglob=\n%s,\nvar=\n%s,\ndescription=\n%s)' % (self.glob, self.var, '\n'.join(self.description)))
def to_file(self, filename, float_formatter='ivers'):
"""Save the model to an FGONG file.
Parameters
----------
filename: str
Filename to which the data is written.
float_formatter: str or function
Determines how floating point numbers are formatted. If
``'ivers'`` (the default), use the standard formats
``%16.9E`` if ``ivers < 1000`` or ``%26.18E3`` if ``ivers
>= 1000``. If a Python format specifier
(e.g. ``'%16.9E'``), pass floats into that like
``float_formatter % float``. Otherwise, must be a
function that takes a float as an argument and returns a
string. In most circumstances you'll want to control the
output by changing the value of ``'ivers'``.
"""
save_fgong(filename, self.glob, self.var,
ivers=self.ivers, comment=self.description,
float_formatter=float_formatter)
def to_amdl(self):
"""Convert the model to an ``ADIPLSStellarModel`` object."""
from .adipls import ADIPLSStellarModel
return ADIPLSStellarModel(
*fgong_to_amdl(self.glob, self.var, G=self.G), G=self.G)
def to_gyre(self, version=None):
"""Convert the model to a ``GYREStellarModel`` object.
Parameters
----------
version: int, optional
Specify GYRE format version number times 100. i.e.,
``version=101`` produce a file with data version 1.01. If
``None`` (the default), the latest version available in
TOMSO is used.
"""
from .gyre import gyre_header_dtypes, gyre_data_dtypes, GYREStellarModel
if version is None:
version = max([k for k in gyre_header_dtypes.keys()])
header = np.zeros(1, gyre_header_dtypes[version])
header['M'] = self.glob[0]
header['R'] = self.glob[1]
header['L'] = self.glob[2]
if version > 1:
header['version'] = version
data = np.zeros(self.nn, gyre_data_dtypes[version])
# data['r'] = self.var[:,0]
# data['T'] = self.var[:,2]
# data['P'] = self.var[:,3]
# data['rho'] = self.var[:,4]
# if np.all(np.diff(data['r']) <= 0):
# return GYREStellarModel(header, data[::-1], G=self.G)
# else:
# return GYREStellarModel(header, data, G=self.G)
g = GYREStellarModel(header[0], data, G=self.G)
g.r = self.r
g.m = self.m
g.T = self.T
g.P = self.P
g.rho = self.rho
g.Gamma_1 = self.Gamma_1
g.N2 = self.N2
g.kappa = self.kappa
g.L_r = self.L_r
g.data['nabla_ad'] = self.var[:,10]
g.data['delta'] = self.var[:,11]
# The definitions of epsilon in FGONG and GYRE formats might
# be different. Compute non-adiabatic modes at your peril!
if version < 101:
g.data['eps_tot'] = self.epsilon
else:
g.data['eps'] = self.epsilon
if np.all(np.diff(g.r) <= 0):
g.data = g.data[::-1]
g.data['k'] = np.arange(self.nn) + 1
return g
# FGONG parameters that can be derived from data
@property
def iconst(self): return len(self.glob)
@property
def nn(self): return self.var.shape[0]
@property
def ivar(self): return self.var.shape[1]
# Various properties for easier access to the data in `glob` and
# `var`.
@property
def M(self): return self.glob[0]
@M.setter
def M(self, val): self.glob[0] = val
@property
def R(self): return self.glob[1]
@R.setter
def R(self, val): self.glob[1] = val
@property
def L(self): return self.glob[2]
@L.setter
def L(self, val): self.glob[2] = val
@property
def r(self): return self.var[:,0]
@r.setter
def r(self, val):
self.var[:,0] = val
self.var[:,17] = self.R-val
@property
def lnq(self): return self.var[:,1]
@lnq.setter
def lnq(self, val): self.var[:,1] = val
@property
def T(self): return self.var[:,2]
@T.setter
def T(self, val): self.var[:,2] = val
@property
def P(self): return self.var[:,3]
@P.setter
def P(self, val): self.var[:,3] = val
@property
def rho(self): return self.var[:,4]
@rho.setter
def rho(self, val): self.var[:,4] = val
@property
def X(self): return self.var[:,5]
@X.setter
def X(self, val): self.var[:,5] = val
@property
def L_r(self): return self.var[:,6]
@L_r.setter
def L_r(self, val): self.var[:,6] = val
@property
def kappa(self): return self.var[:,7]
@kappa.setter
def kappa(self): self.var[:,7] = val
@property
def epsilon(self): return self.var[:,8]
@epsilon.setter
def epsilon(self, val): self.var[:,8] = val
@property
def Gamma_1(self): return self.var[:,9]
@Gamma_1.setter
def Gamma_1(self, val): self.var[:,9] = val
@property
def G1(self): return self.var[:,9]
@G1.setter
def G1(self, val): self.var[:,9] = val
@property
def grad_a(self): return self.var[:,10]
@grad_a.setter
def grad_a(self, val): self.var[:,10] = val
@property
def cp(self): return self.var[:,12]
@cp.setter
def cp(self, val): self.var[:,12] = val
@property
def AA(self): return self.var[:,14]
@AA.setter
def AA(self, val): self.var[:,14] = val
@property
def Z(self): return self.var[:,16]
@Z.setter
def Z(self, val): self.var[:,16] = val
# Some convenient quantities derived from `glob` and `var`.
@property
def x(self): return self.r/self.R
@x.setter
def x(self, val): self.r = val*self.R
@property
def q(self): return np.exp(self.lnq)
@q.setter
def q(self, val): self.lnq = np.log(val)
@property
def m(self): return self.q*self.M
@m.setter
def m(self, val): self.q = val/self.M
@property
@regularize()
def N2(self): return self.AA*self.g/self.r
@property
@regularize(y0=3)
def U(self): return 4.*np.pi*self.rho*self.r**3/self.m
@property
@regularize()
def V(self): return self.G*self.m*self.rho/self.P/self.r
@property
def Vg(self): return self.V/self.Gamma_1
@property
def tau(self):
if np.all(np.diff(self.x) < 0):
return -integrate(1./self.cs, self.r)
else:
tau = integrate(1./self.cs[::-1], self.r[::-1])[::-1]
return np.max(tau)-tau
# - ``G1``: first adiabatic index (array)
| warrickball/tomso | tomso/fgong.py | Python | mit | 22,737 |
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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 org.spongepowered.mod.mixin.core.world;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.BlockPos;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.storage.WorldInfo;
import net.minecraftforge.common.util.BlockSnapshot;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import java.util.ArrayList;
@Mixin(value = net.minecraft.world.World.class, priority = 1001)
public abstract class MixinWorld implements org.spongepowered.api.world.World {
@Shadow public WorldInfo worldInfo;
private long weatherStartTime;
private Block tempBlock;
private BlockSnapshot tempSnapshot;
@Inject(method = "updateWeatherBody()V", remap = false, at = {
@At(value = "INVOKE", target = "Lnet/minecraft/world/storage/WorldInfo;setThundering(Z)V"),
@At(value = "INVOKE", target = "Lnet/minecraft/world/storage/WorldInfo;setRaining(Z)V")
})
private void onUpdateWeatherBody(CallbackInfo ci) {
this.weatherStartTime = this.worldInfo.getWorldTotalTime();
}
@Inject(method = "setBlockState", at = @At(value = "INVOKE", target = "Ljava/util/ArrayList;add(Ljava/lang/Object;)Z", remap = false, ordinal = 0),
locals = LocalCapture.CAPTURE_FAILEXCEPTION)
public void onSetBlockState(BlockPos pos, IBlockState newState, int flags, CallbackInfoReturnable<Boolean> cir, Chunk chunk, Block block, BlockSnapshot blockSnapshot) {
this.tempBlock = block;
this.tempSnapshot = blockSnapshot;
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Redirect(method = "setBlockState",
at = @At(value = "INVOKE", target = "Ljava/util/ArrayList;add(Ljava/lang/Object;)Z", remap = false))
public boolean onAddSnapshot(ArrayList list, Object snapshot) {
// Only capture if existing block was replaced by different block type
if (tempSnapshot.getReplacedBlock().getBlock() != tempBlock) {
return list.add(snapshot);
} else {
// ignore block state changes for replaced blocks
tempSnapshot = null;
}
return false;
}
@Override
public long getRunningDuration() {
return this.worldInfo.getWorldTotalTime() - this.weatherStartTime;
}
}
| joseph00713/Sponge | src/main/java/org/spongepowered/mod/mixin/core/world/MixinWorld.java | Java | mit | 3,950 |
namespace Tharga.Toolkit.Console.Entities
{
public class Position
{
public int Left { get; }
public int Top { get; }
public int? Width { get; }
public int? Height { get; }
public int? BufferWidth { get; }
public int? BufferHeight { get; }
public Position(int left, int top, int? width = null, int? height = null, int? bufferWidth = null, int? bufferHeight = null)
{
Left = left;
Top = top;
Width = width;
Height = height;
BufferWidth = bufferWidth;
BufferHeight = bufferHeight;
}
}
} | poxet/tharga-console | Tharga.Toolkit.Console/Entities/Position.cs | C# | mit | 640 |
"""Automatically format references in a LaTeX file."""
import argparse
from multiprocessing import Pool
from reference_utils import Reference, extract_bibtex_items
from latex_utils import read_latex_file, write_latex_file
class ReferenceFormatter:
def __init__(self, add_arxiv):
self.add_arxiv = add_arxiv
def get_reference(self, bibtex_entry):
"""Wrapper for multithreading."""
reference = Reference(bibtex_entry.rstrip(), self.add_arxiv)
reference.main()
return reference.bibitem_data, reference.bibitem_identifier, reference.reformatted_original_reference, reference.formatted_reference
def format_references(self, latex_source):
"""Format all references in the given LaTeX source."""
bibtex_entries = extract_bibtex_items(latex_source)
# Parallelising the reference lookup gives a 15x speedup.
# Values larger than 15 for the poolsize do not give a further speedup.
with Pool(15) as pool:
res = pool.map(self.get_reference, bibtex_entries)
for r in res:
bibitem_data, bibitem_identifier, reformatted_original_reference, formatted_reference = r
latex_source = latex_source.replace(bibitem_data, f"\\bibitem{{{bibitem_identifier}}} \\textcolor{{red}}{{TODO}}\n{reformatted_original_reference}\n\n%{formatted_reference}\n\n\n")
return latex_source
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('latex_file')
parser.add_argument('--add_arxiv', action="store_true")
args = parser.parse_args()
latex_source = read_latex_file(args.latex_file)
print("Processing references...")
reference_formatter = ReferenceFormatter(args.add_arxiv)
latex_source = reference_formatter.format_references(latex_source)
write_latex_file(args.latex_file, latex_source)
| teunzwart/latex-production-tools | reference_formatter.py | Python | mit | 1,870 |
<!-- SECTION Judul-->
<!--===============================================================-->
<div class="section-heading-page">
<div class="container">
<div class="row">
<div class="col-sm-6">
<h1 class="heading-page text-center-xs">Dashboard</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb text-right text-center-xs">
<li>
<a href="#">Home</a>
</li>
<li class="active">Dashboard</li>
</ol>
</div>
</div>
</div>
</div>
<!-- SECTION KONTEN -->
<div class="container">
<div class="row">
<!-- SIDE NAV -->
<!--===============================================================-->
<?php $this->load->view('front/template/menu_member'); ?>
<!-- END SIDE NAV -->
<!-- CONTENT COLUMN -->
<!--===============================================================-->
<div class="col-md-9">
<div class="row">
<div class="col-md-12">
<h3 class="title-v2">Transaksi anda</h3>
</div>
</div>
<div class="row">
<div class="col-md-12">
<?php if ($this->session->flashdata('msg_success')): ?>
<!-- alert jika sukses simpan -->
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<?php echo $this->session->flashdata('msg_success'); ?>
</div>
<?php endif ?>
<?php if ($this->session->flashdata('msg_error_upload')): ?>
<!-- alert jika ada error ketika upload -->
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<?php echo $this->session->flashdata('msg_error_upload'); ?>
</div>
<?php endif ?>
<!-- alert jika ada form error -->
<?php echo validation_errors('<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>','</div>'); ?>
</div>
</div>
<div class="row">
<div class="col-md-12">
<?php foreach ($arr_transaksi as $transaksi): ?>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Informasi Pemesanan</h3>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-6">
<h3 class="text-theme title-sm hr-before">Tanggal Pesan</h3>
<p class="text-theme">
<?php
$date = new DateTime($transaksi->tgl_pesan);
echo $date->format('d F Y H:i'); ?>
</p>
<h3 class="text-theme title-md hr-left">Biaya</h3>
<table class="table table-bordered">
<thead>
<tr>
<th>No</th>
<th>Deskripsi</th>
<th>Harga</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Total</td>
<td><h3 class="text-right text-theme title-md">Rp <?php echo number_format($total['sub_total'],2,'.',','); ?></h3></td>
</tr>
<tr>
<td colspan="2" class="btn-sea text-right">Sub Total</td>
<td class="btn-sea"><h3 class=" text-right text-theme title-md">
Rp <?php echo number_format($total['sub_total'],2,'.',','); ?>
</h3></td>
</tr>
<tr>
<td>2</td>
<td>Ongkir</td>
<td><h3 class="text-right text-theme title-md">
Rp <?php echo number_format($transaksi->tarif,2,'.',','); ?>
</h3>
</td>
</tr>
<tr>
<td colspan="2" class="btn-green text-right">Total Bayar</td>
<td class="btn-green"><h3 class=" text-right text-theme title-md">Rp <?php echo number_format($total['grand_total'],2,'.',','); ?></h3></td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-6">
<h3 class="text-theme title-sm hr-before">Status</h3>
<p class="text-theme">
<?php if ($transaksi->status=='pending'): ?>
<div class="label label-warning">Pending</div>
<small><a href="<?php echo site_url('member/konfirmasi') ?>">Silahkan Konfirmasi</a></small>
<?php elseif($transaksi->status=='terkonfirmasi'): ?>
<div class="label label-info">Terkonfirmasi</div>
<?php elseif($transaksi->status=='proses'): ?>
<div class="label label-primary">Sedang Diproses</div>
<?php elseif($transaksi->status=='kirim'): ?>
<div class="label label-success">Dikirim</div>
<?php endif ?>
</p>
<h3 class="text-theme title-sm hr-before">No Resi</h3>
<p class="text-theme">
<?php if (empty($transaksi->no_resi)): ?>
-
<?php else: ?>
<?php echo $transaksi->no_resi; ?>
<?php endif ?>
</p>
<h3 class="text-theme title-sm hr-before">Dikirim ke</h3>
<p class="text-theme"><?php echo $transaksi->alamat_kirim; ?></p>
<h3 class="text-theme title-sm hr-before">Kota Tujuan</h3>
<p class="text-theme"><?php echo $transaksi->nama_kota; ?></p>
</div>
</div>
</div>
</div>
<?php endforeach ?>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Informasi barang yang dipesan</h3>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-12">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>#</th>
<th>Kode</th>
<th>Nama</th>
<th>Jumlah</th>
<th>Harga</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<?php $no=1; ?>
<?php foreach ($arr_transaksi_detail as $transaksi_detail): ?>
<tr>
<td><?php echo $no;$no++; ?></td>
<td>BRG<?php echo $transaksi_detail->id_barang; ?></td>
<td><?php echo $transaksi_detail->nama_barang; ?></td>
<td><?php echo $transaksi_detail->jumlah; ?></td>
<td>Rp <?php echo number_format($transaksi_detail->harga,2,'.',','); ?></td>
<td>Rp <?php echo number_format($transaksi_detail->sub_total,2,'.',','); ?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
</div>
</div>
<hr class="hr-divider-ghost">
</div>
</div>
</div>
</div>
<hr class="hr-divider-ghost">
</div>
</div>
</div>
<!-- END SECTION KONTEN -->
<script type="text/javascript">
window.pilih_alamat = function() {
if(document.getElementById("alamat_baru1").checked) {
document.getElementById("input_alamat").readOnly = false;
document.getElementById("input_alamat").value = '';
} else {
document.getElementById("input_alamat").readOnly = true;
document.getElementById("input_alamat").value = '<?php echo $alamat_user; ?>';
}
}
window.onload = pilih_alamat();
</script>
<!-- modal konfirmasi hapus -->
<div class="modal fade" id="deleteKeranjang" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="exampleModalLabel">Konfirmasi Hapus</h4>
</div>
<div class="modal-body">
Apa Anda yakin akan menghapus Pesanan ini ?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Tutup</button>
<a class="btn btn-primary">Hapus</a>
</div>
</div>
</div>
</div> | reeganaga/tokoonline | application/views/front/history/content_detail.php | PHP | mit | 10,478 |
require 'spec_helper'
describe SerpMetrics::CommandSets::Flux, :vcr do
before do
api_configuration = YAML.load_file('spec/api_credentials.yml')
@client = SerpMetrics.client.configure do |client|
client.key = api_configuration['key']
client.secret = api_configuration['secret']
end
end
describe "flux" do
it "fetches flux trend" do
response = @client.flux.flux('google_en-us')
response['data'].should be_instance_of(Hash)
trend = response['data'].first
trend.should be_instance_of(Array)
trend.length.should == 2
trend[0].should be_instance_of(String)
trend[1].should be_instance_of(Fixnum)
end
end
end
| wearetribe/serp_metrics | spec/lib/serp_metrics/command_sets/flux_spec.rb | Ruby | mit | 686 |
import sqlite3
import requests
from random import sample
import textwrap
from printer import ThermalPrinter
LINE_WIDTH = 32
potm = "http://creepypasta.wikia.com/api/v1/Articles/List?category=PotM&limit=1000"
spotlighted = "http://creepypasta.wikia.com/api/v1/Articles/List?category=Spotlighted_Pastas&limit=1000"
def get_json_from_url(url):
return requests.get(url).json()
def get_ids_from_article_list(data):
return [item['id'] for item in data['items']]
def get_ids_from_url(url):
data = get_json_from_url(url)
return get_ids_from_article_list(data)
def get_id_list():
each = get_ids_from_url(potm) + get_ids_from_url(spotlighted)
return each
def get_newest_story(c, story_list):
if len(story_list) == 0:
return "NO STORIES FOUND"
first = story_list[0]
c.execute("INSERT INTO `visited` (`source`, `source_id`) VALUES (?, ?)", ('creepypasta.wikia.com', first))
story_data = get_json_from_url("http://creepypasta.wikia.com/api/v1/Articles/AsSimpleJson?id=%s" % first)
return story_data
def strip_printed_stories(c, story_list, source):
existing_ids = [item[0] for item in c.execute("SELECT source_id FROM `visited` WHERE `source`='%s'" % source)]
return [story for story in story_list if story not in existing_ids]
def parse_list_item(item):
return textwrap.fill("* %s" % item['text'], LINE_WIDTH)
def parse_content_item(item):
if item['type'] == 'paragraph':
return textwrap.fill(item['text'], LINE_WIDTH)
elif item['type'] == 'list':
return "\n".join(parse_list_item(li) for li in item['elements'])
return ''
def parse_content_list(section):
return "\n".join(parse_content_item(item) for item in section['content'])
def parse_title(section):
# CENTRE ME
return "\n" + textwrap.fill(section['title'], LINE_WIDTH)
def parse_section(section):
return "\n".join([parse_title(section), parse_content_list(section)])
def parse_story(data):
sections = [parse_section(section) for section in data['sections']]
return "\n".join(sections)
conn = sqlite3.connect('creepypasta.db')
c = conn.cursor()
ids = get_id_list()
stripped = strip_printed_stories(c, ids, "creepypasta.wikia.com")
shuffled = sample(ids, len(ids))
newest = get_newest_story(c, shuffled)
lines = parse_story(newest).encode('ascii', 'replace')
printer = ThermalPrinter()
for line in lines.split("\n"):
printer.print_text("\n" + line)
conn.commit()
conn.close()
| AngryLawyer/creepypasta-strainer | src_python/strainer.py | Python | mit | 2,457 |
<?php
class CM_WP_Exception_PluginNotRegisteredException extends
Exception
{
/**
* Plugin slug
*
* @var string
*/
protected $slug;
/**
* [__construct description]
*
* @param string $slug
*/
public function __construct( $slug ) {
$this->slug = $slug;
parent::__construct(
sprintf(
"Plugin with the slug '%s' has not been registered yet",
$this->slug
)
);
}
} | cubicmushroom/wordpress-helper | src/CM/WP/Exception/PluginNotRegisteredException.php | PHP | mit | 504 |
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("01.Money")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("01.Money")]
[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("440019dd-1371-4262-ab79-93b0b6be4cc1")]
// 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")]
| Steffkn/SoftUni | 01.ProgrammingBasicsC#/Exams/17July2016/01.Money/Properties/AssemblyInfo.cs | C# | mit | 1,387 |
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link http://phpdoc.org
*/
namespace phpDocumentor\Descriptor\Filter;
use Mockery as m;
use Mockery\Adapter\Phpunit\MockeryTestCase;
use phpDocumentor\Descriptor\Collection;
use phpDocumentor\Descriptor\DescriptorAbstract;
use phpDocumentor\Descriptor\MethodDescriptor;
use phpDocumentor\Descriptor\ProjectDescriptor\Settings;
use phpDocumentor\Descriptor\ProjectDescriptorBuilder;
use phpDocumentor\Descriptor\TagDescriptor;
/**
* Tests the functionality for the StripOnVisibility class.
*
* @coversDefaultClass \phpDocumentor\Descriptor\Filter\StripOnVisibility
*/
final class StripOnVisibilityTest extends MockeryTestCase
{
/** @var ProjectDescriptorBuilder|m\Mock */
private $builderMock;
/** @var StripOnVisibility $fixture */
private $fixture;
/**
* Creates a new (empty) fixture object.
*/
protected function setUp() : void
{
$this->builderMock = m::mock(ProjectDescriptorBuilder::class);
$this->fixture = new StripOnVisibility($this->builderMock);
}
/**
* @covers ::__invoke
*/
public function testStripsDescriptorIfVisibilityIsNotAllowed() : void
{
$this->builderMock->shouldReceive('getProjectDescriptor->isVisibilityAllowed')
->with(Settings::VISIBILITY_PUBLIC)
->andReturn(false);
$descriptor = m::mock(MethodDescriptor::class);
$descriptor->shouldReceive('getVisibility')->andReturn('public');
$descriptor->shouldReceive('getTags')->andReturn(new Collection());
$this->assertNull($this->fixture->__invoke($descriptor));
}
/**
* @covers ::__invoke
*/
public function testItNeverStripsDescriptorIfApiIsSet() : void
{
$this->builderMock->shouldReceive('getProjectDescriptor->isVisibilityAllowed')
->with(Settings::VISIBILITY_API)->andReturn(true);
// if API already return true; then we do not expect a call with for the PUBLIC visibility
$this->builderMock->shouldNotReceive('getProjectDescriptor->isVisibilityAllowed')
->with(Settings::VISIBILITY_PUBLIC);
$descriptor = m::mock(MethodDescriptor::class);
$descriptor->shouldReceive('getVisibility')->andReturn('public');
$tagsCollection = new Collection();
$tagsCollection->set('api', new TagDescriptor('api'));
$descriptor->shouldReceive('getTags')->andReturn($tagsCollection);
$this->assertSame($descriptor, $this->fixture->__invoke($descriptor));
}
/**
* @covers ::__invoke
*/
public function testKeepsDescriptorIfVisibilityIsAllowed() : void
{
$this->builderMock->shouldReceive('getProjectDescriptor->isVisibilityAllowed')
->with(Settings::VISIBILITY_PUBLIC)
->andReturn(true);
$descriptor = m::mock(MethodDescriptor::class);
$descriptor->shouldReceive('getVisibility')->andReturn('public');
$descriptor->shouldReceive('getTags')->andReturn(new Collection());
$this->assertSame($descriptor, $this->fixture->__invoke($descriptor));
}
/**
* @covers ::__invoke
*/
public function testKeepsDescriptorIfDescriptorNotInstanceOfVisibilityInterface() : void
{
$this->builderMock->shouldReceive('getProjectDescriptor->isVisibilityAllowed')->andReturn(false);
$descriptor = m::mock(DescriptorAbstract::class);
$descriptor->shouldReceive('getTags')->andReturn(new Collection());
$this->assertSame($descriptor, $this->fixture->__invoke($descriptor));
}
}
| rgeraads/phpDocumentor2 | tests/unit/phpDocumentor/Descriptor/Filter/StripOnVisibilityTest.php | PHP | mit | 3,762 |
import { NgModule } from '@angular/core';
import {
ToolbarModule
} from 'primeng/primeng';
import { PageToolbarComponent } from './page-toolbar.component';
@NgModule({
exports: [PageToolbarComponent],
declarations: [PageToolbarComponent],
imports: [
ToolbarModule
]
})
export class PageToolbarModule {
}
| dreamer99x/ceb | src/app/shared/components/page-toolbar/index.ts | TypeScript | mit | 321 |
class ParseException < Exception
end | ably-forks/cloudyscripts | lib/audit/lib/parser/parse_exception.rb | Ruby | mit | 36 |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://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.
# ==============================================================================
import show_and_tell_model
from inference_utils import inference_wrapper_base
class InferenceWrapper(inference_wrapper_base.InferenceWrapperBase):
"""Model wrapper class for performing inference with a ShowAndTellModel."""
def __init__(self):
super(InferenceWrapper, self).__init__()
def build_model(self, model_config):
model = show_and_tell_model.ShowAndTellModel(model_config, mode="inference")
model.build()
return model
def feed_image(self, sess, encoded_image):
initial_state = sess.run(fetches="lstm/initial_state:0",
feed_dict={"image_feed:0": encoded_image})
return initial_state
def inference_step(self, sess, input_feed, state_feed):
softmax_output, state_output = sess.run(
fetches=["softmax:0", "lstm/state:0"],
feed_dict={
"input_feed:0": input_feed,
"lstm/state_feed:0": state_feed,
})
return softmax_output, state_output, None
| hkhpub/show_and_tell_korean | webdemo/webdemo/inference_wrapper.py | Python | mit | 1,658 |
#include <cstdlib>
#include <stack>
#include <vector>
using namespace std;
#include "binary_tree_inorder_traversal.h"
#include "../util/util_tree.h"
vector<int>
BinaryTreeInorderTraversal::inorderTraversalRecursive(TreeNode *root) {
vector<int> traversal_history;
if (root == NULL)
return traversal_history;
// Traverse the left sub-tree.
vector<int> left_traversal_history = inorderTraversalRecursive(root->left);
traversal_history.insert(traversal_history.end(),
left_traversal_history.begin(),
left_traversal_history.end());
// Visit the root node.
traversal_history.push_back(root->val);
// Traverse the right sub-tree.
vector<int> right_traversal_history = inorderTraversalRecursive(root->right);
traversal_history.insert(traversal_history.end(),
right_traversal_history.begin(),
right_traversal_history.end());
return traversal_history;
}
vector<int>
BinaryTreeInorderTraversal::inorderTraversalIterative(TreeNode* root) {
vector<int> traversal_history;
if (root == NULL)
return traversal_history;
TreeNode *root_node = root;
stack<TreeNode*> candidate_list;
do {
// If current sub-tree is empty, then popup LCA node, visit it, and update
// next sub-tree to its right sub-tree.
if (root_node == NULL) {
root_node = candidate_list.top();
candidate_list.pop();
traversal_history.push_back(root_node->val);
root_node = root_node->right;
}
// If current sub-tree is not empty, then push the root node, update next
// sub-tree to its left sub-tree.
if (root_node) {
candidate_list.push(root_node);
root_node = root_node->left;
}
} while (!candidate_list.empty());
return traversal_history;
} | metacpp/LeetCpp | src/tree/binary_tree_inorder_traversal.cc | C++ | mit | 1,826 |
angular.module('zfaModal', ['foundation'])
.provider('zfaModal', function () {
var configs = {};
function register (modalId, config) {
if (typeof modalId === 'string') {
return configs[modalId] = config;
}else{
throw new Error('zfaModalProvider: modalId should be defined');
}
}
return {
register: register,
$get: function (zfaModalFactory, FoundationApi) {
return {
open: function (modalId, modalConfig) {
var newConfig = configs[modalId] || register(modalId,modalConfig);
newConfig.locals = angular.extend({}, newConfig.locals, modalConfig); //Overwrite old config
return zfaModalFactory.createModal(newConfig);
},
close: function (id) {
FoundationApi.publish(id, 'close');
}
}
}
}
});
| Miklecc/foundation-apps-modal | src/zfaModalProvider.js | JavaScript | mit | 1,054 |
package main
import (
"os"
"github.com/codegangsta/cli"
"github.com/denkhaus/tcgl/applog"
"github.com/gitmonster/cmnodes/command"
"github.com/gitmonster/cmnodes/nodes"
)
var initFileName = ".cmnodesrc"
var releaseVersion = "0.0.1"
func main() {
app := cli.NewApp()
app.Name = "cmnodes"
app.Version = releaseVersion
app.Usage = "A cms and static file site generator powerd by golang."
app.Flags = []cli.Flag{
//cli.StringFlag{"group, g", "", "group or container to restrict the command to"},
//cli.StringFlag{"manifest, m", "", "path to a manifest (.json, .yml, .yaml) file to read from"},
cli.BoolFlag{"debug, d", "print debug output", ""},
//cli.BoolFlag{"test, t", "perform selftests"},
//cli.StringSliceFlag{"peers, C", &cli.StringSlice{}, "a comma-delimited list of machine addresses in the cluster (default: {\"127.0.0.1:4001\"})"},
}
if cnf, err := nodes.CreateNodesConfig(initFileName); err != nil {
applog.Errorf("Configuration error:: load config %s", err.Error())
return
} else {
if cmdr, err := command.NewCommander(app, cnf); err != nil {
applog.Errorf("Startup error:: %s", err.Error())
return
} else {
cmdr.Run(os.Args)
}
}
}
| gitmonster/cmnodes | cmnodes.go | GO | mit | 1,188 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>
ERROR - 2015-11-08 00:53:15 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 02:46:43 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 02:47:31 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 03:10:36 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 03:16:58 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 03:27:38 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 04:24:55 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 05:00:06 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 05:27:49 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 05:28:38 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 05:37:42 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 06:05:11 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 06:05:21 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 06:34:01 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 07:14:20 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 08:45:39 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 09:04:40 --> 404 Page Not Found --> manager
ERROR - 2015-11-08 09:33:08 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 09:33:10 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 09:37:13 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 09:41:28 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 10:08:47 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 11:01:06 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 11:01:30 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 11:02:02 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 11:58:34 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 12:03:29 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 13:53:24 --> 404 Page Not Found --> wp-admin
ERROR - 2015-11-08 13:53:25 --> 404 Page Not Found --> wp-admin
ERROR - 2015-11-08 13:53:25 --> 404 Page Not Found --> wp-admin
ERROR - 2015-11-08 13:53:26 --> 404 Page Not Found --> wp-admin
ERROR - 2015-11-08 13:53:27 --> 404 Page Not Found --> wp-admin
ERROR - 2015-11-08 13:53:27 --> 404 Page Not Found --> wp-admin
ERROR - 2015-11-08 18:01:12 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 19:17:50 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 19:18:14 --> 404 Page Not Found --> robots.txt
ERROR - 2015-11-08 22:31:45 --> 404 Page Not Found --> robots.txt
| cmorenokkatoo/kkatooapp | application/logs/log-2015-11-08.php | PHP | mit | 2,507 |
#include <iostream>
#include <stdlib.h>
int main()
{
// int a = 1;
// int *b = &a;
int *b = (int *) malloc(sizeof(int));
*b = 5;
int *c = b;
int *d = c;
free (d);
// *b = 7;
std::cout << *b << std::endl;
}
| lindsayad/programming | cpp/lots_of_pointers.cpp | C++ | mit | 225 |
package no.notanumber.sosql;
import java.util.Objects;
public class Join {
public final DatabaseColumn primary;
public final DatabaseColumn foreign;
public Join(DatabaseColumn primary, DatabaseColumn foreign) {
this.primary = primary;
this.foreign = foreign;
}
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (!(obj instanceof Join))
return false;
Join other = (Join) obj;
return Objects.equals(primary, other.primary) && Objects.equals(foreign, other.foreign);
}
@Override
public int hashCode() {
return Objects.hash(primary, foreign);
}
@Override
public String toString() {
return primary.columnName + " = " + foreign.columnName;
}
}
| NotANumber-no/sosql | src/main/java/no/notanumber/sosql/Join.java | Java | mit | 803 |
package com.bitdubai.fermat_dmp_plugin.layer.world.crypto_index.developer.bitdubai;
import com.bitdubai.fermat_api.Plugin;
import com.bitdubai.fermat_api.PluginDeveloper;
import com.bitdubai.fermat_api.layer.all_definition.enums.CryptoCurrency;
import com.bitdubai.fermat_api.layer.all_definition.enums.TimeFrequency;
import com.bitdubai.fermat_api.layer.all_definition.license.PluginLicensor;
import com.bitdubai.fermat_dmp_plugin.layer.world.crypto_index.developer.bitdubai.version_1.CryptoIndexWorldPluginRoot;
/**
* Created by loui on 12/02/15.
*/
public class DeveloperBitDubai implements PluginDeveloper, PluginLicensor {
Plugin plugin;
@Override
public Plugin getPlugin() {
return plugin;
}
public DeveloperBitDubai () {
/**
* I will choose from the different versions of my implementations which one to start. Now there is only one, so
* it is easy to choose.
*/
plugin = new CryptoIndexWorldPluginRoot();
}
@Override
public int getAmountToPay() {
return 100;
}
@Override
public CryptoCurrency getCryptoCurrency() {
return CryptoCurrency.BITCOIN;
}
@Override
public String getAddress() {
return "13gpMizSNvQCbJzAPyGCUnfUGqFD8ryzcv";
}
@Override
public TimeFrequency getTimePeriod() {
return TimeFrequency.MONTHLY;
}
} | fvasquezjatar/fermat-unused | DMP/plugin/world/fermat-dmp-plugin-world-crypto-index-bitdubai/src/main/java/com/bitdubai/fermat_dmp_plugin/layer/world/crypto_index/developer/bitdubai/DeveloperBitDubai.java | Java | mit | 1,395 |
# -*- coding: utf-8 -*-
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as test_command
class PyTest(test_command):
user_options = [
('pytest-args=', 'a', 'Arguments for pytest'),
]
def initialize_options(self):
test_command.initialize_options(self)
self.pytest_target = []
self.pytest_args = []
def finalize_options(self):
test_command.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errno = pytest.main(self.pytest_args)
sys.exit(errno)
version = '0.1.0'
setup_requires = [
'pytest'
]
tests_require = [
'pytest-timeout',
'mypy-lang',
]
setup(
name='algo_trade',
package=find_packages(),
setup_requires=setup_requires,
## install_requires=install_requires,
tests_require=tests_require,
cmdclass={'test': PyTest},
test_suite='test'
)
| sablet/algo_trade | setup.py | Python | mit | 985 |
'use strict';
/**
* @ngdoc directive
* @name myDashingApp.directive:widgetText
* @description
* # widgetText
*/
angular.module('myDashingApp')
.directive('widgetText', function () {
return {
template: '<div><div class="title">{{data.title}}</div><div class="value">{{data.value}}</div><div updated-at="data.updatedAt"></div></div>',
restrict: 'A',
scope:{
'data': '=widgetText'
}
};
});
| GuyMograbi/ng-dashing | app/scripts/directives/widgettext.js | JavaScript | mit | 482 |
<?php
/* SMASMABundle:Public:about2.html.twig */
class __TwigTemplate_95bc6be8200ffe9eef6c99c778e963bf4ee22d5d533dcb62c75dbe15624dff5e extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = $this->env->loadTemplate("SMASMABundle:Public:templatedetail2.html.twig");
$this->blocks = array(
'body' => array($this, 'block_body'),
);
}
protected function doGetParent(array $context)
{
return "SMASMABundle:Public:templatedetail2.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_body($context, array $blocks = array())
{
// line 4
echo " <h2>Tentang Kami</h2>
<p>
SMA Negeri (SMAN) 11 Medan, merupakan salah satu Sekolah Menengah Atas Negeri yang ada di Provinsi Sumatera Utara, Indonesia. Sama dengan SMA pada umumnya di Indonesia masa pendidikan sekolah di SMAN 11 Medan ditempuh dalam waktu tiga tahun pelajaran, mulai dari Kelas X sampai Kelas XII.
Pada tahun 2007, sekolah ini menggunakan Kurikulum Tingkat Satuan Pendidikan sebelumnya dengan KBK.
<dl class=\"dl-horizontal\">
<dt>Akreditasi :<dt>
<dd> Nilai Akreditasi : 82</dd>
<dd>Peringkat Akreditasi : B</dd>
<dd>Tanggal Penetapan : 05-Oct-2009.</dd>
<dt>Fasilitas</dt>
<dd>Kelas</dd>
<dd>Perpustakaan</dd>
<dd>Laboratorium Biologi</dd>
<dd>Laboratorium Fisika</dd>
<dd>Laboratorium Kimia</dd>
<dd>Laboratorium Komputer</dd>
<dd>Laboratorium Bahasa.</dd>
<dt>ekstrakurikuler</dt>
<dd>PASSDAN</dd>
<dd>BSC (Bio Sains Community)</dd>
<dd>BKM</dd>
<dd>PA</dd>
<dd>IT Community</dd>
<dd>LNC (Eleven English Club)</dd>
<dd>PRAMUKA</dd>
<dd>FAMOUS-T.</dd>
</dl>
</p>
<p>
<dl class=\"dl-horizontal\">
<dt>Alamat :</dt>
<dd>Jl. Pertiwi No.93 Medan Tembung (20236)</dd>
<dt>Email :</dt>
<dd>sman11medan81@yahoo.com</dd>
<dt>Telpon :</dt>
<dd>(061) 7382448</dd>
<dt>NSS :</dt>
<dd>301076009010</dd>
<dt>NPSN :</dt>
<dd>10210875</dd>
</dl>
</p>
";
}
public function getTemplateName()
{
return "SMASMABundle:Public:about2.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 31 => 4, 28 => 3,);
}
}
| matsuyuki/smanegeri11 | app/cache/dev/twig/95/bc/6be8200ffe9eef6c99c778e963bf4ee22d5d533dcb62c75dbe15624dff5e.php | PHP | mit | 2,653 |
window.dev1(1);
| delambo/gettit | test/assets/dev1/js/test2.js | JavaScript | mit | 16 |
/*
* The MIT License
*
* Copyright 2014 Kamnev Georgiy (nt.gocha@gmail.com).
*
* Данная лицензия разрешает, безвозмездно, лицам, получившим копию данного программного
* обеспечения и сопутствующей документации (в дальнейшем именуемыми "Программное Обеспечение"),
* использовать Программное Обеспечение без ограничений, включая неограниченное право на
* использование, копирование, изменение, объединение, публикацию, распространение, сублицензирование
* и/или продажу копий Программного Обеспечения, также как и лицам, которым предоставляется
* данное Программное Обеспечение, при соблюдении следующих условий:
*
* Вышеупомянутый копирайт и данные условия должны быть включены во все копии
* или значимые части данного Программного Обеспечения.
*
* ДАННОЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ», БЕЗ ЛЮБОГО ВИДА ГАРАНТИЙ,
* ЯВНО ВЫРАЖЕННЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ, ВКЛЮЧАЯ, НО НЕ ОГРАНИЧИВАЯСЬ ГАРАНТИЯМИ ТОВАРНОЙ ПРИГОДНОСТИ,
* СООТВЕТСТВИЯ ПО ЕГО КОНКРЕТНОМУ НАЗНАЧЕНИЮ И НЕНАРУШЕНИЯ ПРАВ. НИ В КАКОМ СЛУЧАЕ АВТОРЫ
* ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ ПО ИСКАМ О ВОЗМЕЩЕНИИ УЩЕРБА, УБЫТКОВ
* ИЛИ ДРУГИХ ТРЕБОВАНИЙ ПО ДЕЙСТВУЮЩИМ КОНТРАКТАМ, ДЕЛИКТАМ ИЛИ ИНОМУ, ВОЗНИКШИМ ИЗ, ИМЕЮЩИМ
* ПРИЧИНОЙ ИЛИ СВЯЗАННЫМ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ ИЛИ ИСПОЛЬЗОВАНИЕМ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ
* ИЛИ ИНЫМИ ДЕЙСТВИЯМИ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ.
*/
package xyz.cofe.lang2.parser;
import java.io.OutputStreamWriter;
import java.lang.reflect.Array;
import xyz.cofe.lang2.vm.Value;
import xyz.cofe.lang2.vm.op.AbstractTreeNode;
import xyz.cofe.collection.iterators.TreeWalk;
import xyz.cofe.text.IndentStackWriter;
import xyz.cofe.types.TypesUtil;
import xyz.cofe.types.ValueController;
/**
* Класс отображение дерева
* @author gocha
*/
public class SyntaxTreeDump
{
public void printTree(Value code){
IndentStackWriter w = new IndentStackWriter(new OutputStreamWriter(System.out));
printTree(w, code);
}
protected String getClassNameOf(Value v){
String cls = v.getClass().getName();
return cls;
}
protected boolean isShowAttribute(Value value,String attribute){
return true;
}
protected void printHeader(IndentStackWriter log){
}
public void printTree(IndentStackWriter log, Value codeV){
printHeader(log);
for( TreeWalk<Value> tw : AbstractTreeNode.tree(codeV) ){
int level = tw.currentLevel();
if( level>=0 )log.level(level);
Value v = tw.currentNode();
if( v==null ){
log.println( "node is null" );
continue;
}
int idx = v.getIndex();
String cls = getClassNameOf( v );
log.template("{0}. {1}", idx, cls);
log.println();
Iterable<ValueController> props = TypesUtil.Iterators.propertiesOf(v);
log.incLevel();
for( ValueController vc : props ){
String attr = vc.getName();
// if( attr.equals("parent") )continue;
if( !isShowAttribute(v, attr) )continue;
try{
Object val = vc.getValue();
printAttribute( log, attr, val );
}catch( Throwable ex ){
log.template("Exception ! {0}", ex.getMessage());
log.println();
}
}
}
log.level(0);
log.flush();
}
public void printAttribute( IndentStackWriter log, String attr, Object value ){
if( value!=null ){
Class cval = value.getClass();
if( cval.isArray() ){
log.template("{0} = ", attr);
printArray(log, cval, value);
}else{
log.template("{0} = ", attr);
printValue(log, value);
}
log.println();
}else{
log.template("{0} is null", attr);
log.println();
}
}
public void printValue( IndentStackWriter log, Object value ){
if( value==null ){
log.template("null");
}else{
Class c = value.getClass();
if( c.isArray() ){
printArray(log, c, value);
}else{
log.template("{0}", value);
}
}
}
public void printArray( IndentStackWriter log, Class valueClass, Object value ){
int length = Array.getLength(value);
log.print("{");
for( int idx = 0; idx<length; idx++ ){
if( idx>0 ){
log.print(", ");
}
Object item = Array.get(value, idx);
printValue(log, item);
}
log.print("}");
}
}
| gochaorg/lang2 | src/main/java/xyz/cofe/lang2/parser/SyntaxTreeDump.java | Java | mit | 5,610 |
/* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.office;
import com.wilutions.com.*;
/**
* MsoTextTabAlign.
*
*/
@SuppressWarnings("all")
@CoInterface(guid="{00000000-0000-0000-0000-000000000000}")
public class MsoTextTabAlign implements ComEnum {
static boolean __typelib__loaded = __TypeLib.load();
// Typed constants
public final static MsoTextTabAlign msoTabAlignMixed = new MsoTextTabAlign(-2);
public final static MsoTextTabAlign msoTabAlignLeft = new MsoTextTabAlign(0);
public final static MsoTextTabAlign msoTabAlignCenter = new MsoTextTabAlign(1);
public final static MsoTextTabAlign msoTabAlignRight = new MsoTextTabAlign(2);
public final static MsoTextTabAlign msoTabAlignDecimal = new MsoTextTabAlign(3);
// Integer constants for bitsets and switch statements
public final static int _msoTabAlignMixed = -2;
public final static int _msoTabAlignLeft = 0;
public final static int _msoTabAlignCenter = 1;
public final static int _msoTabAlignRight = 2;
public final static int _msoTabAlignDecimal = 3;
// Value, readonly field.
public final int value;
// Private constructor, use valueOf to create an instance.
private MsoTextTabAlign(int value) { this.value = value; }
// Return one of the predefined typed constants for the given value or create a new object.
public static MsoTextTabAlign valueOf(int value) {
switch(value) {
case -2: return msoTabAlignMixed;
case 0: return msoTabAlignLeft;
case 1: return msoTabAlignCenter;
case 2: return msoTabAlignRight;
case 3: return msoTabAlignDecimal;
default: return new MsoTextTabAlign(value);
}
}
public String toString() {
switch(value) {
case -2: return "msoTabAlignMixed";
case 0: return "msoTabAlignLeft";
case 1: return "msoTabAlignCenter";
case 2: return "msoTabAlignRight";
case 3: return "msoTabAlignDecimal";
default: {
StringBuilder sbuf = new StringBuilder();
sbuf.append("[").append(value).append("=");
if ((value & -2) != 0) sbuf.append("|msoTabAlignMixed");
if ((value & 0) != 0) sbuf.append("|msoTabAlignLeft");
if ((value & 1) != 0) sbuf.append("|msoTabAlignCenter");
if ((value & 2) != 0) sbuf.append("|msoTabAlignRight");
if ((value & 3) != 0) sbuf.append("|msoTabAlignDecimal");
return sbuf.toString();
}
}
}
}
| wolfgangimig/joa | java/joa/src-gen/com/wilutions/mslib/office/MsoTextTabAlign.java | Java | mit | 2,449 |
#include "optionsdialog.h"
#include "ui_optionsdialog.h"
#include "bitcoinunits.h"
#include "monitoreddatamapper.h"
#include "netbase.h"
#include "optionsmodel.h"
#include <QDir>
#include <QIntValidator>
#include <QLocale>
#include <QMessageBox>
OptionsDialog::OptionsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::OptionsDialog),
model(0),
mapper(0),
fRestartWarningDisplayed_Proxy(false),
fRestartWarningDisplayed_Lang(false),
fProxyIpValid(true)
{
ui->setupUi(this);
/* Network elements init */
#ifndef USE_UPNP
ui->mapPortUpnp->setEnabled(false);
#endif
ui->proxyIp->setEnabled(false);
ui->proxyPort->setEnabled(false);
ui->proxyPort->setValidator(new QIntValidator(1, 65535, this));
ui->socksVersion->setEnabled(false);
ui->socksVersion->addItem("5", 5);
ui->socksVersion->addItem("4", 4);
ui->socksVersion->setCurrentIndex(0);
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy()));
ui->proxyIp->installEventFilter(this);
/* Window elements init */
#ifdef Q_OS_MAC
/* remove Window tab on Mac */
ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow));
#endif
/* Display elements init */
QDir translations(":translations");
ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
foreach(const QString &langStr, translations.entryList())
{
QLocale locale(langStr);
/** check if the locale name consists of 2 parts (language_country) */
if(langStr.contains("_"))
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
else
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language (locale name)", e.g. "German (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
}
ui->unit->setModel(new BitcoinUnits(this));
/* Widget-to-option mapper */
mapper = new MonitoredDataMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
mapper->setOrientation(Qt::Vertical);
/* enable apply button when data modified */
connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton()));
/* disable apply button when new data loaded */
connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton()));
/* setup/change UI elements when proxy IP is invalid/valid */
connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool)));
}
OptionsDialog::~OptionsDialog()
{
delete ui;
}
void OptionsDialog::setModel(OptionsModel *model)
{
this->model = model;
if(model)
{
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
mapper->setModel(model);
setMapper();
mapper->toFirst();
}
/* update the display unit, to not use the default ("BTC") */
updateDisplayUnit();
/* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */
connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang()));
/* disable apply button after settings are loaded as there is nothing to save */
disableApplyButton();
}
void OptionsDialog::setMapper()
{
/* Main */
mapper->addMapping(ui->transactionFee, OptionsModel::Fee);
mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);
/* Network */
mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);
mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);
mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);
mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort);
mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion);
/* Window */
#ifndef Q_OS_MAC
mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray);
mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose);
#endif
/* Display */
mapper->addMapping(ui->lang, OptionsModel::Language);
mapper->addMapping(ui->unit, OptionsModel::DisplayUnit);
mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses);
}
void OptionsDialog::enableApplyButton()
{
ui->applyButton->setEnabled(true);
}
void OptionsDialog::disableApplyButton()
{
ui->applyButton->setEnabled(false);
}
void OptionsDialog::enableSaveButtons()
{
/* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */
if(fProxyIpValid)
setSaveButtonState(true);
}
void OptionsDialog::disableSaveButtons()
{
setSaveButtonState(false);
}
void OptionsDialog::setSaveButtonState(bool fState)
{
ui->applyButton->setEnabled(fState);
ui->okButton->setEnabled(fState);
}
void OptionsDialog::on_resetButton_clicked()
{
if(model)
{
// confirmation dialog
QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm options reset"),
tr("Some settings may require a client restart to take effect.") + "<br><br>" + tr("Do you want to proceed?"),
QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
if(btnRetVal == QMessageBox::Cancel)
return;
disableApplyButton();
/* disable restart warning messages display */
fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = true;
/* reset all options and save the default values (QSettings) */
model->Reset();
mapper->toFirst();
mapper->submit();
/* re-enable restart warning messages display */
fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = false;
}
}
void OptionsDialog::on_okButton_clicked()
{
mapper->submit();
accept();
}
void OptionsDialog::on_cancelButton_clicked()
{
reject();
}
void OptionsDialog::on_applyButton_clicked()
{
mapper->submit();
disableApplyButton();
}
void OptionsDialog::showRestartWarning_Proxy()
{
if(!fRestartWarningDisplayed_Proxy)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Maxcoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Proxy = true;
}
}
void OptionsDialog::showRestartWarning_Lang()
{
if(!fRestartWarningDisplayed_Lang)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Maxcoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Lang = true;
}
}
void OptionsDialog::updateDisplayUnit()
{
if(model)
{
/* Update transactionFee with the current unit */
ui->transactionFee->setDisplayUnit(model->getDisplayUnit());
}
}
void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState)
{
// this is used in a check before re-enabling the save buttons
fProxyIpValid = fState;
if(fProxyIpValid)
{
enableSaveButtons();
ui->statusLabel->clear();
}
else
{
disableSaveButtons();
object->setValid(fProxyIpValid);
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
ui->statusLabel->setText(tr("The supplied proxy address is invalid."));
}
}
bool OptionsDialog::eventFilter(QObject *object, QEvent *event)
{
if(event->type() == QEvent::FocusOut)
{
if(object == ui->proxyIp)
{
CService addr;
/* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */
emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr));
}
}
return QDialog::eventFilter(object, event);
}
| max-winderbaum/maxcoin | src/qt/optionsdialog.cpp | C++ | mit | 8,952 |
describe ApiGuardian::Helpers::Digits do
let(:subject) do
ApiGuardian::Helpers::Digits.new(
auth_url,
auth_header
)
end
let(:auth_url) { 'https://api.digits.com/v1/something.json' }
let(:auth_header) { 'OAuth oauth_consumer_key="foo"' }
it { should have_attr_reader(:auth_url) }
it { should have_attr_reader(:auth_header) }
describe 'methods' do
describe '#validate' do
it 'fails when oauth key is missing' do
expect_any_instance_of(ApiGuardian::Configuration::Registration).to(
receive(:digits_key).and_return('')
)
result = subject.validate
expect(result.succeeded).to eq false
expect(result.error).to eq(
'Digits consumer key not set! Please add ' \
'"config.registration.digits_key" to the ApiGuardian initializer!'
)
end
it 'fails with invalid auth header' do
expect_any_instance_of(ApiGuardian::Configuration::Registration).to(
receive(:digits_key).twice.and_return('bar')
)
result = subject.validate
expect(result.succeeded).to eq false
expect(result.error).to eq 'Digits consumer key does not match this request.'
end
context 'with invalid auth url' do
let(:auth_url) { 'https://example.com/stuff.json' }
it 'fails with invalid auth url' do
expect_any_instance_of(ApiGuardian::Configuration::Registration).to(
receive(:digits_key).twice.and_return('foo')
)
result = subject.validate
expect(result.succeeded).to eq false
expect(result.error).to eq 'Auth url is for invalid domain. Must match "api.digits.com".'
end
end
it 'succeeds if validations pass' do
expect_any_instance_of(ApiGuardian::Configuration::Registration).to(
receive(:digits_key).twice.and_return('foo')
)
result = subject.validate
expect(result.succeeded).to eq true
expect(result.error).to eq ''
end
end
describe '#authorize!' do
it 'should authorize digits request' do
stub_request(:get, auth_url).to_return(status: 200)
expect(subject.authorize!).to be_a Net::HTTPResponse
expect(WebMock).to have_requested(:get, auth_url).
with(headers: { 'Authorization' => auth_header }).once
end
it 'fails when HTTP response is not 200' do
stub_request(:get, auth_url).to_return(status: 400)
expect { subject.authorize! }.to raise_error(
ApiGuardian::Errors::IdentityAuthorizationFailed,
'Digits API responded with 400. Expected 200!'
)
expect(WebMock).to have_requested(:get, auth_url).
with(headers: { 'Authorization' => auth_header }).once
end
end
end
end
| lookitsatravis/api_guardian | spec/lib/helpers/digits_spec.rb | Ruby | mit | 2,828 |
<div class="box box-danger">
<div class="box-header with-border">
<h3 class="box-title">Ínteres por tipo de alimento</h3>
<div class="box-tools pull-right">
<button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
<button class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
</div>
</div>
<div class="box-body">
<canvas id="pieChart" style="height:250px"></canvas>
</div>
</div>
<script>
var pieChartCanvas = $("#pieChart").get(0).getContext("2d");
var pieChart = new Chart(pieChartCanvas);
var PieData = [
{
value: 700,
color: "#f56954",
highlight: "#f56954",
label: "Pollo"
},
{
value: 500,
color: "#00a65a",
highlight: "#00a65a",
label: "Pescado"
},
{
value: 400,
color: "#20a40a",
highlight: "#20a40a",
label: "Pavo"
},
{
value: 600,
color: "#33CCFF",
highlight: "#33CCFF",
label: "Solo bebidas"
}
];
var pieOptions = {
segmentShowStroke: true,
segmentStrokeColor: "#fff",
segmentStrokeWidth: 2,
percentageInnerCutout: 50,
animationSteps: 100,
animationEasing: "easeOutBounce",
animateRotate: true,
animateScale: true,
responsive: true,
maintainAspectRatio: true,
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
};
pieChart.Doughnut(PieData, pieOptions);
</script> | adrianturnes/menorcagastronomic | resources/views/backend/partials/donutChart.blade.php | PHP | mit | 1,877 |
var searchData=
[
['parseprocinfo',['ParseProcInfo',['../tinyoslib_8h.html#ab98738d69f4b198fbcad1a6f2e20a44d',1,'tinyoslib.c']]],
['pipe',['Pipe',['../group__syscalls.html#gab6355ce54e047c31538ed5ed9108b5b3',1,'Pipe(pipe_t *pipe): kernel_pipe.c'],['../group__syscalls.html#gab6355ce54e047c31538ed5ed9108b5b3',1,'Pipe(pipe_t *pipe): kernel_pipe.c']]]
];
| TedPap/opsys | doc/html/search/functions_b.js | JavaScript | mit | 367 |
<?php
namespace Ebbe\Test\SpecificationBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* TestCase
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="Ebbe\Test\SpecificationBundle\Entity\TestCaseRepository")
*/
class TestCase
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* @var string
*
* @ORM\Column(name="description", type="text")
*/
private $description;
/**
* @var string
*
* @ORM\Column(name="reference", type="string", length=255)
*/
private $reference;
/**
* @var string
*
* @ORM\Column(name="specification", type="text")
*/
private $specification;
/**
* @var string
*
* @ORM\Column(name="tags", type="string", length=255)
*/
private $tags;
/**
* @var string
*
* @ORM\Column(name="topic", type="string", length=255)
*/
private $topic;
/**
* @var string
*
* @ORM\Column(name="subject_under_test", type="string", length=255)
*/
private $subjectUnderTest;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* @param string $title
* @return TestCase
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* @param string $description
* @return TestCase
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set reference
*
* @param string $reference
* @return TestCase
*/
public function setReference($reference)
{
$this->reference = $reference;
return $this;
}
/**
* Get reference
*
* @return string
*/
public function getReference()
{
return $this->reference;
}
/**
* Set specification
*
* @param string $specification
* @return TestCase
*/
public function setSpecification($specification)
{
$this->specification = $specification;
return $this;
}
/**
* Get specification
*
* @return string
*/
public function getSpecification()
{
return $this->specification;
}
/**
* Set tags
*
* @param string $tags
* @return TestCase
*/
public function setTags($tags)
{
$this->tags = $tags;
return $this;
}
/**
* Get tags
*
* @return string
*/
public function getTags()
{
return $this->tags;
}
/**
* Set topic
*
* @param string $topic
* @return TestCase
*/
public function setTopic($topic)
{
$this->topic = $topic;
return $this;
}
/**
* Get topic
*
* @return string
*/
public function getTopic()
{
return $this->topic;
}
/**
* Set subjectUnderTest
*
* @param string $subjectUnderTest
* @return TestCase
*/
public function setSubjectUnderTest($subjectUnderTest)
{
$this->subjectUnderTest = $subjectUnderTest;
return $this;
}
/**
* Get subjectUnderTest
*
* @return string
*/
public function getSubjectUnderTest()
{
return $this->subjectUnderTest;
}
}
| rschumacher/jvtm | src/Ebbe/Test/SpecificationBundle/Entity/TestCase.php | PHP | mit | 4,027 |
require 'test/unit'
require File.join(File.dirname(__FILE__), '..', '..', 'init.rb')
require File.join(File.dirname(__FILE__), '..', '..', 'lib', 'spark_lines')
require File.join(File.dirname(__FILE__), 'rest_loader')
class Test::Unit::TestCase
def project(name)
@project ||= RESTfulLoaders::ProjectLoader.new(name, nil, self).project
end
def errors
@errors ||= []
end
def alert(message)
errors << message
end
end
| mrmarkyb/spark-line-mingle-macro | test/integration/integration_test_helper.rb | Ruby | mit | 450 |
var util = require('util')
, StoreError = require('jsr-error')
, CommandArgLength = StoreError.CommandArgLength
, InvalidFloat = StoreError.InvalidFloat
, Constants = require('jsr-constants')
, AbstractCommand = require('jsr-exec').DatabaseCommand;
/**
* Handler for the ZADD command.
*/
function SortedSetAdd() {
AbstractCommand.apply(this, arguments);
}
util.inherits(SortedSetAdd, AbstractCommand);
/**
* Validate the ZADD command.
*/
function validate(cmd, args, info) {
AbstractCommand.prototype.validate.apply(this, arguments);
var i
, num;
if((args.length - 1) % 2 !== 0) {
throw new CommandArgLength(cmd);
}
for(i = 1;i < args.length;i += 2) {
num = parseFloat('' + args[i]);
if(isNaN(num)) {
throw InvalidFloat;
}
args[i] = num;
}
}
SortedSetAdd.prototype.validate = validate;
module.exports = new SortedSetAdd(Constants.MAP.zadd);
| freeformsystems/jsr-server | lib/command/database/zset/zadd.js | JavaScript | mit | 907 |
var expect = require('expect.js'),
_ = require('lodash'),
RevisionGuard = require('../../lib/revisionGuard'),
revGuardStore = require('../../lib/revisionGuardStore');
describe('revisionGuard', function () {
var store;
before(function (done) {
revGuardStore.create(function (err, s) {
store = s;
done();
})
});
describe('creating a new guard', function () {
it('it should not throw an error', function () {
expect(function () {
new RevisionGuard(store);
}).not.to.throwError();
});
it('it should return a correct object', function () {
var guard = new RevisionGuard(store);
expect(guard.definition).to.be.an('object');
expect(guard.defineEvent).to.be.a('function');
expect(guard.onEventMissing).to.be.a('function');
});
describe('defining the event structure', function() {
var guard;
beforeEach(function () {
guard = new RevisionGuard(store);
});
describe('using the defaults', function () {
it('it should apply the defaults', function() {
var defaults = _.cloneDeep(guard.definition);
guard.defineEvent({
payload: 'data',
aggregate: 'aggName',
context: 'ctx.Name',
revision: 'rev',
version: 'v.',
meta: 'pass'
});
expect(defaults.correlationId).to.eql(guard.definition.correlationId);
expect(defaults.id).to.eql(guard.definition.id);
expect(guard.definition.payload).to.eql('data');
expect(defaults.payload).not.to.eql(guard.definition.payload);
expect(defaults.name).to.eql(guard.definition.name);
expect(defaults.aggregateId).to.eql(guard.definition.aggregateId);
expect(guard.definition.aggregate).to.eql('aggName');
expect(defaults.aggregate).not.to.eql(guard.definition.aggregate);
expect(guard.definition.context).to.eql('ctx.Name');
expect(defaults.context).not.to.eql(guard.definition.context);
expect(guard.definition.revision).to.eql('rev');
expect(defaults.revision).not.to.eql(guard.definition.revision);
expect(guard.definition.version).to.eql('v.');
expect(defaults.version).not.to.eql(guard.definition.version);
expect(guard.definition.meta).to.eql('pass');
expect(defaults.meta).not.to.eql(guard.definition.meta);
});
});
describe('overwriting the defaults', function () {
it('it should apply them correctly', function() {
var defaults = _.cloneDeep(guard.definition);
guard.defineEvent({
correlationId: 'cmdId',
id: 'eventId',
payload: 'data',
name: 'defName',
aggregateId: 'path.to.aggId',
aggregate: 'aggName',
context: 'ctx.Name',
revision: 'rev',
version: 'v.',
meta: 'pass'
});
expect(guard.definition.correlationId).to.eql('cmdId');
expect(defaults.correlationId).not.to.eql(guard.definition.correlationId);
expect(guard.definition.id).to.eql('eventId');
expect(defaults.id).not.to.eql(guard.definition.id);
expect(guard.definition.payload).to.eql('data');
expect(defaults.payload).not.to.eql(guard.definition.payload);
expect(guard.definition.name).to.eql('defName');
expect(defaults.name).not.to.eql(guard.definition.name);
expect(guard.definition.aggregateId).to.eql('path.to.aggId');
expect(defaults.aggregateId).not.to.eql(guard.definition.aggregateId);
expect(guard.definition.aggregate).to.eql('aggName');
expect(defaults.aggregate).not.to.eql(guard.definition.aggregate);
expect(guard.definition.context).to.eql('ctx.Name');
expect(defaults.context).not.to.eql(guard.definition.context);
expect(guard.definition.revision).to.eql('rev');
expect(defaults.revision).not.to.eql(guard.definition.revision);
expect(guard.definition.version).to.eql('v.');
expect(defaults.version).not.to.eql(guard.definition.version);
expect(guard.definition.meta).to.eql('pass');
expect(defaults.meta).not.to.eql(guard.definition.meta);
});
});
});
describe('guarding an event', function () {
var guard;
var evt1 = {
id: 'evtId1',
aggregate: {
id: 'aggId1',
name: 'agg'
},
context: {
name: 'ctx'
},
revision: 1
};
var evt2 = {
id: 'evtId2',
aggregate: {
id: 'aggId1',
name: 'agg'
},
context: {
name: 'ctx'
},
revision: 2
};
var evt3 = {
id: 'evtId3',
aggregate: {
id: 'aggId1',
name: 'agg'
},
context: {
name: 'ctx'
},
revision: 3
};
before(function () {
guard = new RevisionGuard(store, { queueTimeout: 200 });
guard.defineEvent({
correlationId: 'correlationId',
id: 'id',
payload: 'payload',
name: 'name',
aggregateId: 'aggregate.id',
aggregate: 'aggregate.name',
context: 'context.name',
revision: 'revision',
version: 'version',
meta: 'meta'
});
});
beforeEach(function (done) {
guard.currentHandlingRevisions = {};
store.clear(done);
});
describe('in correct order', function () {
it('it should work as expected', function (done) {
var guarded = 0;
function check () {
guarded++;
if (guarded === 3) {
done();
}
}
guard.guard(evt1, function (err, finish) {
expect(err).not.to.be.ok();
finish(function (err) {
expect(err).not.to.be.ok();
expect(guarded).to.eql(0);
check();
});
});
setTimeout(function () {
guard.guard(evt2, function (err, finish) {
expect(err).not.to.be.ok();
finish(function (err) {
expect(err).not.to.be.ok();
expect(guarded).to.eql(1);
check();
});
});
}, 10);
setTimeout(function () {
guard.guard(evt3, function (err, finish) {
expect(err).not.to.be.ok();
finish(function (err) {
expect(err).not.to.be.ok();
expect(guarded).to.eql(2);
check();
});
});
}, 20);
});
});
describe('in wrong order', function () {
it('it should work as expected', function (done) {
var guarded = 0;
function check () {
guarded++;
// if (guarded === 3) {
// done();
// }
}
guard.guard(evt1, function (err, finish) {
expect(err).not.to.be.ok();
finish(function (err) {
expect(err).not.to.be.ok();
expect(guarded).to.eql(0);
check();
});
});
setTimeout(function () {
guard.guard(evt2, function (err, finish) {
expect(err).not.to.be.ok();
finish(function (err) {
expect(err).not.to.be.ok();
expect(guarded).to.eql(1);
check();
});
});
}, 30);
setTimeout(function () {
guard.guard(evt3, function (err, finish) {
expect(err).not.to.be.ok();
finish(function (err) {
expect(err).not.to.be.ok();
expect(guarded).to.eql(2);
check();
});
});
guard.guard(evt3, function (err, finish) {
expect(err).to.be.ok();
expect(err.name).to.eql('AlreadyHandlingError');
});
}, 10);
setTimeout(function () {
guard.guard(evt2, function (err) {
expect(err).to.be.ok();
expect(err.name).to.eql('AlreadyHandledError');
expect(guarded).to.eql(3);
guard.guard(evt3, function (err) {
expect(err).to.be.ok();
expect(err.name).to.eql('AlreadyHandledError');
expect(guarded).to.eql(3);
store.getLastEvent(function (err, evt) {
expect(err).not.to.be.ok();
expect(evt.id).to.eql(evt3.id);
done();
});
});
});
}, 300);
});
});
describe('and missing something', function () {
it('it should work as expected', function (done) {
var guarded = 0;
function check () {
guarded++;
// if (guarded === 3) {
// done();
// }
}
guard.onEventMissing(function (info, evt) {
expect(guarded).to.eql(1);
expect(evt).to.eql(evt3);
expect(info.aggregateId).to.eql('aggId1');
expect(info.aggregateRevision).to.eql(3);
expect(info.guardRevision).to.eql(2);
expect(info.aggregate).to.eql('agg');
expect(info.context).to.eql('ctx');
done();
});
guard.guard(evt1, function (err, finish) {
expect(err).not.to.be.ok();
finish(function (err) {
expect(err).not.to.be.ok();
expect(guarded).to.eql(0);
check();
});
});
setTimeout(function () {
guard.guard(evt3, function (err, finish) {
expect(err).not.to.be.ok();
finish(function (err) {
expect(err).not.to.be.ok();
expect(guarded).to.eql(2);
check();
});
});
}, 20);
});
});
});
});
});
| togusafish/adrai-_-node-cqrs-saga | test/unit/revisionGuardTest.js | JavaScript | mit | 10,450 |
/**
* Copyright 2016 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright 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
*
* @flow
*/
'use strict';
const React = require('react-native');
const {
View,
ScrollView,
} = React;
const StyleSheet = require('F8StyleSheet');
const Header = require('./Header');
const RatingQuestion = require('./RatingQuestion');
const F8Button = require('F8Button');
import type {Question} from '../reducers/surveys';
import type {Session} from '../reducers/sessions';
type Props = {
session: Session;
questions: Array<Question>;
onSubmit: (answers: Array<number>) => void;
style?: any;
};
class RatingCard extends React.Component {
props: Props;
state: Object;
constructor(props: Props) {
super(props);
this.state = {};
}
render() {
const questions = this.props.questions.map((question, ii) => (
<RatingQuestion
key={ii}
style={styles.question}
question={question}
rating={this.state[ii]}
onChange={(rating) => this.setState({[ii]: rating})}
/>
));
const completed = Object.keys(this.state).length === this.props.questions.length;
return (
<View style={[styles.container, this.props.style]}>
<ScrollView>
<Header session={this.props.session} />
{questions}
</ScrollView>
<F8Button
style={styles.button}
type={completed ? 'primary' : 'bordered'}
caption="Submit Review"
onPress={() => completed && this.submit()}
/>
</View>
);
}
submit() {
const answers = this.props.questions.map((_, ii) => this.state[ii]);
this.props.onSubmit(answers);
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
},
question: {
padding: 40,
paddingVertical: 25,
},
button: {
marginHorizontal: 15,
marginVertical: 20,
}
});
module.exports = RatingCard;
| josedab/react-native-examples | meetup-information/js/rating/RatingCard.js | JavaScript | mit | 2,905 |
#ifndef __ciri_graphics_CullMode__
#define __ciri_graphics_CullMode__
namespace ciri {
/**
* Triangle winding order cull mode.
*/
enum class CullMode {
None, /**< Do not cull triangles regardless of vertex ordering. */
Clockwise, /**< Cull triangles with clockwise vertex ordering. */
CounterClockwise /**< Cull triangles with counter-clockwise vertex ordering. */
};
}
#endif | KasumiL5x/ciri | ciri/inc/ciri/graphics/CullMode.hpp | C++ | mit | 402 |
#region Copyright (c) 2007 Ryan Williams <drcforbin@gmail.com>
/// <copyright>
/// Copyright (c) 2007 Ryan Williams <drcforbin@gmail.com>
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
/// </copyright>
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Text.RegularExpressions;
using System.IO;
using Mono.Cecil;
using Mono.Security.Cryptography;
using System.Security.Cryptography;
namespace Obfuscar
{
class Project : IEnumerable<AssemblyInfo>
{
private const string SPECIALVAR_PROJECTFILEDIRECTORY = "ProjectFileDirectory";
private readonly List<AssemblyInfo> assemblyList = new List<AssemblyInfo> ();
public List<AssemblyInfo> CopyAssemblyList {
get {
return copyAssemblyList;
}
}
private readonly List<AssemblyInfo> copyAssemblyList = new List<AssemblyInfo> ();
private readonly Dictionary<string, AssemblyInfo> assemblyMap = new Dictionary<string, AssemblyInfo> ();
private readonly Variables vars = new Variables ();
InheritMap inheritMap;
Settings settings;
// FIXME: Figure out why this exists if it is never used.
private RSA keyvalue;
// don't create. call FromXml.
private Project ()
{
}
public string [] ExtraPaths {
get {
return vars.GetValue ("ExtraFrameworkFolders", "").Split (new char [] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries);
}
}
public string KeyContainerName = null;
public RSA KeyValue {
get {
if (keyvalue != null)
return keyvalue;
var lKeyFileName = vars.GetValue ("KeyFile", null);
var lKeyContainerName = vars.GetValue ("KeyContainer", null);
if (lKeyFileName == null && lKeyContainerName == null)
return null;
if (lKeyFileName != null && lKeyContainerName != null)
throw new Exception ("'Key file' and 'Key container' properties cann't be setted together.");
if (vars.GetValue ("KeyContainer", null) != null) {
KeyContainerName = vars.GetValue ("KeyContainer", null);
return RSA.Create ();
//if (Type.GetType("System.MonoType") != null)
// throw new Exception("Key containers are not supported for Mono.");
//try
//{
// CspParameters cp = new CspParameters();
// cp.KeyContainerName = vars.GetValue("KeyContainer", null);
// cp.Flags = CspProviderFlags.UseMachineKeyStore | CspProviderFlags.UseExistingKey;
// cp.KeyNumber = 1;
// RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);
// keyvalue = CryptoConvert.FromCapiKeyBlob(rsa.ExportCspBlob(false));
//}
//catch (Exception CryptEx)
////catch (System.Security.Cryptography.CryptographicException CryptEx)
//{
// try
// {
// CspParameters cp = new CspParameters();
// cp.KeyContainerName = vars.GetValue("KeyContainer", null);
// cp.Flags = CspProviderFlags.UseExistingKey;
// cp.KeyNumber = 1;
// RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);
// keyvalue = CryptoConvert.FromCapiKeyBlob(rsa.ExportCspBlob(false));
// }
// catch
// {
// throw new ApplicationException(String.Format("Failure loading key from container - \"{0}\"", vars.GetValue("KeyContainer", null)), CryptEx);
// }
//}
} else {
try {
keyvalue = CryptoConvert.FromCapiKeyBlob (File.ReadAllBytes (vars.GetValue ("KeyFile", null)));
} catch (Exception ex) {
throw new ApplicationException (String.Format ("Failure loading key file \"{0}\"", vars.GetValue ("KeyFile", null)), ex);
}
}
return keyvalue;
}
}
AssemblyCache m_cache;
internal AssemblyCache Cache
{
get
{
if (m_cache == null)
{
m_cache = new AssemblyCache(this);
}
return m_cache;
}
}
public static Project FromXml (XmlReader reader, string projectFileDirectory)
{
Project project = new Project ();
project.vars.Add (SPECIALVAR_PROJECTFILEDIRECTORY, string.IsNullOrEmpty (projectFileDirectory) ? "." : projectFileDirectory);
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element) {
switch (reader.Name) {
case "Var":
{
string name = Helper.GetAttribute (reader, "name");
if (name.Length > 0) {
string value = Helper.GetAttribute (reader, "value");
if (value.Length > 0)
project.vars.Add (name, value);
else
project.vars.Remove (name);
}
break;
}
case "Module":
AssemblyInfo info = AssemblyInfo.FromXml (project, reader, project.vars);
if (info.Exclude) {
project.copyAssemblyList.Add (info);
break;
}
Console.WriteLine ("Processing assembly: " + info.Definition.Name.FullName);
project.assemblyList.Add (info);
project.assemblyMap [info.Name] = info;
break;
}
}
}
return project;
}
/// <summary>
/// Looks through the settings, trys to make sure everything looks ok.
/// </summary>
public void CheckSettings ()
{
if (!Directory.Exists (Settings.InPath))
throw new ApplicationException ("Path specified by InPath variable must exist:" + Settings.InPath);
if (!Directory.Exists (Settings.OutPath)) {
try {
Directory.CreateDirectory (Settings.OutPath);
} catch (IOException e) {
throw new ApplicationException ("Could not create path specified by OutPath: " + Settings.OutPath, e);
}
}
}
internal InheritMap InheritMap {
get { return inheritMap; }
}
internal Settings Settings {
get {
if (settings == null)
settings = new Settings (vars);
return settings;
}
}
public void LoadAssemblies ()
{
// build reference tree
foreach (AssemblyInfo info in assemblyList) {
// add self reference...makes things easier later, when
// we need to go through the member references
info.ReferencedBy.Add (info);
// try to get each assembly referenced by this one. if it's in
// the map (and therefore in the project), set up the mappings
foreach (AssemblyNameReference nameRef in info.Definition.MainModule.AssemblyReferences) {
AssemblyInfo reference;
if (assemblyMap.TryGetValue (nameRef.Name, out reference)) {
info.References.Add (reference);
reference.ReferencedBy.Add (info);
}
}
}
// make each assembly's list of member refs
foreach (AssemblyInfo info in assemblyList) {
info.Init ();
}
// build inheritance map
inheritMap = new InheritMap (this);
}
/// <summary>
/// Returns whether the project contains a given type.
/// </summary>
public bool Contains (TypeReference type)
{
string name = Helper.GetScopeName (type);
return assemblyMap.ContainsKey (name);
}
/// <summary>
/// Returns whether the project contains a given type.
/// </summary>
internal bool Contains (TypeKey type)
{
return assemblyMap.ContainsKey (type.Scope);
}
public TypeDefinition GetTypeDefinition (TypeReference type)
{
if (type == null)
return null;
TypeDefinition typeDef = type as TypeDefinition;
if (typeDef == null) {
string name = Helper.GetScopeName (type);
AssemblyInfo info;
if (assemblyMap.TryGetValue (name, out info)) {
string fullName = type.Namespace + "." + type.Name;
typeDef = info.Definition.MainModule.GetType (fullName);
}
}
return typeDef;
}
IEnumerator IEnumerable.GetEnumerator ()
{
return assemblyList.GetEnumerator ();
}
public IEnumerator<AssemblyInfo> GetEnumerator ()
{
return assemblyList.GetEnumerator ();
}
}
}
| remobjects/Obfuscar | Obfuscar/Project.cs | C# | mit | 8,875 |
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
vector <string> computeKMostFrequentQueries(vector <string> queries) {
}
| tzhenghao/InterviewQuestionExercises | ElementsOfProgrammingInterviews/Chapter13/ComputeKMostFrequentQueries.cpp | C++ | mit | 162 |
namespace Reusable.Diagnostics
{
public static class DebuggerDisplayString
{
public const string DefaultNoQuotes = "{DebuggerDisplay,nq}";
}
} | he-dev/Reusable | Reusable.Core/src/Diagnostics/DebuggerDisplayString.cs | C# | mit | 162 |
/*
* RPCType.cpp
*
* Created on: 30 Apr 2014
* Author: meltuhamy
*/
#include <string>
#include "ppapi/cpp/var.h"
#include "RPCType.h"
#include <vector>
namespace pprpc{
//TODO - right now all the integer type marshaling is just wrapping the int32_t type!
// byte
pp::Var ByteType::AsVar(const ValidType<int8_t>& v){
return pp::Var((int) v.getValue());
}
ValidType<int8_t> ByteType::Extract(const pp::Var& v){
if(v.is_int()){
return ValidType<int8_t>((int8_t)v.AsInt());
} else {
return ValidType<int8_t>();
}
}
// octet
pp::Var OctetType::AsVar(const ValidType<uint8_t>& v){
return pp::Var((int) v.getValue());
}
ValidType<uint8_t> OctetType::Extract(const pp::Var& v){
if(v.is_int()){
return ValidType<uint8_t>((uint8_t)v.AsInt());
} else {
return ValidType<uint8_t>();
}
}
// short
pp::Var ShortType::AsVar(const ValidType<int16_t>& v){
return pp::Var((int) v.getValue());
}
ValidType<int16_t> ShortType::Extract(const pp::Var& v){
if(v.is_int()){
return ValidType<int16_t>((int16_t)v.AsInt());
} else {
return ValidType<int16_t>();
}
}
// ushort
pp::Var UnsignedShortType::AsVar(const ValidType<uint16_t>& v){
return pp::Var((int) v.getValue());
}
ValidType<uint16_t> UnsignedShortType::Extract(const pp::Var& v){
if(v.is_int()){
return ValidType<uint16_t>((uint16_t)v.AsInt());
} else {
return ValidType<uint16_t>();
}
}
// long
pp::Var LongType::AsVar(const ValidType<int32_t>& v){
return pp::Var((int) v.getValue());
}
ValidType<int32_t> LongType::Extract(const pp::Var& v){
if(v.is_int()){
return ValidType<int32_t>((int32_t)v.AsInt());
} else {
return ValidType<int32_t>();
}
}
// ulong
pp::Var UnsignedLongType::AsVar(const ValidType<uint32_t>& v){
return pp::Var((int) v.getValue());
}
ValidType<uint32_t> UnsignedLongType::Extract(const pp::Var& v){
if(v.is_int()){
return ValidType<uint32_t>((uint32_t)v.AsInt());
} else {
return ValidType<uint32_t>();
}
}
// longlong
pp::Var LongLongType::AsVar(const ValidType<int64_t>& v){
return pp::Var((int) v.getValue());
}
ValidType<int64_t> LongLongType::Extract(const pp::Var& v){
if(v.is_int()){
return ValidType<int64_t>((int64_t)v.AsInt());
} else {
return ValidType<int64_t>();
}
}
// ulonglong
pp::Var UnsignedLongLongType::AsVar(const ValidType<uint64_t>& v){
return pp::Var((int) v.getValue());
}
ValidType<uint64_t> UnsignedLongLongType::Extract(const pp::Var& v){
if(v.is_int()){
return ValidType<uint64_t>((uint64_t)v.AsInt());
} else {
return ValidType<uint64_t>();
}
}
// float
pp::Var FloatType::AsVar(const ValidType<float>& v){
return pp::Var(v.getValue());
}
ValidType<float> FloatType::Extract(const pp::Var& v){
if(v.is_number()){
return ValidType<float>((float)v.AsDouble());
} else {
return ValidType<float>();
}
}
// double
pp::Var DoubleType::AsVar(const ValidType<double>& v){
return pp::Var(v.getValue());
}
ValidType<double> DoubleType::Extract(const pp::Var& v){
if(v.is_number()){
return ValidType<double>(v.AsDouble());
} else {
return ValidType<double>();
}
}
// domstring
pp::Var DOMStringType::AsVar(const ValidType<std::string>& v){
return pp::Var(v.getValue());
}
ValidType<std::string> DOMStringType::Extract(const pp::Var& v){
if(v.is_string()){
return ValidType<std::string>(v.AsString());
} else {
return ValidType<std::string>();
}
}
// boolean
pp::Var BooleanType::AsVar(const ValidType<bool>& v){
return pp::Var(v.getValue());
}
ValidType<bool> BooleanType::Extract(const pp::Var& v){
if(v.is_bool()){
return ValidType<bool>(v.AsBool());
} else {
return ValidType<bool>();
}
}
// null
pp::Var NullType::AsVar(const ValidType<pp::Var::Null>& v){
return pp::Var(pp::Var::Null());
}
ValidType<pp::Var::Null> NullType::Extract(const pp::Var& v){
if(v.is_null()){
return ValidType<pp::Var::Null>(pp::Var::Null());
} else {
return ValidType<pp::Var::Null>();
}
}
// object
pp::Var ObjectType::AsVar(const ValidType<pp::VarDictionary>& v){
return v.getValue();
}
ValidType<pp::VarDictionary> ObjectType::Extract(const pp::Var& v){
if(v.is_dictionary()){
return ValidType<pp::VarDictionary>(pp::VarDictionary(v));
} else {
return ValidType<pp::VarDictionary>();
}
}
// error
pp::Var RPCErrorType::AsVar(const ValidType<RPCError>& v){
RPCError value = v.getValue();
pp::VarDictionary r;
r.Set("code", LongType(value.code).AsVar());
r.Set("message", DOMStringType(value.message).AsVar());
r.Set("type", DOMStringType(value.type).AsVar());
return r;
}
ValidType<RPCError> RPCErrorType::Extract(const pp::Var& v){
ValidType<RPCError> invalid;
if(v.is_dictionary()){
pp::VarDictionary vDict(v);
RPCError r;
/* member: code */
if(!vDict.HasKey("code")) return invalid;
const ValidType< int32_t >& codePart = LongType::Extract(vDict.Get("code"));
if(!codePart.isValid()) return invalid;
r.code = codePart.getValue();
/* member: message */
if(!vDict.HasKey("message")) return invalid;
const ValidType< std::string >& messagePart = DOMStringType::Extract(vDict.Get("message"));
if(!messagePart.isValid()) return invalid;
r.message = messagePart.getValue();
/* optional member: type */
if(vDict.HasKey("type")){
const ValidType< std::string >& typePart = DOMStringType::Extract(vDict.Get("type"));
r.type = typePart.isValid() ? typePart.getValue() : "";
} else {
r.type = "";
}
return ValidType<RPCError>(r);
}
return ValidType<RPCError>();
}
//pp::Var MyErrorType::AsVar(const ValidType<MyError>& v){
// MyError value = v.getValue();
// pp::VarDictionary r = pp::VarDictionary(RPCErrorType::AsVar(ValidType<RPCError>(value)));
// r.Set("myNumber", FloatType::AsVar(value.myNumber));
//
// return r;
//}
//
//ValidType<MyError> MyErrorType::Extract(const pp::Var& v){
// MyError r;
// r.init(RPCErrorType::Extract(v).getValue());
// if(v.is_dictionary()){
// pp::VarDictionary vDict(v);
// r.myNumber = FloatType::Extract(vDict.Get("myNumber")).getValue();
// }
// return ValidType<MyError>(r);
//}
}
| meltuhamy/native-calls | cpp/RPCType.cpp | C++ | mit | 5,999 |
package org.knowm.xchange.gemini.v1.service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.stream.Collectors;
import lombok.Getter;
import lombok.Setter;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.Order;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.dto.trade.MarketOrder;
import org.knowm.xchange.dto.trade.OpenOrders;
import org.knowm.xchange.dto.trade.UserTrades;
import org.knowm.xchange.exceptions.ExchangeException;
import org.knowm.xchange.exceptions.NotAvailableFromExchangeException;
import org.knowm.xchange.gemini.v1.GeminiAdapters;
import org.knowm.xchange.gemini.v1.GeminiOrderType;
import org.knowm.xchange.gemini.v1.dto.trade.GeminiCancelAllOrdersParams;
import org.knowm.xchange.gemini.v1.dto.trade.GeminiLimitOrder;
import org.knowm.xchange.gemini.v1.dto.trade.GeminiOrderStatusResponse;
import org.knowm.xchange.gemini.v1.dto.trade.GeminiTradeResponse;
import org.knowm.xchange.service.trade.TradeService;
import org.knowm.xchange.service.trade.params.CancelAllOrders;
import org.knowm.xchange.service.trade.params.CancelOrderByIdParams;
import org.knowm.xchange.service.trade.params.CancelOrderParams;
import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencyPair;
import org.knowm.xchange.service.trade.params.TradeHistoryParamLimit;
import org.knowm.xchange.service.trade.params.TradeHistoryParamPaging;
import org.knowm.xchange.service.trade.params.TradeHistoryParams;
import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan;
import org.knowm.xchange.service.trade.params.orders.DefaultOpenOrdersParamCurrencyPair;
import org.knowm.xchange.service.trade.params.orders.OpenOrdersParamCurrencyPair;
import org.knowm.xchange.service.trade.params.orders.OpenOrdersParams;
import org.knowm.xchange.service.trade.params.orders.OrderQueryParams;
import org.knowm.xchange.utils.DateUtils;
public class GeminiTradeService extends GeminiTradeServiceRaw implements TradeService {
private static final OpenOrders noOpenOrders = new OpenOrders(new ArrayList<LimitOrder>());
public GeminiTradeService(Exchange exchange) {
super(exchange);
}
@Override
public OpenOrders getOpenOrders() throws IOException {
return getOpenOrders(null);
}
@Override
public OpenOrders getOpenOrders(OpenOrdersParams params) throws IOException {
GeminiOrderStatusResponse[] activeOrders = getGeminiOpenOrders();
if (activeOrders.length <= 0) {
return noOpenOrders;
} else {
if (params != null && params instanceof OpenOrdersParamCurrencyPair) {
OpenOrdersParamCurrencyPair openOrdersParamCurrencyPair =
(OpenOrdersParamCurrencyPair) params;
return GeminiAdapters.adaptOrders(
activeOrders, openOrdersParamCurrencyPair.getCurrencyPair());
}
return GeminiAdapters.adaptOrders(activeOrders);
}
}
@Override
public String placeMarketOrder(MarketOrder marketOrder) throws IOException {
throw new NotAvailableFromExchangeException();
}
@Override
public String placeLimitOrder(LimitOrder limitOrder) throws IOException {
GeminiOrderStatusResponse newOrder = placeGeminiLimitOrder(limitOrder, GeminiOrderType.LIMIT);
// The return value contains details of any trades that have been immediately executed as a
// result
// of this order. Make these available to the application if it has provided a GeminiLimitOrder.
if (limitOrder instanceof GeminiLimitOrder) {
GeminiLimitOrder raw = (GeminiLimitOrder) limitOrder;
raw.setResponse(newOrder);
}
return String.valueOf(newOrder.getId());
}
@Override
public boolean cancelOrder(String orderId) throws IOException {
return cancelGeminiOrder(orderId);
}
@Override
public boolean cancelOrder(CancelOrderParams orderParams) throws IOException {
if (orderParams instanceof CancelOrderByIdParams) {
return cancelOrder(((CancelOrderByIdParams) orderParams).getOrderId());
} else {
return false;
}
}
@Override
public Collection<String> cancelAllOrders(CancelAllOrders orderParams) throws IOException {
if (orderParams instanceof GeminiCancelAllOrdersParams) {
return Arrays.stream(
cancelAllGeminiOrders(
((GeminiCancelAllOrdersParams) orderParams).isSessionOnly(),
((GeminiCancelAllOrdersParams) orderParams).getAccount())
.getDetails()
.getCancelledOrders())
.mapToObj(id -> String.valueOf(id))
.collect(Collectors.toList());
} else {
return null;
}
}
/**
* @param params Implementation of {@link TradeHistoryParamCurrencyPair} is mandatory. Can
* optionally implement {@link TradeHistoryParamPaging} and {@link
* TradeHistoryParamsTimeSpan#getStartTime()}. All other TradeHistoryParams types will be
* ignored.
*/
@Override
public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException {
final String symbol;
if (params instanceof TradeHistoryParamCurrencyPair
&& ((TradeHistoryParamCurrencyPair) params).getCurrencyPair() != null) {
symbol =
GeminiAdapters.adaptCurrencyPair(
((TradeHistoryParamCurrencyPair) params).getCurrencyPair());
} else {
// Exchange will return the errors below if CurrencyPair is not provided.
// field not on request: "Key symbol was not present."
// field supplied but blank: "Key symbol may not be the empty string"
throw new ExchangeException("CurrencyPair must be supplied");
}
final long timestamp;
if (params instanceof TradeHistoryParamsTimeSpan) {
Date startTime = ((TradeHistoryParamsTimeSpan) params).getStartTime();
timestamp = DateUtils.toUnixTime(startTime);
} else {
timestamp = 0;
}
Integer limit;
if (params instanceof TradeHistoryParamPaging) {
TradeHistoryParamPaging pagingParams = (TradeHistoryParamPaging) params;
Integer pageLength = pagingParams.getPageLength();
Integer pageNum = pagingParams.getPageNumber();
limit = (pageLength != null && pageNum != null) ? pageLength * (pageNum + 1) : 50;
} else {
limit = 50;
}
if (params instanceof TradeHistoryParamLimit) {
limit = ((TradeHistoryParamLimit) params).getLimit();
}
final GeminiTradeResponse[] trades = getGeminiTradeHistory(symbol, timestamp, limit);
return GeminiAdapters.adaptTradeHistory(trades, symbol);
}
@Override
public TradeHistoryParams createTradeHistoryParams() {
return new GeminiTradeHistoryParams(CurrencyPair.BTC_USD, 500, new Date(0));
}
@Override
public OpenOrdersParams createOpenOrdersParams() {
return new DefaultOpenOrdersParamCurrencyPair();
}
@Override
public Collection<Order> getOrder(OrderQueryParams... params) throws IOException {
Collection<Order> orders = new ArrayList<>(params.length);
for (OrderQueryParams param : params) {
orders.add(GeminiAdapters.adaptOrder(super.getGeminiOrderStatus(param)));
}
return orders;
}
@Getter
@Setter
public static class GeminiOrderQueryParams implements OrderQueryParams {
private String orderId;
private String clientOrderId;
private boolean includeTrades;
private String account;
public GeminiOrderQueryParams(
String orderId, String clientOrderId, boolean includeTrades, String account) {
this.orderId = orderId;
this.clientOrderId = clientOrderId;
this.includeTrades = includeTrades;
this.account = account;
}
@Override
public String getOrderId() {
return orderId;
}
@Override
public void setOrderId(String orderId) {
this.orderId = orderId;
}
}
public static class GeminiTradeHistoryParams
implements TradeHistoryParamCurrencyPair, TradeHistoryParamLimit, TradeHistoryParamsTimeSpan {
private CurrencyPair currencyPair;
private Integer limit;
private Date startTime;
public GeminiTradeHistoryParams(CurrencyPair currencyPair, Integer limit, Date startTime) {
this.currencyPair = currencyPair;
this.limit = limit;
this.startTime = startTime;
}
public GeminiTradeHistoryParams() {}
@Override
public CurrencyPair getCurrencyPair() {
return currencyPair;
}
@Override
public void setCurrencyPair(CurrencyPair currencyPair) {
this.currencyPair = currencyPair;
}
@Override
public Integer getLimit() {
return limit;
}
@Override
public void setLimit(Integer limit) {
this.limit = limit;
}
@Override
public Date getStartTime() {
return startTime;
}
@Override
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
@Override
public Date getEndTime() {
return null;
}
@Override
public void setEndTime(Date endTime) {
// ignored
}
}
}
| stachon/XChange | xchange-gemini/src/main/java/org/knowm/xchange/gemini/v1/service/GeminiTradeService.java | Java | mit | 9,136 |
#include <map>
#include <set>
#include <vector>
#include <memory>
#include <gumbo.h>
#include <goosepp/contentExtraction/BoostChecker.h>
#include <goosepp/contentExtraction/NodeTextCleaner.h>
#include <goosepp/contentExtraction/TextNodeCollector.h>
#include <goosepp/util/gumboUtils.h>
#include <goosepp/stopwords/stopwords.h>
#include <goosepp/stopwords/StopwordCounter.h>
namespace scivey {
namespace goosepp {
namespace contentExtraction {
using stopwords::StopwordCounter;
BoostChecker::BoostChecker(shared_ptr<NodeTextCleanerIf> cleaner,
shared_ptr<StopwordCounterIf> counter,
size_t minStopwords,
size_t maxStepsAway)
: cleaner_(cleaner),
stopwordCounter_(counter),
minStopwords_(minStopwords),
maxStepsAway_(maxStepsAway) {}
bool BoostChecker::shouldBoost(const GumboNode *node) {
bool isOk = false;
size_t stepsAway = 0;
auto visitor = [&isOk, &stepsAway, this](const GumboNode* sibling, function<void()> escape) {
if (sibling->type == GUMBO_NODE_ELEMENT && sibling->v.element.tag == GUMBO_TAG_P) {
if (stepsAway >= this->maxStepsAway_) {
isOk = false;
escape();
return;
}
auto siblingText = this->cleaner_->getText(sibling);
if (this->stopwordCounter_->countStopwords(siblingText) > this->minStopwords_) {
isOk = true;
escape();
return;
}
stepsAway++;
}
};
util::walkSiblings(node, visitor);
return isOk;
}
BoostCheckerFactory::BoostCheckerFactory(shared_ptr<NodeTextCleanerIf> cleaner,
shared_ptr<StopwordCounterIf> counter,
size_t minStopwords,
size_t maxStepsAway)
: cleaner_(cleaner),
stopwordCounter_(counter),
minStopwords_(minStopwords),
maxStepsAway_(maxStepsAway) {}
BoostChecker BoostCheckerFactory::build() {
BoostChecker checker(cleaner_, stopwordCounter_, minStopwords_, maxStepsAway_);
return checker;
}
} // contentExraction
} // goosepp
} // scivey
| scivey/goosepp | src/contentExtraction/BoostChecker.cpp | C++ | mit | 2,214 |
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.4.4.17-7-c-iii-19
description: >
Array.prototype.some - return value of callbackfn is a Number
object
includes: [runTestCase.js]
---*/
function testcase() {
function callbackfn(val, idx, obj) {
return new Number();
}
return [11].some(callbackfn);
}
runTestCase(testcase);
| PiotrDabkowski/Js2Py | tests/test_cases/built-ins/Array/prototype/some/15.4.4.17-7-c-iii-19.js | JavaScript | mit | 707 |
$(document).ready(function(){
$('#environment,#language').change(function(){
var environment = $('#environment').val();
var language = $('#language').val();
if(environment==0)
return true;
$('#file').parent('div').addClass('hidden');
$('#load').addClass('hidden');
$.ajax({
type:'POST',
url:translate_environment,
data:{'_token':_token,'environment':environment,'language':language},
dataType:'json',
success:function(dataJson)
{
if(dataJson.status=='success')
{
$('#file').find('option').remove();
$.each(dataJson.files,function(e,item){
$('#file').append($('<option>', {value:item, text:item}));
});
$('#file').closest('div.form-group').removeClass('hidden');
$('#file').parent('div').removeClass('hidden');
$('#file').select2({width:'50%'});
$('#load').removeClass('hidden');
}
else
{
$.growl.error({'title':'',message:dataJson.msg});
}
}
})
});
}); | cobonto/public | admin/js/translate.js | JavaScript | mit | 1,275 |
using System;
namespace Nancy.Swagger.ObjectModel.Attributes
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum, AllowMultiple = false, Inherited = true)]
public class SwaggerDataAttribute : Attribute { }
} | pinnstrat/snap-nancy-swagger | src/Nancy.Swagger/ObjectModel/Attributes/SwaggerDataAttribute.cs | C# | mit | 261 |
/**
* @author Joe Adams
*/
goog.provide('CrunchJS.Systems.PathfindingSystem');
goog.require('CrunchJS.System');
goog.require('CrunchJS.Components.Path');
goog.require('goog.structs');
goog.require('goog.array');
goog.require('goog.math');
/**
* Creates a new Pathfinding System
* @constructor
* @class
*/
CrunchJS.Systems.PathfindingSystem = function() {
};
goog.inherits(CrunchJS.Systems.PathfindingSystem, CrunchJS.System);
CrunchJS.Systems.PathfindingSystem.prototype.name = 'CrunchJS.Systems.PathfindingSystem';
/**
* Called when the systme is activated. Sets the entity composition
*/
CrunchJS.Systems.PathfindingSystem.prototype.activate = function() {
goog.base(this, 'activate');
this.setEntityComposition(this.getScene().createEntityComposition().all('PathQuery'));
};
CrunchJS.Systems.PathfindingSystem.prototype.processEntity = function(frame, ent) {
var query = this.getScene().getComponent(ent, 'PathQuery'),
transform = this.getScene().getComponent(ent, 'Transform'),
occGrid = this.getScene().getComponent(query.gridId, 'OccupancyGrid'),
steps;
this.getScene().removeComponent(ent, 'PathQuery');
steps = this.astar(occGrid, query.start, query.end, false);
this.getScene().addComponent(ent, new CrunchJS.Components.Path({
steps : steps,
step : 0
}));
};
CrunchJS.Systems.PathfindingSystem.prototype.astar = function(occGrid, start, end, diagEnabled) {
var openList = [],
closedList = new goog.structs.Set(),
startTile = occGrid.coordToTile(start.x, start.y),
endTile = occGrid.findNearestUnoccupiedTile({
x : end.x,
y : end.y
}),
currentNode, neighbors, steps, success = false;
openList.push(this.createSearchNode(startTile,0,endTile));
while(openList.length != 0){
// Expand this node
currentNode = openList.pop();
// we are done here
if(currentNode.x == endTile.x && currentNode.y == endTile.y){
success = true;
break;
}
closedList.add(currentNode);
neighbors = occGrid.getNeighbors({
x : currentNode.x,
y : currentNode.y,
diag : diagEnabled
});
goog.structs.forEach(neighbors, function(neighbor) {
var notOccupied = !occGrid.isOccupied({
x : neighbor.x,
y : neighbor.y
}),
notClosed = goog.structs.every(closedList, function(node) {
return neighbor.x != node.x || neighbor.y != node.y;
});
// If neighbor is not occupied and not already exanded
if(notOccupied && notClosed){
// Create the node
var neighborNode = this.createSearchNode(neighbor, currentNode.distFromStart+1, endTile);
neighborNode.parent = currentNode;
var node = goog.array.find(openList, function(node) {
return node.x == neighborNode.x && node.y == neighborNode.y;
});
// If neighbor is on openlist, but needs updated
if(node && node.distFromStart > neighborNode.distFromStart){
node.distFromStart = neighborNode.distFromStart;
node.parent = neighborNode.parent;
node.heuristic = neighborNode.heuristic;
}
// Put it on the openlist
else
openList.push(neighborNode);
}
}, this);
goog.array.stableSort(openList, function(o1, o2) {
return o2.heuristic-o1.heuristic;
});
}
steps = this.reconstructPath(currentNode, occGrid);
// Make sure it goes to exact coord instead of center of tile
// if(success){
// steps[steps.length-1].x = end.x;
// steps[steps.length-1].y = end.y;
// }
return steps;
};
CrunchJS.Systems.PathfindingSystem.prototype.createSearchNode = function(tile, distFromStart, goalTile) {
var node = {}, distToGoal;
node.x = tile.x;
node.y = tile.y;
distToGoal = goog.math.safeFloor(Math.sqrt(Math.pow(Math.abs(goalTile.x - node.x),2) + Math.pow(Math.abs(goalTile.y - node.y), 2)));
node.heuristic = distFromStart + distToGoal;
node.distFromStart = distFromStart;
return node;
};
CrunchJS.Systems.PathfindingSystem.prototype.reconstructPath = function(node, occGrid) {
var steps = [], step;
while(node){
step = {
x : node.x,
y : node.y
}
steps.push(step);
node = node.parent;
}
steps = this.lineOfSightPath(steps.reverse(), occGrid);
for(var i = 0; i < steps.length; i++){
steps[i] = occGrid.tileToCoord(steps[i].x, steps[i].y);
}
return steps;
};
CrunchJS.Systems.PathfindingSystem.prototype.lineOfSightPath = function(steps, occGrid) {
var newSteps = [],
currentLoc = steps[0];
for(var i = 1; i < steps.length; i++){
if(!this.canSee(currentLoc.x, currentLoc.y, steps[i].x, steps[i].y, occGrid)){
currentLoc = steps[i-1];
newSteps.push(currentLoc);
i--;
}
else if(i == steps.length-1){
newSteps.push(steps[i]);
}
}
return newSteps;
};
// Algorithm : http://playtechs.blogspot.com/2007/03/raytracing-on-grid.html
CrunchJS.Systems.PathfindingSystem.prototype.canSee = function(x0, y0, x1, y1, occGrid) {
var dx = Math.abs(x1-x0),
dy = Math.abs(y1-y0),
x = x0,
y = y0,
n = 1 + dx + dy,
x_inc = (x1>x0) ? 1 : -1,
y_inc = (y1>y0) ? 1 : -1,
error = dx-dy;
dx *= 2;
dy *= 2;
var startN = n;
while(n>0){
if(occGrid.isOccupied({
x : x,
y : y
})){
return false;
}
if(error>0){
x += x_inc;
error -= dy;
}
else if(error == 0){
if(occGrid.isOccupied({
x : x,
y : y+y_inc
}) || occGrid.isOccupied({
x : x+x_inc,
y : y
})){
return false;
}
x += x_inc;
error -= dy;
}
else{
y += y_inc;
error += dx;
}
n--;
}
return true;
};
| jadmz/CrunchJS | app/js/engine/systems/PathfindingSystem.js | JavaScript | mit | 5,422 |
using System;
using System.Windows.Forms;
namespace DocumentExplorerExample
{
/// <summary>
/// Provides full information about application exception.
/// </summary>
public class ExceptionDialog : Form
{
#region Windows Form Designer generated code
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Button buttonOk;
private System.Windows.Forms.TextBox text1;
private void InitializeComponent() {
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(ExceptionDialog));
this.text1 = new System.Windows.Forms.TextBox();
this.buttonOk = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// text1
//
this.text1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.text1.AutoSize = false;
this.text1.Location = new System.Drawing.Point(8, 8);
this.text1.Multiline = true;
this.text1.Name = "text1";
this.text1.ReadOnly = true;
this.text1.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.text1.Size = new System.Drawing.Size(524, 244);
this.text1.TabIndex = 0;
this.text1.Text = "";
this.text1.WordWrap = false;
//
// buttonOk
//
this.buttonOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK;
this.buttonOk.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonOk.Location = new System.Drawing.Point(432, 260);
this.buttonOk.Name = "buttonOk";
this.buttonOk.Size = new System.Drawing.Size(100, 24);
this.buttonOk.TabIndex = 12;
this.buttonOk.Text = "Continue";
//
// ExceptionDialog
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(540, 288);
this.Controls.Add(this.buttonOk);
this.Controls.Add(this.text1);
this.DockPadding.All = 8;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ExceptionDialog";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Unexpected error occured";
this.ResumeLayout(false);
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#endregion
public ExceptionDialog()
{
InitializeComponent();
}
public ExceptionDialog(Exception ex)
{
InitializeComponent();
Text = "Document Explorer - unexpected error occured";
text1.Text = "\r\n" + Application.ProductName + ".exe \r\n\r\n" +
"Version " + Application.ProductVersion + "\r\n\r\n" +
DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + "\r\n\r\n" +
ex.ToString() + "\r\n";
text1.SelectionStart = text1.Text.Length;
}
}
} | assadvirgo/Aspose_Words_NET | Examples/CSharp/Viewers-Visualizers/Document-Explorer/ExceptionDialog.cs | C# | mit | 3,308 |
#region License
//-----------------------------------------------------------------------
// <copyright>
// The MIT License (MIT)
//
// Copyright (c) 2014 Kirk S Woll
//
// 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.
// </copyright>
//-----------------------------------------------------------------------
#endregion
using System;
using System.Linq.Expressions;
using WootzJs.Testing;
namespace WootzJs.Compiler.Tests.Linq.Expressions
{
public class MethodCallExpressionTests : TestFixture
{
[Test]
public void CallZeroParameterStaticMethod()
{
Expression<Action> lambda = () => ClassWithMethods.ZeroParameterStaticMethod();
var methodCallExpression = (MethodCallExpression)lambda.Body;
AssertEquals(methodCallExpression.Method.Name, "ZeroParameterStaticMethod");
}
[Test]
public void CallOneParameterStaticMethod()
{
Expression<Action> lambda = () => ClassWithMethods.OneParameterStaticMethod("foo");
var methodCallExpression = (MethodCallExpression)lambda.Body;
AssertEquals(methodCallExpression.Method.Name, "OneParameterStaticMethod");
var argument = (ConstantExpression)methodCallExpression.Arguments[0];
AssertEquals(argument.Value, "foo");
}
[Test]
public void CallZeroParameterInstanceMethod()
{
var instance = new ClassWithMethods();
Expression<Action> lambda = () => instance.ZeroParameterInstanceMethod();
var methodCallExpression = (MethodCallExpression)lambda.Body;
AssertEquals(methodCallExpression.Method.Name, "ZeroParameterInstanceMethod");
var target = (ConstantExpression)methodCallExpression.Object;
AssertEquals(target.Value, instance);
}
/*
[Test]
public void ArrayIndexMultiDimensional()
{
var array = new[,] { { 1, 2 }, { 3, 4 } };
Expression<Func<int>> lambda = () => array[5, 6];
var callExpression = (MethodCallExpression)lambda.Body;
var target = (ConstantExpression)callExpression.Object;
QUnit.AreEqual(target.Value, array);
var index1 = (ConstantExpression)callExpression.Arguments[0];
var index2 = (ConstantExpression)callExpression.Arguments[1];
QUnit.AreEqual(index1.Value, 5);
QUnit.AreEqual(index2.Value, 6);
QUnit.AreEqual(callExpression.Method.Name, "Get");
}
*/
public class ClassWithMethods
{
public static void ZeroParameterStaticMethod()
{
}
public static void OneParameterStaticMethod(string parameter)
{
}
public void ZeroParameterInstanceMethod()
{
}
}
}
}
| x335/WootzJs | WootzJs.Compiler.Tests/Linq/Expressions/MethodCallExpressionTests.cs | C# | mit | 3,963 |
#define PROTOTYPE
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using ProBuilder2.Common;
using ProBuilder2.MeshOperations;
namespace ProBuilder2.Examples
{
[RequireComponent(typeof(AudioSource))]
public class IcoBumpin : MonoBehaviour
{
pb_Object ico; // A reference to the icosphere pb_Object component
Mesh icoMesh; // A reference to the icosphere mesh (cached because we access the vertex array every frame)
Transform icoTransform; // A reference to the icosphere transform component. Cached because I can't remember if GameObject.transform is still a performance drain :|
AudioSource audioSource;// Cached reference to the audiosource.
/**
* Holds a pb_Face, the normal of that face, and the index of every vertex that touches it (sharedIndices).
*/
struct FaceRef
{
public pb_Face face;
public Vector3 nrm; // face normal
public int[] indices; // all vertex indices (including shared connected vertices)
public FaceRef(pb_Face f, Vector3 n, int[] i)
{
face = f;
nrm = n;
indices = i;
}
}
// All faces that have been extruded
FaceRef[] outsides;
// Keep a copy of the original vertex array to calculate the distance from origin.
Vector3[] original_vertices, displaced_vertices;
// The radius of the mesh icosphere on instantiation.
[Range(1f, 10f)]
public float icoRadius = 2f;
// The number of subdivisions to give the icosphere.
[Range(0, 3)]
public int icoSubdivisions = 2;
// How far along the normal should each face be extruded when at idle (no audio input).
[Range(0f, 1f)]
public float startingExtrusion = .1f;
// The material to apply to the icosphere.
public Material material;
// The max distance a frequency range will extrude a face.
[Range(1f, 50f)]
public float extrusion = 30f;
// An FFT returns a spectrum including frequencies that are out of human hearing range -
// this restricts the number of bins used from the spectrum to the lower @fftBounds.
[Range(8, 128)]
public int fftBounds = 32;
// How high the icosphere transform will bounce (sample volume determines height).
[Range(0f, 10f)]
public float verticalBounce = 4f;
// Optionally weights the frequency amplitude when calculating extrude distance.
public AnimationCurve frequencyCurve;
// A reference to the line renderer that will be used to render the raw waveform.
public LineRenderer waveform;
// The y size of the waveform.
public float waveformHeight = 2f;
// How far from the icosphere should the waveform be.
public float waveformRadius = 20f;
// If @rotateWaveformRing is true, this is the speed it will travel.
public float waveformSpeed = .1f;
// If true, the waveform ring will randomly orbit the icosphere.
public bool rotateWaveformRing = false;
// If true, the waveform will bounce up and down with the icosphere.
public bool bounceWaveform = false;
public GameObject missingClipWarning;
// Icosphere's starting position.
Vector3 icoPosition = Vector3.zero;
float faces_length;
const float TWOPI = 6.283185f; // 2 * PI
const int WAVEFORM_SAMPLES = 1024; // How many samples make up the waveform ring.
const int FFT_SAMPLES = 4096; // How many samples are used in the FFT. More means higher resolution.
// Keep copy of the last frame's sample data to average with the current when calculating
// deformation amounts. Smoothes the visual effect.
float[] fft = new float[FFT_SAMPLES],
fft_history = new float[FFT_SAMPLES],
data = new float[WAVEFORM_SAMPLES],
data_history = new float[WAVEFORM_SAMPLES];
// Root mean square of raw data (volume, but not in dB).
float rms = 0f, rms_history = 0f;
/**
* Creates the icosphere, and loads all the cache information.
*/
void Start()
{
audioSource = GetComponent<AudioSource>();
if( audioSource.clip == null )
missingClipWarning.SetActive(true);
// Create a new icosphere.
ico = pb_ShapeGenerator.IcosahedronGenerator(icoRadius, icoSubdivisions);
// Shell is all the faces on the new icosphere.
pb_Face[] shell = ico.faces;
// Materials are set per-face on pb_Object meshes. pb_Objects will automatically
// condense the mesh to the smallest set of subMeshes possible based on materials.
#if !PROTOTYPE
foreach(pb_Face f in shell)
f.SetMaterial( material );
#else
ico.gameObject.GetComponent<MeshRenderer>().sharedMaterial = material;
#endif
pb_Face[] connectingFaces;
// Extrude all faces on the icosphere by a small amount. The third boolean parameter
// specifies that extrusion should treat each face as an individual, not try to group
// all faces together.
ico.Extrude(shell, startingExtrusion, false, out connectingFaces);
// ToMesh builds the mesh positions, submesh, and triangle arrays. Call after adding
// or deleting vertices, or changing face properties.
ico.ToMesh();
// Refresh builds the normals, tangents, and UVs.
ico.Refresh();
outsides = new FaceRef[shell.Length];
Dictionary<int, int> lookup = ico.sharedIndices.ToDictionary();
// Populate the outsides[] cache. This is a reference to the tops of each extruded column, including
// copies of the sharedIndices.
for(int i = 0; i < shell.Length; ++i)
outsides[i] = new FaceRef( shell[i],
pb_Math.Normal(ico, shell[i]),
ico.sharedIndices.AllIndicesWithValues(lookup, shell[i].distinctIndices).ToArray()
);
// Store copy of positions array un-modified
original_vertices = new Vector3[ico.vertices.Length];
System.Array.Copy(ico.vertices, original_vertices, ico.vertices.Length);
// displaced_vertices should mirror icosphere mesh vertices.
displaced_vertices = ico.vertices;
icoMesh = ico.msh;
icoTransform = ico.transform;
faces_length = (float)outsides.Length;
// Build the waveform ring.
icoPosition = icoTransform.position;
waveform.SetVertexCount(WAVEFORM_SAMPLES);
if( bounceWaveform )
waveform.transform.parent = icoTransform;
audioSource.Play();
}
void Update()
{
// fetch the fft spectrum
audioSource.GetSpectrumData(fft, 0, FFTWindow.BlackmanHarris);
// get raw data for waveform
audioSource.GetOutputData(data, 0);
// calculate root mean square (volume)
rms = RMS(data);
/**
* For each face, translate the vertices some distance depending on the frequency range assigned.
* Not using the TranslateVertices() pb_Object extension method because as a convenience, that method
* gathers the sharedIndices per-face on every call, which while not tremondously expensive in most
* contexts, is far too slow for use when dealing with audio, and especially so when the mesh is
* somewhat large.
*/
for(int i = 0; i < outsides.Length; i++)
{
float normalizedIndex = (i/faces_length);
int n = (int)(normalizedIndex*fftBounds);
Vector3 displacement = outsides[i].nrm * ( ((fft[n]+fft_history[n]) * .5f) * (frequencyCurve.Evaluate(normalizedIndex) * .5f + .5f)) * extrusion;
foreach(int t in outsides[i].indices)
{
displaced_vertices[t] = original_vertices[t] + displacement;
}
}
Vector3 vec = Vector3.zero;
// Waveform ring
for(int i = 0; i < WAVEFORM_SAMPLES; i++)
{
int n = i < WAVEFORM_SAMPLES-1 ? i : 0;
vec.x = Mathf.Cos((float)n/WAVEFORM_SAMPLES * TWOPI) * (waveformRadius + (((data[n] + data_history[n]) * .5f) * waveformHeight));
vec.z = Mathf.Sin((float)n/WAVEFORM_SAMPLES * TWOPI) * (waveformRadius + (((data[n] + data_history[n]) * .5f) * waveformHeight));
vec.y = 0f;
waveform.SetPosition(i, vec);
}
// Ring rotation
if( rotateWaveformRing )
{
Vector3 rot = waveform.transform.localRotation.eulerAngles;
rot.x = Mathf.PerlinNoise(Time.time * waveformSpeed, 0f) * 360f;
rot.y = Mathf.PerlinNoise(0f, Time.time * waveformSpeed) * 360f;
waveform.transform.localRotation = Quaternion.Euler(rot);
}
icoPosition.y = -verticalBounce + ((rms + rms_history) * verticalBounce);
icoTransform.position = icoPosition;
// Keep copy of last FFT samples so we can average with the current. Smoothes the movement.
System.Array.Copy(fft, fft_history, FFT_SAMPLES);
System.Array.Copy(data, data_history, WAVEFORM_SAMPLES);
rms_history = rms;
icoMesh.vertices = displaced_vertices;
}
/**
* Root mean square is a good approximation of perceived loudness.
*/
float RMS(float[] arr)
{
float v = 0f,
len = (float)arr.Length;
for(int i = 0; i < len; i++)
v += Mathf.Abs(arr[i]);
return Mathf.Sqrt(v / (float)len);
}
}
}
| hakur/shooter | Assets/ProCore/ProBuilder/API Examples/Icosphere FFT/Scripts/IcoBumpin.cs | C# | mit | 8,702 |
require 'rails_helper'
RSpec.describe OnlineApplicationPolicy, type: :policy do
subject(:policy) { described_class.new(user, online_application) }
let(:online_application) { build_stubbed(:online_application) }
context 'for staff' do
let(:user) { build_stubbed(:staff) }
it { is_expected.to permit_action(:edit) }
it { is_expected.to permit_action(:update) }
it { is_expected.to permit_action(:show) }
it { is_expected.to permit_action(:complete) }
it { is_expected.to permit_action(:approve) }
it { is_expected.to permit_action(:approve_save) }
end
context 'for manager' do
let(:user) { build_stubbed(:manager) }
it { is_expected.to permit_action(:edit) }
it { is_expected.to permit_action(:update) }
it { is_expected.to permit_action(:show) }
it { is_expected.to permit_action(:complete) }
it { is_expected.to permit_action(:approve) }
it { is_expected.to permit_action(:approve_save) }
end
context 'for admin' do
let(:user) { build_stubbed(:admin) }
it { is_expected.not_to permit_action(:edit) }
it { is_expected.not_to permit_action(:update) }
it { is_expected.not_to permit_action(:show) }
it { is_expected.not_to permit_action(:complete) }
end
end
| ministryofjustice/fr-staffapp | spec/policies/online_application_policy_spec.rb | Ruby | mit | 1,255 |
require "active_record"
require "active_record/mass_assignment_security/associations"
require "active_record/mass_assignment_security/attribute_assignment"
require "active_record/mass_assignment_security/core"
require "active_record/mass_assignment_security/nested_attributes"
require "active_record/mass_assignment_security/persistence"
require "active_record/mass_assignment_security/reflection"
require "active_record/mass_assignment_security/relation"
require "active_record/mass_assignment_security/validations"
require "active_record/mass_assignment_security/associations"
require "active_record/mass_assignment_security/inheritance"
class ActiveRecord::Base
include ActiveRecord::MassAssignmentSecurity::Core
include ActiveRecord::MassAssignmentSecurity::AttributeAssignment
include ActiveRecord::MassAssignmentSecurity::Persistence
include ActiveRecord::MassAssignmentSecurity::Validations
include ActiveRecord::MassAssignmentSecurity::NestedAttributes
include ActiveRecord::MassAssignmentSecurity::Inheritance
end
class ActiveRecord::SchemaMigration < ActiveRecord::Base
attr_accessible :version
end
| rails/protected_attributes | lib/active_record/mass_assignment_security.rb | Ruby | mit | 1,126 |
/**
* Created by james on 3/11/15.
*/
var crypto = Npm.require('crypto');
IntercomHash = function(user, secret) {
var secret = new Buffer(secret, 'utf8')
return crypto.createHmac('sha256', secret)
.update(user._id).digest('hex');
}
| jamesoy/Microscope | packages/intercom/intercom_server.js | JavaScript | mit | 251 |
using System;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
namespace TeknikProgramlama.Tools.Image {
public static class Utils {
public static string Image2Base64(this System.Drawing.Image image, ImageFormat format) {
var imgBytes = image.ToBytes(format);
var b64str = Convert.ToBase64String(imgBytes);
return $@"data:image/{format.ToString().ToLower()};base64,{b64str}";
}
public static string Image2Base64Html( this System.Drawing.Image image, ImageFormat format)
=> $@"<img src='{Image2Base64(image, format)}'/>";
public static byte[] ToBytes(
this System.Drawing.Image image,
ImageFormat format)
{
if (image == null)
throw new ArgumentNullException(nameof(image));
if (format == null)
throw new ArgumentNullException(nameof(format));
using (var stream = new MemoryStream())
{
image.Save(stream, format);
return stream.ToArray();
}
}
}
}
| teknikprogramlama/Teknikprogramlama.Tools | TeknikProgramlama.Tools/Image/Utils.cs | C# | mit | 1,121 |
using UnityEngine;
using System.Collections;
public class sample : MonoBehaviour {
// Use this for initialization
void Start () {
Vector3 startPos = new Vector3(0,0,0);
Vector3 endPos = new Vector3(10,-10,0);
Vector3 center = Vector3.Lerp(startPos, endPos, 0.5f);
Vector3 cut = (endPos - startPos).normalized;
Vector3 fwd = (center).normalized;
Vector3 normal = Vector3.Cross(fwd, cut).normalized;
GameObject goCutPlane = new GameObject("CutPlane", typeof(BoxCollider), typeof(Rigidbody));
goCutPlane.GetComponent<Collider>().isTrigger = true;
Rigidbody bodyCutPlane = goCutPlane.GetComponent<Rigidbody>();
bodyCutPlane.useGravity = false;
bodyCutPlane.isKinematic = true;
Transform transformCutPlane = goCutPlane.transform;
transformCutPlane.position = center;
transformCutPlane.localScale = new Vector3(10f, .01f, 0.01f);
transformCutPlane.rotation = transform.rotation;
transformCutPlane.up = normal;
}
}
| HackathonHC/team-z | Assets/sample.cs | C# | mit | 985 |