file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
__init__.py | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from flask import session
from werkzeug.exceptions import Forbidden
from indico.modules.rb.controllers import RHRoomBookingBase
from indico.modules.rb.util import rb_is_admin
from indico.util.i18n import _
class | (RHRoomBookingBase):
"""
Adds admin authorization. All classes that implement admin
tasks should be derived from this class.
"""
def _checkProtection(self):
if session.user is None:
self._checkSessionUser()
elif not rb_is_admin(session.user):
raise Forbidden(_('You are not authorized to take this action.'))
| RHRoomBookingAdminBase | identifier_name |
__init__.py | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from flask import session
from werkzeug.exceptions import Forbidden
from indico.modules.rb.controllers import RHRoomBookingBase
from indico.modules.rb.util import rb_is_admin
from indico.util.i18n import _
class RHRoomBookingAdminBase(RHRoomBookingBase):
| """
Adds admin authorization. All classes that implement admin
tasks should be derived from this class.
"""
def _checkProtection(self):
if session.user is None:
self._checkSessionUser()
elif not rb_is_admin(session.user):
raise Forbidden(_('You are not authorized to take this action.')) | identifier_body | |
vrtogglebutton.ts | import {ToggleButton, ToggleButtonConfig} from './togglebutton';
import {UIInstanceManager} from '../uimanager';
/**
* A button that toggles the video view between normal/mono and VR/stereo.
*/
export class VRToggleButton extends ToggleButton<ToggleButtonConfig> {
constructor(config: ToggleButtonConfig = {}) {
super(config);
this.config = this.mergeConfig(config, {
cssClass: 'ui-vrtogglebutton',
text: 'VR',
}, this.config);
}
configure(player: bitmovin.PlayerAPI, uimanager: UIInstanceManager): void {
super.configure(player, uimanager);
let isVRConfigured = () => {
// VR availability cannot be checked through getVRStatus() because it is asynchronously populated and not
// available at UI initialization. As an alternative, we check the VR settings in the config.
// TODO use getVRStatus() through isVRStereoAvailable() once the player has been rewritten and the status is
// available in ON_READY
let config = player.getConfig();
return config.source && config.source.vr && config.source.vr.contentType !== 'none';
};
let isVRStereoAvailable = () => {
return player.getVRStatus().contentType !== 'none';
};
let vrStateHandler = () => {
if (isVRConfigured() && isVRStereoAvailable()) {
this.show(); // show button in case it is hidden
if (player.getVRStatus().isStereo) {
this.on();
} else {
this.off();
}
} else {
this.hide(); // hide button if no stereo mode available
}
};
let vrButtonVisibilityHandler = () => {
if (isVRConfigured()) {
this.show();
} else {
this.hide();
}
};
player.addEventHandler(player.EVENT.ON_VR_MODE_CHANGED, vrStateHandler);
player.addEventHandler(player.EVENT.ON_VR_STEREO_CHANGED, vrStateHandler);
player.addEventHandler(player.EVENT.ON_VR_ERROR, vrStateHandler);
// Hide button when VR source goes away
player.addEventHandler(player.EVENT.ON_SOURCE_UNLOADED, vrButtonVisibilityHandler);
// Show button when a new source is loaded and it's VR
player.addEventHandler(player.EVENT.ON_READY, vrButtonVisibilityHandler);
this.onClick.subscribe(() => {
if (!isVRStereoAvailable()) {
if (console) |
} else {
if (player.getVRStatus().isStereo) {
player.setVRStereo(false);
} else {
player.setVRStereo(true);
}
}
});
// Set startup visibility
vrButtonVisibilityHandler();
}
} | {
console.log('No VR content');
} | conditional_block |
vrtogglebutton.ts | import {ToggleButton, ToggleButtonConfig} from './togglebutton';
import {UIInstanceManager} from '../uimanager';
/**
* A button that toggles the video view between normal/mono and VR/stereo.
*/
export class VRToggleButton extends ToggleButton<ToggleButtonConfig> {
constructor(config: ToggleButtonConfig = {}) {
super(config);
this.config = this.mergeConfig(config, {
cssClass: 'ui-vrtogglebutton',
text: 'VR',
}, this.config);
}
configure(player: bitmovin.PlayerAPI, uimanager: UIInstanceManager): void {
super.configure(player, uimanager);
let isVRConfigured = () => {
// VR availability cannot be checked through getVRStatus() because it is asynchronously populated and not | };
let isVRStereoAvailable = () => {
return player.getVRStatus().contentType !== 'none';
};
let vrStateHandler = () => {
if (isVRConfigured() && isVRStereoAvailable()) {
this.show(); // show button in case it is hidden
if (player.getVRStatus().isStereo) {
this.on();
} else {
this.off();
}
} else {
this.hide(); // hide button if no stereo mode available
}
};
let vrButtonVisibilityHandler = () => {
if (isVRConfigured()) {
this.show();
} else {
this.hide();
}
};
player.addEventHandler(player.EVENT.ON_VR_MODE_CHANGED, vrStateHandler);
player.addEventHandler(player.EVENT.ON_VR_STEREO_CHANGED, vrStateHandler);
player.addEventHandler(player.EVENT.ON_VR_ERROR, vrStateHandler);
// Hide button when VR source goes away
player.addEventHandler(player.EVENT.ON_SOURCE_UNLOADED, vrButtonVisibilityHandler);
// Show button when a new source is loaded and it's VR
player.addEventHandler(player.EVENT.ON_READY, vrButtonVisibilityHandler);
this.onClick.subscribe(() => {
if (!isVRStereoAvailable()) {
if (console) {
console.log('No VR content');
}
} else {
if (player.getVRStatus().isStereo) {
player.setVRStereo(false);
} else {
player.setVRStereo(true);
}
}
});
// Set startup visibility
vrButtonVisibilityHandler();
}
} | // available at UI initialization. As an alternative, we check the VR settings in the config.
// TODO use getVRStatus() through isVRStereoAvailable() once the player has been rewritten and the status is
// available in ON_READY
let config = player.getConfig();
return config.source && config.source.vr && config.source.vr.contentType !== 'none'; | random_line_split |
vrtogglebutton.ts | import {ToggleButton, ToggleButtonConfig} from './togglebutton';
import {UIInstanceManager} from '../uimanager';
/**
* A button that toggles the video view between normal/mono and VR/stereo.
*/
export class VRToggleButton extends ToggleButton<ToggleButtonConfig> {
constructor(config: ToggleButtonConfig = {}) {
super(config);
this.config = this.mergeConfig(config, {
cssClass: 'ui-vrtogglebutton',
text: 'VR',
}, this.config);
}
| (player: bitmovin.PlayerAPI, uimanager: UIInstanceManager): void {
super.configure(player, uimanager);
let isVRConfigured = () => {
// VR availability cannot be checked through getVRStatus() because it is asynchronously populated and not
// available at UI initialization. As an alternative, we check the VR settings in the config.
// TODO use getVRStatus() through isVRStereoAvailable() once the player has been rewritten and the status is
// available in ON_READY
let config = player.getConfig();
return config.source && config.source.vr && config.source.vr.contentType !== 'none';
};
let isVRStereoAvailable = () => {
return player.getVRStatus().contentType !== 'none';
};
let vrStateHandler = () => {
if (isVRConfigured() && isVRStereoAvailable()) {
this.show(); // show button in case it is hidden
if (player.getVRStatus().isStereo) {
this.on();
} else {
this.off();
}
} else {
this.hide(); // hide button if no stereo mode available
}
};
let vrButtonVisibilityHandler = () => {
if (isVRConfigured()) {
this.show();
} else {
this.hide();
}
};
player.addEventHandler(player.EVENT.ON_VR_MODE_CHANGED, vrStateHandler);
player.addEventHandler(player.EVENT.ON_VR_STEREO_CHANGED, vrStateHandler);
player.addEventHandler(player.EVENT.ON_VR_ERROR, vrStateHandler);
// Hide button when VR source goes away
player.addEventHandler(player.EVENT.ON_SOURCE_UNLOADED, vrButtonVisibilityHandler);
// Show button when a new source is loaded and it's VR
player.addEventHandler(player.EVENT.ON_READY, vrButtonVisibilityHandler);
this.onClick.subscribe(() => {
if (!isVRStereoAvailable()) {
if (console) {
console.log('No VR content');
}
} else {
if (player.getVRStatus().isStereo) {
player.setVRStereo(false);
} else {
player.setVRStereo(true);
}
}
});
// Set startup visibility
vrButtonVisibilityHandler();
}
} | configure | identifier_name |
Log.ts |
/**
* This is a static Logger class, it is allows you to disable the client side
* application logging at runtime.
* Set the DEBUG property false (default value is true) to disable the client side logging.
*
*
* @author Gabor Kokeny
*/
class Log {
static DEBUG: boolean = true;
/**
*
* @param {string} message The log message
* @param {any[]} The optionals parameters
*
* @return Return the reference of Log variable
*/
static info(message: string, ...params: any[]): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.info(message, params);
}
return this;
}
static error(message: string, ...params: any[]): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.error(message, params);
}
return this;
}
static warn(message: string, ...params: any[]): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.warn(message, params);
}
return this;
}
static debug(message: string, ...params: any[]): Log {
if (!Log.DEBUG) |
if (console) {
console.debug(message, params);
}
return this;
}
static groupStart(title?: string): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.groupCollapsed(title);
}
return this;
}
static groupEnd(): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.groupEnd();
}
return this;
}
} | { return; } | conditional_block |
Log.ts |
/**
* This is a static Logger class, it is allows you to disable the client side
* application logging at runtime.
* Set the DEBUG property false (default value is true) to disable the client side logging.
*
*
* @author Gabor Kokeny
*/
class Log {
static DEBUG: boolean = true;
/**
*
* @param {string} message The log message
* @param {any[]} The optionals parameters
*
* @return Return the reference of Log variable
*/
static info(message: string, ...params: any[]): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.info(message, params);
}
return this;
}
static error(message: string, ...params: any[]): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.error(message, params);
}
return this;
}
static | (message: string, ...params: any[]): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.warn(message, params);
}
return this;
}
static debug(message: string, ...params: any[]): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.debug(message, params);
}
return this;
}
static groupStart(title?: string): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.groupCollapsed(title);
}
return this;
}
static groupEnd(): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.groupEnd();
}
return this;
}
} | warn | identifier_name |
Log.ts | /**
* This is a static Logger class, it is allows you to disable the client side
* application logging at runtime.
* Set the DEBUG property false (default value is true) to disable the client side logging.
*
*
* @author Gabor Kokeny
*/
class Log {
static DEBUG: boolean = true;
/**
*
* @param {string} message The log message
* @param {any[]} The optionals parameters
*
* @return Return the reference of Log variable
*/
static info(message: string, ...params: any[]): Log { |
if (console) {
console.info(message, params);
}
return this;
}
static error(message: string, ...params: any[]): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.error(message, params);
}
return this;
}
static warn(message: string, ...params: any[]): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.warn(message, params);
}
return this;
}
static debug(message: string, ...params: any[]): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.debug(message, params);
}
return this;
}
static groupStart(title?: string): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.groupCollapsed(title);
}
return this;
}
static groupEnd(): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.groupEnd();
}
return this;
}
} | if (!Log.DEBUG) { return; } | random_line_split |
Log.ts |
/**
* This is a static Logger class, it is allows you to disable the client side
* application logging at runtime.
* Set the DEBUG property false (default value is true) to disable the client side logging.
*
*
* @author Gabor Kokeny
*/
class Log {
static DEBUG: boolean = true;
/**
*
* @param {string} message The log message
* @param {any[]} The optionals parameters
*
* @return Return the reference of Log variable
*/
static info(message: string, ...params: any[]): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.info(message, params);
}
return this;
}
static error(message: string, ...params: any[]): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.error(message, params);
}
return this;
}
static warn(message: string, ...params: any[]): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.warn(message, params);
}
return this;
}
static debug(message: string, ...params: any[]): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.debug(message, params);
}
return this;
}
static groupStart(title?: string): Log {
if (!Log.DEBUG) { return; }
if (console) {
console.groupCollapsed(title);
}
return this;
}
static groupEnd(): Log |
} | {
if (!Log.DEBUG) { return; }
if (console) {
console.groupEnd();
}
return this;
} | identifier_body |
connection.py | ###############################################################################
##
## Copyright (C) 2014-2016, New York University.
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## "Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are met:
##
## - Redistributions of source code must retain the above copyright notice,
## this list of conditions and the following disclaimer.
## - Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in the
## documentation and/or other materials provided with the distribution.
## - Neither the name of the New York University nor the names of its
## contributors may be used to endorse or promote products derived from
## this software without specific prior written permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
## THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
## OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
## WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
## OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
## ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
##
###############################################################################
from __future__ import division
""" This python module defines Connection class.
"""
import copy
from vistrails.db.domain import DBConnection
from vistrails.core.vistrail.port import PortEndPoint, Port
import unittest
from vistrails.db.domain import IdScope
################################################################################
class Connection(DBConnection):
""" A Connection is a connection between two modules.
Right now there's only Module connections.
"""
##########################################################################
# Constructors and copy
@staticmethod
def from_port_specs(source, dest):
"""from_port_specs(source: PortSpec, dest: PortSpec) -> Connection
Static method that creates a Connection given source and
destination ports.
"""
conn = Connection()
conn.source = copy.copy(source)
conn.destination = copy.copy(dest)
return conn
@staticmethod
def fromID(id):
"""fromTypeID(id: int) -> Connection
Static method that creates a Connection given an id.
"""
conn = Connection()
conn.id = id
conn.source.endPoint = PortEndPoint.Source
conn.destination.endPoint = PortEndPoint.Destination
return conn
def __init__(self, *args, **kwargs):
"""__init__() -> Connection
Initializes source and destination ports.
"""
DBConnection.__init__(self, *args, **kwargs)
if self.id is None:
self.db_id = -1
if not len(self.ports) > 0:
self.source = Port(type='source')
self.destination = Port(type='destination')
def __copy__(self):
"""__copy__() -> Connection - Returns a clone of self.
"""
return Connection.do_copy(self)
def do_copy(self, new_ids=False, id_scope=None, id_remap=None):
cp = DBConnection.do_copy(self, new_ids, id_scope, id_remap)
cp.__class__ = Connection
for port in cp.ports:
Port.convert(port)
return cp
##########################################################################
@staticmethod
def convert(_connection):
# print "ports: %s" % _Connection._get_ports(_connection)
if _connection.__class__ == Connection:
return
_connection.__class__ = Connection
for port in _connection.ports:
Port.convert(port)
##########################################################################
# Properties
id = DBConnection.db_id
ports = DBConnection.db_ports
def add_port(self, port):
self.db_add_port(port)
def _get_sourceId(self):
""" _get_sourceId() -> int
Returns the module id of source port. Do not use this function,
use sourceId property: c.sourceId
"""
return self.source.moduleId
def _set_sourceId(self, id):
""" _set_sourceId(id : int) -> None
Sets this connection source id. It updates both self.source.moduleId
and self.source.id. Do not use this function, use sourceId
property: c.sourceId = id
"""
self.source.moduleId = id
self.source.id = id
sourceId = property(_get_sourceId, _set_sourceId)
def _get_destinationId(self):
""" _get_destinationId() -> int
Returns the module id of dest port. Do not use this function,
use sourceId property: c.destinationId
"""
return self.destination.moduleId
def _set_destinationId(self, id):
""" _set_destinationId(id : int) -> None
Sets this connection destination id. It updates self.dest.moduleId.
Do not use this function, use destinationId property:
c.destinationId = id
"""
self.destination.moduleId = id
destinationId = property(_get_destinationId, _set_destinationId)
def _get_source(self):
"""_get_source() -> Port
Returns source port. Do not use this function, use source property:
c.source
"""
try:
return self.db_get_port_by_type('source')
except KeyError:
pass
return None
def _set_source(self, source):
"""_set_source(source: Port) -> None
Sets this connection source port. Do not use this function,
use source property instead: c.source = source
"""
try:
port = self.db_get_port_by_type('source')
self.db_delete_port(port)
except KeyError:
pass
if source is not None:
self.db_add_port(source)
source = property(_get_source, _set_source)
def _get_destination(self):
"""_get_destination() -> Port
Returns destination port. Do not use this function, use destination
property: c.destination
"""
# return self.db_ports['destination']
try:
return self.db_get_port_by_type('destination')
except KeyError:
pass
return None
def _set_destination(self, dest):
"""_set_destination(dest: Port) -> None
Sets this connection destination port. Do not use this
function, use destination property instead: c.destination = dest
"""
try:
port = self.db_get_port_by_type('destination')
self.db_delete_port(port)
except KeyError:
pass
if dest is not None:
self.db_add_port(dest)
destination = property(_get_destination, _set_destination)
dest = property(_get_destination, _set_destination)
##########################################################################
# Operators
def __str__(self):
"""__str__() -> str - Returns a string representation of a Connection
object.
"""
rep = "<connection id='%s'>%s%s</connection>"
return rep % (str(self.id), str(self.source), str(self.destination))
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
if type(other) != type(self):
return False
return (self.source == other.source and
self.dest == other.dest)
def equals_no_id(self, other):
"""Checks equality up to ids (connection and ports)."""
if type(self) != type(other):
return False
return (self.source.equals_no_id(other.source) and
self.dest.equals_no_id(other.dest))
################################################################################
# Testing
class TestConnection(unittest.TestCase):
def create_connection(self, id_scope=IdScope()):
from vistrails.core.vistrail.port import Port
from vistrails.core.modules.basic_modules import identifier as basic_pkg
source = Port(id=id_scope.getNewId(Port.vtType),
type='source',
moduleId=21L,
moduleName='String',
name='value',
signature='(%s:String)' % basic_pkg)
destination = Port(id=id_scope.getNewId(Port.vtType),
type='destination',
moduleId=20L,
moduleName='Float',
name='value',
signature='(%s:Float)' % basic_pkg)
connection = Connection(id=id_scope.getNewId(Connection.vtType),
ports=[source, destination])
return connection
def test_copy(self):
id_scope = IdScope()
c1 = self.create_connection(id_scope)
c2 = copy.copy(c1)
self.assertEquals(c1, c2)
self.assertEquals(c1.id, c2.id)
c3 = c1.do_copy(True, id_scope, {})
self.assertEquals(c1, c3)
self.assertNotEquals(c1.id, c3.id)
def test_serialization(self):
import vistrails.core.db.io
c1 = self.create_connection()
xml_str = vistrails.core.db.io.serialize(c1)
c2 = vistrails.core.db.io.unserialize(xml_str, Connection)
self.assertEquals(c1, c2)
self.assertEquals(c1.id, c2.id)
def | (self):
"""Tests sane initialization of empty connection"""
c = Connection()
self.assertEquals(c.source.endPoint, PortEndPoint.Source)
self.assertEquals(c.destination.endPoint, PortEndPoint.Destination)
if __name__ == '__main__':
unittest.main()
| testEmptyConnection | identifier_name |
connection.py | ###############################################################################
##
## Copyright (C) 2014-2016, New York University.
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## "Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are met:
##
## - Redistributions of source code must retain the above copyright notice,
## this list of conditions and the following disclaimer.
## - Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in the
## documentation and/or other materials provided with the distribution.
## - Neither the name of the New York University nor the names of its
## contributors may be used to endorse or promote products derived from
## this software without specific prior written permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
## THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
## OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
## WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
## OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
## ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
##
###############################################################################
from __future__ import division
""" This python module defines Connection class.
"""
import copy
from vistrails.db.domain import DBConnection
from vistrails.core.vistrail.port import PortEndPoint, Port
import unittest
from vistrails.db.domain import IdScope
################################################################################
class Connection(DBConnection):
""" A Connection is a connection between two modules.
Right now there's only Module connections.
"""
##########################################################################
# Constructors and copy
@staticmethod
def from_port_specs(source, dest):
"""from_port_specs(source: PortSpec, dest: PortSpec) -> Connection
Static method that creates a Connection given source and
destination ports.
"""
conn = Connection()
conn.source = copy.copy(source)
conn.destination = copy.copy(dest)
return conn
@staticmethod
def fromID(id):
"""fromTypeID(id: int) -> Connection
Static method that creates a Connection given an id.
"""
conn = Connection()
conn.id = id
conn.source.endPoint = PortEndPoint.Source
conn.destination.endPoint = PortEndPoint.Destination
return conn
def __init__(self, *args, **kwargs):
"""__init__() -> Connection
Initializes source and destination ports.
"""
DBConnection.__init__(self, *args, **kwargs)
if self.id is None:
self.db_id = -1
if not len(self.ports) > 0:
self.source = Port(type='source')
self.destination = Port(type='destination')
def __copy__(self):
"""__copy__() -> Connection - Returns a clone of self.
"""
return Connection.do_copy(self)
def do_copy(self, new_ids=False, id_scope=None, id_remap=None):
cp = DBConnection.do_copy(self, new_ids, id_scope, id_remap)
cp.__class__ = Connection
for port in cp.ports:
|
return cp
##########################################################################
@staticmethod
def convert(_connection):
# print "ports: %s" % _Connection._get_ports(_connection)
if _connection.__class__ == Connection:
return
_connection.__class__ = Connection
for port in _connection.ports:
Port.convert(port)
##########################################################################
# Properties
id = DBConnection.db_id
ports = DBConnection.db_ports
def add_port(self, port):
self.db_add_port(port)
def _get_sourceId(self):
""" _get_sourceId() -> int
Returns the module id of source port. Do not use this function,
use sourceId property: c.sourceId
"""
return self.source.moduleId
def _set_sourceId(self, id):
""" _set_sourceId(id : int) -> None
Sets this connection source id. It updates both self.source.moduleId
and self.source.id. Do not use this function, use sourceId
property: c.sourceId = id
"""
self.source.moduleId = id
self.source.id = id
sourceId = property(_get_sourceId, _set_sourceId)
def _get_destinationId(self):
""" _get_destinationId() -> int
Returns the module id of dest port. Do not use this function,
use sourceId property: c.destinationId
"""
return self.destination.moduleId
def _set_destinationId(self, id):
""" _set_destinationId(id : int) -> None
Sets this connection destination id. It updates self.dest.moduleId.
Do not use this function, use destinationId property:
c.destinationId = id
"""
self.destination.moduleId = id
destinationId = property(_get_destinationId, _set_destinationId)
def _get_source(self):
"""_get_source() -> Port
Returns source port. Do not use this function, use source property:
c.source
"""
try:
return self.db_get_port_by_type('source')
except KeyError:
pass
return None
def _set_source(self, source):
"""_set_source(source: Port) -> None
Sets this connection source port. Do not use this function,
use source property instead: c.source = source
"""
try:
port = self.db_get_port_by_type('source')
self.db_delete_port(port)
except KeyError:
pass
if source is not None:
self.db_add_port(source)
source = property(_get_source, _set_source)
def _get_destination(self):
"""_get_destination() -> Port
Returns destination port. Do not use this function, use destination
property: c.destination
"""
# return self.db_ports['destination']
try:
return self.db_get_port_by_type('destination')
except KeyError:
pass
return None
def _set_destination(self, dest):
"""_set_destination(dest: Port) -> None
Sets this connection destination port. Do not use this
function, use destination property instead: c.destination = dest
"""
try:
port = self.db_get_port_by_type('destination')
self.db_delete_port(port)
except KeyError:
pass
if dest is not None:
self.db_add_port(dest)
destination = property(_get_destination, _set_destination)
dest = property(_get_destination, _set_destination)
##########################################################################
# Operators
def __str__(self):
"""__str__() -> str - Returns a string representation of a Connection
object.
"""
rep = "<connection id='%s'>%s%s</connection>"
return rep % (str(self.id), str(self.source), str(self.destination))
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
if type(other) != type(self):
return False
return (self.source == other.source and
self.dest == other.dest)
def equals_no_id(self, other):
"""Checks equality up to ids (connection and ports)."""
if type(self) != type(other):
return False
return (self.source.equals_no_id(other.source) and
self.dest.equals_no_id(other.dest))
################################################################################
# Testing
class TestConnection(unittest.TestCase):
def create_connection(self, id_scope=IdScope()):
from vistrails.core.vistrail.port import Port
from vistrails.core.modules.basic_modules import identifier as basic_pkg
source = Port(id=id_scope.getNewId(Port.vtType),
type='source',
moduleId=21L,
moduleName='String',
name='value',
signature='(%s:String)' % basic_pkg)
destination = Port(id=id_scope.getNewId(Port.vtType),
type='destination',
moduleId=20L,
moduleName='Float',
name='value',
signature='(%s:Float)' % basic_pkg)
connection = Connection(id=id_scope.getNewId(Connection.vtType),
ports=[source, destination])
return connection
def test_copy(self):
id_scope = IdScope()
c1 = self.create_connection(id_scope)
c2 = copy.copy(c1)
self.assertEquals(c1, c2)
self.assertEquals(c1.id, c2.id)
c3 = c1.do_copy(True, id_scope, {})
self.assertEquals(c1, c3)
self.assertNotEquals(c1.id, c3.id)
def test_serialization(self):
import vistrails.core.db.io
c1 = self.create_connection()
xml_str = vistrails.core.db.io.serialize(c1)
c2 = vistrails.core.db.io.unserialize(xml_str, Connection)
self.assertEquals(c1, c2)
self.assertEquals(c1.id, c2.id)
def testEmptyConnection(self):
"""Tests sane initialization of empty connection"""
c = Connection()
self.assertEquals(c.source.endPoint, PortEndPoint.Source)
self.assertEquals(c.destination.endPoint, PortEndPoint.Destination)
if __name__ == '__main__':
unittest.main()
| Port.convert(port) | conditional_block |
connection.py | ###############################################################################
##
## Copyright (C) 2014-2016, New York University.
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## "Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are met:
##
## - Redistributions of source code must retain the above copyright notice,
## this list of conditions and the following disclaimer.
## - Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in the
## documentation and/or other materials provided with the distribution.
## - Neither the name of the New York University nor the names of its
## contributors may be used to endorse or promote products derived from
## this software without specific prior written permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
## THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
## OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
## WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
## OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
## ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
##
###############################################################################
from __future__ import division
""" This python module defines Connection class.
"""
import copy
from vistrails.db.domain import DBConnection
from vistrails.core.vistrail.port import PortEndPoint, Port
import unittest
from vistrails.db.domain import IdScope
################################################################################
class Connection(DBConnection):
""" A Connection is a connection between two modules.
Right now there's only Module connections.
"""
##########################################################################
# Constructors and copy
@staticmethod
def from_port_specs(source, dest):
"""from_port_specs(source: PortSpec, dest: PortSpec) -> Connection
Static method that creates a Connection given source and
destination ports.
"""
conn = Connection()
conn.source = copy.copy(source)
conn.destination = copy.copy(dest)
return conn
@staticmethod
def fromID(id):
"""fromTypeID(id: int) -> Connection
Static method that creates a Connection given an id.
"""
conn = Connection()
conn.id = id |
def __init__(self, *args, **kwargs):
"""__init__() -> Connection
Initializes source and destination ports.
"""
DBConnection.__init__(self, *args, **kwargs)
if self.id is None:
self.db_id = -1
if not len(self.ports) > 0:
self.source = Port(type='source')
self.destination = Port(type='destination')
def __copy__(self):
"""__copy__() -> Connection - Returns a clone of self.
"""
return Connection.do_copy(self)
def do_copy(self, new_ids=False, id_scope=None, id_remap=None):
cp = DBConnection.do_copy(self, new_ids, id_scope, id_remap)
cp.__class__ = Connection
for port in cp.ports:
Port.convert(port)
return cp
##########################################################################
@staticmethod
def convert(_connection):
# print "ports: %s" % _Connection._get_ports(_connection)
if _connection.__class__ == Connection:
return
_connection.__class__ = Connection
for port in _connection.ports:
Port.convert(port)
##########################################################################
# Properties
id = DBConnection.db_id
ports = DBConnection.db_ports
def add_port(self, port):
self.db_add_port(port)
def _get_sourceId(self):
""" _get_sourceId() -> int
Returns the module id of source port. Do not use this function,
use sourceId property: c.sourceId
"""
return self.source.moduleId
def _set_sourceId(self, id):
""" _set_sourceId(id : int) -> None
Sets this connection source id. It updates both self.source.moduleId
and self.source.id. Do not use this function, use sourceId
property: c.sourceId = id
"""
self.source.moduleId = id
self.source.id = id
sourceId = property(_get_sourceId, _set_sourceId)
def _get_destinationId(self):
""" _get_destinationId() -> int
Returns the module id of dest port. Do not use this function,
use sourceId property: c.destinationId
"""
return self.destination.moduleId
def _set_destinationId(self, id):
""" _set_destinationId(id : int) -> None
Sets this connection destination id. It updates self.dest.moduleId.
Do not use this function, use destinationId property:
c.destinationId = id
"""
self.destination.moduleId = id
destinationId = property(_get_destinationId, _set_destinationId)
def _get_source(self):
"""_get_source() -> Port
Returns source port. Do not use this function, use source property:
c.source
"""
try:
return self.db_get_port_by_type('source')
except KeyError:
pass
return None
def _set_source(self, source):
"""_set_source(source: Port) -> None
Sets this connection source port. Do not use this function,
use source property instead: c.source = source
"""
try:
port = self.db_get_port_by_type('source')
self.db_delete_port(port)
except KeyError:
pass
if source is not None:
self.db_add_port(source)
source = property(_get_source, _set_source)
def _get_destination(self):
"""_get_destination() -> Port
Returns destination port. Do not use this function, use destination
property: c.destination
"""
# return self.db_ports['destination']
try:
return self.db_get_port_by_type('destination')
except KeyError:
pass
return None
def _set_destination(self, dest):
"""_set_destination(dest: Port) -> None
Sets this connection destination port. Do not use this
function, use destination property instead: c.destination = dest
"""
try:
port = self.db_get_port_by_type('destination')
self.db_delete_port(port)
except KeyError:
pass
if dest is not None:
self.db_add_port(dest)
destination = property(_get_destination, _set_destination)
dest = property(_get_destination, _set_destination)
##########################################################################
# Operators
def __str__(self):
"""__str__() -> str - Returns a string representation of a Connection
object.
"""
rep = "<connection id='%s'>%s%s</connection>"
return rep % (str(self.id), str(self.source), str(self.destination))
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
if type(other) != type(self):
return False
return (self.source == other.source and
self.dest == other.dest)
def equals_no_id(self, other):
"""Checks equality up to ids (connection and ports)."""
if type(self) != type(other):
return False
return (self.source.equals_no_id(other.source) and
self.dest.equals_no_id(other.dest))
################################################################################
# Testing
class TestConnection(unittest.TestCase):
def create_connection(self, id_scope=IdScope()):
from vistrails.core.vistrail.port import Port
from vistrails.core.modules.basic_modules import identifier as basic_pkg
source = Port(id=id_scope.getNewId(Port.vtType),
type='source',
moduleId=21L,
moduleName='String',
name='value',
signature='(%s:String)' % basic_pkg)
destination = Port(id=id_scope.getNewId(Port.vtType),
type='destination',
moduleId=20L,
moduleName='Float',
name='value',
signature='(%s:Float)' % basic_pkg)
connection = Connection(id=id_scope.getNewId(Connection.vtType),
ports=[source, destination])
return connection
def test_copy(self):
id_scope = IdScope()
c1 = self.create_connection(id_scope)
c2 = copy.copy(c1)
self.assertEquals(c1, c2)
self.assertEquals(c1.id, c2.id)
c3 = c1.do_copy(True, id_scope, {})
self.assertEquals(c1, c3)
self.assertNotEquals(c1.id, c3.id)
def test_serialization(self):
import vistrails.core.db.io
c1 = self.create_connection()
xml_str = vistrails.core.db.io.serialize(c1)
c2 = vistrails.core.db.io.unserialize(xml_str, Connection)
self.assertEquals(c1, c2)
self.assertEquals(c1.id, c2.id)
def testEmptyConnection(self):
"""Tests sane initialization of empty connection"""
c = Connection()
self.assertEquals(c.source.endPoint, PortEndPoint.Source)
self.assertEquals(c.destination.endPoint, PortEndPoint.Destination)
if __name__ == '__main__':
unittest.main() | conn.source.endPoint = PortEndPoint.Source
conn.destination.endPoint = PortEndPoint.Destination
return conn | random_line_split |
connection.py | ###############################################################################
##
## Copyright (C) 2014-2016, New York University.
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## "Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are met:
##
## - Redistributions of source code must retain the above copyright notice,
## this list of conditions and the following disclaimer.
## - Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in the
## documentation and/or other materials provided with the distribution.
## - Neither the name of the New York University nor the names of its
## contributors may be used to endorse or promote products derived from
## this software without specific prior written permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
## THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
## OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
## WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
## OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
## ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
##
###############################################################################
from __future__ import division
""" This python module defines Connection class.
"""
import copy
from vistrails.db.domain import DBConnection
from vistrails.core.vistrail.port import PortEndPoint, Port
import unittest
from vistrails.db.domain import IdScope
################################################################################
class Connection(DBConnection):
""" A Connection is a connection between two modules.
Right now there's only Module connections.
"""
##########################################################################
# Constructors and copy
@staticmethod
def from_port_specs(source, dest):
"""from_port_specs(source: PortSpec, dest: PortSpec) -> Connection
Static method that creates a Connection given source and
destination ports.
"""
conn = Connection()
conn.source = copy.copy(source)
conn.destination = copy.copy(dest)
return conn
@staticmethod
def fromID(id):
"""fromTypeID(id: int) -> Connection
Static method that creates a Connection given an id.
"""
conn = Connection()
conn.id = id
conn.source.endPoint = PortEndPoint.Source
conn.destination.endPoint = PortEndPoint.Destination
return conn
def __init__(self, *args, **kwargs):
"""__init__() -> Connection
Initializes source and destination ports.
"""
DBConnection.__init__(self, *args, **kwargs)
if self.id is None:
self.db_id = -1
if not len(self.ports) > 0:
self.source = Port(type='source')
self.destination = Port(type='destination')
def __copy__(self):
"""__copy__() -> Connection - Returns a clone of self.
"""
return Connection.do_copy(self)
def do_copy(self, new_ids=False, id_scope=None, id_remap=None):
cp = DBConnection.do_copy(self, new_ids, id_scope, id_remap)
cp.__class__ = Connection
for port in cp.ports:
Port.convert(port)
return cp
##########################################################################
@staticmethod
def convert(_connection):
# print "ports: %s" % _Connection._get_ports(_connection)
if _connection.__class__ == Connection:
return
_connection.__class__ = Connection
for port in _connection.ports:
Port.convert(port)
##########################################################################
# Properties
id = DBConnection.db_id
ports = DBConnection.db_ports
def add_port(self, port):
self.db_add_port(port)
def _get_sourceId(self):
""" _get_sourceId() -> int
Returns the module id of source port. Do not use this function,
use sourceId property: c.sourceId
"""
return self.source.moduleId
def _set_sourceId(self, id):
""" _set_sourceId(id : int) -> None
Sets this connection source id. It updates both self.source.moduleId
and self.source.id. Do not use this function, use sourceId
property: c.sourceId = id
"""
self.source.moduleId = id
self.source.id = id
sourceId = property(_get_sourceId, _set_sourceId)
def _get_destinationId(self):
""" _get_destinationId() -> int
Returns the module id of dest port. Do not use this function,
use sourceId property: c.destinationId
"""
return self.destination.moduleId
def _set_destinationId(self, id):
""" _set_destinationId(id : int) -> None
Sets this connection destination id. It updates self.dest.moduleId.
Do not use this function, use destinationId property:
c.destinationId = id
"""
self.destination.moduleId = id
destinationId = property(_get_destinationId, _set_destinationId)
def _get_source(self):
"""_get_source() -> Port
Returns source port. Do not use this function, use source property:
c.source
"""
try:
return self.db_get_port_by_type('source')
except KeyError:
pass
return None
def _set_source(self, source):
"""_set_source(source: Port) -> None
Sets this connection source port. Do not use this function,
use source property instead: c.source = source
"""
try:
port = self.db_get_port_by_type('source')
self.db_delete_port(port)
except KeyError:
pass
if source is not None:
self.db_add_port(source)
source = property(_get_source, _set_source)
def _get_destination(self):
"""_get_destination() -> Port
Returns destination port. Do not use this function, use destination
property: c.destination
"""
# return self.db_ports['destination']
try:
return self.db_get_port_by_type('destination')
except KeyError:
pass
return None
def _set_destination(self, dest):
"""_set_destination(dest: Port) -> None
Sets this connection destination port. Do not use this
function, use destination property instead: c.destination = dest
"""
try:
port = self.db_get_port_by_type('destination')
self.db_delete_port(port)
except KeyError:
pass
if dest is not None:
self.db_add_port(dest)
destination = property(_get_destination, _set_destination)
dest = property(_get_destination, _set_destination)
##########################################################################
# Operators
def __str__(self):
|
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
if type(other) != type(self):
return False
return (self.source == other.source and
self.dest == other.dest)
def equals_no_id(self, other):
"""Checks equality up to ids (connection and ports)."""
if type(self) != type(other):
return False
return (self.source.equals_no_id(other.source) and
self.dest.equals_no_id(other.dest))
################################################################################
# Testing
class TestConnection(unittest.TestCase):
def create_connection(self, id_scope=IdScope()):
from vistrails.core.vistrail.port import Port
from vistrails.core.modules.basic_modules import identifier as basic_pkg
source = Port(id=id_scope.getNewId(Port.vtType),
type='source',
moduleId=21L,
moduleName='String',
name='value',
signature='(%s:String)' % basic_pkg)
destination = Port(id=id_scope.getNewId(Port.vtType),
type='destination',
moduleId=20L,
moduleName='Float',
name='value',
signature='(%s:Float)' % basic_pkg)
connection = Connection(id=id_scope.getNewId(Connection.vtType),
ports=[source, destination])
return connection
def test_copy(self):
id_scope = IdScope()
c1 = self.create_connection(id_scope)
c2 = copy.copy(c1)
self.assertEquals(c1, c2)
self.assertEquals(c1.id, c2.id)
c3 = c1.do_copy(True, id_scope, {})
self.assertEquals(c1, c3)
self.assertNotEquals(c1.id, c3.id)
def test_serialization(self):
import vistrails.core.db.io
c1 = self.create_connection()
xml_str = vistrails.core.db.io.serialize(c1)
c2 = vistrails.core.db.io.unserialize(xml_str, Connection)
self.assertEquals(c1, c2)
self.assertEquals(c1.id, c2.id)
def testEmptyConnection(self):
"""Tests sane initialization of empty connection"""
c = Connection()
self.assertEquals(c.source.endPoint, PortEndPoint.Source)
self.assertEquals(c.destination.endPoint, PortEndPoint.Destination)
if __name__ == '__main__':
unittest.main()
| """__str__() -> str - Returns a string representation of a Connection
object.
"""
rep = "<connection id='%s'>%s%s</connection>"
return rep % (str(self.id), str(self.source), str(self.destination)) | identifier_body |
0008_auto_20210519_1117.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
| dependencies = [
('servicos', '0007_auto_20210416_0841'),
]
operations = [
migrations.AlterField(
model_name='servico',
name='data_ultimo_uso',
field=models.DateField(help_text='Data em que o servi\xe7o foi utilizado pela Casa Legislativa pela \xfaltima vez', null=True, verbose_name='Data da \xfaltima utiliza\xe7\xe3o', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='servico',
name='erro_atualizacao',
field=models.TextField(help_text='Erro ocorrido na \xfaltima tentativa de verificar a data de \xfaltima atualiza\xe7\xe3o do servi\xe7o', verbose_name='Erro na atualiza\xe7\xe3o', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='tiposervico',
name='modo',
field=models.CharField(max_length=1, verbose_name='modo de presta\xe7\xe3o do servi\xe7o', choices=[(b'H', 'Hospedagem'), (b'R', 'Registro')]),
preserve_default=True,
),
migrations.AlterField(
model_name='tiposervico',
name='nome',
field=models.CharField(max_length=60, verbose_name='nome'),
preserve_default=True,
),
migrations.AlterField(
model_name='tiposervico',
name='sigla',
field=models.CharField(max_length=b'12', verbose_name='sigla'),
preserve_default=True,
),
migrations.AlterField(
model_name='tiposervico',
name='string_pesquisa',
field=models.TextField(help_text='Par\xe2metros da pesquisa para averiguar a data da \xfaltima atualiza\xe7\xe3o do servi\xe7o. Formato:<br/><ul><li>/caminho/da/pesquisa/?parametros [xml|json] campo.de.data</li>', verbose_name='string de pesquisa', blank=True),
preserve_default=True,
),
] | identifier_body | |
0008_auto_20210519_1117.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('servicos', '0007_auto_20210416_0841'),
]
operations = [
migrations.AlterField(
model_name='servico',
name='data_ultimo_uso',
field=models.DateField(help_text='Data em que o servi\xe7o foi utilizado pela Casa Legislativa pela \xfaltima vez', null=True, verbose_name='Data da \xfaltima utiliza\xe7\xe3o', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='servico',
name='erro_atualizacao',
field=models.TextField(help_text='Erro ocorrido na \xfaltima tentativa de verificar a data de \xfaltima atualiza\xe7\xe3o do servi\xe7o', verbose_name='Erro na atualiza\xe7\xe3o', blank=True),
preserve_default=True, | model_name='tiposervico',
name='modo',
field=models.CharField(max_length=1, verbose_name='modo de presta\xe7\xe3o do servi\xe7o', choices=[(b'H', 'Hospedagem'), (b'R', 'Registro')]),
preserve_default=True,
),
migrations.AlterField(
model_name='tiposervico',
name='nome',
field=models.CharField(max_length=60, verbose_name='nome'),
preserve_default=True,
),
migrations.AlterField(
model_name='tiposervico',
name='sigla',
field=models.CharField(max_length=b'12', verbose_name='sigla'),
preserve_default=True,
),
migrations.AlterField(
model_name='tiposervico',
name='string_pesquisa',
field=models.TextField(help_text='Par\xe2metros da pesquisa para averiguar a data da \xfaltima atualiza\xe7\xe3o do servi\xe7o. Formato:<br/><ul><li>/caminho/da/pesquisa/?parametros [xml|json] campo.de.data</li>', verbose_name='string de pesquisa', blank=True),
preserve_default=True,
),
] | ),
migrations.AlterField( | random_line_split |
0008_auto_20210519_1117.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class | (migrations.Migration):
dependencies = [
('servicos', '0007_auto_20210416_0841'),
]
operations = [
migrations.AlterField(
model_name='servico',
name='data_ultimo_uso',
field=models.DateField(help_text='Data em que o servi\xe7o foi utilizado pela Casa Legislativa pela \xfaltima vez', null=True, verbose_name='Data da \xfaltima utiliza\xe7\xe3o', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='servico',
name='erro_atualizacao',
field=models.TextField(help_text='Erro ocorrido na \xfaltima tentativa de verificar a data de \xfaltima atualiza\xe7\xe3o do servi\xe7o', verbose_name='Erro na atualiza\xe7\xe3o', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='tiposervico',
name='modo',
field=models.CharField(max_length=1, verbose_name='modo de presta\xe7\xe3o do servi\xe7o', choices=[(b'H', 'Hospedagem'), (b'R', 'Registro')]),
preserve_default=True,
),
migrations.AlterField(
model_name='tiposervico',
name='nome',
field=models.CharField(max_length=60, verbose_name='nome'),
preserve_default=True,
),
migrations.AlterField(
model_name='tiposervico',
name='sigla',
field=models.CharField(max_length=b'12', verbose_name='sigla'),
preserve_default=True,
),
migrations.AlterField(
model_name='tiposervico',
name='string_pesquisa',
field=models.TextField(help_text='Par\xe2metros da pesquisa para averiguar a data da \xfaltima atualiza\xe7\xe3o do servi\xe7o. Formato:<br/><ul><li>/caminho/da/pesquisa/?parametros [xml|json] campo.de.data</li>', verbose_name='string de pesquisa', blank=True),
preserve_default=True,
),
]
| Migration | identifier_name |
xfixes.py | # Xlib.ext.xfixes -- XFIXES extension module
#
# Copyright (C) 2010-2011 Outpost Embedded, LLC
# Forest Bond <forest.bond@rapidrollout.com>
# | # This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place,
# Suite 330,
# Boston, MA 02111-1307 USA
'''
A partial implementation of the XFIXES extension. Only the HideCursor and
ShowCursor requests are provided.
'''
from Xlib.protocol import rq
extname = 'XFIXES'
class QueryVersion(rq.ReplyRequest):
_request = rq.Struct(rq.Card8('opcode'),
rq.Opcode(0),
rq.RequestLength(),
rq.Card32('major_version'),
rq.Card32('minor_version')
)
_reply = rq.Struct(rq.ReplyCode(),
rq.Pad(1),
rq.Card16('sequence_number'),
rq.ReplyLength(),
rq.Card32('major_version'),
rq.Card32('minor_version'),
rq.Pad(16)
)
def query_version(self):
return QueryVersion(display=self.display,
opcode=self.display.get_extension_major(extname),
major_version=4,
minor_version=0)
class HideCursor(rq.Request):
_request = rq.Struct(rq.Card8('opcode'),
rq.Opcode(29),
rq.RequestLength(),
rq.Window('window')
)
def hide_cursor(self):
HideCursor(display=self.display,
opcode=self.display.get_extension_major(extname),
window=self)
class ShowCursor(rq.Request):
_request = rq.Struct(rq.Card8('opcode'),
rq.Opcode(30),
rq.RequestLength(),
rq.Window('window')
)
def show_cursor(self):
ShowCursor(display=self.display,
opcode=self.display.get_extension_major(extname),
window=self)
def init(disp, info):
disp.extension_add_method('display', 'xfixes_query_version', query_version)
disp.extension_add_method('window', 'xfixes_hide_cursor', hide_cursor)
disp.extension_add_method('window', 'xfixes_show_cursor', show_cursor) | random_line_split | |
xfixes.py | # Xlib.ext.xfixes -- XFIXES extension module
#
# Copyright (C) 2010-2011 Outpost Embedded, LLC
# Forest Bond <forest.bond@rapidrollout.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place,
# Suite 330,
# Boston, MA 02111-1307 USA
'''
A partial implementation of the XFIXES extension. Only the HideCursor and
ShowCursor requests are provided.
'''
from Xlib.protocol import rq
extname = 'XFIXES'
class QueryVersion(rq.ReplyRequest):
_request = rq.Struct(rq.Card8('opcode'),
rq.Opcode(0),
rq.RequestLength(),
rq.Card32('major_version'),
rq.Card32('minor_version')
)
_reply = rq.Struct(rq.ReplyCode(),
rq.Pad(1),
rq.Card16('sequence_number'),
rq.ReplyLength(),
rq.Card32('major_version'),
rq.Card32('minor_version'),
rq.Pad(16)
)
def query_version(self):
return QueryVersion(display=self.display,
opcode=self.display.get_extension_major(extname),
major_version=4,
minor_version=0)
class HideCursor(rq.Request):
_request = rq.Struct(rq.Card8('opcode'),
rq.Opcode(29),
rq.RequestLength(),
rq.Window('window')
)
def hide_cursor(self):
HideCursor(display=self.display,
opcode=self.display.get_extension_major(extname),
window=self)
class ShowCursor(rq.Request):
_request = rq.Struct(rq.Card8('opcode'),
rq.Opcode(30),
rq.RequestLength(),
rq.Window('window')
)
def | (self):
ShowCursor(display=self.display,
opcode=self.display.get_extension_major(extname),
window=self)
def init(disp, info):
disp.extension_add_method('display', 'xfixes_query_version', query_version)
disp.extension_add_method('window', 'xfixes_hide_cursor', hide_cursor)
disp.extension_add_method('window', 'xfixes_show_cursor', show_cursor)
| show_cursor | identifier_name |
xfixes.py | # Xlib.ext.xfixes -- XFIXES extension module
#
# Copyright (C) 2010-2011 Outpost Embedded, LLC
# Forest Bond <forest.bond@rapidrollout.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place,
# Suite 330,
# Boston, MA 02111-1307 USA
'''
A partial implementation of the XFIXES extension. Only the HideCursor and
ShowCursor requests are provided.
'''
from Xlib.protocol import rq
extname = 'XFIXES'
class QueryVersion(rq.ReplyRequest):
_request = rq.Struct(rq.Card8('opcode'),
rq.Opcode(0),
rq.RequestLength(),
rq.Card32('major_version'),
rq.Card32('minor_version')
)
_reply = rq.Struct(rq.ReplyCode(),
rq.Pad(1),
rq.Card16('sequence_number'),
rq.ReplyLength(),
rq.Card32('major_version'),
rq.Card32('minor_version'),
rq.Pad(16)
)
def query_version(self):
|
class HideCursor(rq.Request):
_request = rq.Struct(rq.Card8('opcode'),
rq.Opcode(29),
rq.RequestLength(),
rq.Window('window')
)
def hide_cursor(self):
HideCursor(display=self.display,
opcode=self.display.get_extension_major(extname),
window=self)
class ShowCursor(rq.Request):
_request = rq.Struct(rq.Card8('opcode'),
rq.Opcode(30),
rq.RequestLength(),
rq.Window('window')
)
def show_cursor(self):
ShowCursor(display=self.display,
opcode=self.display.get_extension_major(extname),
window=self)
def init(disp, info):
disp.extension_add_method('display', 'xfixes_query_version', query_version)
disp.extension_add_method('window', 'xfixes_hide_cursor', hide_cursor)
disp.extension_add_method('window', 'xfixes_show_cursor', show_cursor)
| return QueryVersion(display=self.display,
opcode=self.display.get_extension_major(extname),
major_version=4,
minor_version=0) | identifier_body |
CrawlChart.js | import React from 'react';
import PropTypes from 'prop-types';
import _get from 'lodash.get';
import _words from 'lodash.words';
import { VictoryAxis,
VictoryBar,
VictoryChart,
VictoryTheme } from 'victory'; | export class CrawlChart extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{movie: 1, word_count: 0},
{movie: 2, word_count: 0},
{movie: 3, word_count: 0},
{movie: 4, word_count: 0},
{movie: 5, word_count: 0},
{movie: 6, word_count: 0},
{movie: 7, word_count: 0}
]
};
}
componentWillReceiveProps(nextProps) {
let movieCrawls = nextProps.movies.map((m) => _get(m, 'opening_crawl', ''));
let newState = {
data: movieCrawls.map((c, i) => { return { movie: i+1, word_count: _words(c).length}; })
};
this.setState(newState);
}
render() {
return (
<div>
<h3>Opening Crawl Word Count</h3>
<VictoryChart
// adding the material theme provided with Victory
animate={{duration: 500}}
theme={VictoryTheme.material}
domainPadding={20}
>
<VictoryAxis
tickFormat={['Ep 1', 'Ep 2', 'Ep 3', 'Ep 4', 'Ep 5', 'Ep 6', 'Ep 7']}
tickValues={[1, 2, 3, 4, 5, 6, 7]}
/>
<VictoryAxis
dependentAxis
domain={[0, 100]}
tickFormat={(x) => (`${x}`)}
/>
<VictoryBar
data={this.state.data}
style={{
data: {fill: '#fe9901', width:12}
}}
labels={(d) => `${Math.ceil(d.y)}`}
x="movie"
y="word_count"
/>
</VictoryChart>
</div>
);
}
}
CrawlChart.propTypes = {
movies: PropTypes.arrayOf(
PropTypes.shape({
opening_crawl: PropTypes.string.isRequired,
title: PropTypes.string
})
)
}; | random_line_split | |
CrawlChart.js | import React from 'react';
import PropTypes from 'prop-types';
import _get from 'lodash.get';
import _words from 'lodash.words';
import { VictoryAxis,
VictoryBar,
VictoryChart,
VictoryTheme } from 'victory';
export class CrawlChart extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{movie: 1, word_count: 0},
{movie: 2, word_count: 0},
{movie: 3, word_count: 0},
{movie: 4, word_count: 0},
{movie: 5, word_count: 0},
{movie: 6, word_count: 0},
{movie: 7, word_count: 0}
]
};
}
componentWillReceiveProps(nextProps) |
render() {
return (
<div>
<h3>Opening Crawl Word Count</h3>
<VictoryChart
// adding the material theme provided with Victory
animate={{duration: 500}}
theme={VictoryTheme.material}
domainPadding={20}
>
<VictoryAxis
tickFormat={['Ep 1', 'Ep 2', 'Ep 3', 'Ep 4', 'Ep 5', 'Ep 6', 'Ep 7']}
tickValues={[1, 2, 3, 4, 5, 6, 7]}
/>
<VictoryAxis
dependentAxis
domain={[0, 100]}
tickFormat={(x) => (`${x}`)}
/>
<VictoryBar
data={this.state.data}
style={{
data: {fill: '#fe9901', width:12}
}}
labels={(d) => `${Math.ceil(d.y)}`}
x="movie"
y="word_count"
/>
</VictoryChart>
</div>
);
}
}
CrawlChart.propTypes = {
movies: PropTypes.arrayOf(
PropTypes.shape({
opening_crawl: PropTypes.string.isRequired,
title: PropTypes.string
})
)
}; | {
let movieCrawls = nextProps.movies.map((m) => _get(m, 'opening_crawl', ''));
let newState = {
data: movieCrawls.map((c, i) => { return { movie: i+1, word_count: _words(c).length}; })
};
this.setState(newState);
} | identifier_body |
CrawlChart.js | import React from 'react';
import PropTypes from 'prop-types';
import _get from 'lodash.get';
import _words from 'lodash.words';
import { VictoryAxis,
VictoryBar,
VictoryChart,
VictoryTheme } from 'victory';
export class CrawlChart extends React.Component {
| (props) {
super(props);
this.state = {
data: [
{movie: 1, word_count: 0},
{movie: 2, word_count: 0},
{movie: 3, word_count: 0},
{movie: 4, word_count: 0},
{movie: 5, word_count: 0},
{movie: 6, word_count: 0},
{movie: 7, word_count: 0}
]
};
}
componentWillReceiveProps(nextProps) {
let movieCrawls = nextProps.movies.map((m) => _get(m, 'opening_crawl', ''));
let newState = {
data: movieCrawls.map((c, i) => { return { movie: i+1, word_count: _words(c).length}; })
};
this.setState(newState);
}
render() {
return (
<div>
<h3>Opening Crawl Word Count</h3>
<VictoryChart
// adding the material theme provided with Victory
animate={{duration: 500}}
theme={VictoryTheme.material}
domainPadding={20}
>
<VictoryAxis
tickFormat={['Ep 1', 'Ep 2', 'Ep 3', 'Ep 4', 'Ep 5', 'Ep 6', 'Ep 7']}
tickValues={[1, 2, 3, 4, 5, 6, 7]}
/>
<VictoryAxis
dependentAxis
domain={[0, 100]}
tickFormat={(x) => (`${x}`)}
/>
<VictoryBar
data={this.state.data}
style={{
data: {fill: '#fe9901', width:12}
}}
labels={(d) => `${Math.ceil(d.y)}`}
x="movie"
y="word_count"
/>
</VictoryChart>
</div>
);
}
}
CrawlChart.propTypes = {
movies: PropTypes.arrayOf(
PropTypes.shape({
opening_crawl: PropTypes.string.isRequired,
title: PropTypes.string
})
)
}; | constructor | identifier_name |
animations.rs | //! Animation effects embedded in the game world.
use crate::{location::Location, world::World};
use calx::{ease, project, CellSpace, ProjectVec, Space};
use calx_ecs::Entity;
use euclid::{vec2, Vector2D, Vector3D};
use serde::{Deserialize, Serialize};
/// Location with a non-integer offset delta.
///
/// Use for tweened animations.
#[derive(Copy, Clone, PartialEq, Debug, Default)]
pub struct LerpLocation {
pub location: Location,
pub offset: PhysicsVector,
}
impl From<Location> for LerpLocation {
fn from(location: Location) -> LerpLocation {
LerpLocation {
location,
offset: Default::default(),
}
}
}
impl World {
pub fn get_anim_tick(&self) -> u64 { self.flags.anim_tick }
pub fn anim(&self, e: Entity) -> Option<&Anim> { self.ecs.anim.get(e) }
pub(crate) fn anim_mut(&mut self, e: Entity) -> Option<&mut Anim> { self.ecs.anim.get_mut(e) }
/// Advance animations without ticking the world logic.
///
/// Use this when waiting for player input to finish pending animations.
pub fn tick_anims(&mut self) { self.flags.anim_tick += 1; }
/// Return whether entity is a transient effect.
pub fn is_fx(&self, e: Entity) -> bool {
self.anim(e)
.map_or(false, |a| a.state.is_transient_anim_state())
}
/// Return a location structure that includes the entity's animation displacement
pub fn | (&self, e: Entity) -> Option<LerpLocation> {
if let Some(location) = self.location(e) {
Some(LerpLocation {
location,
offset: self.lerp_offset(e),
})
} else {
None
}
}
pub fn lerp_offset(&self, e: Entity) -> PhysicsVector {
if let Some(location) = self.location(e) {
if let Some(anim) = self.anim(e) {
let frame = (self.get_anim_tick() - anim.tween_start) as u32;
if frame < anim.tween_duration {
if let Some(vec) = location.v2_at(anim.tween_from) {
let offset = vec.project::<PhysicsSpace>().to_3d();
let scalar = frame as f32 / anim.tween_duration as f32;
let scalar = ease::cubic_in_out(1.0 - scalar);
return offset * scalar;
}
}
}
}
Default::default()
}
}
/// Entity animation state.
#[derive(Clone, Debug, Eq, PartialEq, Default, Serialize, Deserialize)]
pub struct Anim {
pub tween_from: Location,
/// Anim_tick when tweening started
pub tween_start: u64,
/// How many frames does the tweening take
pub tween_duration: u32,
/// Anim_tick when the animation started
pub anim_start: u64,
/// World tick when anim should be cleaned up.
///
/// NB: Both entity creation and destruction must use world logic and world clock, not the
/// undeterministic animation clock. Deleting entities at unspecified time points through
/// animation logic can inject indeterminism in world progress.
pub anim_done_world_tick: Option<u64>,
pub state: AnimState,
}
#[derive(Eq, PartialEq, Copy, Clone, Debug, Serialize, Deserialize)]
pub enum AnimState {
/// Mob decorator, doing nothing in particular
Mob,
/// Show mob hurt animation
MobHurt,
/// Show mob blocking autoexplore animation
MobBlocks,
/// A death gib
Gib,
/// Puff of smoke
Smoke,
/// Single-cell explosion
Explosion,
/// Pre-exploded fireball
Firespell,
}
impl AnimState {
/// This is a state that belongs to an animation that gets removed, not a status marker for a
/// permanent entity.
pub fn is_transient_anim_state(self) -> bool {
use AnimState::*;
match self {
Mob | MobHurt | MobBlocks => false,
Gib | Smoke | Explosion | Firespell => true,
}
}
}
impl Default for AnimState {
fn default() -> Self { AnimState::Mob }
}
/// 3D physics space, used for eg. lighting.
pub struct PhysicsSpace;
impl Space for PhysicsSpace {
type T = f32;
}
// | 1 -1 |
// | -1/2 -1/2 |
// NB: Produces a 2D PhysicsSpace vector, you need to 3d-ify it manually.
impl project::From<CellSpace> for PhysicsSpace {
fn vec_from(vec: Vector2D<<CellSpace as Space>::T, CellSpace>) -> Vector2D<Self::T, Self> {
let vec = vec.cast::<f32>();
vec2(vec.x - vec.y, -vec.x / 2.0 - vec.y / 2.0)
}
}
// | 1/2 -1 |
// | -1/2 -1 |
impl project::From32<PhysicsSpace> for CellSpace {
fn vec_from(
vec: Vector3D<<PhysicsSpace as Space>::T, PhysicsSpace>,
) -> Vector2D<Self::T, Self> {
vec2(
(vec.x / 2.0 - vec.y).round() as i32,
(-vec.x / 2.0 - vec.y).round() as i32,
)
}
}
pub type PhysicsVector = Vector3D<f32, PhysicsSpace>;
| lerp_location | identifier_name |
animations.rs | use euclid::{vec2, Vector2D, Vector3D};
use serde::{Deserialize, Serialize};
/// Location with a non-integer offset delta.
///
/// Use for tweened animations.
#[derive(Copy, Clone, PartialEq, Debug, Default)]
pub struct LerpLocation {
pub location: Location,
pub offset: PhysicsVector,
}
impl From<Location> for LerpLocation {
fn from(location: Location) -> LerpLocation {
LerpLocation {
location,
offset: Default::default(),
}
}
}
impl World {
pub fn get_anim_tick(&self) -> u64 { self.flags.anim_tick }
pub fn anim(&self, e: Entity) -> Option<&Anim> { self.ecs.anim.get(e) }
pub(crate) fn anim_mut(&mut self, e: Entity) -> Option<&mut Anim> { self.ecs.anim.get_mut(e) }
/// Advance animations without ticking the world logic.
///
/// Use this when waiting for player input to finish pending animations.
pub fn tick_anims(&mut self) { self.flags.anim_tick += 1; }
/// Return whether entity is a transient effect.
pub fn is_fx(&self, e: Entity) -> bool {
self.anim(e)
.map_or(false, |a| a.state.is_transient_anim_state())
}
/// Return a location structure that includes the entity's animation displacement
pub fn lerp_location(&self, e: Entity) -> Option<LerpLocation> {
if let Some(location) = self.location(e) {
Some(LerpLocation {
location,
offset: self.lerp_offset(e),
})
} else {
None
}
}
pub fn lerp_offset(&self, e: Entity) -> PhysicsVector {
if let Some(location) = self.location(e) {
if let Some(anim) = self.anim(e) {
let frame = (self.get_anim_tick() - anim.tween_start) as u32;
if frame < anim.tween_duration {
if let Some(vec) = location.v2_at(anim.tween_from) {
let offset = vec.project::<PhysicsSpace>().to_3d();
let scalar = frame as f32 / anim.tween_duration as f32;
let scalar = ease::cubic_in_out(1.0 - scalar);
return offset * scalar;
}
}
}
}
Default::default()
}
}
/// Entity animation state.
#[derive(Clone, Debug, Eq, PartialEq, Default, Serialize, Deserialize)]
pub struct Anim {
pub tween_from: Location,
/// Anim_tick when tweening started
pub tween_start: u64,
/// How many frames does the tweening take
pub tween_duration: u32,
/// Anim_tick when the animation started
pub anim_start: u64,
/// World tick when anim should be cleaned up.
///
/// NB: Both entity creation and destruction must use world logic and world clock, not the
/// undeterministic animation clock. Deleting entities at unspecified time points through
/// animation logic can inject indeterminism in world progress.
pub anim_done_world_tick: Option<u64>,
pub state: AnimState,
}
#[derive(Eq, PartialEq, Copy, Clone, Debug, Serialize, Deserialize)]
pub enum AnimState {
/// Mob decorator, doing nothing in particular
Mob,
/// Show mob hurt animation
MobHurt,
/// Show mob blocking autoexplore animation
MobBlocks,
/// A death gib
Gib,
/// Puff of smoke
Smoke,
/// Single-cell explosion
Explosion,
/// Pre-exploded fireball
Firespell,
}
impl AnimState {
/// This is a state that belongs to an animation that gets removed, not a status marker for a
/// permanent entity.
pub fn is_transient_anim_state(self) -> bool {
use AnimState::*;
match self {
Mob | MobHurt | MobBlocks => false,
Gib | Smoke | Explosion | Firespell => true,
}
}
}
impl Default for AnimState {
fn default() -> Self { AnimState::Mob }
}
/// 3D physics space, used for eg. lighting.
pub struct PhysicsSpace;
impl Space for PhysicsSpace {
type T = f32;
}
// | 1 -1 |
// | -1/2 -1/2 |
// NB: Produces a 2D PhysicsSpace vector, you need to 3d-ify it manually.
impl project::From<CellSpace> for PhysicsSpace {
fn vec_from(vec: Vector2D<<CellSpace as Space>::T, CellSpace>) -> Vector2D<Self::T, Self> {
let vec = vec.cast::<f32>();
vec2(vec.x - vec.y, -vec.x / 2.0 - vec.y / 2.0)
}
}
// | 1/2 -1 |
// | -1/2 -1 |
impl project::From32<PhysicsSpace> for CellSpace {
fn vec_from(
vec: Vector3D<<PhysicsSpace as Space>::T, PhysicsSpace>,
) -> Vector2D<Self::T, Self> {
vec2(
(vec.x / 2.0 - vec.y).round() as i32,
(-vec.x / 2.0 - vec.y).round() as i32,
)
}
}
pub type PhysicsVector = Vector3D<f32, PhysicsSpace>; | //! Animation effects embedded in the game world.
use crate::{location::Location, world::World};
use calx::{ease, project, CellSpace, ProjectVec, Space};
use calx_ecs::Entity; | random_line_split | |
animations.rs | //! Animation effects embedded in the game world.
use crate::{location::Location, world::World};
use calx::{ease, project, CellSpace, ProjectVec, Space};
use calx_ecs::Entity;
use euclid::{vec2, Vector2D, Vector3D};
use serde::{Deserialize, Serialize};
/// Location with a non-integer offset delta.
///
/// Use for tweened animations.
#[derive(Copy, Clone, PartialEq, Debug, Default)]
pub struct LerpLocation {
pub location: Location,
pub offset: PhysicsVector,
}
impl From<Location> for LerpLocation {
fn from(location: Location) -> LerpLocation {
LerpLocation {
location,
offset: Default::default(),
}
}
}
impl World {
pub fn get_anim_tick(&self) -> u64 { self.flags.anim_tick }
pub fn anim(&self, e: Entity) -> Option<&Anim> { self.ecs.anim.get(e) }
pub(crate) fn anim_mut(&mut self, e: Entity) -> Option<&mut Anim> { self.ecs.anim.get_mut(e) }
/// Advance animations without ticking the world logic.
///
/// Use this when waiting for player input to finish pending animations.
pub fn tick_anims(&mut self) { self.flags.anim_tick += 1; }
/// Return whether entity is a transient effect.
pub fn is_fx(&self, e: Entity) -> bool {
self.anim(e)
.map_or(false, |a| a.state.is_transient_anim_state())
}
/// Return a location structure that includes the entity's animation displacement
pub fn lerp_location(&self, e: Entity) -> Option<LerpLocation> {
if let Some(location) = self.location(e) {
Some(LerpLocation {
location,
offset: self.lerp_offset(e),
})
} else |
}
pub fn lerp_offset(&self, e: Entity) -> PhysicsVector {
if let Some(location) = self.location(e) {
if let Some(anim) = self.anim(e) {
let frame = (self.get_anim_tick() - anim.tween_start) as u32;
if frame < anim.tween_duration {
if let Some(vec) = location.v2_at(anim.tween_from) {
let offset = vec.project::<PhysicsSpace>().to_3d();
let scalar = frame as f32 / anim.tween_duration as f32;
let scalar = ease::cubic_in_out(1.0 - scalar);
return offset * scalar;
}
}
}
}
Default::default()
}
}
/// Entity animation state.
#[derive(Clone, Debug, Eq, PartialEq, Default, Serialize, Deserialize)]
pub struct Anim {
pub tween_from: Location,
/// Anim_tick when tweening started
pub tween_start: u64,
/// How many frames does the tweening take
pub tween_duration: u32,
/// Anim_tick when the animation started
pub anim_start: u64,
/// World tick when anim should be cleaned up.
///
/// NB: Both entity creation and destruction must use world logic and world clock, not the
/// undeterministic animation clock. Deleting entities at unspecified time points through
/// animation logic can inject indeterminism in world progress.
pub anim_done_world_tick: Option<u64>,
pub state: AnimState,
}
#[derive(Eq, PartialEq, Copy, Clone, Debug, Serialize, Deserialize)]
pub enum AnimState {
/// Mob decorator, doing nothing in particular
Mob,
/// Show mob hurt animation
MobHurt,
/// Show mob blocking autoexplore animation
MobBlocks,
/// A death gib
Gib,
/// Puff of smoke
Smoke,
/// Single-cell explosion
Explosion,
/// Pre-exploded fireball
Firespell,
}
impl AnimState {
/// This is a state that belongs to an animation that gets removed, not a status marker for a
/// permanent entity.
pub fn is_transient_anim_state(self) -> bool {
use AnimState::*;
match self {
Mob | MobHurt | MobBlocks => false,
Gib | Smoke | Explosion | Firespell => true,
}
}
}
impl Default for AnimState {
fn default() -> Self { AnimState::Mob }
}
/// 3D physics space, used for eg. lighting.
pub struct PhysicsSpace;
impl Space for PhysicsSpace {
type T = f32;
}
// | 1 -1 |
// | -1/2 -1/2 |
// NB: Produces a 2D PhysicsSpace vector, you need to 3d-ify it manually.
impl project::From<CellSpace> for PhysicsSpace {
fn vec_from(vec: Vector2D<<CellSpace as Space>::T, CellSpace>) -> Vector2D<Self::T, Self> {
let vec = vec.cast::<f32>();
vec2(vec.x - vec.y, -vec.x / 2.0 - vec.y / 2.0)
}
}
// | 1/2 -1 |
// | -1/2 -1 |
impl project::From32<PhysicsSpace> for CellSpace {
fn vec_from(
vec: Vector3D<<PhysicsSpace as Space>::T, PhysicsSpace>,
) -> Vector2D<Self::T, Self> {
vec2(
(vec.x / 2.0 - vec.y).round() as i32,
(-vec.x / 2.0 - vec.y).round() as i32,
)
}
}
pub type PhysicsVector = Vector3D<f32, PhysicsSpace>;
| {
None
} | conditional_block |
window.js | var WINDOW = { | ms_Callbacks: {
70: "WINDOW.toggleFullScreen()" // Toggle fullscreen
},
initialize: function initialize() {
this.updateSize();
// Create callbacks from keyboard
$(document).keydown(function(inEvent) { WINDOW.callAction(inEvent.keyCode); }) ;
$(window).resize(function(inEvent) {
WINDOW.updateSize();
WINDOW.resizeCallback(WINDOW.ms_Width, WINDOW.ms_Height);
});
},
updateSize: function updateSize() {
this.ms_Width = $(window).width();
this.ms_Height = $(window).height() - 4;
},
callAction: function callAction(inId) {
if(inId in this.ms_Callbacks) {
eval(this.ms_Callbacks[inId]);
return false ;
}
},
toggleFullScreen: function toggleFullScreen() {
if(!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement) {
if(document.documentElement.requestFullscreen)
document.documentElement.requestFullscreen();
else if(document.documentElement.mozRequestFullScreen)
document.documentElement.mozRequestFullScreen();
else if(document.documentElement.webkitRequestFullscreen)
document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
}
else {
if(document.cancelFullScreen)
document.cancelFullScreen();
else if(document.mozCancelFullScreen)
document.mozCancelFullScreen();
else if (document.webkitCancelFullScreen)
document.webkitCancelFullScreen();
}
},
resizeCallback: function resizeCallback(inWidth, inHeight) {}
}; | ms_Width: 0,
ms_Height: 0, | random_line_split |
window.js | var WINDOW = {
ms_Width: 0,
ms_Height: 0,
ms_Callbacks: {
70: "WINDOW.toggleFullScreen()" // Toggle fullscreen
},
initialize: function initialize() {
this.updateSize();
// Create callbacks from keyboard
$(document).keydown(function(inEvent) { WINDOW.callAction(inEvent.keyCode); }) ;
$(window).resize(function(inEvent) {
WINDOW.updateSize();
WINDOW.resizeCallback(WINDOW.ms_Width, WINDOW.ms_Height);
});
},
updateSize: function updateSize() {
this.ms_Width = $(window).width();
this.ms_Height = $(window).height() - 4;
},
callAction: function callAction(inId) {
if(inId in this.ms_Callbacks) |
},
toggleFullScreen: function toggleFullScreen() {
if(!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement) {
if(document.documentElement.requestFullscreen)
document.documentElement.requestFullscreen();
else if(document.documentElement.mozRequestFullScreen)
document.documentElement.mozRequestFullScreen();
else if(document.documentElement.webkitRequestFullscreen)
document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
}
else {
if(document.cancelFullScreen)
document.cancelFullScreen();
else if(document.mozCancelFullScreen)
document.mozCancelFullScreen();
else if (document.webkitCancelFullScreen)
document.webkitCancelFullScreen();
}
},
resizeCallback: function resizeCallback(inWidth, inHeight) {}
}; | {
eval(this.ms_Callbacks[inId]);
return false ;
} | conditional_block |
test.py | from trie import Trie
#constructs a tree of this shape ('*' means root)
#
# *
# /|\
# a i o
# / /|\
# n f n u
# | |\
# e r t
#
#The LOUDS bit-string is then
#[1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0]
words = ['an', 'i', 'of', 'one', 'our', 'out']
test_set = {
'out': 11, #'t' in 'out' is at 11th node in the tree
'our': 10, #'r' in 'our' is at 10th node in the tree
'of': 6,
'i': 3,
'an': 5,
'one': 9,
'ant': None #'ant' is not in the tree
}
trie = Trie(words)
for query, answer in test_set.items():
|
##parent [0, 0, 1, 1, 1, 1, 2, 2, 3, 4, 4, 4, 4, 5, 6, 7, 7, 8, 8, 8, 9, 0, 1]
##bit_array [1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0]
##child [1, -, 2, 3, 4, -, 5, -, -, 6, 7, 8, -, -, -, 9, -, 0, 1, -, -, -, -]
##index [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2]
#labels ['', '', 'a', 'i', 'o', 'n', 'f', 'n', 'u', 'e', 'r', 't']
##index [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]
| result = trie.search(query)
print("query: {!s:>5} result: {!s:>5} answer: {!s:>5}".format(
query, result, answer)) | conditional_block |
test.py | #
# *
# /|\
# a i o
# / /|\
# n f n u
# | |\
# e r t
#
#The LOUDS bit-string is then
#[1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0]
words = ['an', 'i', 'of', 'one', 'our', 'out']
test_set = {
'out': 11, #'t' in 'out' is at 11th node in the tree
'our': 10, #'r' in 'our' is at 10th node in the tree
'of': 6,
'i': 3,
'an': 5,
'one': 9,
'ant': None #'ant' is not in the tree
}
trie = Trie(words)
for query, answer in test_set.items():
result = trie.search(query)
print("query: {!s:>5} result: {!s:>5} answer: {!s:>5}".format(
query, result, answer))
##parent [0, 0, 1, 1, 1, 1, 2, 2, 3, 4, 4, 4, 4, 5, 6, 7, 7, 8, 8, 8, 9, 0, 1]
##bit_array [1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0]
##child [1, -, 2, 3, 4, -, 5, -, -, 6, 7, 8, -, -, -, 9, -, 0, 1, -, -, -, -]
##index [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2]
#labels ['', '', 'a', 'i', 'o', 'n', 'f', 'n', 'u', 'e', 'r', 't']
##index [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1] | from trie import Trie
#constructs a tree of this shape ('*' means root) | random_line_split | |
prod_setting.py | ###########################################################
#
# Copyright (c) 2005, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permission.
#
#
#
__all__ = ['ProdSetting']
from pyasm.common import Container, TacticException
from pyasm.search import *
from pyasm.biz import Project
class | (SObject):
'''Defines all of the settings for a given production'''
SEARCH_TYPE = "config/prod_setting"
# FIXME: what is this for?
def get_app_tabs(my):
'''This controls what tabs are visible'''
return ["3D Asset", "Checkin", "Sets", "Anim Loader", "Anim Checkin", "Layer Loader", "Layer Checkin", "Shot"]
def _get_container_key(cls, key, search_type=None):
if search_type:
key = "ProdSetting:%s:%s" % (key, search_type)
else:
key = "ProdSetting:%s" % key
return key
_get_container_key = classmethod(_get_container_key)
def get_value_by_key(cls, key, search_type=None):
'''
container_key = cls._get_container_key(key,search_type)
value = Container.get(container_key)
if value:
return value
'''
if Project.get_project_name() in ['sthpw', 'admin']:
return ''
prod_setting = cls.get_by_key(key, search_type)
value = ''
if prod_setting:
value = prod_setting.get_value("value")
return value
get_value_by_key = classmethod(get_value_by_key)
def get_by_key(cls, key, search_type=None):
dict_key = '%s:%s' %(key, search_type)
search = Search(cls.SEARCH_TYPE)
search.add_filter("key", key)
if search_type:
search.add_filter("search_type", search_type)
if Project.get_project_name() in ['admin', 'sthpw']:
return None
prod_setting = ProdSetting.get_by_search(search, dict_key)
return prod_setting
get_by_key = classmethod(get_by_key)
def get_seq_by_key(cls, key, search_type=None):
seq = []
value = cls.get_value_by_key(key, search_type)
if value:
seq = value.split("|")
return seq
get_seq_by_key = classmethod(get_seq_by_key)
def add_value_by_key(cls, key, value, search_type=None):
seq = cls.get_seq_by_key(key, search_type)
if not seq:
seq = []
elif value in seq:
return
seq.append(value)
setting = cls.get_by_key(key, search_type)
if not setting:
return
setting.set_value( "value", "|".join(seq) )
setting.commit()
container_key = cls._get_container_key(key,search_type)
value = Container.put(container_key, None)
add_value_by_key = classmethod(add_value_by_key)
def get_map_by_key(cls, key, search_type=None):
''' this is more like an ordered map'''
seq = []
map = []
value = cls.get_value_by_key(key, search_type)
if value:
seq = value.split("|")
for item in seq:
try:
key, value = item.split(':')
map.append((key, value))
except Exception, e:
raise TacticException('ProdSettings should be formated like <key1>:<value1>|<key2>:<value2>|...')
return map
get_map_by_key = classmethod(get_map_by_key)
def get_dict_by_key(cls, key, search_type=None):
''' this is to retrieve an unordered dict'''
seq = []
dict = {}
value = cls.get_value_by_key(key, search_type)
if value:
seq = value.split("|")
for item in seq:
try:
key, value = item.split(':')
dict[key] = value
except Exception, e:
raise TacticException('ProdSettings should be formated like <key1>:<value1>|<key2>:<value2>|...')
return dict
get_dict_by_key = classmethod(get_dict_by_key)
def create(key, value, type, description='', search_type=''):
'''create a ProdSetting'''
if Project.get_project_name() in ['admin', 'sthpw']:
return None
ProdSetting.clear_cache()
setting = ProdSetting.get_by_key(key, search_type)
if not setting:
setting= SObjectFactory.create( ProdSetting.SEARCH_TYPE )
setting.set_value("key", key)
setting.set_value("value", value)
setting.set_value("type", type)
if description:
setting.set_value("description", description)
if search_type:
setting.set_value("search_type", search_type)
else:
setting.set_value("value", value)
setting.commit()
return setting
create = staticmethod(create)
| ProdSetting | identifier_name |
prod_setting.py | ###########################################################
#
# Copyright (c) 2005, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permission.
#
#
#
__all__ = ['ProdSetting']
from pyasm.common import Container, TacticException
from pyasm.search import *
from pyasm.biz import Project
class ProdSetting(SObject):
'''Defines all of the settings for a given production'''
SEARCH_TYPE = "config/prod_setting"
# FIXME: what is this for?
def get_app_tabs(my):
'''This controls what tabs are visible'''
return ["3D Asset", "Checkin", "Sets", "Anim Loader", "Anim Checkin", "Layer Loader", "Layer Checkin", "Shot"]
def _get_container_key(cls, key, search_type=None):
if search_type:
key = "ProdSetting:%s:%s" % (key, search_type)
else:
key = "ProdSetting:%s" % key
return key
_get_container_key = classmethod(_get_container_key)
def get_value_by_key(cls, key, search_type=None):
'''
container_key = cls._get_container_key(key,search_type)
value = Container.get(container_key)
if value:
return value
'''
if Project.get_project_name() in ['sthpw', 'admin']:
return ''
prod_setting = cls.get_by_key(key, search_type)
value = ''
if prod_setting:
value = prod_setting.get_value("value")
return value
get_value_by_key = classmethod(get_value_by_key)
def get_by_key(cls, key, search_type=None):
dict_key = '%s:%s' %(key, search_type)
search = Search(cls.SEARCH_TYPE)
search.add_filter("key", key)
if search_type:
search.add_filter("search_type", search_type)
if Project.get_project_name() in ['admin', 'sthpw']:
return None
prod_setting = ProdSetting.get_by_search(search, dict_key)
return prod_setting
get_by_key = classmethod(get_by_key)
def get_seq_by_key(cls, key, search_type=None):
seq = []
value = cls.get_value_by_key(key, search_type)
if value:
seq = value.split("|")
return seq
get_seq_by_key = classmethod(get_seq_by_key)
def add_value_by_key(cls, key, value, search_type=None):
seq = cls.get_seq_by_key(key, search_type)
if not seq:
seq = []
elif value in seq:
return
seq.append(value)
setting = cls.get_by_key(key, search_type)
if not setting:
return
setting.set_value( "value", "|".join(seq) )
setting.commit()
container_key = cls._get_container_key(key,search_type)
value = Container.put(container_key, None)
add_value_by_key = classmethod(add_value_by_key)
def get_map_by_key(cls, key, search_type=None):
''' this is more like an ordered map'''
seq = []
map = []
value = cls.get_value_by_key(key, search_type)
if value:
seq = value.split("|")
for item in seq:
try:
key, value = item.split(':')
map.append((key, value))
except Exception, e:
raise TacticException('ProdSettings should be formated like <key1>:<value1>|<key2>:<value2>|...')
return map
get_map_by_key = classmethod(get_map_by_key)
def get_dict_by_key(cls, key, search_type=None):
''' this is to retrieve an unordered dict'''
seq = []
dict = {}
value = cls.get_value_by_key(key, search_type)
if value:
seq = value.split("|")
for item in seq:
try:
key, value = item.split(':')
dict[key] = value
except Exception, e:
raise TacticException('ProdSettings should be formated like <key1>:<value1>|<key2>:<value2>|...')
return dict
get_dict_by_key = classmethod(get_dict_by_key)
def create(key, value, type, description='', search_type=''):
'''create a ProdSetting'''
if Project.get_project_name() in ['admin', 'sthpw']:
|
ProdSetting.clear_cache()
setting = ProdSetting.get_by_key(key, search_type)
if not setting:
setting= SObjectFactory.create( ProdSetting.SEARCH_TYPE )
setting.set_value("key", key)
setting.set_value("value", value)
setting.set_value("type", type)
if description:
setting.set_value("description", description)
if search_type:
setting.set_value("search_type", search_type)
else:
setting.set_value("value", value)
setting.commit()
return setting
create = staticmethod(create)
| return None | conditional_block |
prod_setting.py | ###########################################################
#
# Copyright (c) 2005, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permission.
#
#
#
__all__ = ['ProdSetting']
from pyasm.common import Container, TacticException
from pyasm.search import *
from pyasm.biz import Project
class ProdSetting(SObject):
| '''Defines all of the settings for a given production'''
SEARCH_TYPE = "config/prod_setting"
# FIXME: what is this for?
def get_app_tabs(my):
'''This controls what tabs are visible'''
return ["3D Asset", "Checkin", "Sets", "Anim Loader", "Anim Checkin", "Layer Loader", "Layer Checkin", "Shot"]
def _get_container_key(cls, key, search_type=None):
if search_type:
key = "ProdSetting:%s:%s" % (key, search_type)
else:
key = "ProdSetting:%s" % key
return key
_get_container_key = classmethod(_get_container_key)
def get_value_by_key(cls, key, search_type=None):
'''
container_key = cls._get_container_key(key,search_type)
value = Container.get(container_key)
if value:
return value
'''
if Project.get_project_name() in ['sthpw', 'admin']:
return ''
prod_setting = cls.get_by_key(key, search_type)
value = ''
if prod_setting:
value = prod_setting.get_value("value")
return value
get_value_by_key = classmethod(get_value_by_key)
def get_by_key(cls, key, search_type=None):
dict_key = '%s:%s' %(key, search_type)
search = Search(cls.SEARCH_TYPE)
search.add_filter("key", key)
if search_type:
search.add_filter("search_type", search_type)
if Project.get_project_name() in ['admin', 'sthpw']:
return None
prod_setting = ProdSetting.get_by_search(search, dict_key)
return prod_setting
get_by_key = classmethod(get_by_key)
def get_seq_by_key(cls, key, search_type=None):
seq = []
value = cls.get_value_by_key(key, search_type)
if value:
seq = value.split("|")
return seq
get_seq_by_key = classmethod(get_seq_by_key)
def add_value_by_key(cls, key, value, search_type=None):
seq = cls.get_seq_by_key(key, search_type)
if not seq:
seq = []
elif value in seq:
return
seq.append(value)
setting = cls.get_by_key(key, search_type)
if not setting:
return
setting.set_value( "value", "|".join(seq) )
setting.commit()
container_key = cls._get_container_key(key,search_type)
value = Container.put(container_key, None)
add_value_by_key = classmethod(add_value_by_key)
def get_map_by_key(cls, key, search_type=None):
''' this is more like an ordered map'''
seq = []
map = []
value = cls.get_value_by_key(key, search_type)
if value:
seq = value.split("|")
for item in seq:
try:
key, value = item.split(':')
map.append((key, value))
except Exception, e:
raise TacticException('ProdSettings should be formated like <key1>:<value1>|<key2>:<value2>|...')
return map
get_map_by_key = classmethod(get_map_by_key)
def get_dict_by_key(cls, key, search_type=None):
''' this is to retrieve an unordered dict'''
seq = []
dict = {}
value = cls.get_value_by_key(key, search_type)
if value:
seq = value.split("|")
for item in seq:
try:
key, value = item.split(':')
dict[key] = value
except Exception, e:
raise TacticException('ProdSettings should be formated like <key1>:<value1>|<key2>:<value2>|...')
return dict
get_dict_by_key = classmethod(get_dict_by_key)
def create(key, value, type, description='', search_type=''):
'''create a ProdSetting'''
if Project.get_project_name() in ['admin', 'sthpw']:
return None
ProdSetting.clear_cache()
setting = ProdSetting.get_by_key(key, search_type)
if not setting:
setting= SObjectFactory.create( ProdSetting.SEARCH_TYPE )
setting.set_value("key", key)
setting.set_value("value", value)
setting.set_value("type", type)
if description:
setting.set_value("description", description)
if search_type:
setting.set_value("search_type", search_type)
else:
setting.set_value("value", value)
setting.commit()
return setting
create = staticmethod(create) | identifier_body | |
prod_setting.py | ###########################################################
#
# Copyright (c) 2005, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permission.
#
#
#
__all__ = ['ProdSetting']
from pyasm.common import Container, TacticException
from pyasm.search import *
from pyasm.biz import Project
class ProdSetting(SObject):
'''Defines all of the settings for a given production'''
SEARCH_TYPE = "config/prod_setting"
# FIXME: what is this for?
def get_app_tabs(my):
'''This controls what tabs are visible'''
return ["3D Asset", "Checkin", "Sets", "Anim Loader", "Anim Checkin", "Layer Loader", "Layer Checkin", "Shot"]
def _get_container_key(cls, key, search_type=None):
if search_type:
key = "ProdSetting:%s:%s" % (key, search_type)
else:
key = "ProdSetting:%s" % key
return key
_get_container_key = classmethod(_get_container_key)
def get_value_by_key(cls, key, search_type=None):
'''
container_key = cls._get_container_key(key,search_type)
value = Container.get(container_key)
if value:
return value
'''
if Project.get_project_name() in ['sthpw', 'admin']:
return ''
prod_setting = cls.get_by_key(key, search_type)
value = ''
if prod_setting:
value = prod_setting.get_value("value")
return value
get_value_by_key = classmethod(get_value_by_key)
def get_by_key(cls, key, search_type=None):
dict_key = '%s:%s' %(key, search_type)
search = Search(cls.SEARCH_TYPE)
search.add_filter("key", key)
if search_type:
search.add_filter("search_type", search_type)
if Project.get_project_name() in ['admin', 'sthpw']:
return None
prod_setting = ProdSetting.get_by_search(search, dict_key)
return prod_setting
get_by_key = classmethod(get_by_key)
def get_seq_by_key(cls, key, search_type=None):
seq = []
value = cls.get_value_by_key(key, search_type)
if value:
seq = value.split("|")
return seq
get_seq_by_key = classmethod(get_seq_by_key)
def add_value_by_key(cls, key, value, search_type=None):
seq = cls.get_seq_by_key(key, search_type)
if not seq:
seq = []
elif value in seq:
return
seq.append(value)
setting = cls.get_by_key(key, search_type)
if not setting:
return
setting.set_value( "value", "|".join(seq) )
setting.commit()
container_key = cls._get_container_key(key,search_type)
value = Container.put(container_key, None)
add_value_by_key = classmethod(add_value_by_key)
def get_map_by_key(cls, key, search_type=None):
''' this is more like an ordered map'''
seq = []
map = []
value = cls.get_value_by_key(key, search_type)
if value:
seq = value.split("|")
for item in seq:
try:
key, value = item.split(':')
map.append((key, value))
except Exception, e: |
def get_dict_by_key(cls, key, search_type=None):
''' this is to retrieve an unordered dict'''
seq = []
dict = {}
value = cls.get_value_by_key(key, search_type)
if value:
seq = value.split("|")
for item in seq:
try:
key, value = item.split(':')
dict[key] = value
except Exception, e:
raise TacticException('ProdSettings should be formated like <key1>:<value1>|<key2>:<value2>|...')
return dict
get_dict_by_key = classmethod(get_dict_by_key)
def create(key, value, type, description='', search_type=''):
'''create a ProdSetting'''
if Project.get_project_name() in ['admin', 'sthpw']:
return None
ProdSetting.clear_cache()
setting = ProdSetting.get_by_key(key, search_type)
if not setting:
setting= SObjectFactory.create( ProdSetting.SEARCH_TYPE )
setting.set_value("key", key)
setting.set_value("value", value)
setting.set_value("type", type)
if description:
setting.set_value("description", description)
if search_type:
setting.set_value("search_type", search_type)
else:
setting.set_value("value", value)
setting.commit()
return setting
create = staticmethod(create) | raise TacticException('ProdSettings should be formated like <key1>:<value1>|<key2>:<value2>|...')
return map
get_map_by_key = classmethod(get_map_by_key) | random_line_split |
components.ts | import { Reflection, Type } from "../models";
import type { Serializer } from "./serializer";
import type { ModelToObject } from "./schema";
/**
* Represents Serializer plugin component.
*
* Like {@link Converter} plugins each {@link Serializer} plugin defines a predicate that instructs if an
* object can be serialized by it, this is done dynamically at runtime via a `supports` method.
*
* Additionally, each {@link Serializer} plugin must define a predicate that instructs the group
* it belongs to.
*
* Serializers are grouped to improve performance when finding serializers that apply to a node,
* this makes it possible to skip the `supports` calls for `Type`s when searching for a
* `Reflection` and vise versa.
*/
export abstract class SerializerComponent<T> {
/**
* The priority this serializer should be executed with.
* A higher priority means the {@link Serializer} will be applied earlier.
*/
static PRIORITY = 0;
constructor(owner: Serializer) { | /**
* Set when the SerializerComponent is added to the serializer.
*/
protected owner: Serializer;
/**
* A high-level predicate filtering which group this serializer belongs to.
* This is a high-level filter before the {@link SerializerComponent.supports} predicate filter.
*
* For example, use the {@link Reflection} class class to group all reflection based serializers:
* ```typescript
* class ReflectionSerializer {
* serializeGroup(instance) { return instance instanceof Reflection }
* }
* ```
*
* Use the {@link Type} class to group all type based serializers:
* ```typescript
* class TypeSerializer {
* serializeGroup(instance) { return instance instanceof Type }
* }
* ```
*/
abstract serializeGroup(instance: unknown): boolean;
/**
* The priority this serializer should be executed with.
* A higher priority means the {@link Serializer} will be applied earlier.
*/
get priority(): number {
return (
(this.constructor as typeof SerializerComponent)["PRIORITY"] ||
SerializerComponent.PRIORITY
);
}
abstract supports(item: unknown): boolean;
abstract toObject(item: T, obj?: object): Partial<ModelToObject<T>>;
}
export abstract class ReflectionSerializerComponent<
T extends Reflection
> extends SerializerComponent<T> {
/**
* Filter for instances of {@link Reflection}
*/
serializeGroup(instance: unknown): boolean {
return instance instanceof Reflection;
}
}
export abstract class TypeSerializerComponent<
T extends Type
> extends SerializerComponent<T> {
/**
* Filter for instances of {@link Type}
*/
serializeGroup(instance: unknown): boolean {
return instance instanceof Type;
}
} | this.owner = owner;
}
| random_line_split |
components.ts | import { Reflection, Type } from "../models";
import type { Serializer } from "./serializer";
import type { ModelToObject } from "./schema";
/**
* Represents Serializer plugin component.
*
* Like {@link Converter} plugins each {@link Serializer} plugin defines a predicate that instructs if an
* object can be serialized by it, this is done dynamically at runtime via a `supports` method.
*
* Additionally, each {@link Serializer} plugin must define a predicate that instructs the group
* it belongs to.
*
* Serializers are grouped to improve performance when finding serializers that apply to a node,
* this makes it possible to skip the `supports` calls for `Type`s when searching for a
* `Reflection` and vise versa.
*/
export abstract class SerializerComponent<T> {
/**
* The priority this serializer should be executed with.
* A higher priority means the {@link Serializer} will be applied earlier.
*/
static PRIORITY = 0;
constructor(owner: Serializer) {
this.owner = owner;
}
/**
* Set when the SerializerComponent is added to the serializer.
*/
protected owner: Serializer;
/**
* A high-level predicate filtering which group this serializer belongs to.
* This is a high-level filter before the {@link SerializerComponent.supports} predicate filter.
*
* For example, use the {@link Reflection} class class to group all reflection based serializers:
* ```typescript
* class ReflectionSerializer {
* serializeGroup(instance) { return instance instanceof Reflection }
* }
* ```
*
* Use the {@link Type} class to group all type based serializers:
* ```typescript
* class TypeSerializer {
* serializeGroup(instance) { return instance instanceof Type }
* }
* ```
*/
abstract serializeGroup(instance: unknown): boolean;
/**
* The priority this serializer should be executed with.
* A higher priority means the {@link Serializer} will be applied earlier.
*/
get priority(): number {
return (
(this.constructor as typeof SerializerComponent)["PRIORITY"] ||
SerializerComponent.PRIORITY
);
}
abstract supports(item: unknown): boolean;
abstract toObject(item: T, obj?: object): Partial<ModelToObject<T>>;
}
export abstract class ReflectionSerializerComponent<
T extends Reflection
> extends SerializerComponent<T> {
/**
* Filter for instances of {@link Reflection}
*/
serializeGroup(instance: unknown): boolean {
return instance instanceof Reflection;
}
}
export abstract class TypeSerializerComponent<
T extends Type
> extends SerializerComponent<T> {
/**
* Filter for instances of {@link Type}
*/
serializeGroup(instance: unknown): boolean |
}
| {
return instance instanceof Type;
} | identifier_body |
components.ts | import { Reflection, Type } from "../models";
import type { Serializer } from "./serializer";
import type { ModelToObject } from "./schema";
/**
* Represents Serializer plugin component.
*
* Like {@link Converter} plugins each {@link Serializer} plugin defines a predicate that instructs if an
* object can be serialized by it, this is done dynamically at runtime via a `supports` method.
*
* Additionally, each {@link Serializer} plugin must define a predicate that instructs the group
* it belongs to.
*
* Serializers are grouped to improve performance when finding serializers that apply to a node,
* this makes it possible to skip the `supports` calls for `Type`s when searching for a
* `Reflection` and vise versa.
*/
export abstract class SerializerComponent<T> {
/**
* The priority this serializer should be executed with.
* A higher priority means the {@link Serializer} will be applied earlier.
*/
static PRIORITY = 0;
constructor(owner: Serializer) {
this.owner = owner;
}
/**
* Set when the SerializerComponent is added to the serializer.
*/
protected owner: Serializer;
/**
* A high-level predicate filtering which group this serializer belongs to.
* This is a high-level filter before the {@link SerializerComponent.supports} predicate filter.
*
* For example, use the {@link Reflection} class class to group all reflection based serializers:
* ```typescript
* class ReflectionSerializer {
* serializeGroup(instance) { return instance instanceof Reflection }
* }
* ```
*
* Use the {@link Type} class to group all type based serializers:
* ```typescript
* class TypeSerializer {
* serializeGroup(instance) { return instance instanceof Type }
* }
* ```
*/
abstract serializeGroup(instance: unknown): boolean;
/**
* The priority this serializer should be executed with.
* A higher priority means the {@link Serializer} will be applied earlier.
*/
get priority(): number {
return (
(this.constructor as typeof SerializerComponent)["PRIORITY"] ||
SerializerComponent.PRIORITY
);
}
abstract supports(item: unknown): boolean;
abstract toObject(item: T, obj?: object): Partial<ModelToObject<T>>;
}
export abstract class ReflectionSerializerComponent<
T extends Reflection
> extends SerializerComponent<T> {
/**
* Filter for instances of {@link Reflection}
*/
serializeGroup(instance: unknown): boolean {
return instance instanceof Reflection;
}
}
export abstract class TypeSerializerComponent<
T extends Type
> extends SerializerComponent<T> {
/**
* Filter for instances of {@link Type}
*/
| (instance: unknown): boolean {
return instance instanceof Type;
}
}
| serializeGroup | identifier_name |
test_vm_rest.py | # -*- coding: utf-8 -*-
import fauxfactory
import pytest
from cfme import test_requirements
from cfme.rest.gen_data import a_provider as _a_provider
from cfme.rest.gen_data import vm as _vm
from cfme.utils import error
from cfme.utils.rest import assert_response, delete_resources_from_collection
from cfme.utils.wait import wait_for
pytestmark = [test_requirements.provision]
@pytest.fixture(scope="function")
def a_provider(request):
return _a_provider(request)
@pytest.fixture(scope="function")
def vm_name(request, a_provider, appliance):
return _vm(request, a_provider, appliance.rest_api)
@pytest.mark.parametrize(
'from_detail', [True, False],
ids=['from_detail', 'from_collection'])
def test_edit_vm(request, vm_name, appliance, from_detail):
"""Tests edit VMs using REST API.
Testing BZ 1428250.
Metadata:
test_flag: rest
"""
vm = appliance.rest_api.collections.vms.get(name=vm_name)
request.addfinalizer(vm.action.delete)
new_description = 'Test REST VM {}'.format(fauxfactory.gen_alphanumeric(5))
payload = {'description': new_description}
if from_detail:
edited = vm.action.edit(**payload)
assert_response(appliance)
else:
payload.update(vm._ref_repr())
edited = appliance.rest_api.collections.vms.action.edit(payload)
assert_response(appliance)
edited = edited[0]
record, __ = wait_for(
lambda: appliance.rest_api.collections.vms.find_by(
description=new_description) or False,
num_sec=100,
delay=5,
)
vm.reload()
assert vm.description == edited.description == record[0].description
@pytest.mark.tier(3)
@pytest.mark.parametrize('method', ['post', 'delete'], ids=['POST', 'DELETE'])
def test_delete_vm_from_detail(vm_name, appliance, method):
vm = appliance.rest_api.collections.vms.get(name=vm_name)
del_action = getattr(vm.action.delete, method.upper())
del_action()
assert_response(appliance)
wait_for(
lambda: not appliance.rest_api.collections.vms.find_by(name=vm_name), num_sec=300, delay=10)
with error.expected('ActiveRecord::RecordNotFound'):
del_action()
assert_response(appliance, http_status=404)
@pytest.mark.tier(3)
def | (vm_name, appliance):
vm = appliance.rest_api.collections.vms.get(name=vm_name)
collection = appliance.rest_api.collections.vms
delete_resources_from_collection(collection, [vm], not_found=True, num_sec=300, delay=10)
| test_delete_vm_from_collection | identifier_name |
test_vm_rest.py | # -*- coding: utf-8 -*-
import fauxfactory
import pytest
from cfme import test_requirements
from cfme.rest.gen_data import a_provider as _a_provider
from cfme.rest.gen_data import vm as _vm
from cfme.utils import error
from cfme.utils.rest import assert_response, delete_resources_from_collection
from cfme.utils.wait import wait_for
pytestmark = [test_requirements.provision]
@pytest.fixture(scope="function")
def a_provider(request):
return _a_provider(request)
@pytest.fixture(scope="function")
def vm_name(request, a_provider, appliance):
return _vm(request, a_provider, appliance.rest_api)
@pytest.mark.parametrize(
'from_detail', [True, False],
ids=['from_detail', 'from_collection'])
def test_edit_vm(request, vm_name, appliance, from_detail):
"""Tests edit VMs using REST API.
Testing BZ 1428250.
Metadata:
test_flag: rest
"""
vm = appliance.rest_api.collections.vms.get(name=vm_name)
request.addfinalizer(vm.action.delete)
new_description = 'Test REST VM {}'.format(fauxfactory.gen_alphanumeric(5))
payload = {'description': new_description}
if from_detail:
edited = vm.action.edit(**payload)
assert_response(appliance)
else:
payload.update(vm._ref_repr())
edited = appliance.rest_api.collections.vms.action.edit(payload)
assert_response(appliance)
edited = edited[0]
record, __ = wait_for(
lambda: appliance.rest_api.collections.vms.find_by(
description=new_description) or False,
num_sec=100,
delay=5,
)
vm.reload()
assert vm.description == edited.description == record[0].description
@pytest.mark.tier(3)
@pytest.mark.parametrize('method', ['post', 'delete'], ids=['POST', 'DELETE'])
def test_delete_vm_from_detail(vm_name, appliance, method):
|
@pytest.mark.tier(3)
def test_delete_vm_from_collection(vm_name, appliance):
vm = appliance.rest_api.collections.vms.get(name=vm_name)
collection = appliance.rest_api.collections.vms
delete_resources_from_collection(collection, [vm], not_found=True, num_sec=300, delay=10)
| vm = appliance.rest_api.collections.vms.get(name=vm_name)
del_action = getattr(vm.action.delete, method.upper())
del_action()
assert_response(appliance)
wait_for(
lambda: not appliance.rest_api.collections.vms.find_by(name=vm_name), num_sec=300, delay=10)
with error.expected('ActiveRecord::RecordNotFound'):
del_action()
assert_response(appliance, http_status=404) | identifier_body |
test_vm_rest.py | # -*- coding: utf-8 -*-
import fauxfactory
import pytest
from cfme import test_requirements
from cfme.rest.gen_data import a_provider as _a_provider
from cfme.rest.gen_data import vm as _vm
from cfme.utils import error
from cfme.utils.rest import assert_response, delete_resources_from_collection
from cfme.utils.wait import wait_for
pytestmark = [test_requirements.provision]
@pytest.fixture(scope="function")
def a_provider(request):
return _a_provider(request)
@pytest.fixture(scope="function")
def vm_name(request, a_provider, appliance):
return _vm(request, a_provider, appliance.rest_api)
@pytest.mark.parametrize(
'from_detail', [True, False],
ids=['from_detail', 'from_collection'])
def test_edit_vm(request, vm_name, appliance, from_detail):
"""Tests edit VMs using REST API.
Testing BZ 1428250.
Metadata:
test_flag: rest
"""
vm = appliance.rest_api.collections.vms.get(name=vm_name)
request.addfinalizer(vm.action.delete)
new_description = 'Test REST VM {}'.format(fauxfactory.gen_alphanumeric(5))
payload = {'description': new_description}
if from_detail:
edited = vm.action.edit(**payload)
assert_response(appliance)
else:
payload.update(vm._ref_repr())
edited = appliance.rest_api.collections.vms.action.edit(payload)
assert_response(appliance)
edited = edited[0]
record, __ = wait_for(
lambda: appliance.rest_api.collections.vms.find_by(
description=new_description) or False, | )
vm.reload()
assert vm.description == edited.description == record[0].description
@pytest.mark.tier(3)
@pytest.mark.parametrize('method', ['post', 'delete'], ids=['POST', 'DELETE'])
def test_delete_vm_from_detail(vm_name, appliance, method):
vm = appliance.rest_api.collections.vms.get(name=vm_name)
del_action = getattr(vm.action.delete, method.upper())
del_action()
assert_response(appliance)
wait_for(
lambda: not appliance.rest_api.collections.vms.find_by(name=vm_name), num_sec=300, delay=10)
with error.expected('ActiveRecord::RecordNotFound'):
del_action()
assert_response(appliance, http_status=404)
@pytest.mark.tier(3)
def test_delete_vm_from_collection(vm_name, appliance):
vm = appliance.rest_api.collections.vms.get(name=vm_name)
collection = appliance.rest_api.collections.vms
delete_resources_from_collection(collection, [vm], not_found=True, num_sec=300, delay=10) | num_sec=100,
delay=5, | random_line_split |
test_vm_rest.py | # -*- coding: utf-8 -*-
import fauxfactory
import pytest
from cfme import test_requirements
from cfme.rest.gen_data import a_provider as _a_provider
from cfme.rest.gen_data import vm as _vm
from cfme.utils import error
from cfme.utils.rest import assert_response, delete_resources_from_collection
from cfme.utils.wait import wait_for
pytestmark = [test_requirements.provision]
@pytest.fixture(scope="function")
def a_provider(request):
return _a_provider(request)
@pytest.fixture(scope="function")
def vm_name(request, a_provider, appliance):
return _vm(request, a_provider, appliance.rest_api)
@pytest.mark.parametrize(
'from_detail', [True, False],
ids=['from_detail', 'from_collection'])
def test_edit_vm(request, vm_name, appliance, from_detail):
"""Tests edit VMs using REST API.
Testing BZ 1428250.
Metadata:
test_flag: rest
"""
vm = appliance.rest_api.collections.vms.get(name=vm_name)
request.addfinalizer(vm.action.delete)
new_description = 'Test REST VM {}'.format(fauxfactory.gen_alphanumeric(5))
payload = {'description': new_description}
if from_detail:
edited = vm.action.edit(**payload)
assert_response(appliance)
else:
|
record, __ = wait_for(
lambda: appliance.rest_api.collections.vms.find_by(
description=new_description) or False,
num_sec=100,
delay=5,
)
vm.reload()
assert vm.description == edited.description == record[0].description
@pytest.mark.tier(3)
@pytest.mark.parametrize('method', ['post', 'delete'], ids=['POST', 'DELETE'])
def test_delete_vm_from_detail(vm_name, appliance, method):
vm = appliance.rest_api.collections.vms.get(name=vm_name)
del_action = getattr(vm.action.delete, method.upper())
del_action()
assert_response(appliance)
wait_for(
lambda: not appliance.rest_api.collections.vms.find_by(name=vm_name), num_sec=300, delay=10)
with error.expected('ActiveRecord::RecordNotFound'):
del_action()
assert_response(appliance, http_status=404)
@pytest.mark.tier(3)
def test_delete_vm_from_collection(vm_name, appliance):
vm = appliance.rest_api.collections.vms.get(name=vm_name)
collection = appliance.rest_api.collections.vms
delete_resources_from_collection(collection, [vm], not_found=True, num_sec=300, delay=10)
| payload.update(vm._ref_repr())
edited = appliance.rest_api.collections.vms.action.edit(payload)
assert_response(appliance)
edited = edited[0] | conditional_block |
patches_matrix.py | import numpy as np
import math
def get_patches(mat, patch_size=(4,4)):
if mat.ndim == 1:
dim = math.sqrt(mat.shape[0])
mat.reshape((dim, dim))
mat_rows = mat.shape[0]
mat_cols = mat.shape[1]
patches = None
for i in xrange(mat_rows / patch_size[0]):
for j in xrange(mat_cols / patch_size[1]):
print patches
patch = mat[i * patch_size[0]: (i + 1)* patch_size[0], j * patch_size[0]: (j + 1) * patch_size[1]]
if patches is None:
patches = patch
else:
if patches.ndim != patch.ndim:
|
else:
patches = np.vstack(([patches], [patch]))
return patches
arr = np.array(xrange(32 * 32)).reshape(32, 32)
patches = get_patches(arr)
print patches
| patches = np.vstack((patches, [patch])) | conditional_block |
patches_matrix.py | import numpy as np
import math
def | (mat, patch_size=(4,4)):
if mat.ndim == 1:
dim = math.sqrt(mat.shape[0])
mat.reshape((dim, dim))
mat_rows = mat.shape[0]
mat_cols = mat.shape[1]
patches = None
for i in xrange(mat_rows / patch_size[0]):
for j in xrange(mat_cols / patch_size[1]):
print patches
patch = mat[i * patch_size[0]: (i + 1)* patch_size[0], j * patch_size[0]: (j + 1) * patch_size[1]]
if patches is None:
patches = patch
else:
if patches.ndim != patch.ndim:
patches = np.vstack((patches, [patch]))
else:
patches = np.vstack(([patches], [patch]))
return patches
arr = np.array(xrange(32 * 32)).reshape(32, 32)
patches = get_patches(arr)
print patches
| get_patches | identifier_name |
patches_matrix.py | import numpy as np
import math
def get_patches(mat, patch_size=(4,4)):
if mat.ndim == 1:
dim = math.sqrt(mat.shape[0])
mat.reshape((dim, dim))
mat_rows = mat.shape[0]
mat_cols = mat.shape[1]
patches = None
for i in xrange(mat_rows / patch_size[0]):
for j in xrange(mat_cols / patch_size[1]):
print patches
patch = mat[i * patch_size[0]: (i + 1)* patch_size[0], j * patch_size[0]: (j + 1) * patch_size[1]]
if patches is None:
patches = patch
else:
if patches.ndim != patch.ndim:
patches = np.vstack((patches, [patch]))
else: | patches = np.vstack(([patches], [patch]))
return patches
arr = np.array(xrange(32 * 32)).reshape(32, 32)
patches = get_patches(arr)
print patches | random_line_split | |
patches_matrix.py | import numpy as np
import math
def get_patches(mat, patch_size=(4,4)):
|
arr = np.array(xrange(32 * 32)).reshape(32, 32)
patches = get_patches(arr)
print patches
| if mat.ndim == 1:
dim = math.sqrt(mat.shape[0])
mat.reshape((dim, dim))
mat_rows = mat.shape[0]
mat_cols = mat.shape[1]
patches = None
for i in xrange(mat_rows / patch_size[0]):
for j in xrange(mat_cols / patch_size[1]):
print patches
patch = mat[i * patch_size[0]: (i + 1)* patch_size[0], j * patch_size[0]: (j + 1) * patch_size[1]]
if patches is None:
patches = patch
else:
if patches.ndim != patch.ndim:
patches = np.vstack((patches, [patch]))
else:
patches = np.vstack(([patches], [patch]))
return patches | identifier_body |
server.js | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import 'babel-core/polyfill';
import path from 'path';
import express from 'express';
import React from 'react';
import ReactDOM from 'react-dom/server';
import Router from './routes';
import Html from './components/Html';
import assets from './assets.json';
const server = global.server = express();
const port = process.env.PORT || 5000;
server.set('port', port);
//
// Register Node.js middleware
// -----------------------------------------------------------------------------
server.use(express.static(path.join(__dirname, 'public')));
//
// Register API middleware
// -----------------------------------------------------------------------------
server.use('/api/content', require('./api/content'));
//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
server.get('*', async (req, res, next) => {
try {
let statusCode = 200;
const data = { title: '', description: '', css: '', body: '', entry: assets.app.js };
const css = [];
const context = {
insertCss: styles => css.push(styles._getCss()),
onSetTitle: value => data.title = value,
onSetMeta: (key, value) => data[key] = value,
onPageNotFound: () => statusCode = 404,
};
await Router.dispatch({ path: req.path, context }, (state, component) => {
data.body = ReactDOM.renderToString(component);
data.css = css.join('');
});
const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);
res.status(statusCode).send('<!doctype html>\n' + html);
} catch (err) {
next(err);
}
});
| /* eslint-disable no-console */
console.log(`The server is running at http://localhost:${port}/`);
}); | //
// Launch the server
// -----------------------------------------------------------------------------
server.listen(port, () => { | random_line_split |
messages.js | /*
* Licensed Materials - Property of IBM
* (C) Copyright IBM Corp. 2010, 2017
* US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*/
define({
// NLS_CHARSET=UTF-8
// configuration
configuration_pane_aspera_url: "Adresa URL servera IBM Aspera",
configuration_pane_aspera_url_hover: "Zadajte adresu URL servera IBM Aspera. Napríklad: https://názov_hostiteľa:číslo_portu/aspera/faspex",
configuration_pane_aspera_url_prompt: "Dôrazne odporúčame, aby ste používali protokol HTTPS.",
configuration_pane_max_docs_to_send: "Maximálny počet odoslaných položiek",
configuration_pane_max_docs_to_send_hover: "Zadajte maximálny počet položiek, ktoré môžu užívatelia naraz odoslať.",
configuration_pane_max_procs_to_send: "Maximálny počet súbežných požiadaviek",
configuration_pane_max_procs_to_send_hover: "Zadajte maximálny počet požiadaviek, ktoré môžu byť súčasne spustené.",
configuration_pane_target_transfer_rate: "Cieľová prenosová rýchlosť (v Mb/s)",
configuration_pane_target_transfer_rate_hover: "Zadajte cieľovú prenosovú rýchlosť ako Mb/s. Maximálna rýchlosť je obmedzená licenčnými oprávneniami.",
configuration_pane_speed_info: "Vaša aktuálna základná licencia umožňuje maximálnu prenosovú rýchlosť 20 Mb/s. Ak chcete vykonať inováciu na rýchlejšiu skúšobnú licenciu (podporujúcu prenosovú rýchlosť až do 10 Gb/s) pre softvér Aspera Faspex, požiadajte o novú licenciu na stránke <a target='_blank' href='https://ibm.biz/BdjYHq'>Aspera Evaluation Request</a>.",
// runtime
send_dialog_sender_title: "Odosielateľ: ${0}",
send_dialog_not_set: "Nenastavené",
send_dialog_send_one: "Poslať '${0}'.",
send_dialog_send_more: "Poslať súbory: ${0}.",
send_dialog_sender: "Meno užívateľa:",
send_dialog_password: "Heslo:",
send_dialog_missing_sender_message: "Je potrebné zadať meno užívateľa pre prihlásenie na server IBM Aspera.",
send_dialog_missing_password_message: "Je potrebné zadať heslo pre prihlásenie na server IBM Aspera.",
send_dialog_title: "Poslať cez IBM Aspera",
send_dialog_missing_title_message: "Musíte zadať názov.",
send_dialog_info: "Posielajte súbory cez server IBM Aspera a upozornite užívateľov, že si môžu stiahnuť súbory.",
send_dialog_recipients_label: "Príjemcovia:", | send_dialog_title_label: "Názov:",
send_dialog_note_label: "Pridajte správu.",
send_dialog_earPassphrase_label: "Heslo pre šifrovanie:",
send_dialog_earPassphrase_textfield_hover_help: "Zadajte heslo pre zašifrovanie súborov na serveri. Toto heslo budú musieť príjemcovia zadať, aby mohli dešifrovať chránené súbory po stiahnutí.",
send_dialog_notify_title: "Upozornenie: ${0}",
send_dialog_notifyOnUpload_label: "Upozorniť ma na nahratie súboru",
send_dialog_notifyOnDownload_label: "Upozorniť ma na stiahnutie súboru",
send_dialog_notifyOnUploadDownload: "Upozorniť ma na nahratie a stiahnutie súboru",
send_dialog_send_button_label: "Odoslať",
send_dialog_started: "Balík ${0} sa posiela.",
status_started: "Stav balíka: ${0} - prebieha (${1} %)",
status_stopped: "Stav balíka: ${0} - zastavené",
status_failed: "Stav balíka: ${0} - neúspešné",
status_completed: "Stav balíka: ${0} - dokončené",
// error
send_dialog_too_many_items_error: "Nepodarilo sa odoslať položky.",
send_dialog_too_many_items_error_explanation: "Môžete odoslať najviac ${0} položiek naraz. Pokúšate sa odoslať ${1} položiek.",
send_dialog_too_many_items_error_userResponse: "Vyberte menší počet položiek a znova sa ich pokúste odoslať. Taktiež sa môžete obrátiť na správcu systému a požiadať ho, aby zvýšil maximálny počet súbežne odosielaných položiek.",
send_dialog_too_many_items_error_0: "maximum_number_of_items",
send_dialog_too_many_items_error_1: "number_of_items",
send_dialog_too_many_items_error_number: 5050,
}); | send_dialog_recipients_textfield_hover_help: "E-mailové adresy alebo mená užívateľov oddeľte čiarkou. Napríklad, zadajte: 'adresa1, adresa2, meno_užívateľa1, meno_užívateľa2'.",
send_dialog_missing_recipients_message: "Zadajte aspoň jednu e-mailovú adresu alebo meno užívateľa.", | random_line_split |
location_providers.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injector, NgZone, PLATFORM_INITIALIZER, Provider} from '@angular/core';
import {ɵBrowserPlatformLocation as BrowserPlatformLocation} from '@angular/platform-browser';
import {MessageBasedPlatformLocation} from './platform_location';
/**
* A list of {@link Provider}s. To use the router in a Worker enabled application you must
* include these providers when setting up the render thread.
* @experimental
*/
export const WORKER_UI_LOCATION_PROVIDERS: Provider[] = [
MessageBasedPlatformLocation, BrowserPlatformLocation,
{provide: PLATFORM_INITIALIZER, useFactory: initUiLocation, multi: true, deps: [Injector]}
];
function i | injector: Injector): () => void {
return () => {
const zone = injector.get(NgZone);
zone.runGuarded(() => injector.get(MessageBasedPlatformLocation).start());
};
}
| nitUiLocation( | identifier_name |
location_providers.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injector, NgZone, PLATFORM_INITIALIZER, Provider} from '@angular/core'; |
/**
* A list of {@link Provider}s. To use the router in a Worker enabled application you must
* include these providers when setting up the render thread.
* @experimental
*/
export const WORKER_UI_LOCATION_PROVIDERS: Provider[] = [
MessageBasedPlatformLocation, BrowserPlatformLocation,
{provide: PLATFORM_INITIALIZER, useFactory: initUiLocation, multi: true, deps: [Injector]}
];
function initUiLocation(injector: Injector): () => void {
return () => {
const zone = injector.get(NgZone);
zone.runGuarded(() => injector.get(MessageBasedPlatformLocation).start());
};
} |
import {ɵBrowserPlatformLocation as BrowserPlatformLocation} from '@angular/platform-browser';
import {MessageBasedPlatformLocation} from './platform_location';
| random_line_split |
location_providers.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injector, NgZone, PLATFORM_INITIALIZER, Provider} from '@angular/core';
import {ɵBrowserPlatformLocation as BrowserPlatformLocation} from '@angular/platform-browser';
import {MessageBasedPlatformLocation} from './platform_location';
/**
* A list of {@link Provider}s. To use the router in a Worker enabled application you must
* include these providers when setting up the render thread.
* @experimental
*/
export const WORKER_UI_LOCATION_PROVIDERS: Provider[] = [
MessageBasedPlatformLocation, BrowserPlatformLocation,
{provide: PLATFORM_INITIALIZER, useFactory: initUiLocation, multi: true, deps: [Injector]}
];
function initUiLocation(injector: Injector): () => void { |
return () => {
const zone = injector.get(NgZone);
zone.runGuarded(() => injector.get(MessageBasedPlatformLocation).start());
};
}
| identifier_body | |
_videoplayerApp.js | /* jshint -W117 */
/*
Copyright 2016 Herko ter Horst
__________________________________________________________________________
Filename: _videoplayerApp.js
__________________________________________________________________________
*/
log.addSrcFile("_videoplayerApp.js", "_videoplayer");
function _videoplayerApp(uiaId) {
log.debug("Constructor called.");
// Base application functionality is provided in a common location via this call to baseApp.init().
// See framework/js/BaseApp.js for details.
baseApp.init(this, uiaId);
}
// load jQuery Globally (if needed)
if (!window.jQuery) {
utility.loadScript("addon-common/jquery.min.js");
}
/*********************************
* App Init is standard function *
* called by framework *
*********************************/
/*
* Called just after the app is instantiated by framework.
* All variables local to this app should be declared in this function
*/
_videoplayerApp.prototype.appInit = function() {
log.debug("_videoplayerApp appInit called...");
// These values need to persist through videoplayer instances
this.hold = false;
this.resumePlay = 0;
this.musicIsPaused = false;
this.savedVideoList = null;
this.resumeVideo = JSON.parse(localStorage.getItem('videoplayer.resumevideo')) || true; // resume is now checked by default
this.currentVideoTrack = JSON.parse(localStorage.getItem('videoplayer.currentvideo')) || null;
//this.resumePlay = JSON.parse(localStorage.getItem('videoplayer.resume')) || 0;
//Context table
//@formatter:off
this._contextTable = {
"Start": { // initial context must be called "Start"
"sbName": "Video Player",
"template": "VideoPlayerTmplt",
"templatePath": "apps/_videoplayer/templates/VideoPlayer", //only needed for app-specific templates
"readyFunction": this._StartContextReady.bind(this),
"contextOutFunction": this._StartContextOut.bind(this),
"noLongerDisplayedFunction": this._noLongerDisplayed.bind(this)
} // end of "VideoPlayer"
}; // end of this.contextTable object
//@formatter:on
//@formatter:off
this._messageTable = {
// haven't yet been able to receive messages from MMUI
};
//@formatter:on
framework.transitionsObj._genObj._TEMPLATE_CATEGORIES_TABLE.VideoPlayerTmplt = "Detail with UMP";
};
/**
* =========================
* CONTEXT CALLBACKS
* =========================
*/
_videoplayerApp.prototype._StartContextReady = function() {
framework.common.setSbDomainIcon("apps/_videoplayer/templates/VideoPlayer/images/icon.png");
};
_videoplayerApp.prototype._StartContextOut = function() {
CloseVideoFrame();
framework.common.setSbName('');
};
_videoplayerApp.prototype._noLongerDisplayed = function() {
// Stop and close video frame
CloseVideoFrame();
// If we are in reverse then save CurrentVideoPlayTime to resume the video where we left of
if (framework.getCurrentApp() === 'backupparking'|| framework.getCurrentApp() === 'phone' || (ResumePlay && CurrentVideoPlayTime !== null)) {
this.resumePlay = this.resumePlay || CurrentVideoPlayTime;
CurrentVideoPlayTime = 0;
//localStorage.setItem('videoplayer.resume', JSON.stringify(CurrentVideoPlayTime));
}
// If we press the 'Entertainment' button we will be running this in the 'usbaudio' context
if (!this.musicIsPaused) |
};
/**
* =========================
* Framework register
* Tell framework this .js file has finished loading
* =========================
*/
framework.registerAppLoaded("_videoplayer", null, false);
| {
setTimeout(function() {
if (framework.getCurrentApp() === 'usbaudio') {
framework.sendEventToMmui('Common', 'Global.Pause');
framework.sendEventToMmui('Common', 'Global.GoBack');
this.musicIsPaused = true; // Only run this once
}
}, 100);
} | conditional_block |
_videoplayerApp.js | /* jshint -W117 */
/*
Copyright 2016 Herko ter Horst
__________________________________________________________________________
Filename: _videoplayerApp.js
__________________________________________________________________________
*/
log.addSrcFile("_videoplayerApp.js", "_videoplayer");
function _videoplayerApp(uiaId) {
log.debug("Constructor called.");
// Base application functionality is provided in a common location via this call to baseApp.init().
// See framework/js/BaseApp.js for details.
baseApp.init(this, uiaId);
}
// load jQuery Globally (if needed)
if (!window.jQuery) {
utility.loadScript("addon-common/jquery.min.js");
}
/*********************************
* App Init is standard function *
* called by framework *
*********************************/
/*
* Called just after the app is instantiated by framework.
* All variables local to this app should be declared in this function
*/
_videoplayerApp.prototype.appInit = function() {
log.debug("_videoplayerApp appInit called...");
// These values need to persist through videoplayer instances
this.hold = false;
this.resumePlay = 0;
this.musicIsPaused = false;
this.savedVideoList = null;
this.resumeVideo = JSON.parse(localStorage.getItem('videoplayer.resumevideo')) || true; // resume is now checked by default
this.currentVideoTrack = JSON.parse(localStorage.getItem('videoplayer.currentvideo')) || null;
//this.resumePlay = JSON.parse(localStorage.getItem('videoplayer.resume')) || 0;
//Context table
//@formatter:off
this._contextTable = {
"Start": { // initial context must be called "Start"
"sbName": "Video Player",
"template": "VideoPlayerTmplt",
"templatePath": "apps/_videoplayer/templates/VideoPlayer", //only needed for app-specific templates
"readyFunction": this._StartContextReady.bind(this),
"contextOutFunction": this._StartContextOut.bind(this),
"noLongerDisplayedFunction": this._noLongerDisplayed.bind(this)
} // end of "VideoPlayer"
}; // end of this.contextTable object
//@formatter:on
//@formatter:off
this._messageTable = {
// haven't yet been able to receive messages from MMUI
};
//@formatter:on
framework.transitionsObj._genObj._TEMPLATE_CATEGORIES_TABLE.VideoPlayerTmplt = "Detail with UMP";
};
/**
* =========================
* CONTEXT CALLBACKS
* =========================
*/
_videoplayerApp.prototype._StartContextReady = function() {
framework.common.setSbDomainIcon("apps/_videoplayer/templates/VideoPlayer/images/icon.png");
};
_videoplayerApp.prototype._StartContextOut = function() {
CloseVideoFrame();
framework.common.setSbName('');
};
_videoplayerApp.prototype._noLongerDisplayed = function() {
// Stop and close video frame
CloseVideoFrame();
// If we are in reverse then save CurrentVideoPlayTime to resume the video where we left of
if (framework.getCurrentApp() === 'backupparking'|| framework.getCurrentApp() === 'phone' || (ResumePlay && CurrentVideoPlayTime !== null)) {
this.resumePlay = this.resumePlay || CurrentVideoPlayTime;
CurrentVideoPlayTime = 0;
//localStorage.setItem('videoplayer.resume', JSON.stringify(CurrentVideoPlayTime));
}
// If we press the 'Entertainment' button we will be running this in the 'usbaudio' context
if (!this.musicIsPaused) {
setTimeout(function() {
if (framework.getCurrentApp() === 'usbaudio') {
framework.sendEventToMmui('Common', 'Global.Pause');
framework.sendEventToMmui('Common', 'Global.GoBack'); | }
}, 100);
}
};
/**
* =========================
* Framework register
* Tell framework this .js file has finished loading
* =========================
*/
framework.registerAppLoaded("_videoplayer", null, false); | this.musicIsPaused = true; // Only run this once | random_line_split |
_videoplayerApp.js | /* jshint -W117 */
/*
Copyright 2016 Herko ter Horst
__________________________________________________________________________
Filename: _videoplayerApp.js
__________________________________________________________________________
*/
log.addSrcFile("_videoplayerApp.js", "_videoplayer");
function _videoplayerApp(uiaId) |
// load jQuery Globally (if needed)
if (!window.jQuery) {
utility.loadScript("addon-common/jquery.min.js");
}
/*********************************
* App Init is standard function *
* called by framework *
*********************************/
/*
* Called just after the app is instantiated by framework.
* All variables local to this app should be declared in this function
*/
_videoplayerApp.prototype.appInit = function() {
log.debug("_videoplayerApp appInit called...");
// These values need to persist through videoplayer instances
this.hold = false;
this.resumePlay = 0;
this.musicIsPaused = false;
this.savedVideoList = null;
this.resumeVideo = JSON.parse(localStorage.getItem('videoplayer.resumevideo')) || true; // resume is now checked by default
this.currentVideoTrack = JSON.parse(localStorage.getItem('videoplayer.currentvideo')) || null;
//this.resumePlay = JSON.parse(localStorage.getItem('videoplayer.resume')) || 0;
//Context table
//@formatter:off
this._contextTable = {
"Start": { // initial context must be called "Start"
"sbName": "Video Player",
"template": "VideoPlayerTmplt",
"templatePath": "apps/_videoplayer/templates/VideoPlayer", //only needed for app-specific templates
"readyFunction": this._StartContextReady.bind(this),
"contextOutFunction": this._StartContextOut.bind(this),
"noLongerDisplayedFunction": this._noLongerDisplayed.bind(this)
} // end of "VideoPlayer"
}; // end of this.contextTable object
//@formatter:on
//@formatter:off
this._messageTable = {
// haven't yet been able to receive messages from MMUI
};
//@formatter:on
framework.transitionsObj._genObj._TEMPLATE_CATEGORIES_TABLE.VideoPlayerTmplt = "Detail with UMP";
};
/**
* =========================
* CONTEXT CALLBACKS
* =========================
*/
_videoplayerApp.prototype._StartContextReady = function() {
framework.common.setSbDomainIcon("apps/_videoplayer/templates/VideoPlayer/images/icon.png");
};
_videoplayerApp.prototype._StartContextOut = function() {
CloseVideoFrame();
framework.common.setSbName('');
};
_videoplayerApp.prototype._noLongerDisplayed = function() {
// Stop and close video frame
CloseVideoFrame();
// If we are in reverse then save CurrentVideoPlayTime to resume the video where we left of
if (framework.getCurrentApp() === 'backupparking'|| framework.getCurrentApp() === 'phone' || (ResumePlay && CurrentVideoPlayTime !== null)) {
this.resumePlay = this.resumePlay || CurrentVideoPlayTime;
CurrentVideoPlayTime = 0;
//localStorage.setItem('videoplayer.resume', JSON.stringify(CurrentVideoPlayTime));
}
// If we press the 'Entertainment' button we will be running this in the 'usbaudio' context
if (!this.musicIsPaused) {
setTimeout(function() {
if (framework.getCurrentApp() === 'usbaudio') {
framework.sendEventToMmui('Common', 'Global.Pause');
framework.sendEventToMmui('Common', 'Global.GoBack');
this.musicIsPaused = true; // Only run this once
}
}, 100);
}
};
/**
* =========================
* Framework register
* Tell framework this .js file has finished loading
* =========================
*/
framework.registerAppLoaded("_videoplayer", null, false);
| {
log.debug("Constructor called.");
// Base application functionality is provided in a common location via this call to baseApp.init().
// See framework/js/BaseApp.js for details.
baseApp.init(this, uiaId);
} | identifier_body |
_videoplayerApp.js | /* jshint -W117 */
/*
Copyright 2016 Herko ter Horst
__________________________________________________________________________
Filename: _videoplayerApp.js
__________________________________________________________________________
*/
log.addSrcFile("_videoplayerApp.js", "_videoplayer");
function | (uiaId) {
log.debug("Constructor called.");
// Base application functionality is provided in a common location via this call to baseApp.init().
// See framework/js/BaseApp.js for details.
baseApp.init(this, uiaId);
}
// load jQuery Globally (if needed)
if (!window.jQuery) {
utility.loadScript("addon-common/jquery.min.js");
}
/*********************************
* App Init is standard function *
* called by framework *
*********************************/
/*
* Called just after the app is instantiated by framework.
* All variables local to this app should be declared in this function
*/
_videoplayerApp.prototype.appInit = function() {
log.debug("_videoplayerApp appInit called...");
// These values need to persist through videoplayer instances
this.hold = false;
this.resumePlay = 0;
this.musicIsPaused = false;
this.savedVideoList = null;
this.resumeVideo = JSON.parse(localStorage.getItem('videoplayer.resumevideo')) || true; // resume is now checked by default
this.currentVideoTrack = JSON.parse(localStorage.getItem('videoplayer.currentvideo')) || null;
//this.resumePlay = JSON.parse(localStorage.getItem('videoplayer.resume')) || 0;
//Context table
//@formatter:off
this._contextTable = {
"Start": { // initial context must be called "Start"
"sbName": "Video Player",
"template": "VideoPlayerTmplt",
"templatePath": "apps/_videoplayer/templates/VideoPlayer", //only needed for app-specific templates
"readyFunction": this._StartContextReady.bind(this),
"contextOutFunction": this._StartContextOut.bind(this),
"noLongerDisplayedFunction": this._noLongerDisplayed.bind(this)
} // end of "VideoPlayer"
}; // end of this.contextTable object
//@formatter:on
//@formatter:off
this._messageTable = {
// haven't yet been able to receive messages from MMUI
};
//@formatter:on
framework.transitionsObj._genObj._TEMPLATE_CATEGORIES_TABLE.VideoPlayerTmplt = "Detail with UMP";
};
/**
* =========================
* CONTEXT CALLBACKS
* =========================
*/
_videoplayerApp.prototype._StartContextReady = function() {
framework.common.setSbDomainIcon("apps/_videoplayer/templates/VideoPlayer/images/icon.png");
};
_videoplayerApp.prototype._StartContextOut = function() {
CloseVideoFrame();
framework.common.setSbName('');
};
_videoplayerApp.prototype._noLongerDisplayed = function() {
// Stop and close video frame
CloseVideoFrame();
// If we are in reverse then save CurrentVideoPlayTime to resume the video where we left of
if (framework.getCurrentApp() === 'backupparking'|| framework.getCurrentApp() === 'phone' || (ResumePlay && CurrentVideoPlayTime !== null)) {
this.resumePlay = this.resumePlay || CurrentVideoPlayTime;
CurrentVideoPlayTime = 0;
//localStorage.setItem('videoplayer.resume', JSON.stringify(CurrentVideoPlayTime));
}
// If we press the 'Entertainment' button we will be running this in the 'usbaudio' context
if (!this.musicIsPaused) {
setTimeout(function() {
if (framework.getCurrentApp() === 'usbaudio') {
framework.sendEventToMmui('Common', 'Global.Pause');
framework.sendEventToMmui('Common', 'Global.GoBack');
this.musicIsPaused = true; // Only run this once
}
}, 100);
}
};
/**
* =========================
* Framework register
* Tell framework this .js file has finished loading
* =========================
*/
framework.registerAppLoaded("_videoplayer", null, false);
| _videoplayerApp | identifier_name |
notifications.js | // add new post notification callback on post submit
postAfterSubmitMethodCallbacks.push(function (post) {
var adminIds = _.pluck(Meteor.users.find({'isAdmin': true}, {fields: {_id:1}}).fetch(), '_id');
var notifiedUserIds = _.pluck(Meteor.users.find({'profile.notifications.posts': 1}, {fields: {_id:1}}).fetch(), '_id');
// remove post author ID from arrays
var adminIds = _.without(adminIds, post.userId);
var notifiedUserIds = _.without(notifiedUserIds, post.userId);
if (post.status === STATUS_PENDING && !!adminIds.length) {
// if post is pending, only notify admins
Herald.createNotification(adminIds, {courier: 'newPendingPost', data: post});
} else if (!!notifiedUserIds.length) {
// if post is approved, notify everybody
Herald.createNotification(notifiedUserIds, {courier: 'newPost', data: post});
}
return post;
});
// notify users that their pending post has been approved
postApproveCallbacks.push(function (post) {
Herald.createNotification(post.userId, {courier: 'postApproved', data: post});
return post;
});
// add new comment notification callback on comment submit
commentAfterSubmitMethodCallbacks.push(function (comment) {
if(Meteor.isServer && !comment.disableNotifications){
var post = Posts.findOne(comment.postId),
notificationData = {
comment: _.pick(comment, '_id', 'userId', 'author', 'body'),
post: _.pick(post, '_id', 'userId', 'title', 'url')
},
userIdsNotified = [];
// 1. Notify author of post
// do not notify author of post if they're the ones posting the comment
if (comment.userId !== post.userId) {
Herald.createNotification(post.userId, {courier: 'newComment', data: notificationData});
userIdsNotified.push(post.userId);
}
// 2. Notify author of comment being replied to
if (!!comment.parentCommentId) {
var parentComment = Comments.findOne(comment.parentCommentId);
// do not notify author of parent comment if they're also post author or comment author
// (someone could be replying to their own comment)
if (parentComment.userId !== post.userId && parentComment.userId !== comment.userId) {
// add parent comment to notification data
notificationData.parentComment = _.pick(parentComment, '_id', 'userId', 'author');
Herald.createNotification(parentComment.userId, {courier: 'newReply', data: notificationData});
userIdsNotified.push(parentComment.userId);
}
}
// 3. Notify users subscribed to the thread
// TODO: ideally this would be injected from the telescope-subscribe-to-posts package
if (!!post.subscribers) {
// remove userIds of users that have already been notified
// and of comment author (they could be replying in a thread they're subscribed to)
var subscriberIdsToNotify = _.difference(post.subscribers, userIdsNotified, [comment.userId]);
Herald.createNotification(subscriberIdsToNotify, {courier: 'newCommentSubscribed', data: notificationData});
userIdsNotified = userIdsNotified.concat(subscriberIdsToNotify);
}
}
return comment;
});
var emailNotifications = {
propertyName: 'emailNotifications',
propertySchema: {
type: Boolean,
optional: true,
defaultValue: true,
autoform: {
group: 'notifications_fieldset',
instructions: 'Enable email notifications for new posts and new comments (requires restart).'
}
}
};
addToSettingsSchema.push(emailNotifications);
// make it possible to disable notifications on a per-comment basis
addToCommentsSchema.push(
{
propertyName: 'disableNotifications',
propertySchema: {
type: Boolean,
optional: true,
autoform: {
omit: true
}
}
}
);
function | (user) {
// set notifications default preferences
user.profile.notifications = {
users: false,
posts: false,
comments: true,
replies: true
};
return user;
}
userCreatedCallbacks.push(setNotificationDefaults);
| setNotificationDefaults | identifier_name |
notifications.js | // add new post notification callback on post submit
postAfterSubmitMethodCallbacks.push(function (post) {
var adminIds = _.pluck(Meteor.users.find({'isAdmin': true}, {fields: {_id:1}}).fetch(), '_id');
var notifiedUserIds = _.pluck(Meteor.users.find({'profile.notifications.posts': 1}, {fields: {_id:1}}).fetch(), '_id');
// remove post author ID from arrays
var adminIds = _.without(adminIds, post.userId);
var notifiedUserIds = _.without(notifiedUserIds, post.userId);
if (post.status === STATUS_PENDING && !!adminIds.length) {
// if post is pending, only notify admins
Herald.createNotification(adminIds, {courier: 'newPendingPost', data: post});
} else if (!!notifiedUserIds.length) {
// if post is approved, notify everybody
Herald.createNotification(notifiedUserIds, {courier: 'newPost', data: post});
}
return post;
});
// notify users that their pending post has been approved
postApproveCallbacks.push(function (post) {
Herald.createNotification(post.userId, {courier: 'postApproved', data: post});
return post;
});
// add new comment notification callback on comment submit
commentAfterSubmitMethodCallbacks.push(function (comment) {
if(Meteor.isServer && !comment.disableNotifications){
var post = Posts.findOne(comment.postId),
notificationData = {
comment: _.pick(comment, '_id', 'userId', 'author', 'body'),
post: _.pick(post, '_id', 'userId', 'title', 'url')
},
userIdsNotified = [];
// 1. Notify author of post
// do not notify author of post if they're the ones posting the comment
if (comment.userId !== post.userId) {
Herald.createNotification(post.userId, {courier: 'newComment', data: notificationData});
userIdsNotified.push(post.userId);
}
// 2. Notify author of comment being replied to
if (!!comment.parentCommentId) {
var parentComment = Comments.findOne(comment.parentCommentId);
// do not notify author of parent comment if they're also post author or comment author
// (someone could be replying to their own comment)
if (parentComment.userId !== post.userId && parentComment.userId !== comment.userId) {
// add parent comment to notification data
notificationData.parentComment = _.pick(parentComment, '_id', 'userId', 'author');
Herald.createNotification(parentComment.userId, {courier: 'newReply', data: notificationData});
userIdsNotified.push(parentComment.userId);
}
}
// 3. Notify users subscribed to the thread
// TODO: ideally this would be injected from the telescope-subscribe-to-posts package
if (!!post.subscribers) |
}
return comment;
});
var emailNotifications = {
propertyName: 'emailNotifications',
propertySchema: {
type: Boolean,
optional: true,
defaultValue: true,
autoform: {
group: 'notifications_fieldset',
instructions: 'Enable email notifications for new posts and new comments (requires restart).'
}
}
};
addToSettingsSchema.push(emailNotifications);
// make it possible to disable notifications on a per-comment basis
addToCommentsSchema.push(
{
propertyName: 'disableNotifications',
propertySchema: {
type: Boolean,
optional: true,
autoform: {
omit: true
}
}
}
);
function setNotificationDefaults (user) {
// set notifications default preferences
user.profile.notifications = {
users: false,
posts: false,
comments: true,
replies: true
};
return user;
}
userCreatedCallbacks.push(setNotificationDefaults);
| {
// remove userIds of users that have already been notified
// and of comment author (they could be replying in a thread they're subscribed to)
var subscriberIdsToNotify = _.difference(post.subscribers, userIdsNotified, [comment.userId]);
Herald.createNotification(subscriberIdsToNotify, {courier: 'newCommentSubscribed', data: notificationData});
userIdsNotified = userIdsNotified.concat(subscriberIdsToNotify);
} | conditional_block |
notifications.js | // add new post notification callback on post submit
postAfterSubmitMethodCallbacks.push(function (post) {
var adminIds = _.pluck(Meteor.users.find({'isAdmin': true}, {fields: {_id:1}}).fetch(), '_id');
var notifiedUserIds = _.pluck(Meteor.users.find({'profile.notifications.posts': 1}, {fields: {_id:1}}).fetch(), '_id');
// remove post author ID from arrays
var adminIds = _.without(adminIds, post.userId);
var notifiedUserIds = _.without(notifiedUserIds, post.userId);
if (post.status === STATUS_PENDING && !!adminIds.length) {
// if post is pending, only notify admins
Herald.createNotification(adminIds, {courier: 'newPendingPost', data: post});
} else if (!!notifiedUserIds.length) {
// if post is approved, notify everybody
Herald.createNotification(notifiedUserIds, {courier: 'newPost', data: post});
}
return post;
});
// notify users that their pending post has been approved
postApproveCallbacks.push(function (post) {
Herald.createNotification(post.userId, {courier: 'postApproved', data: post});
return post;
});
// add new comment notification callback on comment submit
commentAfterSubmitMethodCallbacks.push(function (comment) {
if(Meteor.isServer && !comment.disableNotifications){
var post = Posts.findOne(comment.postId),
notificationData = {
comment: _.pick(comment, '_id', 'userId', 'author', 'body'),
post: _.pick(post, '_id', 'userId', 'title', 'url')
},
userIdsNotified = [];
// 1. Notify author of post
// do not notify author of post if they're the ones posting the comment
if (comment.userId !== post.userId) {
Herald.createNotification(post.userId, {courier: 'newComment', data: notificationData});
userIdsNotified.push(post.userId);
}
// 2. Notify author of comment being replied to
if (!!comment.parentCommentId) {
var parentComment = Comments.findOne(comment.parentCommentId);
// do not notify author of parent comment if they're also post author or comment author
// (someone could be replying to their own comment)
if (parentComment.userId !== post.userId && parentComment.userId !== comment.userId) {
// add parent comment to notification data
notificationData.parentComment = _.pick(parentComment, '_id', 'userId', 'author');
Herald.createNotification(parentComment.userId, {courier: 'newReply', data: notificationData});
userIdsNotified.push(parentComment.userId);
}
}
// 3. Notify users subscribed to the thread
// TODO: ideally this would be injected from the telescope-subscribe-to-posts package
if (!!post.subscribers) {
// remove userIds of users that have already been notified
// and of comment author (they could be replying in a thread they're subscribed to)
var subscriberIdsToNotify = _.difference(post.subscribers, userIdsNotified, [comment.userId]);
Herald.createNotification(subscriberIdsToNotify, {courier: 'newCommentSubscribed', data: notificationData});
userIdsNotified = userIdsNotified.concat(subscriberIdsToNotify);
}
}
return comment;
});
var emailNotifications = {
propertyName: 'emailNotifications',
propertySchema: {
type: Boolean,
optional: true,
defaultValue: true,
autoform: {
group: 'notifications_fieldset',
instructions: 'Enable email notifications for new posts and new comments (requires restart).'
}
}
};
addToSettingsSchema.push(emailNotifications);
// make it possible to disable notifications on a per-comment basis
addToCommentsSchema.push(
{
propertyName: 'disableNotifications',
propertySchema: {
type: Boolean,
optional: true,
autoform: {
omit: true
}
}
}
);
function setNotificationDefaults (user) {
// set notifications default preferences | comments: true,
replies: true
};
return user;
}
userCreatedCallbacks.push(setNotificationDefaults); | user.profile.notifications = {
users: false,
posts: false, | random_line_split |
notifications.js | // add new post notification callback on post submit
postAfterSubmitMethodCallbacks.push(function (post) {
var adminIds = _.pluck(Meteor.users.find({'isAdmin': true}, {fields: {_id:1}}).fetch(), '_id');
var notifiedUserIds = _.pluck(Meteor.users.find({'profile.notifications.posts': 1}, {fields: {_id:1}}).fetch(), '_id');
// remove post author ID from arrays
var adminIds = _.without(adminIds, post.userId);
var notifiedUserIds = _.without(notifiedUserIds, post.userId);
if (post.status === STATUS_PENDING && !!adminIds.length) {
// if post is pending, only notify admins
Herald.createNotification(adminIds, {courier: 'newPendingPost', data: post});
} else if (!!notifiedUserIds.length) {
// if post is approved, notify everybody
Herald.createNotification(notifiedUserIds, {courier: 'newPost', data: post});
}
return post;
});
// notify users that their pending post has been approved
postApproveCallbacks.push(function (post) {
Herald.createNotification(post.userId, {courier: 'postApproved', data: post});
return post;
});
// add new comment notification callback on comment submit
commentAfterSubmitMethodCallbacks.push(function (comment) {
if(Meteor.isServer && !comment.disableNotifications){
var post = Posts.findOne(comment.postId),
notificationData = {
comment: _.pick(comment, '_id', 'userId', 'author', 'body'),
post: _.pick(post, '_id', 'userId', 'title', 'url')
},
userIdsNotified = [];
// 1. Notify author of post
// do not notify author of post if they're the ones posting the comment
if (comment.userId !== post.userId) {
Herald.createNotification(post.userId, {courier: 'newComment', data: notificationData});
userIdsNotified.push(post.userId);
}
// 2. Notify author of comment being replied to
if (!!comment.parentCommentId) {
var parentComment = Comments.findOne(comment.parentCommentId);
// do not notify author of parent comment if they're also post author or comment author
// (someone could be replying to their own comment)
if (parentComment.userId !== post.userId && parentComment.userId !== comment.userId) {
// add parent comment to notification data
notificationData.parentComment = _.pick(parentComment, '_id', 'userId', 'author');
Herald.createNotification(parentComment.userId, {courier: 'newReply', data: notificationData});
userIdsNotified.push(parentComment.userId);
}
}
// 3. Notify users subscribed to the thread
// TODO: ideally this would be injected from the telescope-subscribe-to-posts package
if (!!post.subscribers) {
// remove userIds of users that have already been notified
// and of comment author (they could be replying in a thread they're subscribed to)
var subscriberIdsToNotify = _.difference(post.subscribers, userIdsNotified, [comment.userId]);
Herald.createNotification(subscriberIdsToNotify, {courier: 'newCommentSubscribed', data: notificationData});
userIdsNotified = userIdsNotified.concat(subscriberIdsToNotify);
}
}
return comment;
});
var emailNotifications = {
propertyName: 'emailNotifications',
propertySchema: {
type: Boolean,
optional: true,
defaultValue: true,
autoform: {
group: 'notifications_fieldset',
instructions: 'Enable email notifications for new posts and new comments (requires restart).'
}
}
};
addToSettingsSchema.push(emailNotifications);
// make it possible to disable notifications on a per-comment basis
addToCommentsSchema.push(
{
propertyName: 'disableNotifications',
propertySchema: {
type: Boolean,
optional: true,
autoform: {
omit: true
}
}
}
);
function setNotificationDefaults (user) |
userCreatedCallbacks.push(setNotificationDefaults);
| {
// set notifications default preferences
user.profile.notifications = {
users: false,
posts: false,
comments: true,
replies: true
};
return user;
} | identifier_body |
errors.rs | use rstest::*;
#[fixture]
pub fn fixture() -> u32 { 42 }
#[fixture]
fn error_inner(fixture: u32) {
let a: u32 = "";
}
#[fixture]
fn error_cannot_resolve_fixture(no_fixture: u32) {
}
#[fixture]
fn error_fixture_wrong_type(fixture: String) {
}
#[fixture(not_a_fixture(24))]
fn error_inject_an_invalid_fixture(fixture: String) {
}
#[fixture]
fn name() -> &'static str {
"name"
}
#[fixture]
fn f(name: &str) -> String {
name.to_owned()
}
#[fixture(f("first"), f("second"))]
fn error_inject_a_fixture_more_than_once(f: String) |
#[fixture]
#[once]
async fn error_async_once_fixture() {
}
#[fixture]
#[once]
fn error_generics_once_fixture<T: std::fmt::Debug>() -> T {
42
}
#[fixture]
#[once]
fn error_generics_once_fixture() -> impl Iterator<Item: u32> {
std::iter::once(42)
}
| {
} | identifier_body |
errors.rs | use rstest::*;
#[fixture]
pub fn fixture() -> u32 { 42 }
#[fixture]
fn error_inner(fixture: u32) {
let a: u32 = "";
}
#[fixture]
fn error_cannot_resolve_fixture(no_fixture: u32) {
}
#[fixture]
fn error_fixture_wrong_type(fixture: String) {
}
#[fixture(not_a_fixture(24))]
fn error_inject_an_invalid_fixture(fixture: String) {
}
#[fixture]
fn name() -> &'static str {
"name"
}
#[fixture]
fn f(name: &str) -> String {
name.to_owned()
}
#[fixture(f("first"), f("second"))]
fn error_inject_a_fixture_more_than_once(f: String) {
}
#[fixture]
#[once]
async fn error_async_once_fixture() {
}
#[fixture]
#[once]
fn error_generics_once_fixture<T: std::fmt::Debug>() -> T {
42 | fn error_generics_once_fixture() -> impl Iterator<Item: u32> {
std::iter::once(42)
} | }
#[fixture]
#[once] | random_line_split |
errors.rs | use rstest::*;
#[fixture]
pub fn fixture() -> u32 { 42 }
#[fixture]
fn error_inner(fixture: u32) {
let a: u32 = "";
}
#[fixture]
fn error_cannot_resolve_fixture(no_fixture: u32) {
}
#[fixture]
fn error_fixture_wrong_type(fixture: String) {
}
#[fixture(not_a_fixture(24))]
fn error_inject_an_invalid_fixture(fixture: String) {
}
#[fixture]
fn name() -> &'static str {
"name"
}
#[fixture]
fn | (name: &str) -> String {
name.to_owned()
}
#[fixture(f("first"), f("second"))]
fn error_inject_a_fixture_more_than_once(f: String) {
}
#[fixture]
#[once]
async fn error_async_once_fixture() {
}
#[fixture]
#[once]
fn error_generics_once_fixture<T: std::fmt::Debug>() -> T {
42
}
#[fixture]
#[once]
fn error_generics_once_fixture() -> impl Iterator<Item: u32> {
std::iter::once(42)
}
| f | identifier_name |
multipart.rs | use std::fmt;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
use mime_guess;
use crate::error::Result;
use crate::http::plus::random_alphanumeric;
const BOUNDARY_LEN: usize = 32;
fn gen_boundary() -> String {
random_alphanumeric(BOUNDARY_LEN)
}
use crate::http::mime::{self, Mime};
/// Create a structure to process the multipart/form-data data format for
/// the client to initiate the request.
///
/// # Examples
///
/// ```
/// use sincere::http::plus::client::Multipart;
///
/// let mut multipart = Multipart::new();
///
/// multipart.add_text("hello", "world");
///
/// let (boundary, data) = multipart.convert().unwrap();
/// ```
///
#[derive(Debug, Default)]
pub struct Multipart<'a> {
fields: Vec<Field<'a>>,
}
impl<'a> Multipart<'a> {
/// Returns the empty `Multipart` set.
///
/// # Examples
///
/// ```
/// use sincere::http::plus::client;
///
/// let mut multipart = client::Multipart::new();
/// ```
#[inline]
pub fn new() -> Multipart<'a> {
Multipart { fields: Vec::new() }
}
/// Add text 'key-value' into `Multipart`.
///
/// # Examples
///
/// ```
/// use sincere::http::plus::client;
///
/// let mut multipart = client::Multipart::new();
///
/// multipart.add_text("hello", "world");
/// ```
#[inline]
pub fn add_text<V>(&mut self, name: V, value: V) -> &mut Self
where
V: Into<String>,
{
let filed = Field {
name: name.into(),
data: Data::Text(value.into()),
};
self.fields.push(filed);
self
}
/// Add file into `Multipart`.
///
/// # Examples
///
/// ```no_test
/// use sincere::http::plus::client;
///
/// let mut multipart = client::Multipart::new();
///
/// multipart.add_file("hello.rs", "/aaa/bbb");
/// ```
#[inline]
pub fn add_file<V, P>(&mut self, name: V, path: P) -> &mut Self
where
V: Into<String>,
P: Into<PathBuf>,
{
let filed = Field {
name: name.into(),
data: Data::File(path.into()),
};
self.fields.push(filed);
self
}
/// Add reader stream into `Multipart`.
///
/// # Examples
///
/// ```
/// use sincere::http::plus::client;
///
/// let temp = r#"{"hello": "world"}"#.as_bytes();
/// let reader = ::std::io::Cursor::new(temp);
///
/// let mut multipart = client::Multipart::new();
///
/// multipart.add_stream("ddd", reader, Some("hello.rs"), Some(sincere::http::mime::APPLICATION_JSON));
/// ```
#[inline]
pub fn add_stream<V, R>(
&mut self,
name: V,
stream: R,
filename: Option<V>,
mime: Option<Mime>,
) -> &mut Self
where
R: Read + 'a,
V: Into<String>,
{
let filed = Field {
name: name.into(),
data: Data::Stream(Stream {
content_type: mime.unwrap_or(mime::APPLICATION_OCTET_STREAM),
filename: filename.map(|f| f.into()),
stream: Box::new(stream),
}),
};
self.fields.push(filed);
self
}
/// Convert `Multipart` to client boundary and body.
///
/// # Examples
///
/// ```
/// use sincere::http::plus::client;
///
/// let mut multipart = client::Multipart::new();
///
/// multipart.add_text("hello", "world");
///
/// let (boundary, data) = multipart.convert().unwrap();
/// ```
pub fn convert(&mut self) -> Result<(String, Vec<u8>)> |
}
#[derive(Debug)]
struct Field<'a> {
name: String,
data: Data<'a>,
}
enum Data<'a> {
Text(String),
File(PathBuf),
Stream(Stream<'a>),
}
impl<'a> fmt::Debug for Data<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Data::Text(ref value) => write!(f, "Data::Text({:?})", value),
Data::File(ref path) => write!(f, "Data::File({:?})", path),
Data::Stream(_) => f.write_str("Data::Stream(Box<Read>)"),
}
}
}
struct Stream<'a> {
filename: Option<String>,
content_type: Mime,
stream: Box<dyn Read + 'a>,
}
fn mime_filename(path: &PathBuf) -> (Mime, Option<&str>) {
let content_type = mime_guess::from_path(path).first_or_octet_stream();
let filename = opt_filename(path);
(content_type, filename)
}
fn opt_filename(path: &PathBuf) -> Option<&str> {
path.file_name().and_then(|filename| filename.to_str())
}
| {
let mut boundary = format!("\r\n--{}", gen_boundary());
let mut buf: Vec<u8> = Vec::new();
for field in self.fields.drain(..) {
match field.data {
Data::Text(value) => {
write!(
buf,
"{}\r\nContent-Disposition: form-data; name=\"{}\"\r\n\r\n{}",
boundary, field.name, value
)?;
}
Data::File(path) => {
let (content_type, filename) = mime_filename(&path);
let mut file = File::open(&path)?;
write!(
buf,
"{}\r\nContent-Disposition: form-data; name=\"{}\"",
boundary, field.name
)?;
if let Some(filename) = filename {
write!(buf, "; filename=\"{}\"", filename)?;
}
write!(buf, "\r\nContent-Type: {}\r\n\r\n", content_type)?;
let mut temp: Vec<u8> = Vec::new();
file.read_to_end(&mut temp)?;
buf.extend(temp);
}
Data::Stream(mut stream) => {
write!(
buf,
"{}\r\nContent-Disposition: form-data; name=\"{}\"",
boundary, field.name
)?;
if let Some(filename) = stream.filename {
write!(buf, "; filename=\"{}\"", filename)?;
}
write!(buf, "\r\nContent-Type: {}\r\n\r\n", stream.content_type)?;
let mut temp: Vec<u8> = Vec::new();
stream.stream.read_to_end(&mut temp)?;
buf.extend(temp);
}
}
}
boundary.push_str("--");
buf.extend(boundary.as_bytes());
Ok((boundary[4..boundary.len() - 2].to_string(), buf))
} | identifier_body |
multipart.rs | use std::fmt;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
use mime_guess;
use crate::error::Result;
use crate::http::plus::random_alphanumeric;
const BOUNDARY_LEN: usize = 32;
fn gen_boundary() -> String {
random_alphanumeric(BOUNDARY_LEN)
}
use crate::http::mime::{self, Mime};
/// Create a structure to process the multipart/form-data data format for
/// the client to initiate the request.
///
/// # Examples
///
/// ```
/// use sincere::http::plus::client::Multipart;
///
/// let mut multipart = Multipart::new();
///
/// multipart.add_text("hello", "world");
///
/// let (boundary, data) = multipart.convert().unwrap();
/// ```
///
#[derive(Debug, Default)]
pub struct Multipart<'a> {
fields: Vec<Field<'a>>,
}
impl<'a> Multipart<'a> {
/// Returns the empty `Multipart` set.
///
/// # Examples
///
/// ```
/// use sincere::http::plus::client;
///
/// let mut multipart = client::Multipart::new();
/// ```
#[inline]
pub fn new() -> Multipart<'a> {
Multipart { fields: Vec::new() }
}
/// Add text 'key-value' into `Multipart`.
///
/// # Examples
///
/// ```
/// use sincere::http::plus::client;
///
/// let mut multipart = client::Multipart::new();
///
/// multipart.add_text("hello", "world");
/// ```
#[inline]
pub fn add_text<V>(&mut self, name: V, value: V) -> &mut Self
where
V: Into<String>,
{
let filed = Field {
name: name.into(),
data: Data::Text(value.into()),
};
self.fields.push(filed);
self
}
/// Add file into `Multipart`.
///
/// # Examples
///
/// ```no_test
/// use sincere::http::plus::client;
///
/// let mut multipart = client::Multipart::new();
///
/// multipart.add_file("hello.rs", "/aaa/bbb");
/// ```
#[inline]
pub fn add_file<V, P>(&mut self, name: V, path: P) -> &mut Self
where
V: Into<String>,
P: Into<PathBuf>,
{
let filed = Field {
name: name.into(),
data: Data::File(path.into()),
};
self.fields.push(filed);
self
}
/// Add reader stream into `Multipart`.
///
/// # Examples
///
/// ```
/// use sincere::http::plus::client;
///
/// let temp = r#"{"hello": "world"}"#.as_bytes();
/// let reader = ::std::io::Cursor::new(temp);
///
/// let mut multipart = client::Multipart::new();
///
/// multipart.add_stream("ddd", reader, Some("hello.rs"), Some(sincere::http::mime::APPLICATION_JSON));
/// ```
#[inline]
pub fn add_stream<V, R>(
&mut self,
name: V,
stream: R,
filename: Option<V>,
mime: Option<Mime>,
) -> &mut Self
where
R: Read + 'a,
V: Into<String>,
{
let filed = Field {
name: name.into(),
data: Data::Stream(Stream {
content_type: mime.unwrap_or(mime::APPLICATION_OCTET_STREAM),
filename: filename.map(|f| f.into()),
stream: Box::new(stream),
}),
};
self.fields.push(filed);
self
}
/// Convert `Multipart` to client boundary and body.
///
/// # Examples
///
/// ```
/// use sincere::http::plus::client;
///
/// let mut multipart = client::Multipart::new();
///
/// multipart.add_text("hello", "world");
///
/// let (boundary, data) = multipart.convert().unwrap();
/// ```
pub fn convert(&mut self) -> Result<(String, Vec<u8>)> {
let mut boundary = format!("\r\n--{}", gen_boundary());
let mut buf: Vec<u8> = Vec::new();
for field in self.fields.drain(..) {
match field.data {
Data::Text(value) => {
write!(
buf,
"{}\r\nContent-Disposition: form-data; name=\"{}\"\r\n\r\n{}",
boundary, field.name, value
)?;
}
Data::File(path) => {
let (content_type, filename) = mime_filename(&path);
let mut file = File::open(&path)?;
write!(
buf,
"{}\r\nContent-Disposition: form-data; name=\"{}\"",
boundary, field.name
)?;
if let Some(filename) = filename {
write!(buf, "; filename=\"{}\"", filename)?;
}
write!(buf, "\r\nContent-Type: {}\r\n\r\n", content_type)?;
let mut temp: Vec<u8> = Vec::new();
file.read_to_end(&mut temp)?;
buf.extend(temp);
}
Data::Stream(mut stream) => {
write!(
buf,
"{}\r\nContent-Disposition: form-data; name=\"{}\"",
boundary, field.name
)?;
if let Some(filename) = stream.filename {
write!(buf, "; filename=\"{}\"", filename)?;
}
write!(buf, "\r\nContent-Type: {}\r\n\r\n", stream.content_type)?;
let mut temp: Vec<u8> = Vec::new();
stream.stream.read_to_end(&mut temp)?;
buf.extend(temp);
}
}
}
boundary.push_str("--");
buf.extend(boundary.as_bytes());
Ok((boundary[4..boundary.len() - 2].to_string(), buf))
}
}
#[derive(Debug)]
struct Field<'a> {
name: String,
data: Data<'a>,
}
enum | <'a> {
Text(String),
File(PathBuf),
Stream(Stream<'a>),
}
impl<'a> fmt::Debug for Data<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Data::Text(ref value) => write!(f, "Data::Text({:?})", value),
Data::File(ref path) => write!(f, "Data::File({:?})", path),
Data::Stream(_) => f.write_str("Data::Stream(Box<Read>)"),
}
}
}
struct Stream<'a> {
filename: Option<String>,
content_type: Mime,
stream: Box<dyn Read + 'a>,
}
fn mime_filename(path: &PathBuf) -> (Mime, Option<&str>) {
let content_type = mime_guess::from_path(path).first_or_octet_stream();
let filename = opt_filename(path);
(content_type, filename)
}
fn opt_filename(path: &PathBuf) -> Option<&str> {
path.file_name().and_then(|filename| filename.to_str())
}
| Data | identifier_name |
multipart.rs | use std::fmt;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
use mime_guess;
use crate::error::Result;
use crate::http::plus::random_alphanumeric;
const BOUNDARY_LEN: usize = 32;
fn gen_boundary() -> String {
random_alphanumeric(BOUNDARY_LEN)
}
use crate::http::mime::{self, Mime};
/// Create a structure to process the multipart/form-data data format for
/// the client to initiate the request.
///
/// # Examples
///
/// ```
/// use sincere::http::plus::client::Multipart;
///
/// let mut multipart = Multipart::new();
///
/// multipart.add_text("hello", "world");
///
/// let (boundary, data) = multipart.convert().unwrap();
/// ```
///
#[derive(Debug, Default)]
pub struct Multipart<'a> {
fields: Vec<Field<'a>>,
}
impl<'a> Multipart<'a> {
/// Returns the empty `Multipart` set.
///
/// # Examples
///
/// ```
/// use sincere::http::plus::client;
///
/// let mut multipart = client::Multipart::new();
/// ```
#[inline]
pub fn new() -> Multipart<'a> {
Multipart { fields: Vec::new() }
}
/// Add text 'key-value' into `Multipart`.
///
/// # Examples
///
/// ```
/// use sincere::http::plus::client;
///
/// let mut multipart = client::Multipart::new();
///
/// multipart.add_text("hello", "world");
/// ```
#[inline]
pub fn add_text<V>(&mut self, name: V, value: V) -> &mut Self | V: Into<String>,
{
let filed = Field {
name: name.into(),
data: Data::Text(value.into()),
};
self.fields.push(filed);
self
}
/// Add file into `Multipart`.
///
/// # Examples
///
/// ```no_test
/// use sincere::http::plus::client;
///
/// let mut multipart = client::Multipart::new();
///
/// multipart.add_file("hello.rs", "/aaa/bbb");
/// ```
#[inline]
pub fn add_file<V, P>(&mut self, name: V, path: P) -> &mut Self
where
V: Into<String>,
P: Into<PathBuf>,
{
let filed = Field {
name: name.into(),
data: Data::File(path.into()),
};
self.fields.push(filed);
self
}
/// Add reader stream into `Multipart`.
///
/// # Examples
///
/// ```
/// use sincere::http::plus::client;
///
/// let temp = r#"{"hello": "world"}"#.as_bytes();
/// let reader = ::std::io::Cursor::new(temp);
///
/// let mut multipart = client::Multipart::new();
///
/// multipart.add_stream("ddd", reader, Some("hello.rs"), Some(sincere::http::mime::APPLICATION_JSON));
/// ```
#[inline]
pub fn add_stream<V, R>(
&mut self,
name: V,
stream: R,
filename: Option<V>,
mime: Option<Mime>,
) -> &mut Self
where
R: Read + 'a,
V: Into<String>,
{
let filed = Field {
name: name.into(),
data: Data::Stream(Stream {
content_type: mime.unwrap_or(mime::APPLICATION_OCTET_STREAM),
filename: filename.map(|f| f.into()),
stream: Box::new(stream),
}),
};
self.fields.push(filed);
self
}
/// Convert `Multipart` to client boundary and body.
///
/// # Examples
///
/// ```
/// use sincere::http::plus::client;
///
/// let mut multipart = client::Multipart::new();
///
/// multipart.add_text("hello", "world");
///
/// let (boundary, data) = multipart.convert().unwrap();
/// ```
pub fn convert(&mut self) -> Result<(String, Vec<u8>)> {
let mut boundary = format!("\r\n--{}", gen_boundary());
let mut buf: Vec<u8> = Vec::new();
for field in self.fields.drain(..) {
match field.data {
Data::Text(value) => {
write!(
buf,
"{}\r\nContent-Disposition: form-data; name=\"{}\"\r\n\r\n{}",
boundary, field.name, value
)?;
}
Data::File(path) => {
let (content_type, filename) = mime_filename(&path);
let mut file = File::open(&path)?;
write!(
buf,
"{}\r\nContent-Disposition: form-data; name=\"{}\"",
boundary, field.name
)?;
if let Some(filename) = filename {
write!(buf, "; filename=\"{}\"", filename)?;
}
write!(buf, "\r\nContent-Type: {}\r\n\r\n", content_type)?;
let mut temp: Vec<u8> = Vec::new();
file.read_to_end(&mut temp)?;
buf.extend(temp);
}
Data::Stream(mut stream) => {
write!(
buf,
"{}\r\nContent-Disposition: form-data; name=\"{}\"",
boundary, field.name
)?;
if let Some(filename) = stream.filename {
write!(buf, "; filename=\"{}\"", filename)?;
}
write!(buf, "\r\nContent-Type: {}\r\n\r\n", stream.content_type)?;
let mut temp: Vec<u8> = Vec::new();
stream.stream.read_to_end(&mut temp)?;
buf.extend(temp);
}
}
}
boundary.push_str("--");
buf.extend(boundary.as_bytes());
Ok((boundary[4..boundary.len() - 2].to_string(), buf))
}
}
#[derive(Debug)]
struct Field<'a> {
name: String,
data: Data<'a>,
}
enum Data<'a> {
Text(String),
File(PathBuf),
Stream(Stream<'a>),
}
impl<'a> fmt::Debug for Data<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Data::Text(ref value) => write!(f, "Data::Text({:?})", value),
Data::File(ref path) => write!(f, "Data::File({:?})", path),
Data::Stream(_) => f.write_str("Data::Stream(Box<Read>)"),
}
}
}
struct Stream<'a> {
filename: Option<String>,
content_type: Mime,
stream: Box<dyn Read + 'a>,
}
fn mime_filename(path: &PathBuf) -> (Mime, Option<&str>) {
let content_type = mime_guess::from_path(path).first_or_octet_stream();
let filename = opt_filename(path);
(content_type, filename)
}
fn opt_filename(path: &PathBuf) -> Option<&str> {
path.file_name().and_then(|filename| filename.to_str())
} | where | random_line_split |
multipart.rs | use std::fmt;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
use mime_guess;
use crate::error::Result;
use crate::http::plus::random_alphanumeric;
const BOUNDARY_LEN: usize = 32;
fn gen_boundary() -> String {
random_alphanumeric(BOUNDARY_LEN)
}
use crate::http::mime::{self, Mime};
/// Create a structure to process the multipart/form-data data format for
/// the client to initiate the request.
///
/// # Examples
///
/// ```
/// use sincere::http::plus::client::Multipart;
///
/// let mut multipart = Multipart::new();
///
/// multipart.add_text("hello", "world");
///
/// let (boundary, data) = multipart.convert().unwrap();
/// ```
///
#[derive(Debug, Default)]
pub struct Multipart<'a> {
fields: Vec<Field<'a>>,
}
impl<'a> Multipart<'a> {
/// Returns the empty `Multipart` set.
///
/// # Examples
///
/// ```
/// use sincere::http::plus::client;
///
/// let mut multipart = client::Multipart::new();
/// ```
#[inline]
pub fn new() -> Multipart<'a> {
Multipart { fields: Vec::new() }
}
/// Add text 'key-value' into `Multipart`.
///
/// # Examples
///
/// ```
/// use sincere::http::plus::client;
///
/// let mut multipart = client::Multipart::new();
///
/// multipart.add_text("hello", "world");
/// ```
#[inline]
pub fn add_text<V>(&mut self, name: V, value: V) -> &mut Self
where
V: Into<String>,
{
let filed = Field {
name: name.into(),
data: Data::Text(value.into()),
};
self.fields.push(filed);
self
}
/// Add file into `Multipart`.
///
/// # Examples
///
/// ```no_test
/// use sincere::http::plus::client;
///
/// let mut multipart = client::Multipart::new();
///
/// multipart.add_file("hello.rs", "/aaa/bbb");
/// ```
#[inline]
pub fn add_file<V, P>(&mut self, name: V, path: P) -> &mut Self
where
V: Into<String>,
P: Into<PathBuf>,
{
let filed = Field {
name: name.into(),
data: Data::File(path.into()),
};
self.fields.push(filed);
self
}
/// Add reader stream into `Multipart`.
///
/// # Examples
///
/// ```
/// use sincere::http::plus::client;
///
/// let temp = r#"{"hello": "world"}"#.as_bytes();
/// let reader = ::std::io::Cursor::new(temp);
///
/// let mut multipart = client::Multipart::new();
///
/// multipart.add_stream("ddd", reader, Some("hello.rs"), Some(sincere::http::mime::APPLICATION_JSON));
/// ```
#[inline]
pub fn add_stream<V, R>(
&mut self,
name: V,
stream: R,
filename: Option<V>,
mime: Option<Mime>,
) -> &mut Self
where
R: Read + 'a,
V: Into<String>,
{
let filed = Field {
name: name.into(),
data: Data::Stream(Stream {
content_type: mime.unwrap_or(mime::APPLICATION_OCTET_STREAM),
filename: filename.map(|f| f.into()),
stream: Box::new(stream),
}),
};
self.fields.push(filed);
self
}
/// Convert `Multipart` to client boundary and body.
///
/// # Examples
///
/// ```
/// use sincere::http::plus::client;
///
/// let mut multipart = client::Multipart::new();
///
/// multipart.add_text("hello", "world");
///
/// let (boundary, data) = multipart.convert().unwrap();
/// ```
pub fn convert(&mut self) -> Result<(String, Vec<u8>)> {
let mut boundary = format!("\r\n--{}", gen_boundary());
let mut buf: Vec<u8> = Vec::new();
for field in self.fields.drain(..) {
match field.data {
Data::Text(value) => |
Data::File(path) => {
let (content_type, filename) = mime_filename(&path);
let mut file = File::open(&path)?;
write!(
buf,
"{}\r\nContent-Disposition: form-data; name=\"{}\"",
boundary, field.name
)?;
if let Some(filename) = filename {
write!(buf, "; filename=\"{}\"", filename)?;
}
write!(buf, "\r\nContent-Type: {}\r\n\r\n", content_type)?;
let mut temp: Vec<u8> = Vec::new();
file.read_to_end(&mut temp)?;
buf.extend(temp);
}
Data::Stream(mut stream) => {
write!(
buf,
"{}\r\nContent-Disposition: form-data; name=\"{}\"",
boundary, field.name
)?;
if let Some(filename) = stream.filename {
write!(buf, "; filename=\"{}\"", filename)?;
}
write!(buf, "\r\nContent-Type: {}\r\n\r\n", stream.content_type)?;
let mut temp: Vec<u8> = Vec::new();
stream.stream.read_to_end(&mut temp)?;
buf.extend(temp);
}
}
}
boundary.push_str("--");
buf.extend(boundary.as_bytes());
Ok((boundary[4..boundary.len() - 2].to_string(), buf))
}
}
#[derive(Debug)]
struct Field<'a> {
name: String,
data: Data<'a>,
}
enum Data<'a> {
Text(String),
File(PathBuf),
Stream(Stream<'a>),
}
impl<'a> fmt::Debug for Data<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Data::Text(ref value) => write!(f, "Data::Text({:?})", value),
Data::File(ref path) => write!(f, "Data::File({:?})", path),
Data::Stream(_) => f.write_str("Data::Stream(Box<Read>)"),
}
}
}
struct Stream<'a> {
filename: Option<String>,
content_type: Mime,
stream: Box<dyn Read + 'a>,
}
fn mime_filename(path: &PathBuf) -> (Mime, Option<&str>) {
let content_type = mime_guess::from_path(path).first_or_octet_stream();
let filename = opt_filename(path);
(content_type, filename)
}
fn opt_filename(path: &PathBuf) -> Option<&str> {
path.file_name().and_then(|filename| filename.to_str())
}
| {
write!(
buf,
"{}\r\nContent-Disposition: form-data; name=\"{}\"\r\n\r\n{}",
boundary, field.name, value
)?;
} | conditional_block |
reimport_knowls_and_userdb.sage.py |
# This file was *autogenerated* from the file reimport_knowls_and_userdb.sage
from sage.all_cmdline import * # import sage library
_sage_const_0 = Integer(0)
os.chdir("/home/edgarcosta/lmfdb/")
import lmfdb
db = lmfdb.db_backend.db
DelayCommit = lmfdb.db_backend.DelayCommit
load("/home/edgarcosta/lmfdb-gce/transition_scripts/export_special.py")
def backup():
import subprocess
timestamp = datetime.now().strftime("%Y%m%d-%H%M")
userdbdump="/scratch/postgres-backup/userdb-backup-%s.tar" % timestamp
knowlsdump="/scratch/postgres-backup/knowls-backup-%s.tar" % timestamp
a = subprocess.check_call(["sudo", "-u", "postgres", "pg_dump", "--clean", "--if-exists", "--schema=userdb", "--file", userdbdump, "--format", "tar", "lmfdb"])
b = subprocess.check_call(["sudo", "-u", "postgres", "pg_dump", "--clean", "--if-exists", "--schema=public", "-t", 'kwl_knowls', "-t", "kwl_deleted", "-t", "kwl_history", "--file", knowlsdump, "--format", "tar", "lmfdb"], stderr=subprocess.STDOUT)
if a + b != _sage_const_0 :
print "Failed to backup users and kwl_*"
raise ValueError
print "Succeeded in backing up knowls and userdb"
return a + b
def import_knowls():
|
def import_users():
with DelayCommit(db, silence=True):
try:
conn = db.conn
cur = conn.cursor()
# delete rows of usersdb.users
"DELETE FROM userdb.users;"
with open('/scratch/importing/users.txt') as F:
cur.copy_from(F, 'userdb.users', columns=["username", "password", "bcpassword", "admin", "color_scheme", "full_name", "email", "url", "about", "created"])
except DatabaseError as err:
conn.rollback()
print "Failure in importing users"
print err
print "Successfully imported users"
export_knowls()
export_users()
backup()
import_knowls()
import_users()
| from psycopg2.sql import SQL
cur = db.conn.cursor()
tablenames = ['kwl_history', 'kwl_deleted', 'kwl_knowls'];
with DelayCommit(db, silence=True):
try:
# rename old tables
for name in tablenames:
cur.execute("ALTER TABLE IF EXISTS %s DROP CONSTRAINT IF EXISTS %s_pkey" % (name, name));
cur.execute("DROP TABLE IF EXISTS %s" % name);
# create tables
cur.execute("CREATE TABLE kwl_knowls (id text, cat text, title text, content text, authors jsonb, last_author text, quality text, timestamp timestamp, _keywords jsonb, history jsonb)")
cur.execute("CREATE TABLE kwl_deleted (id text, cat text, title text, content text, authors jsonb, last_author text, quality text, timestamp timestamp, _keywords jsonb, history jsonb)")
cur.execute("CREATE TABLE kwl_history (id text, title text, time timestamp, who text, state text)")
for tbl in ["kwl_knowls", "kwl_deleted", "kwl_history"]:
for action in ["INSERT", "UPDATE", "DELETE"]:
db._grant(action, tbl, ['webserver'])
db.grant_select(tbl)
with open('/scratch/importing/kwl_knowls.txt') as F:
cur.copy_from(F, 'kwl_knowls', columns=["id", "cat", "title", "content", "authors", "last_author", "quality", "timestamp", "_keywords", "history"])
with open('/scratch/importing/kwl_history.txt') as F:
cur.copy_from(F, 'kwl_history', columns=["id", "title", "time", "who", "state"])
cur.execute("ALTER TABLE kwl_knowls ADD CONSTRAINT kwl_knowls_pkey PRIMARY KEY (id)")
# no primary key on deleted
#cur.execute("ALTER TABLE kwl_deleted ADD CONSTRAINT kwl_deleted_pkey PRIMARY KEY (id)")
cur.execute("ALTER TABLE kwl_history ADD CONSTRAINT kwl_history_pkey PRIMARY KEY (id)")
except Exception:
print "Failure in importing knowls"
traceback.print_exc()
db.conn.rollback()
raise
print "Succeeded in importing knowls" | identifier_body |
reimport_knowls_and_userdb.sage.py | # This file was *autogenerated* from the file reimport_knowls_and_userdb.sage
from sage.all_cmdline import * # import sage library
_sage_const_0 = Integer(0)
os.chdir("/home/edgarcosta/lmfdb/")
import lmfdb
db = lmfdb.db_backend.db
DelayCommit = lmfdb.db_backend.DelayCommit
load("/home/edgarcosta/lmfdb-gce/transition_scripts/export_special.py")
def backup():
import subprocess
timestamp = datetime.now().strftime("%Y%m%d-%H%M")
userdbdump="/scratch/postgres-backup/userdb-backup-%s.tar" % timestamp
knowlsdump="/scratch/postgres-backup/knowls-backup-%s.tar" % timestamp
a = subprocess.check_call(["sudo", "-u", "postgres", "pg_dump", "--clean", "--if-exists", "--schema=userdb", "--file", userdbdump, "--format", "tar", "lmfdb"])
b = subprocess.check_call(["sudo", "-u", "postgres", "pg_dump", "--clean", "--if-exists", "--schema=public", "-t", 'kwl_knowls', "-t", "kwl_deleted", "-t", "kwl_history", "--file", knowlsdump, "--format", "tar", "lmfdb"], stderr=subprocess.STDOUT)
if a + b != _sage_const_0 :
print "Failed to backup users and kwl_*"
raise ValueError
print "Succeeded in backing up knowls and userdb"
return a + b
def import_knowls():
from psycopg2.sql import SQL
cur = db.conn.cursor()
tablenames = ['kwl_history', 'kwl_deleted', 'kwl_knowls'];
with DelayCommit(db, silence=True):
try:
# rename old tables
for name in tablenames:
cur.execute("ALTER TABLE IF EXISTS %s DROP CONSTRAINT IF EXISTS %s_pkey" % (name, name));
cur.execute("DROP TABLE IF EXISTS %s" % name);
# create tables
cur.execute("CREATE TABLE kwl_knowls (id text, cat text, title text, content text, authors jsonb, last_author text, quality text, timestamp timestamp, _keywords jsonb, history jsonb)")
cur.execute("CREATE TABLE kwl_deleted (id text, cat text, title text, content text, authors jsonb, last_author text, quality text, timestamp timestamp, _keywords jsonb, history jsonb)")
cur.execute("CREATE TABLE kwl_history (id text, title text, time timestamp, who text, state text)")
for tbl in ["kwl_knowls", "kwl_deleted", "kwl_history"]:
for action in ["INSERT", "UPDATE", "DELETE"]:
db._grant(action, tbl, ['webserver'])
db.grant_select(tbl)
with open('/scratch/importing/kwl_knowls.txt') as F:
cur.copy_from(F, 'kwl_knowls', columns=["id", "cat", "title", "content", "authors", "last_author", "quality", "timestamp", "_keywords", "history"])
with open('/scratch/importing/kwl_history.txt') as F:
cur.copy_from(F, 'kwl_history', columns=["id", "title", "time", "who", "state"])
cur.execute("ALTER TABLE kwl_knowls ADD CONSTRAINT kwl_knowls_pkey PRIMARY KEY (id)")
# no primary key on deleted
#cur.execute("ALTER TABLE kwl_deleted ADD CONSTRAINT kwl_deleted_pkey PRIMARY KEY (id)")
cur.execute("ALTER TABLE kwl_history ADD CONSTRAINT kwl_history_pkey PRIMARY KEY (id)")
except Exception:
print "Failure in importing knowls"
traceback.print_exc()
db.conn.rollback()
raise
print "Succeeded in importing knowls"
def import_users():
with DelayCommit(db, silence=True):
try:
conn = db.conn
cur = conn.cursor()
# delete rows of usersdb.users
"DELETE FROM userdb.users;"
with open('/scratch/importing/users.txt') as F:
cur.copy_from(F, 'userdb.users', columns=["username", "password", "bcpassword", "admin", "color_scheme", "full_name", "email", "url", "about", "created"]) |
except DatabaseError as err:
conn.rollback()
print "Failure in importing users"
print err
print "Successfully imported users"
export_knowls()
export_users()
backup()
import_knowls()
import_users() | random_line_split | |
reimport_knowls_and_userdb.sage.py |
# This file was *autogenerated* from the file reimport_knowls_and_userdb.sage
from sage.all_cmdline import * # import sage library
_sage_const_0 = Integer(0)
os.chdir("/home/edgarcosta/lmfdb/")
import lmfdb
db = lmfdb.db_backend.db
DelayCommit = lmfdb.db_backend.DelayCommit
load("/home/edgarcosta/lmfdb-gce/transition_scripts/export_special.py")
def backup():
import subprocess
timestamp = datetime.now().strftime("%Y%m%d-%H%M")
userdbdump="/scratch/postgres-backup/userdb-backup-%s.tar" % timestamp
knowlsdump="/scratch/postgres-backup/knowls-backup-%s.tar" % timestamp
a = subprocess.check_call(["sudo", "-u", "postgres", "pg_dump", "--clean", "--if-exists", "--schema=userdb", "--file", userdbdump, "--format", "tar", "lmfdb"])
b = subprocess.check_call(["sudo", "-u", "postgres", "pg_dump", "--clean", "--if-exists", "--schema=public", "-t", 'kwl_knowls', "-t", "kwl_deleted", "-t", "kwl_history", "--file", knowlsdump, "--format", "tar", "lmfdb"], stderr=subprocess.STDOUT)
if a + b != _sage_const_0 :
print "Failed to backup users and kwl_*"
raise ValueError
print "Succeeded in backing up knowls and userdb"
return a + b
def import_knowls():
from psycopg2.sql import SQL
cur = db.conn.cursor()
tablenames = ['kwl_history', 'kwl_deleted', 'kwl_knowls'];
with DelayCommit(db, silence=True):
try:
# rename old tables
for name in tablenames:
|
# create tables
cur.execute("CREATE TABLE kwl_knowls (id text, cat text, title text, content text, authors jsonb, last_author text, quality text, timestamp timestamp, _keywords jsonb, history jsonb)")
cur.execute("CREATE TABLE kwl_deleted (id text, cat text, title text, content text, authors jsonb, last_author text, quality text, timestamp timestamp, _keywords jsonb, history jsonb)")
cur.execute("CREATE TABLE kwl_history (id text, title text, time timestamp, who text, state text)")
for tbl in ["kwl_knowls", "kwl_deleted", "kwl_history"]:
for action in ["INSERT", "UPDATE", "DELETE"]:
db._grant(action, tbl, ['webserver'])
db.grant_select(tbl)
with open('/scratch/importing/kwl_knowls.txt') as F:
cur.copy_from(F, 'kwl_knowls', columns=["id", "cat", "title", "content", "authors", "last_author", "quality", "timestamp", "_keywords", "history"])
with open('/scratch/importing/kwl_history.txt') as F:
cur.copy_from(F, 'kwl_history', columns=["id", "title", "time", "who", "state"])
cur.execute("ALTER TABLE kwl_knowls ADD CONSTRAINT kwl_knowls_pkey PRIMARY KEY (id)")
# no primary key on deleted
#cur.execute("ALTER TABLE kwl_deleted ADD CONSTRAINT kwl_deleted_pkey PRIMARY KEY (id)")
cur.execute("ALTER TABLE kwl_history ADD CONSTRAINT kwl_history_pkey PRIMARY KEY (id)")
except Exception:
print "Failure in importing knowls"
traceback.print_exc()
db.conn.rollback()
raise
print "Succeeded in importing knowls"
def import_users():
with DelayCommit(db, silence=True):
try:
conn = db.conn
cur = conn.cursor()
# delete rows of usersdb.users
"DELETE FROM userdb.users;"
with open('/scratch/importing/users.txt') as F:
cur.copy_from(F, 'userdb.users', columns=["username", "password", "bcpassword", "admin", "color_scheme", "full_name", "email", "url", "about", "created"])
except DatabaseError as err:
conn.rollback()
print "Failure in importing users"
print err
print "Successfully imported users"
export_knowls()
export_users()
backup()
import_knowls()
import_users()
| cur.execute("ALTER TABLE IF EXISTS %s DROP CONSTRAINT IF EXISTS %s_pkey" % (name, name));
cur.execute("DROP TABLE IF EXISTS %s" % name); | conditional_block |
reimport_knowls_and_userdb.sage.py |
# This file was *autogenerated* from the file reimport_knowls_and_userdb.sage
from sage.all_cmdline import * # import sage library
_sage_const_0 = Integer(0)
os.chdir("/home/edgarcosta/lmfdb/")
import lmfdb
db = lmfdb.db_backend.db
DelayCommit = lmfdb.db_backend.DelayCommit
load("/home/edgarcosta/lmfdb-gce/transition_scripts/export_special.py")
def | ():
import subprocess
timestamp = datetime.now().strftime("%Y%m%d-%H%M")
userdbdump="/scratch/postgres-backup/userdb-backup-%s.tar" % timestamp
knowlsdump="/scratch/postgres-backup/knowls-backup-%s.tar" % timestamp
a = subprocess.check_call(["sudo", "-u", "postgres", "pg_dump", "--clean", "--if-exists", "--schema=userdb", "--file", userdbdump, "--format", "tar", "lmfdb"])
b = subprocess.check_call(["sudo", "-u", "postgres", "pg_dump", "--clean", "--if-exists", "--schema=public", "-t", 'kwl_knowls', "-t", "kwl_deleted", "-t", "kwl_history", "--file", knowlsdump, "--format", "tar", "lmfdb"], stderr=subprocess.STDOUT)
if a + b != _sage_const_0 :
print "Failed to backup users and kwl_*"
raise ValueError
print "Succeeded in backing up knowls and userdb"
return a + b
def import_knowls():
from psycopg2.sql import SQL
cur = db.conn.cursor()
tablenames = ['kwl_history', 'kwl_deleted', 'kwl_knowls'];
with DelayCommit(db, silence=True):
try:
# rename old tables
for name in tablenames:
cur.execute("ALTER TABLE IF EXISTS %s DROP CONSTRAINT IF EXISTS %s_pkey" % (name, name));
cur.execute("DROP TABLE IF EXISTS %s" % name);
# create tables
cur.execute("CREATE TABLE kwl_knowls (id text, cat text, title text, content text, authors jsonb, last_author text, quality text, timestamp timestamp, _keywords jsonb, history jsonb)")
cur.execute("CREATE TABLE kwl_deleted (id text, cat text, title text, content text, authors jsonb, last_author text, quality text, timestamp timestamp, _keywords jsonb, history jsonb)")
cur.execute("CREATE TABLE kwl_history (id text, title text, time timestamp, who text, state text)")
for tbl in ["kwl_knowls", "kwl_deleted", "kwl_history"]:
for action in ["INSERT", "UPDATE", "DELETE"]:
db._grant(action, tbl, ['webserver'])
db.grant_select(tbl)
with open('/scratch/importing/kwl_knowls.txt') as F:
cur.copy_from(F, 'kwl_knowls', columns=["id", "cat", "title", "content", "authors", "last_author", "quality", "timestamp", "_keywords", "history"])
with open('/scratch/importing/kwl_history.txt') as F:
cur.copy_from(F, 'kwl_history', columns=["id", "title", "time", "who", "state"])
cur.execute("ALTER TABLE kwl_knowls ADD CONSTRAINT kwl_knowls_pkey PRIMARY KEY (id)")
# no primary key on deleted
#cur.execute("ALTER TABLE kwl_deleted ADD CONSTRAINT kwl_deleted_pkey PRIMARY KEY (id)")
cur.execute("ALTER TABLE kwl_history ADD CONSTRAINT kwl_history_pkey PRIMARY KEY (id)")
except Exception:
print "Failure in importing knowls"
traceback.print_exc()
db.conn.rollback()
raise
print "Succeeded in importing knowls"
def import_users():
with DelayCommit(db, silence=True):
try:
conn = db.conn
cur = conn.cursor()
# delete rows of usersdb.users
"DELETE FROM userdb.users;"
with open('/scratch/importing/users.txt') as F:
cur.copy_from(F, 'userdb.users', columns=["username", "password", "bcpassword", "admin", "color_scheme", "full_name", "email", "url", "about", "created"])
except DatabaseError as err:
conn.rollback()
print "Failure in importing users"
print err
print "Successfully imported users"
export_knowls()
export_users()
backup()
import_knowls()
import_users()
| backup | identifier_name |
grover_example.py | #!/usr/bin/env python
"""Grover's quantum search algorithm example."""
from sympy import pprint
from sympy.physics.quantum import qapply
from sympy.physics.quantum.qubit import IntQubit
from sympy.physics.quantum.grover import (OracleGate, superposition_basis,
WGate, grover_iteration)
def demo_vgate_app(v):
for i in range(2**v.nqubits):
print('qapply(v*IntQubit(%i, %r))' % (i, v.nqubits))
pprint(qapply(v*IntQubit(i, nqubits=v.nqubits)))
qapply(v*IntQubit(i, nqubits=v.nqubits))
def black_box(qubits):
return True if qubits == IntQubit(1, nqubits=qubits.nqubits) else False
def main():
print()
print('Demonstration of Grover\'s Algorithm')
print('The OracleGate or V Gate carries the unknown function f(x)')
print('> V|x> = ((-1)^f(x))|x> where f(x) = 1 when x = a (True in our case)')
print('> and 0 (False in our case) otherwise')
print()
nqubits = 2
print('nqubits = ', nqubits)
v = OracleGate(nqubits, black_box)
print('Oracle or v = OracleGate(%r, black_box)' % nqubits)
print()
psi = superposition_basis(nqubits)
print('psi:')
pprint(psi)
demo_vgate_app(v) | print('WGate or w = WGate(%r)' % nqubits)
print('On a 2 Qubit system like psi, 1 iteration is enough to yield |1>')
print('qapply(w*v*psi)')
pprint(qapply(w*v*psi))
print()
nqubits = 3
print('On a 3 Qubit system, it requires 2 iterations to achieve')
print('|1> with high enough probability')
psi = superposition_basis(nqubits)
print('psi:')
pprint(psi)
v = OracleGate(nqubits, black_box)
print('Oracle or v = OracleGate(%r, black_box)' % nqubits)
print()
print('iter1 = grover.grover_iteration(psi, v)')
iter1 = qapply(grover_iteration(psi, v))
pprint(iter1)
print()
print('iter2 = grover.grover_iteration(iter1, v)')
iter2 = qapply(grover_iteration(iter1, v))
pprint(iter2)
print()
if __name__ == "__main__":
main() | print('qapply(v*psi)')
pprint(qapply(v*psi))
print()
w = WGate(nqubits) | random_line_split |
grover_example.py | #!/usr/bin/env python
"""Grover's quantum search algorithm example."""
from sympy import pprint
from sympy.physics.quantum import qapply
from sympy.physics.quantum.qubit import IntQubit
from sympy.physics.quantum.grover import (OracleGate, superposition_basis,
WGate, grover_iteration)
def demo_vgate_app(v):
for i in range(2**v.nqubits):
print('qapply(v*IntQubit(%i, %r))' % (i, v.nqubits))
pprint(qapply(v*IntQubit(i, nqubits=v.nqubits)))
qapply(v*IntQubit(i, nqubits=v.nqubits))
def black_box(qubits):
return True if qubits == IntQubit(1, nqubits=qubits.nqubits) else False
def | ():
print()
print('Demonstration of Grover\'s Algorithm')
print('The OracleGate or V Gate carries the unknown function f(x)')
print('> V|x> = ((-1)^f(x))|x> where f(x) = 1 when x = a (True in our case)')
print('> and 0 (False in our case) otherwise')
print()
nqubits = 2
print('nqubits = ', nqubits)
v = OracleGate(nqubits, black_box)
print('Oracle or v = OracleGate(%r, black_box)' % nqubits)
print()
psi = superposition_basis(nqubits)
print('psi:')
pprint(psi)
demo_vgate_app(v)
print('qapply(v*psi)')
pprint(qapply(v*psi))
print()
w = WGate(nqubits)
print('WGate or w = WGate(%r)' % nqubits)
print('On a 2 Qubit system like psi, 1 iteration is enough to yield |1>')
print('qapply(w*v*psi)')
pprint(qapply(w*v*psi))
print()
nqubits = 3
print('On a 3 Qubit system, it requires 2 iterations to achieve')
print('|1> with high enough probability')
psi = superposition_basis(nqubits)
print('psi:')
pprint(psi)
v = OracleGate(nqubits, black_box)
print('Oracle or v = OracleGate(%r, black_box)' % nqubits)
print()
print('iter1 = grover.grover_iteration(psi, v)')
iter1 = qapply(grover_iteration(psi, v))
pprint(iter1)
print()
print('iter2 = grover.grover_iteration(iter1, v)')
iter2 = qapply(grover_iteration(iter1, v))
pprint(iter2)
print()
if __name__ == "__main__":
main()
| main | identifier_name |
grover_example.py | #!/usr/bin/env python
"""Grover's quantum search algorithm example."""
from sympy import pprint
from sympy.physics.quantum import qapply
from sympy.physics.quantum.qubit import IntQubit
from sympy.physics.quantum.grover import (OracleGate, superposition_basis,
WGate, grover_iteration)
def demo_vgate_app(v):
for i in range(2**v.nqubits):
print('qapply(v*IntQubit(%i, %r))' % (i, v.nqubits))
pprint(qapply(v*IntQubit(i, nqubits=v.nqubits)))
qapply(v*IntQubit(i, nqubits=v.nqubits))
def black_box(qubits):
return True if qubits == IntQubit(1, nqubits=qubits.nqubits) else False
def main():
print()
print('Demonstration of Grover\'s Algorithm')
print('The OracleGate or V Gate carries the unknown function f(x)')
print('> V|x> = ((-1)^f(x))|x> where f(x) = 1 when x = a (True in our case)')
print('> and 0 (False in our case) otherwise')
print()
nqubits = 2
print('nqubits = ', nqubits)
v = OracleGate(nqubits, black_box)
print('Oracle or v = OracleGate(%r, black_box)' % nqubits)
print()
psi = superposition_basis(nqubits)
print('psi:')
pprint(psi)
demo_vgate_app(v)
print('qapply(v*psi)')
pprint(qapply(v*psi))
print()
w = WGate(nqubits)
print('WGate or w = WGate(%r)' % nqubits)
print('On a 2 Qubit system like psi, 1 iteration is enough to yield |1>')
print('qapply(w*v*psi)')
pprint(qapply(w*v*psi))
print()
nqubits = 3
print('On a 3 Qubit system, it requires 2 iterations to achieve')
print('|1> with high enough probability')
psi = superposition_basis(nqubits)
print('psi:')
pprint(psi)
v = OracleGate(nqubits, black_box)
print('Oracle or v = OracleGate(%r, black_box)' % nqubits)
print()
print('iter1 = grover.grover_iteration(psi, v)')
iter1 = qapply(grover_iteration(psi, v))
pprint(iter1)
print()
print('iter2 = grover.grover_iteration(iter1, v)')
iter2 = qapply(grover_iteration(iter1, v))
pprint(iter2)
print()
if __name__ == "__main__":
| main() | conditional_block | |
grover_example.py | #!/usr/bin/env python
"""Grover's quantum search algorithm example."""
from sympy import pprint
from sympy.physics.quantum import qapply
from sympy.physics.quantum.qubit import IntQubit
from sympy.physics.quantum.grover import (OracleGate, superposition_basis,
WGate, grover_iteration)
def demo_vgate_app(v):
|
def black_box(qubits):
return True if qubits == IntQubit(1, nqubits=qubits.nqubits) else False
def main():
print()
print('Demonstration of Grover\'s Algorithm')
print('The OracleGate or V Gate carries the unknown function f(x)')
print('> V|x> = ((-1)^f(x))|x> where f(x) = 1 when x = a (True in our case)')
print('> and 0 (False in our case) otherwise')
print()
nqubits = 2
print('nqubits = ', nqubits)
v = OracleGate(nqubits, black_box)
print('Oracle or v = OracleGate(%r, black_box)' % nqubits)
print()
psi = superposition_basis(nqubits)
print('psi:')
pprint(psi)
demo_vgate_app(v)
print('qapply(v*psi)')
pprint(qapply(v*psi))
print()
w = WGate(nqubits)
print('WGate or w = WGate(%r)' % nqubits)
print('On a 2 Qubit system like psi, 1 iteration is enough to yield |1>')
print('qapply(w*v*psi)')
pprint(qapply(w*v*psi))
print()
nqubits = 3
print('On a 3 Qubit system, it requires 2 iterations to achieve')
print('|1> with high enough probability')
psi = superposition_basis(nqubits)
print('psi:')
pprint(psi)
v = OracleGate(nqubits, black_box)
print('Oracle or v = OracleGate(%r, black_box)' % nqubits)
print()
print('iter1 = grover.grover_iteration(psi, v)')
iter1 = qapply(grover_iteration(psi, v))
pprint(iter1)
print()
print('iter2 = grover.grover_iteration(iter1, v)')
iter2 = qapply(grover_iteration(iter1, v))
pprint(iter2)
print()
if __name__ == "__main__":
main()
| for i in range(2**v.nqubits):
print('qapply(v*IntQubit(%i, %r))' % (i, v.nqubits))
pprint(qapply(v*IntQubit(i, nqubits=v.nqubits)))
qapply(v*IntQubit(i, nqubits=v.nqubits)) | identifier_body |
default.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{MetaItem, Item, Expr};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
use ptr::P;
pub fn expand_deriving_default<F>(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Item,
push: F) where
F: FnOnce(P<Item>),
|
fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let default_ident = vec!(
cx.ident_of_std("core"),
cx.ident_of("default"),
cx.ident_of("Default"),
cx.ident_of("default")
);
let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
return match *substr.fields {
StaticStruct(_, ref summary) => {
match *summary {
Unnamed(ref fields) => {
if fields.is_empty() {
cx.expr_ident(trait_span, substr.type_ident)
} else {
let exprs = fields.iter().map(|sp| default_call(*sp)).collect();
cx.expr_call_ident(trait_span, substr.type_ident, exprs)
}
}
Named(ref fields) => {
let default_fields = fields.iter().map(|&(ident, span)| {
cx.field_imm(span, ident, default_call(span))
}).collect();
cx.expr_struct_ident(trait_span, substr.type_ident, default_fields)
}
}
}
StaticEnum(..) => {
cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs");
// let compilation continue
cx.expr_usize(trait_span, 0)
}
_ => cx.span_bug(trait_span, "Non-static method in `derive(Default)`")
};
}
| {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: path_std!(cx, core::default::Default),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "default",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: Vec::new(),
ret_ty: Self,
attributes: attrs,
combine_substructure: combine_substructure(box |a, b, c| {
default_substructure(a, b, c)
})
}
),
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, item, push)
} | identifier_body |
default.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{MetaItem, Item, Expr};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
use ptr::P;
pub fn expand_deriving_default<F>(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Item,
push: F) where
F: FnOnce(P<Item>),
{
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: path_std!(cx, core::default::Default),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "default",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: Vec::new(),
ret_ty: Self,
attributes: attrs,
combine_substructure: combine_substructure(box |a, b, c| {
default_substructure(a, b, c)
})
}
),
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, item, push)
}
fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let default_ident = vec!(
cx.ident_of_std("core"),
cx.ident_of("default"),
cx.ident_of("Default"),
cx.ident_of("default")
);
let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
return match *substr.fields {
StaticStruct(_, ref summary) => |
StaticEnum(..) => {
cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs");
// let compilation continue
cx.expr_usize(trait_span, 0)
}
_ => cx.span_bug(trait_span, "Non-static method in `derive(Default)`")
};
}
| {
match *summary {
Unnamed(ref fields) => {
if fields.is_empty() {
cx.expr_ident(trait_span, substr.type_ident)
} else {
let exprs = fields.iter().map(|sp| default_call(*sp)).collect();
cx.expr_call_ident(trait_span, substr.type_ident, exprs)
}
}
Named(ref fields) => {
let default_fields = fields.iter().map(|&(ident, span)| {
cx.field_imm(span, ident, default_call(span))
}).collect();
cx.expr_struct_ident(trait_span, substr.type_ident, default_fields)
}
}
} | conditional_block |
default.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{MetaItem, Item, Expr};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder; | use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
use ptr::P;
pub fn expand_deriving_default<F>(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Item,
push: F) where
F: FnOnce(P<Item>),
{
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: path_std!(cx, core::default::Default),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "default",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: Vec::new(),
ret_ty: Self,
attributes: attrs,
combine_substructure: combine_substructure(box |a, b, c| {
default_substructure(a, b, c)
})
}
),
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, item, push)
}
fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let default_ident = vec!(
cx.ident_of_std("core"),
cx.ident_of("default"),
cx.ident_of("Default"),
cx.ident_of("default")
);
let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
return match *substr.fields {
StaticStruct(_, ref summary) => {
match *summary {
Unnamed(ref fields) => {
if fields.is_empty() {
cx.expr_ident(trait_span, substr.type_ident)
} else {
let exprs = fields.iter().map(|sp| default_call(*sp)).collect();
cx.expr_call_ident(trait_span, substr.type_ident, exprs)
}
}
Named(ref fields) => {
let default_fields = fields.iter().map(|&(ident, span)| {
cx.field_imm(span, ident, default_call(span))
}).collect();
cx.expr_struct_ident(trait_span, substr.type_ident, default_fields)
}
}
}
StaticEnum(..) => {
cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs");
// let compilation continue
cx.expr_usize(trait_span, 0)
}
_ => cx.span_bug(trait_span, "Non-static method in `derive(Default)`")
};
} | random_line_split | |
default.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{MetaItem, Item, Expr};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
use ptr::P;
pub fn | <F>(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Item,
push: F) where
F: FnOnce(P<Item>),
{
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: path_std!(cx, core::default::Default),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "default",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: Vec::new(),
ret_ty: Self,
attributes: attrs,
combine_substructure: combine_substructure(box |a, b, c| {
default_substructure(a, b, c)
})
}
),
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, item, push)
}
fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let default_ident = vec!(
cx.ident_of_std("core"),
cx.ident_of("default"),
cx.ident_of("Default"),
cx.ident_of("default")
);
let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
return match *substr.fields {
StaticStruct(_, ref summary) => {
match *summary {
Unnamed(ref fields) => {
if fields.is_empty() {
cx.expr_ident(trait_span, substr.type_ident)
} else {
let exprs = fields.iter().map(|sp| default_call(*sp)).collect();
cx.expr_call_ident(trait_span, substr.type_ident, exprs)
}
}
Named(ref fields) => {
let default_fields = fields.iter().map(|&(ident, span)| {
cx.field_imm(span, ident, default_call(span))
}).collect();
cx.expr_struct_ident(trait_span, substr.type_ident, default_fields)
}
}
}
StaticEnum(..) => {
cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs");
// let compilation continue
cx.expr_usize(trait_span, 0)
}
_ => cx.span_bug(trait_span, "Non-static method in `derive(Default)`")
};
}
| expand_deriving_default | identifier_name |
pipes.py | from cgi import escape
import gzip as gzip_module
import re
import time
import types
import uuid
from cStringIO import StringIO
def resolve_content(response):
rv = "".join(item for item in response.iter_content())
if type(rv) == unicode:
rv = rv.encode(response.encoding)
return rv
class Pipeline(object):
pipes = {}
def __init__(self, pipe_string):
self.pipe_functions = self.parse(pipe_string)
def parse(self, pipe_string):
functions = []
for item in PipeTokenizer().tokenize(pipe_string):
if not item:
break
if item[0] == "function":
functions.append((self.pipes[item[1]], []))
elif item[0] == "argument":
functions[-1][1].append(item[1])
return functions
def __call__(self, request, response):
for func, args in self.pipe_functions:
response = func(request, response, *args)
return response
class PipeTokenizer(object):
def __init__(self):
#This whole class can likely be replaced by some regexps
self.state = None
def tokenize(self, string):
self.string = string
self.state = self.func_name_state
self._index = 0
while self.state:
yield self.state()
yield None
def get_char(self):
if self._index >= len(self.string):
return None
rv = self.string[self._index]
self._index += 1
return rv
def func_name_state(self):
rv = ""
while True:
char = self.get_char()
if char is None:
self.state = None
if rv:
return ("function", rv)
else:
return None
elif char == "(":
self.state = self.argument_state
return ("function", rv)
elif char == "|":
if rv:
return ("function", rv)
else:
rv += char
def argument_state(self):
rv = ""
while True:
char = self.get_char()
if char is None:
self.state = None
return ("argument", rv)
elif char == "\\":
|
elif char == ",":
return ("argument", rv)
elif char == ")":
self.state = self.func_name_state
return ("argument", rv)
else:
rv += char
def get_escape(self):
char = self.get_char()
escapes = {"n": "\n",
"r": "\r",
"t": "\t"}
return escapes.get(char, char)
class pipe(object):
def __init__(self, *arg_converters):
self.arg_converters = arg_converters
self.max_args = len(self.arg_converters)
self.min_args = 0
opt_seen = False
for item in self.arg_converters:
if not opt_seen:
if isinstance(item, opt):
opt_seen = True
else:
self.min_args += 1
else:
if not isinstance(item, opt):
raise ValueError("Non-optional argument cannot follow optional argument")
def __call__(self, f):
def inner(request, response, *args):
if not (self.min_args <= len(args) <= self.max_args):
raise ValueError("Expected between %d and %d args, got %d" %
(self.min_args, self.max_args, len(args)))
arg_values = tuple(f(x) for f, x in zip(self.arg_converters, args))
return f(request, response, *arg_values)
Pipeline.pipes[f.__name__] = inner
#We actually want the undecorated function in the main namespace
return f
class opt(object):
def __init__(self, f):
self.f = f
def __call__(self, arg):
return self.f(arg)
def nullable(func):
def inner(arg):
if arg.lower() == "null":
return None
else:
return func(arg)
return inner
def boolean(arg):
if arg.lower() in ("true", "1"):
return True
elif arg.lower() in ("false", "0"):
return False
raise ValueError
@pipe(int)
def status(request, response, code):
"""Alter the status code.
:param code: Status code to use for the response."""
response.status = code
return response
@pipe(str, str, opt(boolean))
def header(request, response, name, value, append=False):
"""Set a HTTP header.
Replaces any existing HTTP header of the same name unless
append is set, in which case the header is appended without
replacement.
:param name: Name of the header to set.
:param value: Value to use for the header.
:param append: True if existing headers should not be replaced
"""
if not append:
response.headers.set(name, value)
else:
response.headers.append(name, value)
return response
@pipe(str)
def trickle(request, response, delays):
"""Send the response in parts, with time delays.
:param delays: A string of delays and amounts, in bytes, of the
response to send. Each component is separated by
a colon. Amounts in bytes are plain integers, whilst
delays are floats prefixed with a single d e.g.
d1:100:d2
Would cause a 1 second delay, would then send 100 bytes
of the file, and then cause a 2 second delay, before sending
the remainder of the file.
If the last token is of the form rN, instead of sending the
remainder of the file, the previous N instructions will be
repeated until the whole file has been sent e.g.
d1:100:d2:r2
Causes a delay of 1s, then 100 bytes to be sent, then a 2s delay
and then a further 100 bytes followed by a two second delay
until the response has been fully sent.
"""
def parse_delays():
parts = delays.split(":")
rv = []
for item in parts:
if item.startswith("d"):
item_type = "delay"
item = item[1:]
value = float(item)
elif item.startswith("r"):
item_type = "repeat"
value = int(item[1:])
if not value % 2 == 0:
raise ValueError
else:
item_type = "bytes"
value = int(item)
if len(rv) and rv[-1][0] == item_type:
rv[-1][1] += value
else:
rv.append((item_type, value))
return rv
delays = parse_delays()
if not delays:
return response
content = resolve_content(response)
modified_content = []
offset = [0]
def sleep(seconds):
def inner():
time.sleep(seconds)
return ""
return inner
def add_content(delays, repeat=False):
for i, (item_type, value) in enumerate(delays):
if item_type == "bytes":
modified_content.append(content[offset[0]:offset[0] + value])
offset[0] += value
elif item_type == "delay":
modified_content.append(sleep(value))
elif item_type == "repeat":
assert i == len(delays) - 1
while offset[0] < len(content):
add_content(delays[-(value + 1):-1], True)
if not repeat and offset[0] < len(content):
modified_content.append(content[offset[0]:])
add_content(delays)
response.content = modified_content
return response
@pipe(nullable(int), opt(nullable(int)))
def slice(request, response, start, end=None):
"""Send a byte range of the response body
:param start: The starting offset. Follows python semantics including
negative numbers.
:param end: The ending offset, again with python semantics and None
(spelled "null" in a query string) to indicate the end of
the file.
"""
content = resolve_content(response)
response.content = content[start:end]
return response
class ReplacementTokenizer(object):
def ident(scanner, token):
return ("ident", token)
def index(scanner, token):
token = token[1:-1]
try:
token = int(token)
except ValueError:
token = unicode(token, "utf8")
return ("index", token)
def var(scanner, token):
token = token[:-1]
return ("var", token)
def tokenize(self, string):
return self.scanner.scan(string)[0]
scanner = re.Scanner([(r"\$\w+:", var),
(r"\$?\w+(?:\(\))?", ident),
(r"\[[^\]]*\]", index)])
class FirstWrapper(object):
def __init__(self, params):
self.params = params
def __getitem__(self, key):
try:
return self.params.first(key)
except KeyError:
return ""
@pipe()
def sub(request, response):
"""Substitute environment information about the server and request into the script.
The format is a very limited template language. Substitutions are
enclosed by {{ and }}. There are several avaliable substitutions:
host
A simple string value and represents the primary host from which the
tests are being run.
domains
A dictionary of available domains indexed by subdomain name.
ports
A dictionary of lists of ports indexed by protocol.
location
A dictionary of parts of the request URL. Valid keys are
'server, 'scheme', 'host', 'hostname', 'port', 'path' and 'query'.
'server' is scheme://host:port, 'host' is hostname:port, and query
includes the leading '?', but other delimiters are omitted.
headers
A dictionary of HTTP headers in the request.
GET
A dictionary of query parameters supplied with the request.
uuid()
A pesudo-random UUID suitable for usage with stash
So for example in a setup running on localhost with a www
subdomain and a http server on ports 80 and 81::
{{host}} => localhost
{{domains[www]}} => www.localhost
{{ports[http][1]}} => 81
It is also possible to assign a value to a variable name, which must start with
the $ character, using the ":" syntax e.g.
{{$id:uuid()}
Later substitutions in the same file may then refer to the variable
by name e.g.
{{$id}}
"""
content = resolve_content(response)
new_content = template(request, content)
response.content = new_content
return response
def template(request, content):
#TODO: There basically isn't any error handling here
tokenizer = ReplacementTokenizer()
variables = {}
def config_replacement(match):
content, = match.groups()
tokens = tokenizer.tokenize(content)
if tokens[0][0] == "var":
variable = tokens[0][1]
tokens = tokens[1:]
else:
variable = None
assert tokens[0][0] == "ident" and all(item[0] == "index" for item in tokens[1:]), tokens
field = tokens[0][1]
if field in variables:
value = variables[field]
elif field == "headers":
value = request.headers
elif field == "GET":
value = FirstWrapper(request.GET)
elif field in request.server.config:
value = request.server.config[tokens[0][1]]
elif field == "location":
value = {"server": "%s://%s:%s" % (request.url_parts.scheme,
request.url_parts.hostname,
request.url_parts.port),
"scheme": request.url_parts.scheme,
"host": "%s:%s" % (request.url_parts.hostname,
request.url_parts.port),
"hostname": request.url_parts.hostname,
"port": request.url_parts.port,
"path": request.url_parts.path,
"query": "?%s" % request.url_parts.query}
elif field == "uuid()":
value = str(uuid.uuid4())
elif field == "url_base":
value = request.url_base
else:
raise Exception("Undefined template variable %s" % field)
for item in tokens[1:]:
value = value[item[1]]
assert isinstance(value, (int,) + types.StringTypes), tokens
if variable is not None:
variables[variable] = value
#Should possibly support escaping for other contexts e.g. script
#TODO: read the encoding of the response
return escape(unicode(value), quote=True).encode("utf-8")
template_regexp = re.compile(r"{{([^}]*)}}")
new_content, count = template_regexp.subn(config_replacement, content)
return new_content
@pipe()
def gzip(request, response):
"""This pipe gzip-encodes response data.
It sets (or overwrites) these HTTP headers:
Content-Encoding is set to gzip
Content-Length is set to the length of the compressed content
"""
content = resolve_content(response)
response.headers.set("Content-Encoding", "gzip")
out = StringIO()
with gzip_module.GzipFile(fileobj=out, mode="w") as f:
f.write(content)
response.content = out.getvalue()
response.headers.set("Content-Length", len(response.content))
return response
| rv += self.get_escape()
if rv is None:
#This should perhaps be an error instead
return ("argument", rv) | conditional_block |
pipes.py | from cgi import escape
import gzip as gzip_module
import re
import time
import types
import uuid
from cStringIO import StringIO
def resolve_content(response):
rv = "".join(item for item in response.iter_content())
if type(rv) == unicode:
rv = rv.encode(response.encoding)
return rv
class Pipeline(object):
pipes = {}
def __init__(self, pipe_string):
self.pipe_functions = self.parse(pipe_string)
def parse(self, pipe_string):
functions = []
for item in PipeTokenizer().tokenize(pipe_string):
if not item:
break
if item[0] == "function":
functions.append((self.pipes[item[1]], []))
elif item[0] == "argument":
functions[-1][1].append(item[1])
return functions
def __call__(self, request, response):
for func, args in self.pipe_functions:
response = func(request, response, *args)
return response
class PipeTokenizer(object):
def __init__(self):
#This whole class can likely be replaced by some regexps
self.state = None
def tokenize(self, string):
self.string = string
self.state = self.func_name_state
self._index = 0
while self.state:
yield self.state()
yield None
def get_char(self):
if self._index >= len(self.string):
return None
rv = self.string[self._index]
self._index += 1
return rv
def func_name_state(self):
rv = ""
while True:
char = self.get_char()
if char is None:
self.state = None
if rv:
return ("function", rv)
else:
return None
elif char == "(":
self.state = self.argument_state
return ("function", rv)
elif char == "|":
if rv:
return ("function", rv)
else:
rv += char
def argument_state(self):
rv = ""
while True:
char = self.get_char()
if char is None:
self.state = None
return ("argument", rv)
elif char == "\\":
rv += self.get_escape()
if rv is None:
#This should perhaps be an error instead
return ("argument", rv)
elif char == ",":
return ("argument", rv)
elif char == ")":
self.state = self.func_name_state
return ("argument", rv)
else:
rv += char
def get_escape(self):
char = self.get_char()
escapes = {"n": "\n",
"r": "\r",
"t": "\t"}
return escapes.get(char, char)
class pipe(object):
def __init__(self, *arg_converters):
self.arg_converters = arg_converters
self.max_args = len(self.arg_converters)
self.min_args = 0
opt_seen = False
for item in self.arg_converters:
if not opt_seen:
if isinstance(item, opt):
opt_seen = True
else:
self.min_args += 1
else: | def inner(request, response, *args):
if not (self.min_args <= len(args) <= self.max_args):
raise ValueError("Expected between %d and %d args, got %d" %
(self.min_args, self.max_args, len(args)))
arg_values = tuple(f(x) for f, x in zip(self.arg_converters, args))
return f(request, response, *arg_values)
Pipeline.pipes[f.__name__] = inner
#We actually want the undecorated function in the main namespace
return f
class opt(object):
def __init__(self, f):
self.f = f
def __call__(self, arg):
return self.f(arg)
def nullable(func):
def inner(arg):
if arg.lower() == "null":
return None
else:
return func(arg)
return inner
def boolean(arg):
if arg.lower() in ("true", "1"):
return True
elif arg.lower() in ("false", "0"):
return False
raise ValueError
@pipe(int)
def status(request, response, code):
"""Alter the status code.
:param code: Status code to use for the response."""
response.status = code
return response
@pipe(str, str, opt(boolean))
def header(request, response, name, value, append=False):
"""Set a HTTP header.
Replaces any existing HTTP header of the same name unless
append is set, in which case the header is appended without
replacement.
:param name: Name of the header to set.
:param value: Value to use for the header.
:param append: True if existing headers should not be replaced
"""
if not append:
response.headers.set(name, value)
else:
response.headers.append(name, value)
return response
@pipe(str)
def trickle(request, response, delays):
"""Send the response in parts, with time delays.
:param delays: A string of delays and amounts, in bytes, of the
response to send. Each component is separated by
a colon. Amounts in bytes are plain integers, whilst
delays are floats prefixed with a single d e.g.
d1:100:d2
Would cause a 1 second delay, would then send 100 bytes
of the file, and then cause a 2 second delay, before sending
the remainder of the file.
If the last token is of the form rN, instead of sending the
remainder of the file, the previous N instructions will be
repeated until the whole file has been sent e.g.
d1:100:d2:r2
Causes a delay of 1s, then 100 bytes to be sent, then a 2s delay
and then a further 100 bytes followed by a two second delay
until the response has been fully sent.
"""
def parse_delays():
parts = delays.split(":")
rv = []
for item in parts:
if item.startswith("d"):
item_type = "delay"
item = item[1:]
value = float(item)
elif item.startswith("r"):
item_type = "repeat"
value = int(item[1:])
if not value % 2 == 0:
raise ValueError
else:
item_type = "bytes"
value = int(item)
if len(rv) and rv[-1][0] == item_type:
rv[-1][1] += value
else:
rv.append((item_type, value))
return rv
delays = parse_delays()
if not delays:
return response
content = resolve_content(response)
modified_content = []
offset = [0]
def sleep(seconds):
def inner():
time.sleep(seconds)
return ""
return inner
def add_content(delays, repeat=False):
for i, (item_type, value) in enumerate(delays):
if item_type == "bytes":
modified_content.append(content[offset[0]:offset[0] + value])
offset[0] += value
elif item_type == "delay":
modified_content.append(sleep(value))
elif item_type == "repeat":
assert i == len(delays) - 1
while offset[0] < len(content):
add_content(delays[-(value + 1):-1], True)
if not repeat and offset[0] < len(content):
modified_content.append(content[offset[0]:])
add_content(delays)
response.content = modified_content
return response
@pipe(nullable(int), opt(nullable(int)))
def slice(request, response, start, end=None):
"""Send a byte range of the response body
:param start: The starting offset. Follows python semantics including
negative numbers.
:param end: The ending offset, again with python semantics and None
(spelled "null" in a query string) to indicate the end of
the file.
"""
content = resolve_content(response)
response.content = content[start:end]
return response
class ReplacementTokenizer(object):
def ident(scanner, token):
return ("ident", token)
def index(scanner, token):
token = token[1:-1]
try:
token = int(token)
except ValueError:
token = unicode(token, "utf8")
return ("index", token)
def var(scanner, token):
token = token[:-1]
return ("var", token)
def tokenize(self, string):
return self.scanner.scan(string)[0]
scanner = re.Scanner([(r"\$\w+:", var),
(r"\$?\w+(?:\(\))?", ident),
(r"\[[^\]]*\]", index)])
class FirstWrapper(object):
def __init__(self, params):
self.params = params
def __getitem__(self, key):
try:
return self.params.first(key)
except KeyError:
return ""
@pipe()
def sub(request, response):
"""Substitute environment information about the server and request into the script.
The format is a very limited template language. Substitutions are
enclosed by {{ and }}. There are several avaliable substitutions:
host
A simple string value and represents the primary host from which the
tests are being run.
domains
A dictionary of available domains indexed by subdomain name.
ports
A dictionary of lists of ports indexed by protocol.
location
A dictionary of parts of the request URL. Valid keys are
'server, 'scheme', 'host', 'hostname', 'port', 'path' and 'query'.
'server' is scheme://host:port, 'host' is hostname:port, and query
includes the leading '?', but other delimiters are omitted.
headers
A dictionary of HTTP headers in the request.
GET
A dictionary of query parameters supplied with the request.
uuid()
A pesudo-random UUID suitable for usage with stash
So for example in a setup running on localhost with a www
subdomain and a http server on ports 80 and 81::
{{host}} => localhost
{{domains[www]}} => www.localhost
{{ports[http][1]}} => 81
It is also possible to assign a value to a variable name, which must start with
the $ character, using the ":" syntax e.g.
{{$id:uuid()}
Later substitutions in the same file may then refer to the variable
by name e.g.
{{$id}}
"""
content = resolve_content(response)
new_content = template(request, content)
response.content = new_content
return response
def template(request, content):
#TODO: There basically isn't any error handling here
tokenizer = ReplacementTokenizer()
variables = {}
def config_replacement(match):
content, = match.groups()
tokens = tokenizer.tokenize(content)
if tokens[0][0] == "var":
variable = tokens[0][1]
tokens = tokens[1:]
else:
variable = None
assert tokens[0][0] == "ident" and all(item[0] == "index" for item in tokens[1:]), tokens
field = tokens[0][1]
if field in variables:
value = variables[field]
elif field == "headers":
value = request.headers
elif field == "GET":
value = FirstWrapper(request.GET)
elif field in request.server.config:
value = request.server.config[tokens[0][1]]
elif field == "location":
value = {"server": "%s://%s:%s" % (request.url_parts.scheme,
request.url_parts.hostname,
request.url_parts.port),
"scheme": request.url_parts.scheme,
"host": "%s:%s" % (request.url_parts.hostname,
request.url_parts.port),
"hostname": request.url_parts.hostname,
"port": request.url_parts.port,
"path": request.url_parts.path,
"query": "?%s" % request.url_parts.query}
elif field == "uuid()":
value = str(uuid.uuid4())
elif field == "url_base":
value = request.url_base
else:
raise Exception("Undefined template variable %s" % field)
for item in tokens[1:]:
value = value[item[1]]
assert isinstance(value, (int,) + types.StringTypes), tokens
if variable is not None:
variables[variable] = value
#Should possibly support escaping for other contexts e.g. script
#TODO: read the encoding of the response
return escape(unicode(value), quote=True).encode("utf-8")
template_regexp = re.compile(r"{{([^}]*)}}")
new_content, count = template_regexp.subn(config_replacement, content)
return new_content
@pipe()
def gzip(request, response):
"""This pipe gzip-encodes response data.
It sets (or overwrites) these HTTP headers:
Content-Encoding is set to gzip
Content-Length is set to the length of the compressed content
"""
content = resolve_content(response)
response.headers.set("Content-Encoding", "gzip")
out = StringIO()
with gzip_module.GzipFile(fileobj=out, mode="w") as f:
f.write(content)
response.content = out.getvalue()
response.headers.set("Content-Length", len(response.content))
return response | if not isinstance(item, opt):
raise ValueError("Non-optional argument cannot follow optional argument")
def __call__(self, f): | random_line_split |
pipes.py | from cgi import escape
import gzip as gzip_module
import re
import time
import types
import uuid
from cStringIO import StringIO
def resolve_content(response):
rv = "".join(item for item in response.iter_content())
if type(rv) == unicode:
rv = rv.encode(response.encoding)
return rv
class Pipeline(object):
pipes = {}
def __init__(self, pipe_string):
self.pipe_functions = self.parse(pipe_string)
def parse(self, pipe_string):
functions = []
for item in PipeTokenizer().tokenize(pipe_string):
if not item:
break
if item[0] == "function":
functions.append((self.pipes[item[1]], []))
elif item[0] == "argument":
functions[-1][1].append(item[1])
return functions
def __call__(self, request, response):
for func, args in self.pipe_functions:
response = func(request, response, *args)
return response
class PipeTokenizer(object):
def __init__(self):
#This whole class can likely be replaced by some regexps
self.state = None
def tokenize(self, string):
self.string = string
self.state = self.func_name_state
self._index = 0
while self.state:
yield self.state()
yield None
def get_char(self):
if self._index >= len(self.string):
return None
rv = self.string[self._index]
self._index += 1
return rv
def func_name_state(self):
rv = ""
while True:
char = self.get_char()
if char is None:
self.state = None
if rv:
return ("function", rv)
else:
return None
elif char == "(":
self.state = self.argument_state
return ("function", rv)
elif char == "|":
if rv:
return ("function", rv)
else:
rv += char
def | (self):
rv = ""
while True:
char = self.get_char()
if char is None:
self.state = None
return ("argument", rv)
elif char == "\\":
rv += self.get_escape()
if rv is None:
#This should perhaps be an error instead
return ("argument", rv)
elif char == ",":
return ("argument", rv)
elif char == ")":
self.state = self.func_name_state
return ("argument", rv)
else:
rv += char
def get_escape(self):
char = self.get_char()
escapes = {"n": "\n",
"r": "\r",
"t": "\t"}
return escapes.get(char, char)
class pipe(object):
def __init__(self, *arg_converters):
self.arg_converters = arg_converters
self.max_args = len(self.arg_converters)
self.min_args = 0
opt_seen = False
for item in self.arg_converters:
if not opt_seen:
if isinstance(item, opt):
opt_seen = True
else:
self.min_args += 1
else:
if not isinstance(item, opt):
raise ValueError("Non-optional argument cannot follow optional argument")
def __call__(self, f):
def inner(request, response, *args):
if not (self.min_args <= len(args) <= self.max_args):
raise ValueError("Expected between %d and %d args, got %d" %
(self.min_args, self.max_args, len(args)))
arg_values = tuple(f(x) for f, x in zip(self.arg_converters, args))
return f(request, response, *arg_values)
Pipeline.pipes[f.__name__] = inner
#We actually want the undecorated function in the main namespace
return f
class opt(object):
def __init__(self, f):
self.f = f
def __call__(self, arg):
return self.f(arg)
def nullable(func):
def inner(arg):
if arg.lower() == "null":
return None
else:
return func(arg)
return inner
def boolean(arg):
if arg.lower() in ("true", "1"):
return True
elif arg.lower() in ("false", "0"):
return False
raise ValueError
@pipe(int)
def status(request, response, code):
"""Alter the status code.
:param code: Status code to use for the response."""
response.status = code
return response
@pipe(str, str, opt(boolean))
def header(request, response, name, value, append=False):
"""Set a HTTP header.
Replaces any existing HTTP header of the same name unless
append is set, in which case the header is appended without
replacement.
:param name: Name of the header to set.
:param value: Value to use for the header.
:param append: True if existing headers should not be replaced
"""
if not append:
response.headers.set(name, value)
else:
response.headers.append(name, value)
return response
@pipe(str)
def trickle(request, response, delays):
"""Send the response in parts, with time delays.
:param delays: A string of delays and amounts, in bytes, of the
response to send. Each component is separated by
a colon. Amounts in bytes are plain integers, whilst
delays are floats prefixed with a single d e.g.
d1:100:d2
Would cause a 1 second delay, would then send 100 bytes
of the file, and then cause a 2 second delay, before sending
the remainder of the file.
If the last token is of the form rN, instead of sending the
remainder of the file, the previous N instructions will be
repeated until the whole file has been sent e.g.
d1:100:d2:r2
Causes a delay of 1s, then 100 bytes to be sent, then a 2s delay
and then a further 100 bytes followed by a two second delay
until the response has been fully sent.
"""
def parse_delays():
parts = delays.split(":")
rv = []
for item in parts:
if item.startswith("d"):
item_type = "delay"
item = item[1:]
value = float(item)
elif item.startswith("r"):
item_type = "repeat"
value = int(item[1:])
if not value % 2 == 0:
raise ValueError
else:
item_type = "bytes"
value = int(item)
if len(rv) and rv[-1][0] == item_type:
rv[-1][1] += value
else:
rv.append((item_type, value))
return rv
delays = parse_delays()
if not delays:
return response
content = resolve_content(response)
modified_content = []
offset = [0]
def sleep(seconds):
def inner():
time.sleep(seconds)
return ""
return inner
def add_content(delays, repeat=False):
for i, (item_type, value) in enumerate(delays):
if item_type == "bytes":
modified_content.append(content[offset[0]:offset[0] + value])
offset[0] += value
elif item_type == "delay":
modified_content.append(sleep(value))
elif item_type == "repeat":
assert i == len(delays) - 1
while offset[0] < len(content):
add_content(delays[-(value + 1):-1], True)
if not repeat and offset[0] < len(content):
modified_content.append(content[offset[0]:])
add_content(delays)
response.content = modified_content
return response
@pipe(nullable(int), opt(nullable(int)))
def slice(request, response, start, end=None):
"""Send a byte range of the response body
:param start: The starting offset. Follows python semantics including
negative numbers.
:param end: The ending offset, again with python semantics and None
(spelled "null" in a query string) to indicate the end of
the file.
"""
content = resolve_content(response)
response.content = content[start:end]
return response
class ReplacementTokenizer(object):
def ident(scanner, token):
return ("ident", token)
def index(scanner, token):
token = token[1:-1]
try:
token = int(token)
except ValueError:
token = unicode(token, "utf8")
return ("index", token)
def var(scanner, token):
token = token[:-1]
return ("var", token)
def tokenize(self, string):
return self.scanner.scan(string)[0]
scanner = re.Scanner([(r"\$\w+:", var),
(r"\$?\w+(?:\(\))?", ident),
(r"\[[^\]]*\]", index)])
class FirstWrapper(object):
def __init__(self, params):
self.params = params
def __getitem__(self, key):
try:
return self.params.first(key)
except KeyError:
return ""
@pipe()
def sub(request, response):
"""Substitute environment information about the server and request into the script.
The format is a very limited template language. Substitutions are
enclosed by {{ and }}. There are several avaliable substitutions:
host
A simple string value and represents the primary host from which the
tests are being run.
domains
A dictionary of available domains indexed by subdomain name.
ports
A dictionary of lists of ports indexed by protocol.
location
A dictionary of parts of the request URL. Valid keys are
'server, 'scheme', 'host', 'hostname', 'port', 'path' and 'query'.
'server' is scheme://host:port, 'host' is hostname:port, and query
includes the leading '?', but other delimiters are omitted.
headers
A dictionary of HTTP headers in the request.
GET
A dictionary of query parameters supplied with the request.
uuid()
A pesudo-random UUID suitable for usage with stash
So for example in a setup running on localhost with a www
subdomain and a http server on ports 80 and 81::
{{host}} => localhost
{{domains[www]}} => www.localhost
{{ports[http][1]}} => 81
It is also possible to assign a value to a variable name, which must start with
the $ character, using the ":" syntax e.g.
{{$id:uuid()}
Later substitutions in the same file may then refer to the variable
by name e.g.
{{$id}}
"""
content = resolve_content(response)
new_content = template(request, content)
response.content = new_content
return response
def template(request, content):
#TODO: There basically isn't any error handling here
tokenizer = ReplacementTokenizer()
variables = {}
def config_replacement(match):
content, = match.groups()
tokens = tokenizer.tokenize(content)
if tokens[0][0] == "var":
variable = tokens[0][1]
tokens = tokens[1:]
else:
variable = None
assert tokens[0][0] == "ident" and all(item[0] == "index" for item in tokens[1:]), tokens
field = tokens[0][1]
if field in variables:
value = variables[field]
elif field == "headers":
value = request.headers
elif field == "GET":
value = FirstWrapper(request.GET)
elif field in request.server.config:
value = request.server.config[tokens[0][1]]
elif field == "location":
value = {"server": "%s://%s:%s" % (request.url_parts.scheme,
request.url_parts.hostname,
request.url_parts.port),
"scheme": request.url_parts.scheme,
"host": "%s:%s" % (request.url_parts.hostname,
request.url_parts.port),
"hostname": request.url_parts.hostname,
"port": request.url_parts.port,
"path": request.url_parts.path,
"query": "?%s" % request.url_parts.query}
elif field == "uuid()":
value = str(uuid.uuid4())
elif field == "url_base":
value = request.url_base
else:
raise Exception("Undefined template variable %s" % field)
for item in tokens[1:]:
value = value[item[1]]
assert isinstance(value, (int,) + types.StringTypes), tokens
if variable is not None:
variables[variable] = value
#Should possibly support escaping for other contexts e.g. script
#TODO: read the encoding of the response
return escape(unicode(value), quote=True).encode("utf-8")
template_regexp = re.compile(r"{{([^}]*)}}")
new_content, count = template_regexp.subn(config_replacement, content)
return new_content
@pipe()
def gzip(request, response):
"""This pipe gzip-encodes response data.
It sets (or overwrites) these HTTP headers:
Content-Encoding is set to gzip
Content-Length is set to the length of the compressed content
"""
content = resolve_content(response)
response.headers.set("Content-Encoding", "gzip")
out = StringIO()
with gzip_module.GzipFile(fileobj=out, mode="w") as f:
f.write(content)
response.content = out.getvalue()
response.headers.set("Content-Length", len(response.content))
return response
| argument_state | identifier_name |
pipes.py | from cgi import escape
import gzip as gzip_module
import re
import time
import types
import uuid
from cStringIO import StringIO
def resolve_content(response):
rv = "".join(item for item in response.iter_content())
if type(rv) == unicode:
rv = rv.encode(response.encoding)
return rv
class Pipeline(object):
pipes = {}
def __init__(self, pipe_string):
self.pipe_functions = self.parse(pipe_string)
def parse(self, pipe_string):
functions = []
for item in PipeTokenizer().tokenize(pipe_string):
if not item:
break
if item[0] == "function":
functions.append((self.pipes[item[1]], []))
elif item[0] == "argument":
functions[-1][1].append(item[1])
return functions
def __call__(self, request, response):
for func, args in self.pipe_functions:
response = func(request, response, *args)
return response
class PipeTokenizer(object):
def __init__(self):
#This whole class can likely be replaced by some regexps
self.state = None
def tokenize(self, string):
self.string = string
self.state = self.func_name_state
self._index = 0
while self.state:
yield self.state()
yield None
def get_char(self):
if self._index >= len(self.string):
return None
rv = self.string[self._index]
self._index += 1
return rv
def func_name_state(self):
rv = ""
while True:
char = self.get_char()
if char is None:
self.state = None
if rv:
return ("function", rv)
else:
return None
elif char == "(":
self.state = self.argument_state
return ("function", rv)
elif char == "|":
if rv:
return ("function", rv)
else:
rv += char
def argument_state(self):
rv = ""
while True:
char = self.get_char()
if char is None:
self.state = None
return ("argument", rv)
elif char == "\\":
rv += self.get_escape()
if rv is None:
#This should perhaps be an error instead
return ("argument", rv)
elif char == ",":
return ("argument", rv)
elif char == ")":
self.state = self.func_name_state
return ("argument", rv)
else:
rv += char
def get_escape(self):
char = self.get_char()
escapes = {"n": "\n",
"r": "\r",
"t": "\t"}
return escapes.get(char, char)
class pipe(object):
def __init__(self, *arg_converters):
self.arg_converters = arg_converters
self.max_args = len(self.arg_converters)
self.min_args = 0
opt_seen = False
for item in self.arg_converters:
if not opt_seen:
if isinstance(item, opt):
opt_seen = True
else:
self.min_args += 1
else:
if not isinstance(item, opt):
raise ValueError("Non-optional argument cannot follow optional argument")
def __call__(self, f):
def inner(request, response, *args):
if not (self.min_args <= len(args) <= self.max_args):
raise ValueError("Expected between %d and %d args, got %d" %
(self.min_args, self.max_args, len(args)))
arg_values = tuple(f(x) for f, x in zip(self.arg_converters, args))
return f(request, response, *arg_values)
Pipeline.pipes[f.__name__] = inner
#We actually want the undecorated function in the main namespace
return f
class opt(object):
def __init__(self, f):
self.f = f
def __call__(self, arg):
return self.f(arg)
def nullable(func):
def inner(arg):
|
return inner
def boolean(arg):
if arg.lower() in ("true", "1"):
return True
elif arg.lower() in ("false", "0"):
return False
raise ValueError
@pipe(int)
def status(request, response, code):
"""Alter the status code.
:param code: Status code to use for the response."""
response.status = code
return response
@pipe(str, str, opt(boolean))
def header(request, response, name, value, append=False):
"""Set a HTTP header.
Replaces any existing HTTP header of the same name unless
append is set, in which case the header is appended without
replacement.
:param name: Name of the header to set.
:param value: Value to use for the header.
:param append: True if existing headers should not be replaced
"""
if not append:
response.headers.set(name, value)
else:
response.headers.append(name, value)
return response
@pipe(str)
def trickle(request, response, delays):
"""Send the response in parts, with time delays.
:param delays: A string of delays and amounts, in bytes, of the
response to send. Each component is separated by
a colon. Amounts in bytes are plain integers, whilst
delays are floats prefixed with a single d e.g.
d1:100:d2
Would cause a 1 second delay, would then send 100 bytes
of the file, and then cause a 2 second delay, before sending
the remainder of the file.
If the last token is of the form rN, instead of sending the
remainder of the file, the previous N instructions will be
repeated until the whole file has been sent e.g.
d1:100:d2:r2
Causes a delay of 1s, then 100 bytes to be sent, then a 2s delay
and then a further 100 bytes followed by a two second delay
until the response has been fully sent.
"""
def parse_delays():
parts = delays.split(":")
rv = []
for item in parts:
if item.startswith("d"):
item_type = "delay"
item = item[1:]
value = float(item)
elif item.startswith("r"):
item_type = "repeat"
value = int(item[1:])
if not value % 2 == 0:
raise ValueError
else:
item_type = "bytes"
value = int(item)
if len(rv) and rv[-1][0] == item_type:
rv[-1][1] += value
else:
rv.append((item_type, value))
return rv
delays = parse_delays()
if not delays:
return response
content = resolve_content(response)
modified_content = []
offset = [0]
def sleep(seconds):
def inner():
time.sleep(seconds)
return ""
return inner
def add_content(delays, repeat=False):
for i, (item_type, value) in enumerate(delays):
if item_type == "bytes":
modified_content.append(content[offset[0]:offset[0] + value])
offset[0] += value
elif item_type == "delay":
modified_content.append(sleep(value))
elif item_type == "repeat":
assert i == len(delays) - 1
while offset[0] < len(content):
add_content(delays[-(value + 1):-1], True)
if not repeat and offset[0] < len(content):
modified_content.append(content[offset[0]:])
add_content(delays)
response.content = modified_content
return response
@pipe(nullable(int), opt(nullable(int)))
def slice(request, response, start, end=None):
"""Send a byte range of the response body
:param start: The starting offset. Follows python semantics including
negative numbers.
:param end: The ending offset, again with python semantics and None
(spelled "null" in a query string) to indicate the end of
the file.
"""
content = resolve_content(response)
response.content = content[start:end]
return response
class ReplacementTokenizer(object):
def ident(scanner, token):
return ("ident", token)
def index(scanner, token):
token = token[1:-1]
try:
token = int(token)
except ValueError:
token = unicode(token, "utf8")
return ("index", token)
def var(scanner, token):
token = token[:-1]
return ("var", token)
def tokenize(self, string):
return self.scanner.scan(string)[0]
scanner = re.Scanner([(r"\$\w+:", var),
(r"\$?\w+(?:\(\))?", ident),
(r"\[[^\]]*\]", index)])
class FirstWrapper(object):
def __init__(self, params):
self.params = params
def __getitem__(self, key):
try:
return self.params.first(key)
except KeyError:
return ""
@pipe()
def sub(request, response):
"""Substitute environment information about the server and request into the script.
The format is a very limited template language. Substitutions are
enclosed by {{ and }}. There are several avaliable substitutions:
host
A simple string value and represents the primary host from which the
tests are being run.
domains
A dictionary of available domains indexed by subdomain name.
ports
A dictionary of lists of ports indexed by protocol.
location
A dictionary of parts of the request URL. Valid keys are
'server, 'scheme', 'host', 'hostname', 'port', 'path' and 'query'.
'server' is scheme://host:port, 'host' is hostname:port, and query
includes the leading '?', but other delimiters are omitted.
headers
A dictionary of HTTP headers in the request.
GET
A dictionary of query parameters supplied with the request.
uuid()
A pesudo-random UUID suitable for usage with stash
So for example in a setup running on localhost with a www
subdomain and a http server on ports 80 and 81::
{{host}} => localhost
{{domains[www]}} => www.localhost
{{ports[http][1]}} => 81
It is also possible to assign a value to a variable name, which must start with
the $ character, using the ":" syntax e.g.
{{$id:uuid()}
Later substitutions in the same file may then refer to the variable
by name e.g.
{{$id}}
"""
content = resolve_content(response)
new_content = template(request, content)
response.content = new_content
return response
def template(request, content):
#TODO: There basically isn't any error handling here
tokenizer = ReplacementTokenizer()
variables = {}
def config_replacement(match):
content, = match.groups()
tokens = tokenizer.tokenize(content)
if tokens[0][0] == "var":
variable = tokens[0][1]
tokens = tokens[1:]
else:
variable = None
assert tokens[0][0] == "ident" and all(item[0] == "index" for item in tokens[1:]), tokens
field = tokens[0][1]
if field in variables:
value = variables[field]
elif field == "headers":
value = request.headers
elif field == "GET":
value = FirstWrapper(request.GET)
elif field in request.server.config:
value = request.server.config[tokens[0][1]]
elif field == "location":
value = {"server": "%s://%s:%s" % (request.url_parts.scheme,
request.url_parts.hostname,
request.url_parts.port),
"scheme": request.url_parts.scheme,
"host": "%s:%s" % (request.url_parts.hostname,
request.url_parts.port),
"hostname": request.url_parts.hostname,
"port": request.url_parts.port,
"path": request.url_parts.path,
"query": "?%s" % request.url_parts.query}
elif field == "uuid()":
value = str(uuid.uuid4())
elif field == "url_base":
value = request.url_base
else:
raise Exception("Undefined template variable %s" % field)
for item in tokens[1:]:
value = value[item[1]]
assert isinstance(value, (int,) + types.StringTypes), tokens
if variable is not None:
variables[variable] = value
#Should possibly support escaping for other contexts e.g. script
#TODO: read the encoding of the response
return escape(unicode(value), quote=True).encode("utf-8")
template_regexp = re.compile(r"{{([^}]*)}}")
new_content, count = template_regexp.subn(config_replacement, content)
return new_content
@pipe()
def gzip(request, response):
"""This pipe gzip-encodes response data.
It sets (or overwrites) these HTTP headers:
Content-Encoding is set to gzip
Content-Length is set to the length of the compressed content
"""
content = resolve_content(response)
response.headers.set("Content-Encoding", "gzip")
out = StringIO()
with gzip_module.GzipFile(fileobj=out, mode="w") as f:
f.write(content)
response.content = out.getvalue()
response.headers.set("Content-Length", len(response.content))
return response
| if arg.lower() == "null":
return None
else:
return func(arg) | identifier_body |
mixcloud.js | import React from 'react'
import Icon from 'react-icon-base'
const FaMixcloud = props => ( | <Icon viewBox="0 0 40 40" {...props}>
<g><path d="m28.8 23.5q0-1-0.6-1.8t-1.5-1.2q-0.1 0.8-0.4 1.6-0.1 0.4-0.5 0.6t-0.8 0.3q-0.2 0-0.4-0.1-0.5-0.1-0.8-0.6t-0.1-1.1q0.4-1.2 0.4-2.5 0-2.1-1-3.9t-2.9-2.9-4-1.1q-2.4 0-4.3 1.3t-3 3.4q1.9 0.5 3.3 1.8 0.4 0.4 0.4 1t-0.4 0.9-0.9 0.4-1-0.4q-1.3-1.3-3.1-1.3-1.9 0-3.2 1.3t-1.3 3.2 1.3 3.1 3.2 1.3h18.3q1.4 0 2.3-0.9t1-2.4z m2.7 0q0 2.5-1.8 4.3t-4.2 1.7h-18.3q-3 0-5.1-2.1t-2.1-5q0-2.7 1.8-4.7t4.3-2.4q1.1-3.2 3.9-5.2t6.2-2q4.1 0 7.1 2.8t3.5 6.8q2 0.4 3.3 2.1t1.4 3.7z m4.4 0q0 3.1-1.7 5.6-0.4 0.6-1.2 0.6-0.4 0-0.7-0.2-0.5-0.3-0.6-0.9t0.2-1q1.3-1.8 1.3-4.1t-1.3-4q-0.3-0.5-0.2-1t0.6-0.9 1-0.2 0.9 0.6q1.7 2.5 1.7 5.5z m4.4 0q0 4.3-2.3 7.8-0.4 0.6-1.1 0.6-0.4 0-0.8-0.2-0.4-0.4-0.5-0.9t0.2-1q1.9-2.9 1.9-6.3 0-3.4-1.9-6.2-0.3-0.5-0.2-1t0.5-0.9q0.5-0.3 1-0.2t0.9 0.6q2.3 3.5 2.3 7.7z"/></g>
</Icon>
)
export default FaMixcloud | random_line_split | |
hostproof_auth.js | function supports_html5_storage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
function randomString(length) |
function register(baseUrl, username, email, password) {
var deferred = new $.Deferred();
if (username && email && password) {
challenge = randomString(10)
encrypted_challenge = sjcl.encrypt(password, challenge)
$.when(
$.ajax({
type: "POST",
url: baseUrl,
data: {
"username" : username,
"email" : email,
"challenge" : challenge,
"encrypted_challenge" : encrypted_challenge
}
})
).done(function() {
deferred.resolve("Registration completed");
}).fail(function() {
deferred.reject("Registration failed");
});
} else {
deferred.reject("Invalid parameters");
}
return deferred.promise();
}
function login(baseUrl, username, password) {
var deferred = new $.Deferred();
if (username && password) {
$.when(
$.ajax({
type: "GET",
url: baseUrl + "?username=" + username,
})
).then(function(data) {
return sjcl.decrypt(password, data)
}).then(function(challenge) {
return $.ajax({
type: "POST",
url: baseUrl,
data: {
"username" : username,
"challenge" : challenge,
}
})
}).then(function(rsa_public) {
if (supports_html5_storage()) {
localStorage.setItem("rsa_public", rsa_public);
}
}).done(function(data) {
deferred.resolve("Login completed");
}).fail(function() {
deferred.reject("Login failed");
});
} else {
deferred.reject("Invalid parameters");
}
return deferred.promise();
}
| {
var text = "";
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i=0; i < length; i++) {
text += chars.charAt(Math.floor(Math.random() * chars.length));
}
return text;
} | identifier_body |
hostproof_auth.js | function supports_html5_storage() { | }
function randomString(length) {
var text = "";
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i=0; i < length; i++) {
text += chars.charAt(Math.floor(Math.random() * chars.length));
}
return text;
}
function register(baseUrl, username, email, password) {
var deferred = new $.Deferred();
if (username && email && password) {
challenge = randomString(10)
encrypted_challenge = sjcl.encrypt(password, challenge)
$.when(
$.ajax({
type: "POST",
url: baseUrl,
data: {
"username" : username,
"email" : email,
"challenge" : challenge,
"encrypted_challenge" : encrypted_challenge
}
})
).done(function() {
deferred.resolve("Registration completed");
}).fail(function() {
deferred.reject("Registration failed");
});
} else {
deferred.reject("Invalid parameters");
}
return deferred.promise();
}
function login(baseUrl, username, password) {
var deferred = new $.Deferred();
if (username && password) {
$.when(
$.ajax({
type: "GET",
url: baseUrl + "?username=" + username,
})
).then(function(data) {
return sjcl.decrypt(password, data)
}).then(function(challenge) {
return $.ajax({
type: "POST",
url: baseUrl,
data: {
"username" : username,
"challenge" : challenge,
}
})
}).then(function(rsa_public) {
if (supports_html5_storage()) {
localStorage.setItem("rsa_public", rsa_public);
}
}).done(function(data) {
deferred.resolve("Login completed");
}).fail(function() {
deferred.reject("Login failed");
});
} else {
deferred.reject("Invalid parameters");
}
return deferred.promise();
} | try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
} | random_line_split |
hostproof_auth.js | function supports_html5_storage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
function randomString(length) {
var text = "";
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i=0; i < length; i++) |
return text;
}
function register(baseUrl, username, email, password) {
var deferred = new $.Deferred();
if (username && email && password) {
challenge = randomString(10)
encrypted_challenge = sjcl.encrypt(password, challenge)
$.when(
$.ajax({
type: "POST",
url: baseUrl,
data: {
"username" : username,
"email" : email,
"challenge" : challenge,
"encrypted_challenge" : encrypted_challenge
}
})
).done(function() {
deferred.resolve("Registration completed");
}).fail(function() {
deferred.reject("Registration failed");
});
} else {
deferred.reject("Invalid parameters");
}
return deferred.promise();
}
function login(baseUrl, username, password) {
var deferred = new $.Deferred();
if (username && password) {
$.when(
$.ajax({
type: "GET",
url: baseUrl + "?username=" + username,
})
).then(function(data) {
return sjcl.decrypt(password, data)
}).then(function(challenge) {
return $.ajax({
type: "POST",
url: baseUrl,
data: {
"username" : username,
"challenge" : challenge,
}
})
}).then(function(rsa_public) {
if (supports_html5_storage()) {
localStorage.setItem("rsa_public", rsa_public);
}
}).done(function(data) {
deferred.resolve("Login completed");
}).fail(function() {
deferred.reject("Login failed");
});
} else {
deferred.reject("Invalid parameters");
}
return deferred.promise();
}
| {
text += chars.charAt(Math.floor(Math.random() * chars.length));
} | conditional_block |
hostproof_auth.js | function | () {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
function randomString(length) {
var text = "";
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i=0; i < length; i++) {
text += chars.charAt(Math.floor(Math.random() * chars.length));
}
return text;
}
function register(baseUrl, username, email, password) {
var deferred = new $.Deferred();
if (username && email && password) {
challenge = randomString(10)
encrypted_challenge = sjcl.encrypt(password, challenge)
$.when(
$.ajax({
type: "POST",
url: baseUrl,
data: {
"username" : username,
"email" : email,
"challenge" : challenge,
"encrypted_challenge" : encrypted_challenge
}
})
).done(function() {
deferred.resolve("Registration completed");
}).fail(function() {
deferred.reject("Registration failed");
});
} else {
deferred.reject("Invalid parameters");
}
return deferred.promise();
}
function login(baseUrl, username, password) {
var deferred = new $.Deferred();
if (username && password) {
$.when(
$.ajax({
type: "GET",
url: baseUrl + "?username=" + username,
})
).then(function(data) {
return sjcl.decrypt(password, data)
}).then(function(challenge) {
return $.ajax({
type: "POST",
url: baseUrl,
data: {
"username" : username,
"challenge" : challenge,
}
})
}).then(function(rsa_public) {
if (supports_html5_storage()) {
localStorage.setItem("rsa_public", rsa_public);
}
}).done(function(data) {
deferred.resolve("Login completed");
}).fail(function() {
deferred.reject("Login failed");
});
} else {
deferred.reject("Invalid parameters");
}
return deferred.promise();
}
| supports_html5_storage | identifier_name |
utils.py | # Copyright 2015 Palo Alto Networks, Inc
#
# 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 time
import operator
import functools
import datetime
import pytz
import re
import gevent
import gevent.lock
import gevent.event
EPOCH = datetime.datetime.utcfromtimestamp(0).replace(tzinfo=pytz.UTC)
def utc_millisec():
return int(time.time()*1000)
def dt_to_millisec(dt):
if dt.tzinfo == None:
dt = dt.replace(tzinfo=pytz.UTC)
delta = dt - EPOCH
return int(delta.total_seconds()*1000)
def interval_in_sec(val):
if isinstance(val, int):
return val
multipliers = {
'': 1,
'm': 60,
'h': 3600,
'd': 86400
}
mo = re.match("([0-9]+)([dmh]?)", val)
if mo is None:
return None
return int(mo.group(1))*multipliers[mo.group(2)]
def age_out_in_millisec(val):
multipliers = {
'': 1000,
'm': 60000,
'h': 3600000,
'd': 86400000
}
mo = re.match("([0-9]+)([dmh]?)", val)
if mo is None:
return None
return int(mo.group(1))*multipliers[mo.group(2)]
def _merge_atomic_values(op, v1, v2):
if op(v1, v2):
return v2
return v1
def _merge_array(v1, v2):
for e in v2:
if e not in v1:
v1.append(e)
return v1
RESERVED_ATTRIBUTES = {
'sources': _merge_array,
'first_seen': functools.partial(_merge_atomic_values, operator.gt),
'last_seen': functools.partial(_merge_atomic_values, operator.lt),
'type': functools.partial(_merge_atomic_values, operator.eq),
'direction': functools.partial(_merge_atomic_values, operator.eq),
'confidence': functools.partial(_merge_atomic_values, operator.lt),
'country': functools.partial(_merge_atomic_values, operator.eq),
'AS': functools.partial(_merge_atomic_values, operator.eq)
}
class RWLock(object):
def __init__(self):
self.num_readers = 0
self.num_writers = 0
self.m1 = gevent.lock.Semaphore(1)
self.m2 = gevent.lock.Semaphore(1)
self.m3 = gevent.lock.Semaphore(1)
self.w = gevent.lock.Semaphore(1)
self.r = gevent.lock.Semaphore(1)
def lock(self):
self.m2.acquire()
self.num_writers += 1
if self.num_writers == 1:
self.r.acquire()
self.m2.release()
self.w.acquire()
def | (self):
self.w.release()
self.m2.acquire()
self.num_writers -= 1
if self.num_writers == 0:
self.r.release()
self.m2.release()
def rlock(self):
self.m3.acquire()
self.r.acquire()
self.m1.acquire()
self.num_readers += 1
if self.num_readers == 1:
self.w.acquire()
self.m1.release()
self.r.release()
self.m3.release()
def runlock(self):
self.m1.acquire()
self.num_readers -= 1
if self.num_readers == 0:
self.w.release()
self.m1.release()
def __enter__(self):
self.rlock()
def __exit__(self, type, value, traceback):
self.runlock()
_AGE_OUT_BASES = ['last_seen', 'first_seen']
def parse_age_out(s, age_out_bases=None, default_base=None):
if s is None:
return None
if age_out_bases is None:
age_out_bases = _AGE_OUT_BASES
if default_base is None:
default_base = 'first_seen'
if default_base not in age_out_bases:
raise ValueError('%s not in %s' % (default_base, age_out_bases))
result = {}
toks = s.split('+', 1)
if len(toks) == 1:
t = toks[0].strip()
if t in age_out_bases:
result['base'] = t
result['offset'] = 0
else:
result['base'] = default_base
result['offset'] = age_out_in_millisec(t)
if result['offset'] is None:
raise ValueError('Invalid age out offset %s' % t)
else:
base = toks[0].strip()
if base not in age_out_bases:
raise ValueError('Invalid age out base %s' % base)
result['base'] = base
result['offset'] = age_out_in_millisec(toks[1].strip())
if result['offset'] is None:
raise ValueError('Invalid age out offset %s' % t)
return result
class GThrottled(object):
def __init__(self, f, wait):
self._timeout = None
self._previous = 0
self._cancelled = False
self._args = []
self._kwargs = {}
self.f = f
self.wait = wait
def later(self):
self._previous = utc_millisec()
self._timeout = None
self.f(*self._args, **self._kwargs)
def __call__(self, *args, **kwargs):
now = utc_millisec()
remaining = self.wait - (now - self._previous)
if self._cancelled:
return
if remaining <= 0 or remaining > self.wait:
if self._timeout is not None:
self._timeout.join(timeout=5)
self._timeout = None
self._previous = now
self.f(*args, **kwargs)
elif self._timeout is None:
self._args = args
self._kwargs = kwargs
self._timeout = gevent.spawn_later(remaining/1000.0, self.later)
else:
self._args = args
self._kwargs = kwargs
def cancel(self):
self._cancelled = True
if self._timeout:
self._timeout.join(timeout=5)
if self._timeout is not None:
self._timeout.kill()
self._previous = 0
self._timeout = None
self._args = []
self._kwargs = {}
| unlock | identifier_name |
utils.py | # Copyright 2015 Palo Alto Networks, Inc
#
# 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 time
import operator
import functools
import datetime
import pytz
import re
import gevent
import gevent.lock
import gevent.event
EPOCH = datetime.datetime.utcfromtimestamp(0).replace(tzinfo=pytz.UTC)
def utc_millisec():
return int(time.time()*1000)
def dt_to_millisec(dt):
if dt.tzinfo == None:
dt = dt.replace(tzinfo=pytz.UTC)
delta = dt - EPOCH
return int(delta.total_seconds()*1000)
def interval_in_sec(val):
if isinstance(val, int):
return val
multipliers = {
'': 1,
'm': 60,
'h': 3600,
'd': 86400
}
mo = re.match("([0-9]+)([dmh]?)", val)
if mo is None:
return None
return int(mo.group(1))*multipliers[mo.group(2)]
def age_out_in_millisec(val):
multipliers = {
'': 1000,
'm': 60000,
'h': 3600000,
'd': 86400000
}
mo = re.match("([0-9]+)([dmh]?)", val)
if mo is None:
return None
return int(mo.group(1))*multipliers[mo.group(2)]
def _merge_atomic_values(op, v1, v2):
if op(v1, v2):
return v2
return v1
def _merge_array(v1, v2):
for e in v2:
|
return v1
RESERVED_ATTRIBUTES = {
'sources': _merge_array,
'first_seen': functools.partial(_merge_atomic_values, operator.gt),
'last_seen': functools.partial(_merge_atomic_values, operator.lt),
'type': functools.partial(_merge_atomic_values, operator.eq),
'direction': functools.partial(_merge_atomic_values, operator.eq),
'confidence': functools.partial(_merge_atomic_values, operator.lt),
'country': functools.partial(_merge_atomic_values, operator.eq),
'AS': functools.partial(_merge_atomic_values, operator.eq)
}
class RWLock(object):
def __init__(self):
self.num_readers = 0
self.num_writers = 0
self.m1 = gevent.lock.Semaphore(1)
self.m2 = gevent.lock.Semaphore(1)
self.m3 = gevent.lock.Semaphore(1)
self.w = gevent.lock.Semaphore(1)
self.r = gevent.lock.Semaphore(1)
def lock(self):
self.m2.acquire()
self.num_writers += 1
if self.num_writers == 1:
self.r.acquire()
self.m2.release()
self.w.acquire()
def unlock(self):
self.w.release()
self.m2.acquire()
self.num_writers -= 1
if self.num_writers == 0:
self.r.release()
self.m2.release()
def rlock(self):
self.m3.acquire()
self.r.acquire()
self.m1.acquire()
self.num_readers += 1
if self.num_readers == 1:
self.w.acquire()
self.m1.release()
self.r.release()
self.m3.release()
def runlock(self):
self.m1.acquire()
self.num_readers -= 1
if self.num_readers == 0:
self.w.release()
self.m1.release()
def __enter__(self):
self.rlock()
def __exit__(self, type, value, traceback):
self.runlock()
_AGE_OUT_BASES = ['last_seen', 'first_seen']
def parse_age_out(s, age_out_bases=None, default_base=None):
if s is None:
return None
if age_out_bases is None:
age_out_bases = _AGE_OUT_BASES
if default_base is None:
default_base = 'first_seen'
if default_base not in age_out_bases:
raise ValueError('%s not in %s' % (default_base, age_out_bases))
result = {}
toks = s.split('+', 1)
if len(toks) == 1:
t = toks[0].strip()
if t in age_out_bases:
result['base'] = t
result['offset'] = 0
else:
result['base'] = default_base
result['offset'] = age_out_in_millisec(t)
if result['offset'] is None:
raise ValueError('Invalid age out offset %s' % t)
else:
base = toks[0].strip()
if base not in age_out_bases:
raise ValueError('Invalid age out base %s' % base)
result['base'] = base
result['offset'] = age_out_in_millisec(toks[1].strip())
if result['offset'] is None:
raise ValueError('Invalid age out offset %s' % t)
return result
class GThrottled(object):
def __init__(self, f, wait):
self._timeout = None
self._previous = 0
self._cancelled = False
self._args = []
self._kwargs = {}
self.f = f
self.wait = wait
def later(self):
self._previous = utc_millisec()
self._timeout = None
self.f(*self._args, **self._kwargs)
def __call__(self, *args, **kwargs):
now = utc_millisec()
remaining = self.wait - (now - self._previous)
if self._cancelled:
return
if remaining <= 0 or remaining > self.wait:
if self._timeout is not None:
self._timeout.join(timeout=5)
self._timeout = None
self._previous = now
self.f(*args, **kwargs)
elif self._timeout is None:
self._args = args
self._kwargs = kwargs
self._timeout = gevent.spawn_later(remaining/1000.0, self.later)
else:
self._args = args
self._kwargs = kwargs
def cancel(self):
self._cancelled = True
if self._timeout:
self._timeout.join(timeout=5)
if self._timeout is not None:
self._timeout.kill()
self._previous = 0
self._timeout = None
self._args = []
self._kwargs = {}
| if e not in v1:
v1.append(e) | conditional_block |
utils.py | # Copyright 2015 Palo Alto Networks, Inc
#
# 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 time
import operator
import functools
import datetime
import pytz
import re
import gevent
import gevent.lock
import gevent.event
EPOCH = datetime.datetime.utcfromtimestamp(0).replace(tzinfo=pytz.UTC)
def utc_millisec():
return int(time.time()*1000)
def dt_to_millisec(dt):
if dt.tzinfo == None:
dt = dt.replace(tzinfo=pytz.UTC)
delta = dt - EPOCH
return int(delta.total_seconds()*1000)
def interval_in_sec(val):
|
def age_out_in_millisec(val):
multipliers = {
'': 1000,
'm': 60000,
'h': 3600000,
'd': 86400000
}
mo = re.match("([0-9]+)([dmh]?)", val)
if mo is None:
return None
return int(mo.group(1))*multipliers[mo.group(2)]
def _merge_atomic_values(op, v1, v2):
if op(v1, v2):
return v2
return v1
def _merge_array(v1, v2):
for e in v2:
if e not in v1:
v1.append(e)
return v1
RESERVED_ATTRIBUTES = {
'sources': _merge_array,
'first_seen': functools.partial(_merge_atomic_values, operator.gt),
'last_seen': functools.partial(_merge_atomic_values, operator.lt),
'type': functools.partial(_merge_atomic_values, operator.eq),
'direction': functools.partial(_merge_atomic_values, operator.eq),
'confidence': functools.partial(_merge_atomic_values, operator.lt),
'country': functools.partial(_merge_atomic_values, operator.eq),
'AS': functools.partial(_merge_atomic_values, operator.eq)
}
class RWLock(object):
def __init__(self):
self.num_readers = 0
self.num_writers = 0
self.m1 = gevent.lock.Semaphore(1)
self.m2 = gevent.lock.Semaphore(1)
self.m3 = gevent.lock.Semaphore(1)
self.w = gevent.lock.Semaphore(1)
self.r = gevent.lock.Semaphore(1)
def lock(self):
self.m2.acquire()
self.num_writers += 1
if self.num_writers == 1:
self.r.acquire()
self.m2.release()
self.w.acquire()
def unlock(self):
self.w.release()
self.m2.acquire()
self.num_writers -= 1
if self.num_writers == 0:
self.r.release()
self.m2.release()
def rlock(self):
self.m3.acquire()
self.r.acquire()
self.m1.acquire()
self.num_readers += 1
if self.num_readers == 1:
self.w.acquire()
self.m1.release()
self.r.release()
self.m3.release()
def runlock(self):
self.m1.acquire()
self.num_readers -= 1
if self.num_readers == 0:
self.w.release()
self.m1.release()
def __enter__(self):
self.rlock()
def __exit__(self, type, value, traceback):
self.runlock()
_AGE_OUT_BASES = ['last_seen', 'first_seen']
def parse_age_out(s, age_out_bases=None, default_base=None):
if s is None:
return None
if age_out_bases is None:
age_out_bases = _AGE_OUT_BASES
if default_base is None:
default_base = 'first_seen'
if default_base not in age_out_bases:
raise ValueError('%s not in %s' % (default_base, age_out_bases))
result = {}
toks = s.split('+', 1)
if len(toks) == 1:
t = toks[0].strip()
if t in age_out_bases:
result['base'] = t
result['offset'] = 0
else:
result['base'] = default_base
result['offset'] = age_out_in_millisec(t)
if result['offset'] is None:
raise ValueError('Invalid age out offset %s' % t)
else:
base = toks[0].strip()
if base not in age_out_bases:
raise ValueError('Invalid age out base %s' % base)
result['base'] = base
result['offset'] = age_out_in_millisec(toks[1].strip())
if result['offset'] is None:
raise ValueError('Invalid age out offset %s' % t)
return result
class GThrottled(object):
def __init__(self, f, wait):
self._timeout = None
self._previous = 0
self._cancelled = False
self._args = []
self._kwargs = {}
self.f = f
self.wait = wait
def later(self):
self._previous = utc_millisec()
self._timeout = None
self.f(*self._args, **self._kwargs)
def __call__(self, *args, **kwargs):
now = utc_millisec()
remaining = self.wait - (now - self._previous)
if self._cancelled:
return
if remaining <= 0 or remaining > self.wait:
if self._timeout is not None:
self._timeout.join(timeout=5)
self._timeout = None
self._previous = now
self.f(*args, **kwargs)
elif self._timeout is None:
self._args = args
self._kwargs = kwargs
self._timeout = gevent.spawn_later(remaining/1000.0, self.later)
else:
self._args = args
self._kwargs = kwargs
def cancel(self):
self._cancelled = True
if self._timeout:
self._timeout.join(timeout=5)
if self._timeout is not None:
self._timeout.kill()
self._previous = 0
self._timeout = None
self._args = []
self._kwargs = {}
| if isinstance(val, int):
return val
multipliers = {
'': 1,
'm': 60,
'h': 3600,
'd': 86400
}
mo = re.match("([0-9]+)([dmh]?)", val)
if mo is None:
return None
return int(mo.group(1))*multipliers[mo.group(2)] | identifier_body |
utils.py | # Copyright 2015 Palo Alto Networks, Inc
#
# 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 time
import operator
import functools
import datetime
import pytz
import re
import gevent
import gevent.lock
import gevent.event
EPOCH = datetime.datetime.utcfromtimestamp(0).replace(tzinfo=pytz.UTC)
def utc_millisec():
return int(time.time()*1000)
def dt_to_millisec(dt):
if dt.tzinfo == None:
dt = dt.replace(tzinfo=pytz.UTC)
delta = dt - EPOCH
return int(delta.total_seconds()*1000)
def interval_in_sec(val):
if isinstance(val, int):
return val
multipliers = {
'': 1,
'm': 60,
'h': 3600,
'd': 86400
}
mo = re.match("([0-9]+)([dmh]?)", val)
if mo is None:
return None
return int(mo.group(1))*multipliers[mo.group(2)]
def age_out_in_millisec(val):
multipliers = {
'': 1000,
'm': 60000,
'h': 3600000,
'd': 86400000
}
mo = re.match("([0-9]+)([dmh]?)", val)
if mo is None:
return None
return int(mo.group(1))*multipliers[mo.group(2)]
def _merge_atomic_values(op, v1, v2):
if op(v1, v2):
return v2
return v1
def _merge_array(v1, v2):
for e in v2:
if e not in v1:
v1.append(e)
return v1
RESERVED_ATTRIBUTES = {
'sources': _merge_array,
'first_seen': functools.partial(_merge_atomic_values, operator.gt),
'last_seen': functools.partial(_merge_atomic_values, operator.lt),
'type': functools.partial(_merge_atomic_values, operator.eq),
'direction': functools.partial(_merge_atomic_values, operator.eq),
'confidence': functools.partial(_merge_atomic_values, operator.lt),
'country': functools.partial(_merge_atomic_values, operator.eq),
'AS': functools.partial(_merge_atomic_values, operator.eq)
}
class RWLock(object):
def __init__(self):
self.num_readers = 0
self.num_writers = 0
self.m1 = gevent.lock.Semaphore(1)
self.m2 = gevent.lock.Semaphore(1)
self.m3 = gevent.lock.Semaphore(1)
self.w = gevent.lock.Semaphore(1)
self.r = gevent.lock.Semaphore(1)
def lock(self):
self.m2.acquire()
self.num_writers += 1
if self.num_writers == 1:
self.r.acquire()
self.m2.release()
self.w.acquire()
def unlock(self):
self.w.release()
self.m2.acquire()
self.num_writers -= 1
if self.num_writers == 0:
self.r.release()
self.m2.release()
def rlock(self):
self.m3.acquire()
self.r.acquire()
self.m1.acquire()
self.num_readers += 1
if self.num_readers == 1:
self.w.acquire()
self.m1.release()
self.r.release()
self.m3.release()
def runlock(self):
self.m1.acquire()
self.num_readers -= 1
if self.num_readers == 0: |
self.m1.release()
def __enter__(self):
self.rlock()
def __exit__(self, type, value, traceback):
self.runlock()
_AGE_OUT_BASES = ['last_seen', 'first_seen']
def parse_age_out(s, age_out_bases=None, default_base=None):
if s is None:
return None
if age_out_bases is None:
age_out_bases = _AGE_OUT_BASES
if default_base is None:
default_base = 'first_seen'
if default_base not in age_out_bases:
raise ValueError('%s not in %s' % (default_base, age_out_bases))
result = {}
toks = s.split('+', 1)
if len(toks) == 1:
t = toks[0].strip()
if t in age_out_bases:
result['base'] = t
result['offset'] = 0
else:
result['base'] = default_base
result['offset'] = age_out_in_millisec(t)
if result['offset'] is None:
raise ValueError('Invalid age out offset %s' % t)
else:
base = toks[0].strip()
if base not in age_out_bases:
raise ValueError('Invalid age out base %s' % base)
result['base'] = base
result['offset'] = age_out_in_millisec(toks[1].strip())
if result['offset'] is None:
raise ValueError('Invalid age out offset %s' % t)
return result
class GThrottled(object):
def __init__(self, f, wait):
self._timeout = None
self._previous = 0
self._cancelled = False
self._args = []
self._kwargs = {}
self.f = f
self.wait = wait
def later(self):
self._previous = utc_millisec()
self._timeout = None
self.f(*self._args, **self._kwargs)
def __call__(self, *args, **kwargs):
now = utc_millisec()
remaining = self.wait - (now - self._previous)
if self._cancelled:
return
if remaining <= 0 or remaining > self.wait:
if self._timeout is not None:
self._timeout.join(timeout=5)
self._timeout = None
self._previous = now
self.f(*args, **kwargs)
elif self._timeout is None:
self._args = args
self._kwargs = kwargs
self._timeout = gevent.spawn_later(remaining/1000.0, self.later)
else:
self._args = args
self._kwargs = kwargs
def cancel(self):
self._cancelled = True
if self._timeout:
self._timeout.join(timeout=5)
if self._timeout is not None:
self._timeout.kill()
self._previous = 0
self._timeout = None
self._args = []
self._kwargs = {} | self.w.release() | random_line_split |
htmlCombinatorCommentBody.js | 'use strict';
exports.__esModule = true;
var _postcssSelectorParser = require('postcss-selector-parser');
var _postcssSelectorParser2 = _interopRequireDefault(_postcssSelectorParser);
var _exists = require('../exists');
var _exists2 = _interopRequireDefault(_exists);
var _isMixin = require('../isMixin');
var _isMixin2 = _interopRequireDefault(_isMixin);
var _plugin = require('../plugin'); | var _browsers = require('../dictionary/browsers');
var _identifiers = require('../dictionary/identifiers');
var _postcss = require('../dictionary/postcss');
var _tags = require('../dictionary/tags');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function analyse(ctx, rule) {
return function (selectors) {
selectors.each(function (selector) {
if ((0, _exists2.default)(selector, 0, _tags.HTML) && ((0, _exists2.default)(selector, 1, '>') || (0, _exists2.default)(selector, 1, '~')) && selector.at(2) && selector.at(2).type === 'comment' && (0, _exists2.default)(selector, 3, ' ') && (0, _exists2.default)(selector, 4, _tags.BODY) && (0, _exists2.default)(selector, 5, ' ') && selector.at(6)) {
ctx.push(rule, {
identifier: _identifiers.SELECTOR,
hack: selector.toString()
});
}
});
};
}
exports.default = (0, _plugin2.default)([_browsers.IE_5_5, _browsers.IE_6, _browsers.IE_7], [_postcss.RULE], function (rule) {
if ((0, _isMixin2.default)(rule)) {
return;
}
if (rule.raws.selector && rule.raws.selector.raw) {
(0, _postcssSelectorParser2.default)(analyse(this, rule)).process(rule.raws.selector.raw);
}
});
module.exports = exports['default']; |
var _plugin2 = _interopRequireDefault(_plugin);
| random_line_split |
htmlCombinatorCommentBody.js | 'use strict';
exports.__esModule = true;
var _postcssSelectorParser = require('postcss-selector-parser');
var _postcssSelectorParser2 = _interopRequireDefault(_postcssSelectorParser);
var _exists = require('../exists');
var _exists2 = _interopRequireDefault(_exists);
var _isMixin = require('../isMixin');
var _isMixin2 = _interopRequireDefault(_isMixin);
var _plugin = require('../plugin');
var _plugin2 = _interopRequireDefault(_plugin);
var _browsers = require('../dictionary/browsers');
var _identifiers = require('../dictionary/identifiers');
var _postcss = require('../dictionary/postcss');
var _tags = require('../dictionary/tags');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function | (ctx, rule) {
return function (selectors) {
selectors.each(function (selector) {
if ((0, _exists2.default)(selector, 0, _tags.HTML) && ((0, _exists2.default)(selector, 1, '>') || (0, _exists2.default)(selector, 1, '~')) && selector.at(2) && selector.at(2).type === 'comment' && (0, _exists2.default)(selector, 3, ' ') && (0, _exists2.default)(selector, 4, _tags.BODY) && (0, _exists2.default)(selector, 5, ' ') && selector.at(6)) {
ctx.push(rule, {
identifier: _identifiers.SELECTOR,
hack: selector.toString()
});
}
});
};
}
exports.default = (0, _plugin2.default)([_browsers.IE_5_5, _browsers.IE_6, _browsers.IE_7], [_postcss.RULE], function (rule) {
if ((0, _isMixin2.default)(rule)) {
return;
}
if (rule.raws.selector && rule.raws.selector.raw) {
(0, _postcssSelectorParser2.default)(analyse(this, rule)).process(rule.raws.selector.raw);
}
});
module.exports = exports['default']; | analyse | identifier_name |
htmlCombinatorCommentBody.js | 'use strict';
exports.__esModule = true;
var _postcssSelectorParser = require('postcss-selector-parser');
var _postcssSelectorParser2 = _interopRequireDefault(_postcssSelectorParser);
var _exists = require('../exists');
var _exists2 = _interopRequireDefault(_exists);
var _isMixin = require('../isMixin');
var _isMixin2 = _interopRequireDefault(_isMixin);
var _plugin = require('../plugin');
var _plugin2 = _interopRequireDefault(_plugin);
var _browsers = require('../dictionary/browsers');
var _identifiers = require('../dictionary/identifiers');
var _postcss = require('../dictionary/postcss');
var _tags = require('../dictionary/tags');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function analyse(ctx, rule) {
return function (selectors) {
selectors.each(function (selector) {
if ((0, _exists2.default)(selector, 0, _tags.HTML) && ((0, _exists2.default)(selector, 1, '>') || (0, _exists2.default)(selector, 1, '~')) && selector.at(2) && selector.at(2).type === 'comment' && (0, _exists2.default)(selector, 3, ' ') && (0, _exists2.default)(selector, 4, _tags.BODY) && (0, _exists2.default)(selector, 5, ' ') && selector.at(6)) |
});
};
}
exports.default = (0, _plugin2.default)([_browsers.IE_5_5, _browsers.IE_6, _browsers.IE_7], [_postcss.RULE], function (rule) {
if ((0, _isMixin2.default)(rule)) {
return;
}
if (rule.raws.selector && rule.raws.selector.raw) {
(0, _postcssSelectorParser2.default)(analyse(this, rule)).process(rule.raws.selector.raw);
}
});
module.exports = exports['default']; | {
ctx.push(rule, {
identifier: _identifiers.SELECTOR,
hack: selector.toString()
});
} | conditional_block |
htmlCombinatorCommentBody.js | 'use strict';
exports.__esModule = true;
var _postcssSelectorParser = require('postcss-selector-parser');
var _postcssSelectorParser2 = _interopRequireDefault(_postcssSelectorParser);
var _exists = require('../exists');
var _exists2 = _interopRequireDefault(_exists);
var _isMixin = require('../isMixin');
var _isMixin2 = _interopRequireDefault(_isMixin);
var _plugin = require('../plugin');
var _plugin2 = _interopRequireDefault(_plugin);
var _browsers = require('../dictionary/browsers');
var _identifiers = require('../dictionary/identifiers');
var _postcss = require('../dictionary/postcss');
var _tags = require('../dictionary/tags');
function _interopRequireDefault(obj) |
function analyse(ctx, rule) {
return function (selectors) {
selectors.each(function (selector) {
if ((0, _exists2.default)(selector, 0, _tags.HTML) && ((0, _exists2.default)(selector, 1, '>') || (0, _exists2.default)(selector, 1, '~')) && selector.at(2) && selector.at(2).type === 'comment' && (0, _exists2.default)(selector, 3, ' ') && (0, _exists2.default)(selector, 4, _tags.BODY) && (0, _exists2.default)(selector, 5, ' ') && selector.at(6)) {
ctx.push(rule, {
identifier: _identifiers.SELECTOR,
hack: selector.toString()
});
}
});
};
}
exports.default = (0, _plugin2.default)([_browsers.IE_5_5, _browsers.IE_6, _browsers.IE_7], [_postcss.RULE], function (rule) {
if ((0, _isMixin2.default)(rule)) {
return;
}
if (rule.raws.selector && rule.raws.selector.raw) {
(0, _postcssSelectorParser2.default)(analyse(this, rule)).process(rule.raws.selector.raw);
}
});
module.exports = exports['default']; | { return obj && obj.__esModule ? obj : { default: obj }; } | identifier_body |
05_ExampleDoc.py | #ImportModules
import ShareYourSystem as SYS
#figure
MyPyploter=SYS.PyploterClass(
).mapSet(
{
'-Charts':
{
'|a':{
'-Draws':[
('|0',{
'PyplotingDrawVariable':
[
(
'plot',
{
'#liarg':[
[1,2,3],
[2,6,3]
],
'#kwarg':{
'linestyle':"",
'marker':'o'
}
}
)
]
}), | 'PyplotingDrawVariable':
[
(
'plot',
{
'#liarg':[
[0,1,2],
[2,3,4]
],
'#kwarg':{
'linestyle':"--",
'color':'r'
}
}
)
],
})
],
'PyplotingChartVariable':
[
('set_xlim',[0,5])
]
}
}
}
).pyplot(
)
#print
print('MyPyploter is ')
SYS._print(MyPyploter)
#show
SYS.matplotlib.pyplot.show() | ('|1',{ | random_line_split |
cmd.rs |
use std::f32;
use std::sync::Arc;
use std::sync::Mutex;
use std::fs::File;
use std::time::{Duration, Instant};
use std::io::{BufRead, BufReader};
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use crate::eval_paths::EvalPaths;
use crate::debug_path::DebugPath;
use crate::graph::Graph;
use crate::progress::Progress;
use crate::sim::{Io, GlobalState, RoutingAlgorithm};
use crate::algorithms::vivaldi_routing::VivaldiRouting;
use crate::algorithms::random_routing::RandomRouting;
use crate::algorithms::spring_routing::SpringRouting;
use crate::algorithms::genetic_routing::GeneticRouting;
use crate::algorithms::spanning_tree_routing::SpanningTreeRouting;
use crate::importer::import_file;
use crate::exporter::export_file;
use crate::utils::{fmt_duration, DEG2KM, MyError};
use crate::movements::Movements;
#[derive(PartialEq)]
enum AllowRecursiveCall {
No,
Yes
}
// trigger blocking read to exit loop
fn send_dummy_to_socket(address: &str) {
match TcpStream::connect(address) {
Ok(mut stream) => {
let _ = stream.set_read_timeout(Some(Duration::from_millis(100)));
let _ = stream.write("".as_bytes());
},
Err(e) => {
eprintln!("{}", e);
}
}
}
fn send_dummy_to_stdin() {
let _ = std::io::stdout().write("".as_bytes());
}
pub fn ext_loop(sim: Arc<Mutex<GlobalState>>, address: &str) {
match TcpListener::bind(address) {
Err(err) => {
println!("{}", err);
},
Ok(listener) => {
println!("Listen for commands on {}", address);
//let mut input = vec![0u8; 512];
let mut output = String::new();
loop {
//input.clear();
output.clear();
if let Ok((mut stream, _addr)) = listener.accept() {
let mut buf = [0; 512];
if let Ok(n) = stream.read(&mut buf) {
if let (Ok(s), Ok(mut sim)) = (std::str::from_utf8(&buf[0..n]), sim.lock()) {
if sim.abort_simulation {
// abort loop
break;
} else if let Err(e) = cmd_handler(&mut output, &mut sim, s, AllowRecursiveCall::Yes) {
let _ = stream.write(e.to_string().as_bytes());
} else {
let _ = stream.write(&output.as_bytes());
}
}
}
}
}
}
}
}
pub fn cmd_loop(sim: Arc<Mutex<GlobalState>>, run: &str) {
let mut input = run.to_owned();
let mut output = String::new();
loop {
if input.len() == 0 {
let _ = std::io::stdin().read_line(&mut input);
}
if let Ok(mut sim) = sim.lock() {
output.clear();
if let Err(e) = cmd_handler(&mut output, &mut sim, &input, AllowRecursiveCall::Yes) {
let _ = std::io::stderr().write(e.to_string().as_bytes());
} else {
let _ = std::io::stdout().write(output.as_bytes());
}
if sim.abort_simulation {
// abort loop
break;
}
}
input.clear();
}
}
macro_rules! scan {
( $iter:expr, $( $x:ty ),+ ) => {{
($($iter.next().and_then(|word| word.parse::<$x>().ok()),)*)
}}
}
enum Command {
Error(String),
Ignore,
Help,
ClearGraph,
GraphInfo,
SimInfo,
ResetSim,
Exit,
Progress(Option<bool>),
ShowMinimumSpanningTree,
CropMinimumSpanningTree,
Test(u32),
Debug(u32, u32),
DebugStep(u32),
Get(String),
Set(String, String),
ConnectInRange(f32),
RandomizePositions(f32),
RemoveUnconnected,
Algorithm(Option<String>),
AddLine(u32, bool),
AddTree(u32, u32),
AddStar(u32),
AddLattice4(u32, u32),
AddLattice8(u32, u32),
Positions(bool),
RemoveNodes(Vec<u32>),
ConnectNodes(Vec<u32>),
DisconnectNodes(Vec<u32>),
SimStep(u32),
Run(String),
Import(String),
ExportPath(Option<String>),
MoveNode(u32, f32, f32, f32),
MoveNodes(f32, f32, f32),
MoveTo(f32, f32, f32),
}
#[derive(Clone, Copy, PartialEq)]
enum Cid {
Error,
Help,
ClearGraph,
GraphInfo,
SimInfo,
ResetSim,
Exit,
Progress,
ShowMinimumSpanningTree,
CropMinimumSpanningTree,
Test,
Debug,
DebugStep,
Get,
Set,
ConnectInRange,
RandomizePositions,
RemoveUnconnected,
Algorithm,
AddLine,
AddTree,
AddStar,
AddLattice4,
AddLattice8,
Positions,
RemoveNodes,
ConnectNodes,
DisconnectNodes,
SimStep,
Run,
Import,
ExportPath,
MoveNode,
MoveNodes,
MoveTo
}
const COMMANDS: &'static [(&'static str, Cid)] = &[
("algo [<algorithm>] Get or set given algorithm.", Cid::Algorithm),
("sim_step [<steps>] Run simulation steps. Default is 1.", Cid::SimStep),
("sim_reset Reset simulation.", Cid::ResetSim),
("sim_info Show simulator information.", Cid::SimInfo),
("progress [<true|false>] Show simulation progress.", Cid::Progress),
("test [<samples>] Test routing algorithm with (test packets arrived, path stretch).", Cid::Test),
("debug_init <from> <to> Debug a path step wise.", Cid::Debug),
("debug_step [<steps>] Perform step on path.", Cid::DebugStep),
("", Cid::Error),
("graph_info Show graph information", Cid::GraphInfo),
("get <key> Get node property.", Cid::Get),
("set <key> <value> Set node property.", Cid::Set),
("", Cid::Error),
("graph_clear Clear graph", Cid::ClearGraph),
("line <node_count> [<create_loop>] Add a line of nodes. Connect ends to create a loop.", Cid::AddLine),
("star <edge_count> Add star structure of nodes.", Cid::AddStar),
("tree <node_count> [<inter_count>] Add a tree structure of nodes with interconnections", Cid::AddTree),
("lattice4 <x_xount> <y_count> Create a lattice structure of squares.", Cid::AddLattice4),
("lattice8 <x_xount> <y_count> Create a lattice structure of squares and diagonal connections.", Cid::AddLattice8),
("remove_nodes <node_list> Remove nodes. Node list is a comma separated list of node ids.", Cid::RemoveNodes),
("connect_nodes <node_list> Connect nodes. Node list is a comma separated list of node ids.", Cid::ConnectNodes),
("disconnect_nodes <node_list> Disconnect nodes. Node list is a comma separated list of node ids.", Cid::DisconnectNodes),
("remove_unconnected Remove nodes without any connections.", Cid::RemoveUnconnected),
("", Cid::Error),
("positions <true|false> Enable geo positions.", Cid::Positions),
("move_node <node_id> <x> <y> <z> Move a node by x/y/z (in km).", Cid::MoveNode),
("move_nodes <x> <y> <z> Move all nodes by x/y/z (in km).", Cid::MoveNodes),
("move_to <x> <y> <z> Move all nodes to x/y/z (in degrees).", Cid::MoveTo),
("rnd_pos <range> Randomize node positions in an area with width (in km) around node center.", Cid::RandomizePositions),
("connect_in_range <range> Connect all nodes in range of less then range (in km).", Cid::ConnectInRange),
("", Cid::Error),
("run <file> Run commands from a script.", Cid::Run),
("import <file> Import a graph as JSON file.", Cid::Import),
("export [<file>] Get or set graph export file.", Cid::ExportPath),
("show_mst Mark the minimum spanning tree.", Cid::ShowMinimumSpanningTree),
("crop_mst Only leave the minimum spanning tree.", Cid::CropMinimumSpanningTree),
("exit Exit simulator.", Cid::Exit),
("help Show this help.", Cid::Help),
];
fn parse_command(input: &str) -> Command {
let mut tokens = Vec::new();
for tok in input.split_whitespace() {
// trim ' " characters
tokens.push(tok.trim_matches(|c: char| (c == '\'') || (c == '"')));
}
let mut iter = tokens.iter().skip(1);
let cmd = tokens.get(0).unwrap_or(&"");
fn is_first_token(string: &str, tok: &str) -> bool {
string.starts_with(tok)
&& (string.len() > tok.len())
&& (string.as_bytes()[tok.len()] == ' ' as u8)
}
fn lookup_cmd(cmd: &str) -> Cid {
for item in COMMANDS {
if is_first_token(item.0, cmd) {
return item.1;
}
}
Cid::Error
}
// parse number separated list of numbers
fn parse_list(numbers: Option<&&str>) -> Result<Vec<u32>, ()> {
let mut v = Vec::<u32>::new();
for num in numbers.unwrap_or(&"").split(",") {
if let Ok(n) = num.parse::<u32>() {
v.push(n);
} else {
return Err(());
}
}
Ok(v)
}
let error = Command::Error("Missing Arguments".to_string());
match lookup_cmd(cmd) {
Cid::Help => Command::Help,
Cid::SimInfo => Command::SimInfo,
Cid::GraphInfo => Command::GraphInfo,
Cid::ClearGraph => Command::ClearGraph,
Cid::ResetSim => Command::ResetSim,
Cid::Exit => Command::Exit,
Cid::Progress => {
if let (Some(progress),) = scan!(iter, bool) {
Command::Progress(Some(progress))
} else {
Command::Progress(None)
}
},
Cid::ShowMinimumSpanningTree => Command::ShowMinimumSpanningTree,
Cid::CropMinimumSpanningTree => Command::CropMinimumSpanningTree,
Cid::Test => {
if let (Some(samples),) = scan!(iter, u32) {
Command::Test(samples)
} else {
Command::Test(1000)
}
},
Cid::Debug => {
if let (Some(from), Some(to)) = scan!(iter, u32, u32) {
Command::Debug(from, to)
} else {
error
}
},
Cid::DebugStep => {
if let (Some(steps),) = scan!(iter, u32) {
Command::DebugStep(steps)
} else {
Command::DebugStep(1)
}
},
Cid::Get => { if let (Some(key),) = scan!(iter, String) {
Command::Get(key)
} else {
error
}
},
Cid::Set => { if let (Some(key),Some(value)) = scan!(iter, String, String) {
Command::Set(key, value)
} else {
error
}
},
Cid::SimStep => {
Command::SimStep(if let (Some(count),) = scan!(iter, u32) {
count
} else {
1
})
},
Cid::Run => {
if let (Some(path),) = scan!(iter, String) {
Command::Run(path)
} else {
error
}
},
Cid::Import => {
if let (Some(path),) = scan!(iter, String) {
Command::Import(path)
} else {
error
}
},
Cid::ExportPath => {
if let (Some(path),) = scan!(iter, String) {
Command::ExportPath(Some(path))
} else {
Command::ExportPath(None)
}
},
Cid::MoveNodes => {
if let (Some(x), Some(y), Some(z)) = scan!(iter, f32, f32, f32) {
Command::MoveNodes(x, y, z)
} else {
error
}
},
Cid::MoveNode => {
if let (Some(id), Some(x), Some(y), Some(z)) = scan!(iter, u32, f32, f32, f32) {
Command::MoveNode(id, x, y, z)
} else {
error
}
},
Cid::AddLine => {
let mut iter1 = iter.clone();
let mut iter2 = iter.clone();
if let (Some(count), Some(close)) = scan!(iter1, u32, bool) {
Command::AddLine(count, close)
} else if let (Some(count),) = scan!(iter2, u32) {
Command::AddLine(count, false)
} else {
error
}
},
Cid::AddTree => {
let mut iter1 = iter.clone();
let mut iter2 = iter.clone();
if let (Some(count), Some(intra)) = scan!(iter1, u32, u32) {
Command::AddTree(count, intra)
} else if let (Some(count),) = scan!(iter2, u32) {
Command::AddTree(count, 0)
} else {
error
}
},
Cid::AddStar => {
if let (Some(count),) = scan!(iter, u32) {
Command::AddStar(count)
} else {
error
}
},
Cid::AddLattice4 => {
if let (Some(x_count), Some(y_count)) = scan!(iter, u32, u32) {
Command::AddLattice4(x_count, y_count)
} else {
error
}
},
Cid::AddLattice8 => {
if let (Some(x_count), Some(y_count)) = scan!(iter, u32, u32) {
Command::AddLattice8(x_count, y_count)
} else {
error
}
},
Cid::Positions => {
if let (Some(enable),) = scan!(iter, bool) {
Command::Positions(enable)
} else {
error
}
},
Cid::ConnectInRange => {
if let (Some(range),) = scan!(iter, f32) {
Command::ConnectInRange(range)
} else {
error
}
},
Cid::RandomizePositions => {
if let (Some(range),) = scan!(iter, f32) {
Command::RandomizePositions(range)
} else {
error
}
},
Cid::Algorithm => {
if let (Some(algo),) = scan!(iter, String) {
Command::Algorithm(Some(algo))
} else {
Command::Algorithm(None)
}
},
Cid::RemoveNodes => {
if let Ok(ids) = parse_list(tokens.get(1)) {
Command::RemoveNodes(ids)
} else {
error
}
},
Cid::ConnectNodes => {
if let Ok(ids) = parse_list(tokens.get(1)) {
Command::ConnectNodes(ids)
} else {
error
}
},
Cid::DisconnectNodes => {
if let Ok(ids) = parse_list(tokens.get(1)) {
Command::DisconnectNodes(ids)
} else {
error
}
},
Cid::RemoveUnconnected => {
Command::RemoveUnconnected
},
Cid::MoveTo => {
if let (Some(x), Some(y), Some(z)) = scan!(iter, f32, f32, f32) {
Command::MoveTo(x, y, z)
} else {
error
}
},
Cid::Error => {
if cmd.is_empty() {
Command::Ignore
} else if cmd.trim_start().starts_with("#") {
Command::Ignore
} else {
Command::Error(format!("Unknown Command: {}", cmd))
}
}
}
}
fn | (out: &mut std::fmt::Write) -> Result<(), MyError> {
for item in COMMANDS {
if item.1 != Cid::Error {
writeln!(out, "{}", item.0)?;
}
}
Ok(())
}
fn cmd_handler(out: &mut std::fmt::Write, sim: &mut GlobalState, input: &str, call: AllowRecursiveCall) -> Result<(), MyError> {
let mut mark_links : Option<Graph> = None;
let mut do_init = false;
//println!("command: '{}'", input);
let command = parse_command(input);
match command {
Command::Ignore => {
// nothing to do
},
Command::Progress(show) => {
if let Some(show) = show {
sim.show_progress = show;
}
writeln!(out, "show progress: {}", if sim.show_progress {
"enabled"
} else {
"disabled"
})?;
},
Command::Exit => {
sim.abort_simulation = true;
send_dummy_to_socket(&sim.cmd_address);
send_dummy_to_stdin();
},
Command::ShowMinimumSpanningTree => {
let mst = sim.graph.minimum_spanning_tree();
if mst.node_count() > 0 {
mark_links = Some(mst);
}
},
Command::CropMinimumSpanningTree => {
// mst is only a uni-directional graph...!!
let mst = sim.graph.minimum_spanning_tree();
if mst.node_count() > 0 {
sim.graph = mst;
}
},
Command::Error(msg) => {
//TODO: return Result error
writeln!(out, "{}", msg)?;
},
Command::Help => {
print_help(out)?;
},
Command::Get(key) => {
let mut buf = String::new();
sim.algorithm.get(&key, &mut buf)?;
writeln!(out, "{}", buf)?;
},
Command::Set(key, value) => {
sim.algorithm.set(&key, &value)?;
},
Command::GraphInfo => {
let node_count = sim.graph.node_count();
let link_count = sim.graph.link_count();
let avg_node_degree = sim.graph.get_avg_node_degree();
writeln!(out, "nodes: {}, links: {}", node_count, link_count)?;
writeln!(out, "locations: {}, metadata: {}", sim.locations.data.len(), sim.meta.data.len())?;
writeln!(out, "average node degree: {}", avg_node_degree)?;
/*
if (verbose) {
let mean_clustering_coefficient = state.graph.get_mean_clustering_coefficient();
let mean_link_count = state.graph.get_mean_link_count();
let mean_link_distance = state.get_mean_link_distance();
writeln!(out, "mean clustering coefficient: {}", mean_clustering_coefficient)?;
writeln!(out, "mean link count: {} ({} variance)", mean_link_count.0, mean_link_count.1)?;
writeln!(out, "mean link distance: {} ({} variance)", mean_link_distance.0, mean_link_distance.1)?;
}
*/
},
Command::SimInfo => {
write!(out, " algo: ")?;
sim.algorithm.get("name", out)?;
writeln!(out, "\n steps: {}", sim.sim_steps)?;
},
Command::ClearGraph => {
sim.graph.clear();
do_init = true;
writeln!(out, "done")?;
},
Command::ResetSim => {
sim.test.clear();
//state.graph.clear();
sim.sim_steps = 0;
do_init = true;
writeln!(out, "done")?;
},
Command::SimStep(count) => {
let mut progress = Progress::new();
let now = Instant::now();
let mut io = Io::new(&sim.graph);
for step in 0..count {
if sim.abort_simulation {
break;
}
sim.algorithm.step(&mut io);
sim.movements.step(&mut sim.locations);
sim.sim_steps += 1;
if sim.show_progress {
progress.update((count + 1) as usize, step as usize);
}
}
let duration = now.elapsed();
writeln!(out, "Run {} simulation steps, duration: {}", count, fmt_duration(duration))?;
},
Command::Test(samples) => {
fn run_test(out: &mut std::fmt::Write, test: &mut EvalPaths, graph: &Graph, algo: &Box<RoutingAlgorithm>, samples: u32)
-> Result<(), std::fmt::Error>
{
test.clear();
test.run_samples(graph, |p| algo.route(&p), samples as usize);
writeln!(out, "samples: {}, arrived: {:.1}, stretch: {}, duration: {}",
samples,
test.arrived(), test.stretch(),
fmt_duration(test.duration())
)
}
sim.test.show_progress(sim.show_progress);
run_test(out, &mut sim.test, &sim.graph, &sim.algorithm, samples)?;
},
Command::Debug(from, to) => {
let node_count = sim.graph.node_count() as u32;
if (from < node_count) && (from < node_count) {
sim.debug_path.init(from, to);
writeln!(out, "Init path debugger: {} => {}", from, to)?;
} else {
writeln!(out, "Invalid path: {} => {}", from, to)?;
}
},
Command::DebugStep(steps) => {
fn run_test(out: &mut std::fmt::Write, debug_path: &mut DebugPath, graph: &Graph, algo: &Box<RoutingAlgorithm>)
-> Result<(), MyError>
{
debug_path.step(out, graph, |p| algo.route(&p))
}
for _ in 0..steps {
run_test(out, &mut sim.debug_path, &sim.graph, &sim.algorithm)?;
}
}
Command::Import(ref path) => {
import_file(&mut sim.graph, Some(&mut sim.locations), Some(&mut sim.meta), path.as_str())?;
do_init = true;
writeln!(out, "Import done: {}", path)?;
},
Command::ExportPath(path) => {
if let Some(path) = path {
sim.export_path = path;
}
writeln!(out, "Export done: {}", sim.export_path)?;
},
Command::AddLine(count, close) => {
sim.add_line(count, close);
do_init = true;
},
Command::MoveNodes(x, y, z) => {
sim.locations.move_nodes([x, y, z]);
},
Command::MoveNode(id, x, y, z) => {
sim.locations.move_node(id, [x, y, z]);
},
Command::AddTree(count, intra) => {
sim.add_tree(count, intra);
do_init = true;
},
Command::AddStar(count) => {
sim.add_star(count);
do_init = true;
},
Command::AddLattice4(x_count, y_count) => {
sim.add_lattice4(x_count, y_count);
do_init = true;
},
Command::AddLattice8(x_count, y_count) => {
sim.add_lattice8(x_count, y_count);
do_init = true;
},
Command::Positions(enable) => {
if enable {
// add positions to node that have none
let node_count = sim.graph.node_count();
sim.locations.init_positions(node_count, [0.0, 0.0, 0.0]);
} else {
sim.locations.clear();
}
writeln!(out, "positions: {}", if enable {
"enabled"
} else {
"disabled"
})?;
}
Command::RandomizePositions(range) => {
let center = sim.locations.graph_center();
sim.locations.randomize_positions_2d(center, range);
},
Command::ConnectInRange(range) => {
sim.connect_in_range(range);
},
Command::Algorithm(algo) => {
if let Some(algo) = algo {
match algo.as_str() {
"random" => {
sim.algorithm = Box::new(RandomRouting::new());
do_init = true;
},
"vivaldi" => {
sim.algorithm = Box::new(VivaldiRouting::new());
do_init = true;
},
"spring" => {
sim.algorithm = Box::new(SpringRouting::new());
do_init = true;
},
"genetic" => {
sim.algorithm = Box::new(GeneticRouting::new());
do_init = true;
},
"tree" => {
sim.algorithm = Box::new(SpanningTreeRouting::new());
do_init = true;
}
_ => {
writeln!(out, "Unknown algorithm: {}", algo)?;
}
}
if do_init {
writeln!(out, "Done")?;
}
} else {
write!(out, "selected: ")?;
sim.algorithm.get("name", out)?;
write!(out, "\n")?;
write!(out, "available: random, vivaldi, spring, genetic, tree\n")?;
}
},
Command::Run(path) => {
if call == AllowRecursiveCall::Yes {
if let Ok(file) = File::open(&path) {
for (index, line) in BufReader::new(file).lines().enumerate() {
let line = line.unwrap();
if let Err(err) = cmd_handler(out, sim, &line, AllowRecursiveCall::No) {
writeln!(out, "Error in {}:{}: {}", path, index, err)?;
sim.abort_simulation = true;
break;
}
}
} else {
writeln!(out, "File not found: {}", &path)?;
}
} else {
writeln!(out, "Recursive call not allowed: {}", &path)?;
}
},
Command::RemoveUnconnected => {
sim.graph.remove_unconnected_nodes();
do_init = true;
},
Command::RemoveNodes(ids) => {
sim.graph.remove_nodes(&ids);
},
Command::ConnectNodes(ids) => {
sim.graph.connect_nodes(&ids);
},
Command::DisconnectNodes(ids) => {
sim.graph.disconnect_nodes(&ids);
},
Command::MoveTo(x, y, z) => {
let center = sim.locations.graph_center();
sim.locations.move_nodes([center[0] + x * DEG2KM, center[1] + y * DEG2KM, center[2] + z * DEG2KM]);
}
};
if do_init {
sim.algorithm.reset(sim.graph.node_count());
sim.test.clear();
}
export_file(
&sim.graph,
Some(&sim.locations),
Some(&*sim.algorithm),
mark_links.as_ref(),
sim.export_path.as_ref()
);
Ok(())
}
| print_help | identifier_name |
cmd.rs |
use std::f32;
use std::sync::Arc;
use std::sync::Mutex;
use std::fs::File;
use std::time::{Duration, Instant};
use std::io::{BufRead, BufReader};
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use crate::eval_paths::EvalPaths;
use crate::debug_path::DebugPath;
use crate::graph::Graph;
use crate::progress::Progress;
use crate::sim::{Io, GlobalState, RoutingAlgorithm};
use crate::algorithms::vivaldi_routing::VivaldiRouting;
use crate::algorithms::random_routing::RandomRouting;
use crate::algorithms::spring_routing::SpringRouting;
use crate::algorithms::genetic_routing::GeneticRouting;
use crate::algorithms::spanning_tree_routing::SpanningTreeRouting;
use crate::importer::import_file;
use crate::exporter::export_file;
use crate::utils::{fmt_duration, DEG2KM, MyError};
use crate::movements::Movements;
#[derive(PartialEq)]
enum AllowRecursiveCall {
No,
Yes
}
// trigger blocking read to exit loop
fn send_dummy_to_socket(address: &str) {
match TcpStream::connect(address) {
Ok(mut stream) => {
let _ = stream.set_read_timeout(Some(Duration::from_millis(100)));
let _ = stream.write("".as_bytes());
},
Err(e) => {
eprintln!("{}", e);
}
}
}
fn send_dummy_to_stdin() {
let _ = std::io::stdout().write("".as_bytes());
}
pub fn ext_loop(sim: Arc<Mutex<GlobalState>>, address: &str) {
match TcpListener::bind(address) {
Err(err) => {
println!("{}", err);
},
Ok(listener) => {
println!("Listen for commands on {}", address);
//let mut input = vec![0u8; 512];
let mut output = String::new();
loop {
//input.clear();
output.clear();
if let Ok((mut stream, _addr)) = listener.accept() {
let mut buf = [0; 512];
if let Ok(n) = stream.read(&mut buf) {
if let (Ok(s), Ok(mut sim)) = (std::str::from_utf8(&buf[0..n]), sim.lock()) {
if sim.abort_simulation {
// abort loop
break;
} else if let Err(e) = cmd_handler(&mut output, &mut sim, s, AllowRecursiveCall::Yes) {
let _ = stream.write(e.to_string().as_bytes());
} else {
let _ = stream.write(&output.as_bytes());
}
}
}
}
}
}
}
}
pub fn cmd_loop(sim: Arc<Mutex<GlobalState>>, run: &str) {
let mut input = run.to_owned();
let mut output = String::new();
loop {
if input.len() == 0 {
let _ = std::io::stdin().read_line(&mut input);
}
if let Ok(mut sim) = sim.lock() {
output.clear();
if let Err(e) = cmd_handler(&mut output, &mut sim, &input, AllowRecursiveCall::Yes) {
let _ = std::io::stderr().write(e.to_string().as_bytes());
} else {
let _ = std::io::stdout().write(output.as_bytes());
}
if sim.abort_simulation {
// abort loop
break;
}
}
input.clear();
}
}
macro_rules! scan {
( $iter:expr, $( $x:ty ),+ ) => {{
($($iter.next().and_then(|word| word.parse::<$x>().ok()),)*)
}}
}
enum Command {
Error(String),
Ignore,
Help,
ClearGraph,
GraphInfo,
SimInfo,
ResetSim,
Exit,
Progress(Option<bool>),
ShowMinimumSpanningTree,
CropMinimumSpanningTree,
Test(u32),
Debug(u32, u32),
DebugStep(u32),
Get(String),
Set(String, String),
ConnectInRange(f32),
RandomizePositions(f32),
RemoveUnconnected,
Algorithm(Option<String>),
AddLine(u32, bool),
AddTree(u32, u32),
AddStar(u32),
AddLattice4(u32, u32),
AddLattice8(u32, u32),
Positions(bool),
RemoveNodes(Vec<u32>),
ConnectNodes(Vec<u32>),
DisconnectNodes(Vec<u32>),
SimStep(u32),
Run(String),
Import(String),
ExportPath(Option<String>),
MoveNode(u32, f32, f32, f32),
MoveNodes(f32, f32, f32),
MoveTo(f32, f32, f32),
}
#[derive(Clone, Copy, PartialEq)]
enum Cid {
Error,
Help,
ClearGraph,
GraphInfo,
SimInfo,
ResetSim,
Exit,
Progress,
ShowMinimumSpanningTree,
CropMinimumSpanningTree,
Test,
Debug,
DebugStep,
Get,
Set,
ConnectInRange,
RandomizePositions,
RemoveUnconnected,
Algorithm,
AddLine,
AddTree,
AddStar,
AddLattice4,
AddLattice8,
Positions,
RemoveNodes,
ConnectNodes,
DisconnectNodes,
SimStep,
Run,
Import,
ExportPath,
MoveNode,
MoveNodes,
MoveTo
}
const COMMANDS: &'static [(&'static str, Cid)] = &[
("algo [<algorithm>] Get or set given algorithm.", Cid::Algorithm),
("sim_step [<steps>] Run simulation steps. Default is 1.", Cid::SimStep),
("sim_reset Reset simulation.", Cid::ResetSim),
("sim_info Show simulator information.", Cid::SimInfo),
("progress [<true|false>] Show simulation progress.", Cid::Progress),
("test [<samples>] Test routing algorithm with (test packets arrived, path stretch).", Cid::Test),
("debug_init <from> <to> Debug a path step wise.", Cid::Debug),
("debug_step [<steps>] Perform step on path.", Cid::DebugStep),
("", Cid::Error),
("graph_info Show graph information", Cid::GraphInfo),
("get <key> Get node property.", Cid::Get),
("set <key> <value> Set node property.", Cid::Set),
("", Cid::Error),
("graph_clear Clear graph", Cid::ClearGraph),
("line <node_count> [<create_loop>] Add a line of nodes. Connect ends to create a loop.", Cid::AddLine),
("star <edge_count> Add star structure of nodes.", Cid::AddStar),
("tree <node_count> [<inter_count>] Add a tree structure of nodes with interconnections", Cid::AddTree),
("lattice4 <x_xount> <y_count> Create a lattice structure of squares.", Cid::AddLattice4),
("lattice8 <x_xount> <y_count> Create a lattice structure of squares and diagonal connections.", Cid::AddLattice8),
("remove_nodes <node_list> Remove nodes. Node list is a comma separated list of node ids.", Cid::RemoveNodes),
("connect_nodes <node_list> Connect nodes. Node list is a comma separated list of node ids.", Cid::ConnectNodes),
("disconnect_nodes <node_list> Disconnect nodes. Node list is a comma separated list of node ids.", Cid::DisconnectNodes),
("remove_unconnected Remove nodes without any connections.", Cid::RemoveUnconnected),
("", Cid::Error),
("positions <true|false> Enable geo positions.", Cid::Positions),
("move_node <node_id> <x> <y> <z> Move a node by x/y/z (in km).", Cid::MoveNode),
("move_nodes <x> <y> <z> Move all nodes by x/y/z (in km).", Cid::MoveNodes),
("move_to <x> <y> <z> Move all nodes to x/y/z (in degrees).", Cid::MoveTo),
("rnd_pos <range> Randomize node positions in an area with width (in km) around node center.", Cid::RandomizePositions),
("connect_in_range <range> Connect all nodes in range of less then range (in km).", Cid::ConnectInRange),
("", Cid::Error),
("run <file> Run commands from a script.", Cid::Run),
("import <file> Import a graph as JSON file.", Cid::Import),
("export [<file>] Get or set graph export file.", Cid::ExportPath),
("show_mst Mark the minimum spanning tree.", Cid::ShowMinimumSpanningTree),
("crop_mst Only leave the minimum spanning tree.", Cid::CropMinimumSpanningTree),
("exit Exit simulator.", Cid::Exit),
("help Show this help.", Cid::Help),
];
fn parse_command(input: &str) -> Command {
let mut tokens = Vec::new();
for tok in input.split_whitespace() {
// trim ' " characters
tokens.push(tok.trim_matches(|c: char| (c == '\'') || (c == '"')));
}
let mut iter = tokens.iter().skip(1);
let cmd = tokens.get(0).unwrap_or(&"");
fn is_first_token(string: &str, tok: &str) -> bool {
string.starts_with(tok)
&& (string.len() > tok.len())
&& (string.as_bytes()[tok.len()] == ' ' as u8)
}
fn lookup_cmd(cmd: &str) -> Cid {
for item in COMMANDS {
if is_first_token(item.0, cmd) {
return item.1;
}
}
Cid::Error
}
// parse number separated list of numbers
fn parse_list(numbers: Option<&&str>) -> Result<Vec<u32>, ()> {
let mut v = Vec::<u32>::new();
for num in numbers.unwrap_or(&"").split(",") {
if let Ok(n) = num.parse::<u32>() {
v.push(n);
} else {
return Err(());
}
}
Ok(v)
}
let error = Command::Error("Missing Arguments".to_string());
match lookup_cmd(cmd) {
Cid::Help => Command::Help,
Cid::SimInfo => Command::SimInfo,
Cid::GraphInfo => Command::GraphInfo,
Cid::ClearGraph => Command::ClearGraph,
Cid::ResetSim => Command::ResetSim,
Cid::Exit => Command::Exit,
Cid::Progress => {
if let (Some(progress),) = scan!(iter, bool) {
Command::Progress(Some(progress))
} else {
Command::Progress(None)
}
},
Cid::ShowMinimumSpanningTree => Command::ShowMinimumSpanningTree,
Cid::CropMinimumSpanningTree => Command::CropMinimumSpanningTree,
Cid::Test => {
if let (Some(samples),) = scan!(iter, u32) {
Command::Test(samples)
} else {
Command::Test(1000)
}
},
Cid::Debug => {
if let (Some(from), Some(to)) = scan!(iter, u32, u32) {
Command::Debug(from, to)
} else {
error
}
},
Cid::DebugStep => {
if let (Some(steps),) = scan!(iter, u32) {
Command::DebugStep(steps)
} else {
Command::DebugStep(1)
}
},
Cid::Get => { if let (Some(key),) = scan!(iter, String) {
Command::Get(key)
} else {
error
}
},
Cid::Set => { if let (Some(key),Some(value)) = scan!(iter, String, String) {
Command::Set(key, value)
} else {
error
}
},
Cid::SimStep => {
Command::SimStep(if let (Some(count),) = scan!(iter, u32) {
count
} else {
1
})
},
Cid::Run => {
if let (Some(path),) = scan!(iter, String) {
Command::Run(path)
} else {
error
}
},
Cid::Import => {
if let (Some(path),) = scan!(iter, String) {
Command::Import(path)
} else {
error
}
},
Cid::ExportPath => {
if let (Some(path),) = scan!(iter, String) {
Command::ExportPath(Some(path))
} else {
Command::ExportPath(None)
}
},
Cid::MoveNodes => {
if let (Some(x), Some(y), Some(z)) = scan!(iter, f32, f32, f32) {
Command::MoveNodes(x, y, z)
} else {
error
}
},
Cid::MoveNode => {
if let (Some(id), Some(x), Some(y), Some(z)) = scan!(iter, u32, f32, f32, f32) {
Command::MoveNode(id, x, y, z)
} else {
error
}
},
Cid::AddLine => {
let mut iter1 = iter.clone();
let mut iter2 = iter.clone();
if let (Some(count), Some(close)) = scan!(iter1, u32, bool) {
Command::AddLine(count, close)
} else if let (Some(count),) = scan!(iter2, u32) {
Command::AddLine(count, false)
} else {
error
}
},
Cid::AddTree => {
let mut iter1 = iter.clone();
let mut iter2 = iter.clone();
if let (Some(count), Some(intra)) = scan!(iter1, u32, u32) {
Command::AddTree(count, intra)
} else if let (Some(count),) = scan!(iter2, u32) {
Command::AddTree(count, 0)
} else {
error
}
},
Cid::AddStar => {
if let (Some(count),) = scan!(iter, u32) {
Command::AddStar(count)
} else {
error
}
},
Cid::AddLattice4 => {
if let (Some(x_count), Some(y_count)) = scan!(iter, u32, u32) {
Command::AddLattice4(x_count, y_count)
} else {
error
}
},
Cid::AddLattice8 => {
if let (Some(x_count), Some(y_count)) = scan!(iter, u32, u32) {
Command::AddLattice8(x_count, y_count)
} else {
error
}
},
Cid::Positions => {
if let (Some(enable),) = scan!(iter, bool) {
Command::Positions(enable)
} else {
error
}
},
Cid::ConnectInRange => {
if let (Some(range),) = scan!(iter, f32) {
Command::ConnectInRange(range)
} else {
error
}
},
Cid::RandomizePositions => {
if let (Some(range),) = scan!(iter, f32) {
Command::RandomizePositions(range)
} else {
error
}
},
Cid::Algorithm => {
if let (Some(algo),) = scan!(iter, String) {
Command::Algorithm(Some(algo))
} else {
Command::Algorithm(None)
}
},
Cid::RemoveNodes => {
if let Ok(ids) = parse_list(tokens.get(1)) {
Command::RemoveNodes(ids)
} else {
error
}
},
Cid::ConnectNodes => {
if let Ok(ids) = parse_list(tokens.get(1)) {
Command::ConnectNodes(ids)
} else {
error
}
},
Cid::DisconnectNodes => {
if let Ok(ids) = parse_list(tokens.get(1)) {
Command::DisconnectNodes(ids)
} else {
error
}
},
Cid::RemoveUnconnected => {
Command::RemoveUnconnected
},
Cid::MoveTo => {
if let (Some(x), Some(y), Some(z)) = scan!(iter, f32, f32, f32) {
Command::MoveTo(x, y, z)
} else {
error
}
},
Cid::Error => {
if cmd.is_empty() {
Command::Ignore
} else if cmd.trim_start().starts_with("#") {
Command::Ignore
} else {
Command::Error(format!("Unknown Command: {}", cmd))
}
}
}
}
fn print_help(out: &mut std::fmt::Write) -> Result<(), MyError> {
for item in COMMANDS {
if item.1 != Cid::Error {
writeln!(out, "{}", item.0)?;
}
}
Ok(())
}
fn cmd_handler(out: &mut std::fmt::Write, sim: &mut GlobalState, input: &str, call: AllowRecursiveCall) -> Result<(), MyError> {
let mut mark_links : Option<Graph> = None;
let mut do_init = false;
//println!("command: '{}'", input);
let command = parse_command(input);
match command {
Command::Ignore => {
// nothing to do
},
Command::Progress(show) => {
if let Some(show) = show {
sim.show_progress = show;
}
writeln!(out, "show progress: {}", if sim.show_progress {
"enabled"
} else {
"disabled"
})?;
},
Command::Exit => {
sim.abort_simulation = true;
send_dummy_to_socket(&sim.cmd_address);
send_dummy_to_stdin();
},
Command::ShowMinimumSpanningTree => {
let mst = sim.graph.minimum_spanning_tree();
if mst.node_count() > 0 {
mark_links = Some(mst);
}
},
Command::CropMinimumSpanningTree => {
// mst is only a uni-directional graph...!!
let mst = sim.graph.minimum_spanning_tree();
if mst.node_count() > 0 {
sim.graph = mst;
}
},
Command::Error(msg) => {
//TODO: return Result error
writeln!(out, "{}", msg)?;
},
Command::Help => {
print_help(out)?;
},
Command::Get(key) => {
let mut buf = String::new();
sim.algorithm.get(&key, &mut buf)?;
writeln!(out, "{}", buf)?;
},
Command::Set(key, value) => {
sim.algorithm.set(&key, &value)?;
},
Command::GraphInfo => {
let node_count = sim.graph.node_count();
let link_count = sim.graph.link_count();
let avg_node_degree = sim.graph.get_avg_node_degree();
writeln!(out, "nodes: {}, links: {}", node_count, link_count)?;
writeln!(out, "locations: {}, metadata: {}", sim.locations.data.len(), sim.meta.data.len())?;
writeln!(out, "average node degree: {}", avg_node_degree)?;
/*
if (verbose) {
let mean_clustering_coefficient = state.graph.get_mean_clustering_coefficient();
let mean_link_count = state.graph.get_mean_link_count();
let mean_link_distance = state.get_mean_link_distance();
writeln!(out, "mean clustering coefficient: {}", mean_clustering_coefficient)?;
writeln!(out, "mean link count: {} ({} variance)", mean_link_count.0, mean_link_count.1)?;
writeln!(out, "mean link distance: {} ({} variance)", mean_link_distance.0, mean_link_distance.1)?;
}
*/
},
Command::SimInfo => {
write!(out, " algo: ")?;
sim.algorithm.get("name", out)?;
writeln!(out, "\n steps: {}", sim.sim_steps)?;
},
Command::ClearGraph => {
sim.graph.clear();
do_init = true;
writeln!(out, "done")?;
},
Command::ResetSim => {
sim.test.clear();
//state.graph.clear();
sim.sim_steps = 0;
do_init = true;
writeln!(out, "done")?;
},
Command::SimStep(count) => {
let mut progress = Progress::new();
let now = Instant::now();
let mut io = Io::new(&sim.graph);
for step in 0..count {
if sim.abort_simulation {
break;
}
sim.algorithm.step(&mut io);
sim.movements.step(&mut sim.locations);
sim.sim_steps += 1;
if sim.show_progress {
progress.update((count + 1) as usize, step as usize);
}
}
let duration = now.elapsed();
writeln!(out, "Run {} simulation steps, duration: {}", count, fmt_duration(duration))?;
},
Command::Test(samples) => {
fn run_test(out: &mut std::fmt::Write, test: &mut EvalPaths, graph: &Graph, algo: &Box<RoutingAlgorithm>, samples: u32)
-> Result<(), std::fmt::Error>
|
sim.test.show_progress(sim.show_progress);
run_test(out, &mut sim.test, &sim.graph, &sim.algorithm, samples)?;
},
Command::Debug(from, to) => {
let node_count = sim.graph.node_count() as u32;
if (from < node_count) && (from < node_count) {
sim.debug_path.init(from, to);
writeln!(out, "Init path debugger: {} => {}", from, to)?;
} else {
writeln!(out, "Invalid path: {} => {}", from, to)?;
}
},
Command::DebugStep(steps) => {
fn run_test(out: &mut std::fmt::Write, debug_path: &mut DebugPath, graph: &Graph, algo: &Box<RoutingAlgorithm>)
-> Result<(), MyError>
{
debug_path.step(out, graph, |p| algo.route(&p))
}
for _ in 0..steps {
run_test(out, &mut sim.debug_path, &sim.graph, &sim.algorithm)?;
}
}
Command::Import(ref path) => {
import_file(&mut sim.graph, Some(&mut sim.locations), Some(&mut sim.meta), path.as_str())?;
do_init = true;
writeln!(out, "Import done: {}", path)?;
},
Command::ExportPath(path) => {
if let Some(path) = path {
sim.export_path = path;
}
writeln!(out, "Export done: {}", sim.export_path)?;
},
Command::AddLine(count, close) => {
sim.add_line(count, close);
do_init = true;
},
Command::MoveNodes(x, y, z) => {
sim.locations.move_nodes([x, y, z]);
},
Command::MoveNode(id, x, y, z) => {
sim.locations.move_node(id, [x, y, z]);
},
Command::AddTree(count, intra) => {
sim.add_tree(count, intra);
do_init = true;
},
Command::AddStar(count) => {
sim.add_star(count);
do_init = true;
},
Command::AddLattice4(x_count, y_count) => {
sim.add_lattice4(x_count, y_count);
do_init = true;
},
Command::AddLattice8(x_count, y_count) => {
sim.add_lattice8(x_count, y_count);
do_init = true;
},
Command::Positions(enable) => {
if enable {
// add positions to node that have none
let node_count = sim.graph.node_count();
sim.locations.init_positions(node_count, [0.0, 0.0, 0.0]);
} else {
sim.locations.clear();
}
writeln!(out, "positions: {}", if enable {
"enabled"
} else {
"disabled"
})?;
}
Command::RandomizePositions(range) => {
let center = sim.locations.graph_center();
sim.locations.randomize_positions_2d(center, range);
},
Command::ConnectInRange(range) => {
sim.connect_in_range(range);
},
Command::Algorithm(algo) => {
if let Some(algo) = algo {
match algo.as_str() {
"random" => {
sim.algorithm = Box::new(RandomRouting::new());
do_init = true;
},
"vivaldi" => {
sim.algorithm = Box::new(VivaldiRouting::new());
do_init = true;
},
"spring" => {
sim.algorithm = Box::new(SpringRouting::new());
do_init = true;
},
"genetic" => {
sim.algorithm = Box::new(GeneticRouting::new());
do_init = true;
},
"tree" => {
sim.algorithm = Box::new(SpanningTreeRouting::new());
do_init = true;
}
_ => {
writeln!(out, "Unknown algorithm: {}", algo)?;
}
}
if do_init {
writeln!(out, "Done")?;
}
} else {
write!(out, "selected: ")?;
sim.algorithm.get("name", out)?;
write!(out, "\n")?;
write!(out, "available: random, vivaldi, spring, genetic, tree\n")?;
}
},
Command::Run(path) => {
if call == AllowRecursiveCall::Yes {
if let Ok(file) = File::open(&path) {
for (index, line) in BufReader::new(file).lines().enumerate() {
let line = line.unwrap();
if let Err(err) = cmd_handler(out, sim, &line, AllowRecursiveCall::No) {
writeln!(out, "Error in {}:{}: {}", path, index, err)?;
sim.abort_simulation = true;
break;
}
}
} else {
writeln!(out, "File not found: {}", &path)?;
}
} else {
writeln!(out, "Recursive call not allowed: {}", &path)?;
}
},
Command::RemoveUnconnected => {
sim.graph.remove_unconnected_nodes();
do_init = true;
},
Command::RemoveNodes(ids) => {
sim.graph.remove_nodes(&ids);
},
Command::ConnectNodes(ids) => {
sim.graph.connect_nodes(&ids);
},
Command::DisconnectNodes(ids) => {
sim.graph.disconnect_nodes(&ids);
},
Command::MoveTo(x, y, z) => {
let center = sim.locations.graph_center();
sim.locations.move_nodes([center[0] + x * DEG2KM, center[1] + y * DEG2KM, center[2] + z * DEG2KM]);
}
};
if do_init {
sim.algorithm.reset(sim.graph.node_count());
sim.test.clear();
}
export_file(
&sim.graph,
Some(&sim.locations),
Some(&*sim.algorithm),
mark_links.as_ref(),
sim.export_path.as_ref()
);
Ok(())
}
| {
test.clear();
test.run_samples(graph, |p| algo.route(&p), samples as usize);
writeln!(out, "samples: {}, arrived: {:.1}, stretch: {}, duration: {}",
samples,
test.arrived(), test.stretch(),
fmt_duration(test.duration())
)
} | identifier_body |
cmd.rs | use std::f32;
use std::sync::Arc;
use std::sync::Mutex;
use std::fs::File;
use std::time::{Duration, Instant};
use std::io::{BufRead, BufReader};
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use crate::eval_paths::EvalPaths;
use crate::debug_path::DebugPath;
use crate::graph::Graph;
use crate::progress::Progress;
use crate::sim::{Io, GlobalState, RoutingAlgorithm};
use crate::algorithms::vivaldi_routing::VivaldiRouting;
use crate::algorithms::random_routing::RandomRouting;
use crate::algorithms::spring_routing::SpringRouting;
use crate::algorithms::genetic_routing::GeneticRouting;
use crate::algorithms::spanning_tree_routing::SpanningTreeRouting;
use crate::importer::import_file;
use crate::exporter::export_file;
use crate::utils::{fmt_duration, DEG2KM, MyError};
use crate::movements::Movements;
#[derive(PartialEq)]
enum AllowRecursiveCall {
No,
Yes
}
// trigger blocking read to exit loop
fn send_dummy_to_socket(address: &str) {
match TcpStream::connect(address) {
Ok(mut stream) => {
let _ = stream.set_read_timeout(Some(Duration::from_millis(100)));
let _ = stream.write("".as_bytes());
},
Err(e) => {
eprintln!("{}", e);
}
}
}
fn send_dummy_to_stdin() {
let _ = std::io::stdout().write("".as_bytes());
}
pub fn ext_loop(sim: Arc<Mutex<GlobalState>>, address: &str) {
match TcpListener::bind(address) {
Err(err) => {
println!("{}", err);
},
Ok(listener) => {
println!("Listen for commands on {}", address);
//let mut input = vec![0u8; 512];
let mut output = String::new();
loop {
//input.clear();
output.clear();
if let Ok((mut stream, _addr)) = listener.accept() {
let mut buf = [0; 512];
if let Ok(n) = stream.read(&mut buf) {
if let (Ok(s), Ok(mut sim)) = (std::str::from_utf8(&buf[0..n]), sim.lock()) {
if sim.abort_simulation {
// abort loop
break;
} else if let Err(e) = cmd_handler(&mut output, &mut sim, s, AllowRecursiveCall::Yes) {
let _ = stream.write(e.to_string().as_bytes());
} else {
let _ = stream.write(&output.as_bytes());
}
}
}
}
}
}
}
}
pub fn cmd_loop(sim: Arc<Mutex<GlobalState>>, run: &str) {
let mut input = run.to_owned();
let mut output = String::new();
loop {
if input.len() == 0 {
let _ = std::io::stdin().read_line(&mut input);
}
if let Ok(mut sim) = sim.lock() {
output.clear();
if let Err(e) = cmd_handler(&mut output, &mut sim, &input, AllowRecursiveCall::Yes) {
let _ = std::io::stderr().write(e.to_string().as_bytes());
} else {
let _ = std::io::stdout().write(output.as_bytes());
}
if sim.abort_simulation {
// abort loop
break;
}
}
input.clear();
}
}
macro_rules! scan {
( $iter:expr, $( $x:ty ),+ ) => {{
($($iter.next().and_then(|word| word.parse::<$x>().ok()),)*)
}}
}
enum Command {
Error(String),
Ignore,
Help,
ClearGraph,
GraphInfo,
SimInfo,
ResetSim,
Exit,
Progress(Option<bool>),
ShowMinimumSpanningTree,
CropMinimumSpanningTree,
Test(u32),
Debug(u32, u32),
DebugStep(u32),
Get(String),
Set(String, String),
ConnectInRange(f32),
RandomizePositions(f32),
RemoveUnconnected,
Algorithm(Option<String>),
AddLine(u32, bool),
AddTree(u32, u32),
AddStar(u32),
AddLattice4(u32, u32),
AddLattice8(u32, u32),
Positions(bool),
RemoveNodes(Vec<u32>),
ConnectNodes(Vec<u32>),
DisconnectNodes(Vec<u32>),
SimStep(u32),
Run(String),
Import(String),
ExportPath(Option<String>),
MoveNode(u32, f32, f32, f32),
MoveNodes(f32, f32, f32),
MoveTo(f32, f32, f32),
}
#[derive(Clone, Copy, PartialEq)]
enum Cid {
Error,
Help,
ClearGraph,
GraphInfo,
SimInfo,
ResetSim,
Exit,
Progress,
ShowMinimumSpanningTree,
CropMinimumSpanningTree,
Test,
Debug,
DebugStep,
Get,
Set,
ConnectInRange,
RandomizePositions,
RemoveUnconnected,
Algorithm,
AddLine,
AddTree,
AddStar,
AddLattice4,
AddLattice8,
Positions,
RemoveNodes,
ConnectNodes,
DisconnectNodes,
SimStep,
Run,
Import,
ExportPath,
MoveNode,
MoveNodes,
MoveTo
}
const COMMANDS: &'static [(&'static str, Cid)] = &[
("algo [<algorithm>] Get or set given algorithm.", Cid::Algorithm),
("sim_step [<steps>] Run simulation steps. Default is 1.", Cid::SimStep),
("sim_reset Reset simulation.", Cid::ResetSim),
("sim_info Show simulator information.", Cid::SimInfo),
("progress [<true|false>] Show simulation progress.", Cid::Progress),
("test [<samples>] Test routing algorithm with (test packets arrived, path stretch).", Cid::Test),
("debug_init <from> <to> Debug a path step wise.", Cid::Debug),
("debug_step [<steps>] Perform step on path.", Cid::DebugStep),
("", Cid::Error),
("graph_info Show graph information", Cid::GraphInfo),
("get <key> Get node property.", Cid::Get),
("set <key> <value> Set node property.", Cid::Set),
("", Cid::Error),
("graph_clear Clear graph", Cid::ClearGraph), | ("tree <node_count> [<inter_count>] Add a tree structure of nodes with interconnections", Cid::AddTree),
("lattice4 <x_xount> <y_count> Create a lattice structure of squares.", Cid::AddLattice4),
("lattice8 <x_xount> <y_count> Create a lattice structure of squares and diagonal connections.", Cid::AddLattice8),
("remove_nodes <node_list> Remove nodes. Node list is a comma separated list of node ids.", Cid::RemoveNodes),
("connect_nodes <node_list> Connect nodes. Node list is a comma separated list of node ids.", Cid::ConnectNodes),
("disconnect_nodes <node_list> Disconnect nodes. Node list is a comma separated list of node ids.", Cid::DisconnectNodes),
("remove_unconnected Remove nodes without any connections.", Cid::RemoveUnconnected),
("", Cid::Error),
("positions <true|false> Enable geo positions.", Cid::Positions),
("move_node <node_id> <x> <y> <z> Move a node by x/y/z (in km).", Cid::MoveNode),
("move_nodes <x> <y> <z> Move all nodes by x/y/z (in km).", Cid::MoveNodes),
("move_to <x> <y> <z> Move all nodes to x/y/z (in degrees).", Cid::MoveTo),
("rnd_pos <range> Randomize node positions in an area with width (in km) around node center.", Cid::RandomizePositions),
("connect_in_range <range> Connect all nodes in range of less then range (in km).", Cid::ConnectInRange),
("", Cid::Error),
("run <file> Run commands from a script.", Cid::Run),
("import <file> Import a graph as JSON file.", Cid::Import),
("export [<file>] Get or set graph export file.", Cid::ExportPath),
("show_mst Mark the minimum spanning tree.", Cid::ShowMinimumSpanningTree),
("crop_mst Only leave the minimum spanning tree.", Cid::CropMinimumSpanningTree),
("exit Exit simulator.", Cid::Exit),
("help Show this help.", Cid::Help),
];
fn parse_command(input: &str) -> Command {
let mut tokens = Vec::new();
for tok in input.split_whitespace() {
// trim ' " characters
tokens.push(tok.trim_matches(|c: char| (c == '\'') || (c == '"')));
}
let mut iter = tokens.iter().skip(1);
let cmd = tokens.get(0).unwrap_or(&"");
fn is_first_token(string: &str, tok: &str) -> bool {
string.starts_with(tok)
&& (string.len() > tok.len())
&& (string.as_bytes()[tok.len()] == ' ' as u8)
}
fn lookup_cmd(cmd: &str) -> Cid {
for item in COMMANDS {
if is_first_token(item.0, cmd) {
return item.1;
}
}
Cid::Error
}
// parse number separated list of numbers
fn parse_list(numbers: Option<&&str>) -> Result<Vec<u32>, ()> {
let mut v = Vec::<u32>::new();
for num in numbers.unwrap_or(&"").split(",") {
if let Ok(n) = num.parse::<u32>() {
v.push(n);
} else {
return Err(());
}
}
Ok(v)
}
let error = Command::Error("Missing Arguments".to_string());
match lookup_cmd(cmd) {
Cid::Help => Command::Help,
Cid::SimInfo => Command::SimInfo,
Cid::GraphInfo => Command::GraphInfo,
Cid::ClearGraph => Command::ClearGraph,
Cid::ResetSim => Command::ResetSim,
Cid::Exit => Command::Exit,
Cid::Progress => {
if let (Some(progress),) = scan!(iter, bool) {
Command::Progress(Some(progress))
} else {
Command::Progress(None)
}
},
Cid::ShowMinimumSpanningTree => Command::ShowMinimumSpanningTree,
Cid::CropMinimumSpanningTree => Command::CropMinimumSpanningTree,
Cid::Test => {
if let (Some(samples),) = scan!(iter, u32) {
Command::Test(samples)
} else {
Command::Test(1000)
}
},
Cid::Debug => {
if let (Some(from), Some(to)) = scan!(iter, u32, u32) {
Command::Debug(from, to)
} else {
error
}
},
Cid::DebugStep => {
if let (Some(steps),) = scan!(iter, u32) {
Command::DebugStep(steps)
} else {
Command::DebugStep(1)
}
},
Cid::Get => { if let (Some(key),) = scan!(iter, String) {
Command::Get(key)
} else {
error
}
},
Cid::Set => { if let (Some(key),Some(value)) = scan!(iter, String, String) {
Command::Set(key, value)
} else {
error
}
},
Cid::SimStep => {
Command::SimStep(if let (Some(count),) = scan!(iter, u32) {
count
} else {
1
})
},
Cid::Run => {
if let (Some(path),) = scan!(iter, String) {
Command::Run(path)
} else {
error
}
},
Cid::Import => {
if let (Some(path),) = scan!(iter, String) {
Command::Import(path)
} else {
error
}
},
Cid::ExportPath => {
if let (Some(path),) = scan!(iter, String) {
Command::ExportPath(Some(path))
} else {
Command::ExportPath(None)
}
},
Cid::MoveNodes => {
if let (Some(x), Some(y), Some(z)) = scan!(iter, f32, f32, f32) {
Command::MoveNodes(x, y, z)
} else {
error
}
},
Cid::MoveNode => {
if let (Some(id), Some(x), Some(y), Some(z)) = scan!(iter, u32, f32, f32, f32) {
Command::MoveNode(id, x, y, z)
} else {
error
}
},
Cid::AddLine => {
let mut iter1 = iter.clone();
let mut iter2 = iter.clone();
if let (Some(count), Some(close)) = scan!(iter1, u32, bool) {
Command::AddLine(count, close)
} else if let (Some(count),) = scan!(iter2, u32) {
Command::AddLine(count, false)
} else {
error
}
},
Cid::AddTree => {
let mut iter1 = iter.clone();
let mut iter2 = iter.clone();
if let (Some(count), Some(intra)) = scan!(iter1, u32, u32) {
Command::AddTree(count, intra)
} else if let (Some(count),) = scan!(iter2, u32) {
Command::AddTree(count, 0)
} else {
error
}
},
Cid::AddStar => {
if let (Some(count),) = scan!(iter, u32) {
Command::AddStar(count)
} else {
error
}
},
Cid::AddLattice4 => {
if let (Some(x_count), Some(y_count)) = scan!(iter, u32, u32) {
Command::AddLattice4(x_count, y_count)
} else {
error
}
},
Cid::AddLattice8 => {
if let (Some(x_count), Some(y_count)) = scan!(iter, u32, u32) {
Command::AddLattice8(x_count, y_count)
} else {
error
}
},
Cid::Positions => {
if let (Some(enable),) = scan!(iter, bool) {
Command::Positions(enable)
} else {
error
}
},
Cid::ConnectInRange => {
if let (Some(range),) = scan!(iter, f32) {
Command::ConnectInRange(range)
} else {
error
}
},
Cid::RandomizePositions => {
if let (Some(range),) = scan!(iter, f32) {
Command::RandomizePositions(range)
} else {
error
}
},
Cid::Algorithm => {
if let (Some(algo),) = scan!(iter, String) {
Command::Algorithm(Some(algo))
} else {
Command::Algorithm(None)
}
},
Cid::RemoveNodes => {
if let Ok(ids) = parse_list(tokens.get(1)) {
Command::RemoveNodes(ids)
} else {
error
}
},
Cid::ConnectNodes => {
if let Ok(ids) = parse_list(tokens.get(1)) {
Command::ConnectNodes(ids)
} else {
error
}
},
Cid::DisconnectNodes => {
if let Ok(ids) = parse_list(tokens.get(1)) {
Command::DisconnectNodes(ids)
} else {
error
}
},
Cid::RemoveUnconnected => {
Command::RemoveUnconnected
},
Cid::MoveTo => {
if let (Some(x), Some(y), Some(z)) = scan!(iter, f32, f32, f32) {
Command::MoveTo(x, y, z)
} else {
error
}
},
Cid::Error => {
if cmd.is_empty() {
Command::Ignore
} else if cmd.trim_start().starts_with("#") {
Command::Ignore
} else {
Command::Error(format!("Unknown Command: {}", cmd))
}
}
}
}
fn print_help(out: &mut std::fmt::Write) -> Result<(), MyError> {
for item in COMMANDS {
if item.1 != Cid::Error {
writeln!(out, "{}", item.0)?;
}
}
Ok(())
}
fn cmd_handler(out: &mut std::fmt::Write, sim: &mut GlobalState, input: &str, call: AllowRecursiveCall) -> Result<(), MyError> {
let mut mark_links : Option<Graph> = None;
let mut do_init = false;
//println!("command: '{}'", input);
let command = parse_command(input);
match command {
Command::Ignore => {
// nothing to do
},
Command::Progress(show) => {
if let Some(show) = show {
sim.show_progress = show;
}
writeln!(out, "show progress: {}", if sim.show_progress {
"enabled"
} else {
"disabled"
})?;
},
Command::Exit => {
sim.abort_simulation = true;
send_dummy_to_socket(&sim.cmd_address);
send_dummy_to_stdin();
},
Command::ShowMinimumSpanningTree => {
let mst = sim.graph.minimum_spanning_tree();
if mst.node_count() > 0 {
mark_links = Some(mst);
}
},
Command::CropMinimumSpanningTree => {
// mst is only a uni-directional graph...!!
let mst = sim.graph.minimum_spanning_tree();
if mst.node_count() > 0 {
sim.graph = mst;
}
},
Command::Error(msg) => {
//TODO: return Result error
writeln!(out, "{}", msg)?;
},
Command::Help => {
print_help(out)?;
},
Command::Get(key) => {
let mut buf = String::new();
sim.algorithm.get(&key, &mut buf)?;
writeln!(out, "{}", buf)?;
},
Command::Set(key, value) => {
sim.algorithm.set(&key, &value)?;
},
Command::GraphInfo => {
let node_count = sim.graph.node_count();
let link_count = sim.graph.link_count();
let avg_node_degree = sim.graph.get_avg_node_degree();
writeln!(out, "nodes: {}, links: {}", node_count, link_count)?;
writeln!(out, "locations: {}, metadata: {}", sim.locations.data.len(), sim.meta.data.len())?;
writeln!(out, "average node degree: {}", avg_node_degree)?;
/*
if (verbose) {
let mean_clustering_coefficient = state.graph.get_mean_clustering_coefficient();
let mean_link_count = state.graph.get_mean_link_count();
let mean_link_distance = state.get_mean_link_distance();
writeln!(out, "mean clustering coefficient: {}", mean_clustering_coefficient)?;
writeln!(out, "mean link count: {} ({} variance)", mean_link_count.0, mean_link_count.1)?;
writeln!(out, "mean link distance: {} ({} variance)", mean_link_distance.0, mean_link_distance.1)?;
}
*/
},
Command::SimInfo => {
write!(out, " algo: ")?;
sim.algorithm.get("name", out)?;
writeln!(out, "\n steps: {}", sim.sim_steps)?;
},
Command::ClearGraph => {
sim.graph.clear();
do_init = true;
writeln!(out, "done")?;
},
Command::ResetSim => {
sim.test.clear();
//state.graph.clear();
sim.sim_steps = 0;
do_init = true;
writeln!(out, "done")?;
},
Command::SimStep(count) => {
let mut progress = Progress::new();
let now = Instant::now();
let mut io = Io::new(&sim.graph);
for step in 0..count {
if sim.abort_simulation {
break;
}
sim.algorithm.step(&mut io);
sim.movements.step(&mut sim.locations);
sim.sim_steps += 1;
if sim.show_progress {
progress.update((count + 1) as usize, step as usize);
}
}
let duration = now.elapsed();
writeln!(out, "Run {} simulation steps, duration: {}", count, fmt_duration(duration))?;
},
Command::Test(samples) => {
fn run_test(out: &mut std::fmt::Write, test: &mut EvalPaths, graph: &Graph, algo: &Box<RoutingAlgorithm>, samples: u32)
-> Result<(), std::fmt::Error>
{
test.clear();
test.run_samples(graph, |p| algo.route(&p), samples as usize);
writeln!(out, "samples: {}, arrived: {:.1}, stretch: {}, duration: {}",
samples,
test.arrived(), test.stretch(),
fmt_duration(test.duration())
)
}
sim.test.show_progress(sim.show_progress);
run_test(out, &mut sim.test, &sim.graph, &sim.algorithm, samples)?;
},
Command::Debug(from, to) => {
let node_count = sim.graph.node_count() as u32;
if (from < node_count) && (from < node_count) {
sim.debug_path.init(from, to);
writeln!(out, "Init path debugger: {} => {}", from, to)?;
} else {
writeln!(out, "Invalid path: {} => {}", from, to)?;
}
},
Command::DebugStep(steps) => {
fn run_test(out: &mut std::fmt::Write, debug_path: &mut DebugPath, graph: &Graph, algo: &Box<RoutingAlgorithm>)
-> Result<(), MyError>
{
debug_path.step(out, graph, |p| algo.route(&p))
}
for _ in 0..steps {
run_test(out, &mut sim.debug_path, &sim.graph, &sim.algorithm)?;
}
}
Command::Import(ref path) => {
import_file(&mut sim.graph, Some(&mut sim.locations), Some(&mut sim.meta), path.as_str())?;
do_init = true;
writeln!(out, "Import done: {}", path)?;
},
Command::ExportPath(path) => {
if let Some(path) = path {
sim.export_path = path;
}
writeln!(out, "Export done: {}", sim.export_path)?;
},
Command::AddLine(count, close) => {
sim.add_line(count, close);
do_init = true;
},
Command::MoveNodes(x, y, z) => {
sim.locations.move_nodes([x, y, z]);
},
Command::MoveNode(id, x, y, z) => {
sim.locations.move_node(id, [x, y, z]);
},
Command::AddTree(count, intra) => {
sim.add_tree(count, intra);
do_init = true;
},
Command::AddStar(count) => {
sim.add_star(count);
do_init = true;
},
Command::AddLattice4(x_count, y_count) => {
sim.add_lattice4(x_count, y_count);
do_init = true;
},
Command::AddLattice8(x_count, y_count) => {
sim.add_lattice8(x_count, y_count);
do_init = true;
},
Command::Positions(enable) => {
if enable {
// add positions to node that have none
let node_count = sim.graph.node_count();
sim.locations.init_positions(node_count, [0.0, 0.0, 0.0]);
} else {
sim.locations.clear();
}
writeln!(out, "positions: {}", if enable {
"enabled"
} else {
"disabled"
})?;
}
Command::RandomizePositions(range) => {
let center = sim.locations.graph_center();
sim.locations.randomize_positions_2d(center, range);
},
Command::ConnectInRange(range) => {
sim.connect_in_range(range);
},
Command::Algorithm(algo) => {
if let Some(algo) = algo {
match algo.as_str() {
"random" => {
sim.algorithm = Box::new(RandomRouting::new());
do_init = true;
},
"vivaldi" => {
sim.algorithm = Box::new(VivaldiRouting::new());
do_init = true;
},
"spring" => {
sim.algorithm = Box::new(SpringRouting::new());
do_init = true;
},
"genetic" => {
sim.algorithm = Box::new(GeneticRouting::new());
do_init = true;
},
"tree" => {
sim.algorithm = Box::new(SpanningTreeRouting::new());
do_init = true;
}
_ => {
writeln!(out, "Unknown algorithm: {}", algo)?;
}
}
if do_init {
writeln!(out, "Done")?;
}
} else {
write!(out, "selected: ")?;
sim.algorithm.get("name", out)?;
write!(out, "\n")?;
write!(out, "available: random, vivaldi, spring, genetic, tree\n")?;
}
},
Command::Run(path) => {
if call == AllowRecursiveCall::Yes {
if let Ok(file) = File::open(&path) {
for (index, line) in BufReader::new(file).lines().enumerate() {
let line = line.unwrap();
if let Err(err) = cmd_handler(out, sim, &line, AllowRecursiveCall::No) {
writeln!(out, "Error in {}:{}: {}", path, index, err)?;
sim.abort_simulation = true;
break;
}
}
} else {
writeln!(out, "File not found: {}", &path)?;
}
} else {
writeln!(out, "Recursive call not allowed: {}", &path)?;
}
},
Command::RemoveUnconnected => {
sim.graph.remove_unconnected_nodes();
do_init = true;
},
Command::RemoveNodes(ids) => {
sim.graph.remove_nodes(&ids);
},
Command::ConnectNodes(ids) => {
sim.graph.connect_nodes(&ids);
},
Command::DisconnectNodes(ids) => {
sim.graph.disconnect_nodes(&ids);
},
Command::MoveTo(x, y, z) => {
let center = sim.locations.graph_center();
sim.locations.move_nodes([center[0] + x * DEG2KM, center[1] + y * DEG2KM, center[2] + z * DEG2KM]);
}
};
if do_init {
sim.algorithm.reset(sim.graph.node_count());
sim.test.clear();
}
export_file(
&sim.graph,
Some(&sim.locations),
Some(&*sim.algorithm),
mark_links.as_ref(),
sim.export_path.as_ref()
);
Ok(())
} | ("line <node_count> [<create_loop>] Add a line of nodes. Connect ends to create a loop.", Cid::AddLine),
("star <edge_count> Add star structure of nodes.", Cid::AddStar), | random_line_split |
app.module.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component, NgModule, ViewEncapsulation} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {MatRadioModule} from '@angular/material/radio';
/** component: mat-radio-button */
@Component({
selector: 'app-root',
template: `
<button id="show-two" (click)="showTwo()">Show Two</button>
<button id="hide-two" (click)="hideTwo()">Hide Two</button>
<button id="show-ten" (click)="showTen()">Show Ten</button>
<button id="hide-ten" (click)="hideTen()">Hide Ten</button>
<mat-radio-group aria-label="Select an option" *ngIf="isTwoVisible">
<mat-radio-button value="1" id="btn-1">Option 1</mat-radio-button>
<mat-radio-button value="2" id="btn-2">Option 2</mat-radio-button>
</mat-radio-group>
<mat-radio-group aria-label="Select an option" *ngIf="isTenVisible">
<mat-radio-button value="1">Option 1</mat-radio-button>
<mat-radio-button value="2">Option 2</mat-radio-button>
<mat-radio-button value="3">Option 3</mat-radio-button>
<mat-radio-button value="4">Option 4</mat-radio-button>
<mat-radio-button value="5">Option 5</mat-radio-button>
<mat-radio-button value="6">Option 6</mat-radio-button>
<mat-radio-button value="7">Option 7</mat-radio-button>
<mat-radio-button value="8">Option 8</mat-radio-button>
<mat-radio-button value="9">Option 9</mat-radio-button>
<mat-radio-button value="10">Option 10</mat-radio-button>
</mat-radio-group>
`,
encapsulation: ViewEncapsulation.None,
styleUrls: ['//src/material/core/theming/prebuilt/indigo-pink.css'],
})
export class RadioBenchmarkApp {
isTwoVisible = false;
isTenVisible = false;
| () { this.isTwoVisible = true; }
hideTwo() { this.isTwoVisible = false; }
showTen() { this.isTenVisible = true; }
hideTen() { this.isTenVisible = false; }
}
@NgModule({
declarations: [RadioBenchmarkApp],
imports: [
BrowserModule,
MatRadioModule,
],
bootstrap: [RadioBenchmarkApp],
})
export class AppModule {}
| showTwo | identifier_name |
app.module.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component, NgModule, ViewEncapsulation} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {MatRadioModule} from '@angular/material/radio';
/** component: mat-radio-button */
@Component({
selector: 'app-root',
template: `
<button id="show-two" (click)="showTwo()">Show Two</button>
<button id="hide-two" (click)="hideTwo()">Hide Two</button>
<button id="show-ten" (click)="showTen()">Show Ten</button>
<button id="hide-ten" (click)="hideTen()">Hide Ten</button>
<mat-radio-group aria-label="Select an option" *ngIf="isTwoVisible">
<mat-radio-button value="1" id="btn-1">Option 1</mat-radio-button>
<mat-radio-button value="2" id="btn-2">Option 2</mat-radio-button>
</mat-radio-group>
<mat-radio-group aria-label="Select an option" *ngIf="isTenVisible">
<mat-radio-button value="1">Option 1</mat-radio-button>
<mat-radio-button value="2">Option 2</mat-radio-button>
<mat-radio-button value="3">Option 3</mat-radio-button>
<mat-radio-button value="4">Option 4</mat-radio-button>
<mat-radio-button value="5">Option 5</mat-radio-button>
<mat-radio-button value="6">Option 6</mat-radio-button>
<mat-radio-button value="7">Option 7</mat-radio-button>
<mat-radio-button value="8">Option 8</mat-radio-button>
<mat-radio-button value="9">Option 9</mat-radio-button>
<mat-radio-button value="10">Option 10</mat-radio-button>
</mat-radio-group>
`,
encapsulation: ViewEncapsulation.None,
styleUrls: ['//src/material/core/theming/prebuilt/indigo-pink.css'],
})
export class RadioBenchmarkApp {
isTwoVisible = false;
isTenVisible = false;
showTwo() |
hideTwo() { this.isTwoVisible = false; }
showTen() { this.isTenVisible = true; }
hideTen() { this.isTenVisible = false; }
}
@NgModule({
declarations: [RadioBenchmarkApp],
imports: [
BrowserModule,
MatRadioModule,
],
bootstrap: [RadioBenchmarkApp],
})
export class AppModule {}
| { this.isTwoVisible = true; } | identifier_body |
app.module.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component, NgModule, ViewEncapsulation} from '@angular/core'; | /** component: mat-radio-button */
@Component({
selector: 'app-root',
template: `
<button id="show-two" (click)="showTwo()">Show Two</button>
<button id="hide-two" (click)="hideTwo()">Hide Two</button>
<button id="show-ten" (click)="showTen()">Show Ten</button>
<button id="hide-ten" (click)="hideTen()">Hide Ten</button>
<mat-radio-group aria-label="Select an option" *ngIf="isTwoVisible">
<mat-radio-button value="1" id="btn-1">Option 1</mat-radio-button>
<mat-radio-button value="2" id="btn-2">Option 2</mat-radio-button>
</mat-radio-group>
<mat-radio-group aria-label="Select an option" *ngIf="isTenVisible">
<mat-radio-button value="1">Option 1</mat-radio-button>
<mat-radio-button value="2">Option 2</mat-radio-button>
<mat-radio-button value="3">Option 3</mat-radio-button>
<mat-radio-button value="4">Option 4</mat-radio-button>
<mat-radio-button value="5">Option 5</mat-radio-button>
<mat-radio-button value="6">Option 6</mat-radio-button>
<mat-radio-button value="7">Option 7</mat-radio-button>
<mat-radio-button value="8">Option 8</mat-radio-button>
<mat-radio-button value="9">Option 9</mat-radio-button>
<mat-radio-button value="10">Option 10</mat-radio-button>
</mat-radio-group>
`,
encapsulation: ViewEncapsulation.None,
styleUrls: ['//src/material/core/theming/prebuilt/indigo-pink.css'],
})
export class RadioBenchmarkApp {
isTwoVisible = false;
isTenVisible = false;
showTwo() { this.isTwoVisible = true; }
hideTwo() { this.isTwoVisible = false; }
showTen() { this.isTenVisible = true; }
hideTen() { this.isTenVisible = false; }
}
@NgModule({
declarations: [RadioBenchmarkApp],
imports: [
BrowserModule,
MatRadioModule,
],
bootstrap: [RadioBenchmarkApp],
})
export class AppModule {} | import {BrowserModule} from '@angular/platform-browser';
import {MatRadioModule} from '@angular/material/radio';
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.