file_name
large_stringlengths 4
140
| prefix
large_stringlengths 0
12.1k
| suffix
large_stringlengths 0
12k
| middle
large_stringlengths 0
7.51k
| fim_type
large_stringclasses 4
values |
---|---|---|---|---|
donors-list-controller.js | /*
* This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public License for more details.
*
* You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/
*/
function DonorListController($scope, sharedSpace, $location, navigateBackService, Donors) | {
Donors.get(function (data) {
$scope.donors = data.donors;
});
$scope.editDonor = function (id, donationCount) {
var data = {query: $scope.query};
navigateBackService.setData(data);
sharedSpace.setCountOfDonations(donationCount);
$location.path('edit/' + id);
};
} | identifier_body |
|
donors-list-controller.js | /*
* This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public License for more details.
*
* You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/
*/
function | ($scope, sharedSpace, $location, navigateBackService, Donors) {
Donors.get(function (data) {
$scope.donors = data.donors;
});
$scope.editDonor = function (id, donationCount) {
var data = {query: $scope.query};
navigateBackService.setData(data);
sharedSpace.setCountOfDonations(donationCount);
$location.path('edit/' + id);
};
} | DonorListController | identifier_name |
donors-list-controller.js | /*
* This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public License for more details.
*
* You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/
*/
function DonorListController($scope, sharedSpace, $location, navigateBackService, Donors) {
Donors.get(function (data) {
$scope.donors = data.donors;
});
| var data = {query: $scope.query};
navigateBackService.setData(data);
sharedSpace.setCountOfDonations(donationCount);
$location.path('edit/' + id);
};
} |
$scope.editDonor = function (id, donationCount) {
| random_line_split |
authors.js | $(function() {
var resultCache = [];
var allItems = $(".index .item");
$("#filter_text").keyup(function(){
var searchString = $(this).val();
allItems.addClass('visibility_hidden');
var items;
if (resultCache[searchString] === undefined) | else {
items = resultCache[searchString];
}
items.removeClass('visibility_hidden');
$("#numberFiltered").text(items.length);
$("#numberFilteredText").text(items.length == 1 ? $T("author") : $T("authors"));
});
$(".material_icon").each(function() {
$(this).qtip({
style: {
classes: 'material_tip'
},
content: {
text: $(this).siblings('.material_list')
},
show: {
event: 'click'
},
hide: {
event: 'unfocus'
},
position: {
my: 'top right',
at: 'bottom left'
}
});
});
});
| {
items = $(".index .item .text").textContains(searchString).parent().parent();
resultCache[searchString] = items;
} | conditional_block |
authors.js | $("#filter_text").keyup(function(){
var searchString = $(this).val();
allItems.addClass('visibility_hidden');
var items;
if (resultCache[searchString] === undefined) {
items = $(".index .item .text").textContains(searchString).parent().parent();
resultCache[searchString] = items;
} else {
items = resultCache[searchString];
}
items.removeClass('visibility_hidden');
$("#numberFiltered").text(items.length);
$("#numberFilteredText").text(items.length == 1 ? $T("author") : $T("authors"));
});
$(".material_icon").each(function() {
$(this).qtip({
style: {
classes: 'material_tip'
},
content: {
text: $(this).siblings('.material_list')
},
show: {
event: 'click'
},
hide: {
event: 'unfocus'
},
position: {
my: 'top right',
at: 'bottom left'
}
});
});
}); | $(function() {
var resultCache = [];
var allItems = $(".index .item");
| random_line_split |
|
controller.py | from .model import NetworkModel
from .view import NetworkView
from PyQt5.QtWidgets import QAction, QMenu
from PyQt5.QtGui import QCursor, QDesktopServices
from PyQt5.QtCore import pyqtSlot, QUrl, QObject
from duniterpy.api import bma
from duniterpy.documents import BMAEndpoint
class NetworkController(QObject):
""" |
def __init__(self, parent, view, model):
"""
Constructor of the navigation component
:param sakia.gui.network.view.NetworkView: the view
:param sakia.gui.network.model.NetworkModel model: the model
"""
super().__init__(parent)
self.view = view
self.model = model
table_model = self.model.init_network_table_model()
self.view.set_network_table_model(table_model)
self.view.manual_refresh_clicked.connect(self.refresh_nodes_manually)
self.view.table_network.customContextMenuRequested.connect(self.node_context_menu)
@classmethod
def create(cls, parent, app, network_service):
"""
:param PyQt5.QObject parent:
:param sakia.app.Application app:
:param sakia.services.NetworkService network_service:
:return:
"""
view = NetworkView(parent.view,)
model = NetworkModel(None, app, network_service)
txhistory = cls(parent, view, model)
model.setParent(txhistory)
return txhistory
def refresh_nodes_manually(self):
self.model.refresh_nodes_once()
def node_context_menu(self, point):
index = self.view.table_network.indexAt(point)
valid, node = self.model.table_model_data(index)
if self.model.app.parameters.expert_mode:
menu = QMenu()
open_in_browser = QAction(self.tr("Open in browser"), self)
open_in_browser.triggered.connect(self.open_node_in_browser)
open_in_browser.setData(node)
menu.addAction(open_in_browser)
# Show the context menu.
menu.exec_(QCursor.pos())
@pyqtSlot()
def set_root_node(self):
node = self.sender().data()
self.model.add_root_node(node)
@pyqtSlot()
def unset_root_node(self):
node = self.sender().data()
self.model.unset_root_node(node)
@pyqtSlot()
def open_node_in_browser(self):
node = self.sender().data()
bma_endpoints = [e for e in node.endpoints if isinstance(e, BMAEndpoint)]
if bma_endpoints:
conn_handler = next(bma_endpoints[0].conn_handler())
peering_url = bma.API(conn_handler, bma.network.URL_PATH).reverse_url(conn_handler.http_scheme, '/peering')
url = QUrl(peering_url)
QDesktopServices.openUrl(url) | The network panel
""" | random_line_split |
controller.py | from .model import NetworkModel
from .view import NetworkView
from PyQt5.QtWidgets import QAction, QMenu
from PyQt5.QtGui import QCursor, QDesktopServices
from PyQt5.QtCore import pyqtSlot, QUrl, QObject
from duniterpy.api import bma
from duniterpy.documents import BMAEndpoint
class NetworkController(QObject):
"""
The network panel
"""
def __init__(self, parent, view, model):
"""
Constructor of the navigation component
:param sakia.gui.network.view.NetworkView: the view
:param sakia.gui.network.model.NetworkModel model: the model
"""
super().__init__(parent)
self.view = view
self.model = model
table_model = self.model.init_network_table_model()
self.view.set_network_table_model(table_model)
self.view.manual_refresh_clicked.connect(self.refresh_nodes_manually)
self.view.table_network.customContextMenuRequested.connect(self.node_context_menu)
@classmethod
def create(cls, parent, app, network_service):
"""
:param PyQt5.QObject parent:
:param sakia.app.Application app:
:param sakia.services.NetworkService network_service:
:return:
"""
view = NetworkView(parent.view,)
model = NetworkModel(None, app, network_service)
txhistory = cls(parent, view, model)
model.setParent(txhistory)
return txhistory
def refresh_nodes_manually(self):
self.model.refresh_nodes_once()
def node_context_menu(self, point):
index = self.view.table_network.indexAt(point)
valid, node = self.model.table_model_data(index)
if self.model.app.parameters.expert_mode:
menu = QMenu()
open_in_browser = QAction(self.tr("Open in browser"), self)
open_in_browser.triggered.connect(self.open_node_in_browser)
open_in_browser.setData(node)
menu.addAction(open_in_browser)
# Show the context menu.
menu.exec_(QCursor.pos())
@pyqtSlot()
def set_root_node(self):
node = self.sender().data()
self.model.add_root_node(node)
@pyqtSlot()
def unset_root_node(self):
|
@pyqtSlot()
def open_node_in_browser(self):
node = self.sender().data()
bma_endpoints = [e for e in node.endpoints if isinstance(e, BMAEndpoint)]
if bma_endpoints:
conn_handler = next(bma_endpoints[0].conn_handler())
peering_url = bma.API(conn_handler, bma.network.URL_PATH).reverse_url(conn_handler.http_scheme, '/peering')
url = QUrl(peering_url)
QDesktopServices.openUrl(url)
| node = self.sender().data()
self.model.unset_root_node(node) | identifier_body |
controller.py | from .model import NetworkModel
from .view import NetworkView
from PyQt5.QtWidgets import QAction, QMenu
from PyQt5.QtGui import QCursor, QDesktopServices
from PyQt5.QtCore import pyqtSlot, QUrl, QObject
from duniterpy.api import bma
from duniterpy.documents import BMAEndpoint
class NetworkController(QObject):
"""
The network panel
"""
def __init__(self, parent, view, model):
"""
Constructor of the navigation component
:param sakia.gui.network.view.NetworkView: the view
:param sakia.gui.network.model.NetworkModel model: the model
"""
super().__init__(parent)
self.view = view
self.model = model
table_model = self.model.init_network_table_model()
self.view.set_network_table_model(table_model)
self.view.manual_refresh_clicked.connect(self.refresh_nodes_manually)
self.view.table_network.customContextMenuRequested.connect(self.node_context_menu)
@classmethod
def create(cls, parent, app, network_service):
"""
:param PyQt5.QObject parent:
:param sakia.app.Application app:
:param sakia.services.NetworkService network_service:
:return:
"""
view = NetworkView(parent.view,)
model = NetworkModel(None, app, network_service)
txhistory = cls(parent, view, model)
model.setParent(txhistory)
return txhistory
def refresh_nodes_manually(self):
self.model.refresh_nodes_once()
def | (self, point):
index = self.view.table_network.indexAt(point)
valid, node = self.model.table_model_data(index)
if self.model.app.parameters.expert_mode:
menu = QMenu()
open_in_browser = QAction(self.tr("Open in browser"), self)
open_in_browser.triggered.connect(self.open_node_in_browser)
open_in_browser.setData(node)
menu.addAction(open_in_browser)
# Show the context menu.
menu.exec_(QCursor.pos())
@pyqtSlot()
def set_root_node(self):
node = self.sender().data()
self.model.add_root_node(node)
@pyqtSlot()
def unset_root_node(self):
node = self.sender().data()
self.model.unset_root_node(node)
@pyqtSlot()
def open_node_in_browser(self):
node = self.sender().data()
bma_endpoints = [e for e in node.endpoints if isinstance(e, BMAEndpoint)]
if bma_endpoints:
conn_handler = next(bma_endpoints[0].conn_handler())
peering_url = bma.API(conn_handler, bma.network.URL_PATH).reverse_url(conn_handler.http_scheme, '/peering')
url = QUrl(peering_url)
QDesktopServices.openUrl(url)
| node_context_menu | identifier_name |
controller.py | from .model import NetworkModel
from .view import NetworkView
from PyQt5.QtWidgets import QAction, QMenu
from PyQt5.QtGui import QCursor, QDesktopServices
from PyQt5.QtCore import pyqtSlot, QUrl, QObject
from duniterpy.api import bma
from duniterpy.documents import BMAEndpoint
class NetworkController(QObject):
"""
The network panel
"""
def __init__(self, parent, view, model):
"""
Constructor of the navigation component
:param sakia.gui.network.view.NetworkView: the view
:param sakia.gui.network.model.NetworkModel model: the model
"""
super().__init__(parent)
self.view = view
self.model = model
table_model = self.model.init_network_table_model()
self.view.set_network_table_model(table_model)
self.view.manual_refresh_clicked.connect(self.refresh_nodes_manually)
self.view.table_network.customContextMenuRequested.connect(self.node_context_menu)
@classmethod
def create(cls, parent, app, network_service):
"""
:param PyQt5.QObject parent:
:param sakia.app.Application app:
:param sakia.services.NetworkService network_service:
:return:
"""
view = NetworkView(parent.view,)
model = NetworkModel(None, app, network_service)
txhistory = cls(parent, view, model)
model.setParent(txhistory)
return txhistory
def refresh_nodes_manually(self):
self.model.refresh_nodes_once()
def node_context_menu(self, point):
index = self.view.table_network.indexAt(point)
valid, node = self.model.table_model_data(index)
if self.model.app.parameters.expert_mode:
|
@pyqtSlot()
def set_root_node(self):
node = self.sender().data()
self.model.add_root_node(node)
@pyqtSlot()
def unset_root_node(self):
node = self.sender().data()
self.model.unset_root_node(node)
@pyqtSlot()
def open_node_in_browser(self):
node = self.sender().data()
bma_endpoints = [e for e in node.endpoints if isinstance(e, BMAEndpoint)]
if bma_endpoints:
conn_handler = next(bma_endpoints[0].conn_handler())
peering_url = bma.API(conn_handler, bma.network.URL_PATH).reverse_url(conn_handler.http_scheme, '/peering')
url = QUrl(peering_url)
QDesktopServices.openUrl(url)
| menu = QMenu()
open_in_browser = QAction(self.tr("Open in browser"), self)
open_in_browser.triggered.connect(self.open_node_in_browser)
open_in_browser.setData(node)
menu.addAction(open_in_browser)
# Show the context menu.
menu.exec_(QCursor.pos()) | conditional_block |
dropbox.py | ###############################################################################
#
# Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
import os
import sys
import erppeek
import shutil
import parameters # Micronaet: configuration file
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
# -----------------------------------------------------------------------------
# Parameters:
# -----------------------------------------------------------------------------
# ODOO connection:
odoo_server = parameters.odoo_server
odoo_port = parameters.odoo_port
odoo_user = parameters.odoo_user
odoo_password = parameters.odoo_password
odoo_database = parameters.odoo_database
# Dropbox:
demo = parameters.demo
samba_path = parameters.samba_path
dropbox_path = parameters.dropbox_path
print '''
Setup parameters:
ODOO: Connection: %s:%s DB %s utente: %s
Demo: %s
Samba folders: %s
Dropbox path: %s
''' % (
odoo_server,
odoo_port,
odoo_database,
odoo_user,
demo,
samba_path,
dropbox_path,
)
# -----------------------------------------------------------------------------
# UTILITY:
# -----------------------------------------------------------------------------
def get_modify_date(fullname):
''' Return modify date for file
'''
modify_date = datetime.fromtimestamp(
os.stat(fullname).st_mtime).strftime('%Y-%m-%d')
return modify_date
# -----------------------------------------------------------------------------
# ODOO operation:
# -----------------------------------------------------------------------------
odoo = erppeek.Client(
'http://%s:%s' % (
odoo_server, odoo_port),
db=odoo_database,
user=odoo_user,
password=odoo_password, | product_ids = product_pool.search([
('connector_id.wordpress', '=', True),
])
# Check elements:
#error = [] # Error database
#warning = [] # Warning database
#info = [] # Info database
#log = [] # Log database
#log_sym = [] # Log database for symlinks
#product_odoo = {}
# Only if new file (check how):
dropbox_root_path = os.path.expanduser(dropbox_path)
samba_root_path = os.path.expanduser(samba_path)
# -----------------------------------------------------------------------------
# Save current files (Dropbox folder):
# -----------------------------------------------------------------------------
current_files = []
for root, folders, files in os.walk(dropbox_root_path):
for f in files:
current_files.append(
os.path.join(root, f)
break # only first folder!
# -----------------------------------------------------------------------------
# Logg on all product image selected:
# -----------------------------------------------------------------------------
for product in product_pool.browse(product_ids):
for image in product.image_ids:
image_id = image.id
code = image.album_id.code
samba_relative_path = image.album_id.path # TODO dropbox_path
filename = product.filename
origin = os.path.(samba_relative_path, filename)
destination = os.path.(dropbox_root_path, '%s.%s' % (code, filename))
if destination in current_files:
current_files.remove(destination)
# Create symlink:
try:
os.symlink(origin, destination)
log_sym.append('CREATO: origin: %s destination: %s' % (
origin, destination))
except:
log_sym.append('ERRORE: origin: %s destination: %s' % (
origin, destination))
# Find dropbox link:
# Save dropbox link:
os.system('chmod 777 "%s" -R' % dropbox_path)
for filename in current_files:
os.rm(filename)
# file_modify = get_modify_date(fullname)
# os.system('mkdir -p "%s"' % product_folder)
print 'End operation'
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | )
# Pool used:
product_pool = odoo.model('product.product.web.server') | random_line_split |
dropbox.py | ###############################################################################
#
# Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
import os
import sys
import erppeek
import shutil
import parameters # Micronaet: configuration file
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
# -----------------------------------------------------------------------------
# Parameters:
# -----------------------------------------------------------------------------
# ODOO connection:
odoo_server = parameters.odoo_server
odoo_port = parameters.odoo_port
odoo_user = parameters.odoo_user
odoo_password = parameters.odoo_password
odoo_database = parameters.odoo_database
# Dropbox:
demo = parameters.demo
samba_path = parameters.samba_path
dropbox_path = parameters.dropbox_path
print '''
Setup parameters:
ODOO: Connection: %s:%s DB %s utente: %s
Demo: %s
Samba folders: %s
Dropbox path: %s
''' % (
odoo_server,
odoo_port,
odoo_database,
odoo_user,
demo,
samba_path,
dropbox_path,
)
# -----------------------------------------------------------------------------
# UTILITY:
# -----------------------------------------------------------------------------
def get_modify_date(fullname):
''' Return modify date for file
'''
modify_date = datetime.fromtimestamp(
os.stat(fullname).st_mtime).strftime('%Y-%m-%d')
return modify_date
# -----------------------------------------------------------------------------
# ODOO operation:
# -----------------------------------------------------------------------------
odoo = erppeek.Client(
'http://%s:%s' % (
odoo_server, odoo_port),
db=odoo_database,
user=odoo_user,
password=odoo_password,
)
# Pool used:
product_pool = odoo.model('product.product.web.server')
product_ids = product_pool.search([
('connector_id.wordpress', '=', True),
])
# Check elements:
#error = [] # Error database
#warning = [] # Warning database
#info = [] # Info database
#log = [] # Log database
#log_sym = [] # Log database for symlinks
#product_odoo = {}
# Only if new file (check how):
dropbox_root_path = os.path.expanduser(dropbox_path)
samba_root_path = os.path.expanduser(samba_path)
# -----------------------------------------------------------------------------
# Save current files (Dropbox folder):
# -----------------------------------------------------------------------------
current_files = []
for root, folders, files in os.walk(dropbox_root_path):
for f in files:
current_files.append(
os.path.join(root, f)
break # only first folder!
# -----------------------------------------------------------------------------
# Logg on all product image selected:
# -----------------------------------------------------------------------------
for product in product_pool.browse(product_ids):
for image in product.image_ids:
| # Find dropbox link:
# Save dropbox link:
os.system('chmod 777 "%s" -R' % dropbox_path)
for filename in current_files:
os.rm(filename)
# file_modify = get_modify_date(fullname)
# os.system('mkdir -p "%s"' % product_folder)
print 'End operation'
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| image_id = image.id
code = image.album_id.code
samba_relative_path = image.album_id.path # TODO dropbox_path
filename = product.filename
origin = os.path.(samba_relative_path, filename)
destination = os.path.(dropbox_root_path, '%s.%s' % (code, filename))
if destination in current_files:
current_files.remove(destination)
# Create symlink:
try:
os.symlink(origin, destination)
log_sym.append('CREATO: origin: %s destination: %s' % (
origin, destination))
except:
log_sym.append('ERRORE: origin: %s destination: %s' % (
origin, destination))
| conditional_block |
dropbox.py | ###############################################################################
#
# Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
import os
import sys
import erppeek
import shutil
import parameters # Micronaet: configuration file
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
# -----------------------------------------------------------------------------
# Parameters:
# -----------------------------------------------------------------------------
# ODOO connection:
odoo_server = parameters.odoo_server
odoo_port = parameters.odoo_port
odoo_user = parameters.odoo_user
odoo_password = parameters.odoo_password
odoo_database = parameters.odoo_database
# Dropbox:
demo = parameters.demo
samba_path = parameters.samba_path
dropbox_path = parameters.dropbox_path
print '''
Setup parameters:
ODOO: Connection: %s:%s DB %s utente: %s
Demo: %s
Samba folders: %s
Dropbox path: %s
''' % (
odoo_server,
odoo_port,
odoo_database,
odoo_user,
demo,
samba_path,
dropbox_path,
)
# -----------------------------------------------------------------------------
# UTILITY:
# -----------------------------------------------------------------------------
def get_modify_date(fullname):
|
# -----------------------------------------------------------------------------
# ODOO operation:
# -----------------------------------------------------------------------------
odoo = erppeek.Client(
'http://%s:%s' % (
odoo_server, odoo_port),
db=odoo_database,
user=odoo_user,
password=odoo_password,
)
# Pool used:
product_pool = odoo.model('product.product.web.server')
product_ids = product_pool.search([
('connector_id.wordpress', '=', True),
])
# Check elements:
#error = [] # Error database
#warning = [] # Warning database
#info = [] # Info database
#log = [] # Log database
#log_sym = [] # Log database for symlinks
#product_odoo = {}
# Only if new file (check how):
dropbox_root_path = os.path.expanduser(dropbox_path)
samba_root_path = os.path.expanduser(samba_path)
# -----------------------------------------------------------------------------
# Save current files (Dropbox folder):
# -----------------------------------------------------------------------------
current_files = []
for root, folders, files in os.walk(dropbox_root_path):
for f in files:
current_files.append(
os.path.join(root, f)
break # only first folder!
# -----------------------------------------------------------------------------
# Logg on all product image selected:
# -----------------------------------------------------------------------------
for product in product_pool.browse(product_ids):
for image in product.image_ids:
image_id = image.id
code = image.album_id.code
samba_relative_path = image.album_id.path # TODO dropbox_path
filename = product.filename
origin = os.path.(samba_relative_path, filename)
destination = os.path.(dropbox_root_path, '%s.%s' % (code, filename))
if destination in current_files:
current_files.remove(destination)
# Create symlink:
try:
os.symlink(origin, destination)
log_sym.append('CREATO: origin: %s destination: %s' % (
origin, destination))
except:
log_sym.append('ERRORE: origin: %s destination: %s' % (
origin, destination))
# Find dropbox link:
# Save dropbox link:
os.system('chmod 777 "%s" -R' % dropbox_path)
for filename in current_files:
os.rm(filename)
# file_modify = get_modify_date(fullname)
# os.system('mkdir -p "%s"' % product_folder)
print 'End operation'
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| ''' Return modify date for file
'''
modify_date = datetime.fromtimestamp(
os.stat(fullname).st_mtime).strftime('%Y-%m-%d')
return modify_date | identifier_body |
dropbox.py | ###############################################################################
#
# Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
import os
import sys
import erppeek
import shutil
import parameters # Micronaet: configuration file
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
# -----------------------------------------------------------------------------
# Parameters:
# -----------------------------------------------------------------------------
# ODOO connection:
odoo_server = parameters.odoo_server
odoo_port = parameters.odoo_port
odoo_user = parameters.odoo_user
odoo_password = parameters.odoo_password
odoo_database = parameters.odoo_database
# Dropbox:
demo = parameters.demo
samba_path = parameters.samba_path
dropbox_path = parameters.dropbox_path
print '''
Setup parameters:
ODOO: Connection: %s:%s DB %s utente: %s
Demo: %s
Samba folders: %s
Dropbox path: %s
''' % (
odoo_server,
odoo_port,
odoo_database,
odoo_user,
demo,
samba_path,
dropbox_path,
)
# -----------------------------------------------------------------------------
# UTILITY:
# -----------------------------------------------------------------------------
def | (fullname):
''' Return modify date for file
'''
modify_date = datetime.fromtimestamp(
os.stat(fullname).st_mtime).strftime('%Y-%m-%d')
return modify_date
# -----------------------------------------------------------------------------
# ODOO operation:
# -----------------------------------------------------------------------------
odoo = erppeek.Client(
'http://%s:%s' % (
odoo_server, odoo_port),
db=odoo_database,
user=odoo_user,
password=odoo_password,
)
# Pool used:
product_pool = odoo.model('product.product.web.server')
product_ids = product_pool.search([
('connector_id.wordpress', '=', True),
])
# Check elements:
#error = [] # Error database
#warning = [] # Warning database
#info = [] # Info database
#log = [] # Log database
#log_sym = [] # Log database for symlinks
#product_odoo = {}
# Only if new file (check how):
dropbox_root_path = os.path.expanduser(dropbox_path)
samba_root_path = os.path.expanduser(samba_path)
# -----------------------------------------------------------------------------
# Save current files (Dropbox folder):
# -----------------------------------------------------------------------------
current_files = []
for root, folders, files in os.walk(dropbox_root_path):
for f in files:
current_files.append(
os.path.join(root, f)
break # only first folder!
# -----------------------------------------------------------------------------
# Logg on all product image selected:
# -----------------------------------------------------------------------------
for product in product_pool.browse(product_ids):
for image in product.image_ids:
image_id = image.id
code = image.album_id.code
samba_relative_path = image.album_id.path # TODO dropbox_path
filename = product.filename
origin = os.path.(samba_relative_path, filename)
destination = os.path.(dropbox_root_path, '%s.%s' % (code, filename))
if destination in current_files:
current_files.remove(destination)
# Create symlink:
try:
os.symlink(origin, destination)
log_sym.append('CREATO: origin: %s destination: %s' % (
origin, destination))
except:
log_sym.append('ERRORE: origin: %s destination: %s' % (
origin, destination))
# Find dropbox link:
# Save dropbox link:
os.system('chmod 777 "%s" -R' % dropbox_path)
for filename in current_files:
os.rm(filename)
# file_modify = get_modify_date(fullname)
# os.system('mkdir -p "%s"' % product_folder)
print 'End operation'
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| get_modify_date | identifier_name |
timezone.service.ts | import { Injectable } from '@angular/core';
import moment from 'moment-timezone';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { default as timezone } from '../data/timezone.json';
import { HttpRequestService } from './http-request.service';
import { ResourceEndpoints } from '../types/api-endpoints';
import { LocalDateTimeAmbiguityStatus, LocalDateTimeInfo, TimeZones } from '../types/api-output';
/**
* The date time format used in date time resolution.
*/
export const LOCAL_DATE_TIME_FORMAT: string = 'YYYY-MM-DD HH:mm';
/**
* The resolving result of a local data time.
*/
export interface TimeResolvingResult {
timestamp: number;
message: string;
}
/**
* Handles timezone information provision.
*/
@Injectable({
providedIn: 'root',
})
export class TimezoneService {
tzVersion: string = '';
tzOffsets: Record<string, number> = {};
guessedTimezone: string = '';
// These short timezones are not supported by Java
private readonly badZones: Record<string, boolean> = {
EST: true, 'GMT+0': true, 'GMT-0': true, HST: true, MST: true, ROC: true,
};
constructor(private httpRequestService: HttpRequestService) {
const d: Date = new Date();
moment.tz.load(timezone);
this.tzVersion = moment.tz.dataVersion;
moment.tz.names()
.filter((tz: string) => !this.isBadZone(tz))
.forEach((tz: string) => {
const offset: number = moment.tz.zone(tz).utcOffset(d) * -1;
this.tzOffsets[tz] = offset;
});
this.guessedTimezone = moment.tz.guess();
}
/**
* Gets the timezone database version.
*/
getTzVersion(): string {
return this.tzVersion;
}
/**
* Gets the mapping of time zone ID to offset values.
*/
getTzOffsets(): Record<string, number> {
return this.tzOffsets;
}
/**
* Guesses the timezone based on the web browser's settings.
*/
guessTimezone(): string {
return this.guessedTimezone;
}
/**
* Returns true if the specified time zone ID is "bad", i.e. not supported by back-end.
*/
isBadZone(tz: string): boolean {
return this.badZones[tz];
}
getTimeZone(): Observable<TimeZones> {
return this.httpRequestService.get(ResourceEndpoints.TIMEZONE);
}
formatToString(timestamp: number, timeZone: string, format: string): string {
return moment(timestamp).tz(timeZone).format(format);
}
| (timestamp: number | null, timeZone: string): any {
if (!timestamp) {
return moment.tz(timeZone);
}
return moment(timestamp).tz(timeZone);
}
/**
* Gets the resolved UNIX timestamp from a local data time with time zone.
*/
getResolvedTimestamp(localDateTime: string, timeZone: string, fieldName: string): Observable<TimeResolvingResult> {
const params: Record<string, string> = { localdatetime: localDateTime, timezone: timeZone };
return this.httpRequestService.get(ResourceEndpoints.LOCAL_DATE_TIME, params).pipe(
map((info: LocalDateTimeInfo) => {
const resolvingResult: TimeResolvingResult = {
timestamp: info.resolvedTimestamp,
message: '',
};
const DATE_FORMAT_WITHOUT_ZONE_INFO: any = 'ddd, DD MMM, YYYY hh:mm A';
const DATE_FORMAT_WITH_ZONE_INFO: any = "ddd, DD MMM, YYYY hh:mm A z ('UTC'Z)";
switch (info.resolvedStatus) {
case LocalDateTimeAmbiguityStatus.UNAMBIGUOUS:
break;
case LocalDateTimeAmbiguityStatus.GAP:
resolvingResult.message =
`The ${fieldName}, ${moment.format(DATE_FORMAT_WITHOUT_ZONE_INFO)},`
+ 'falls within the gap period when clocks spring forward at the start of DST. '
+ `It was resolved to ${moment(info.resolvedTimestamp).format(DATE_FORMAT_WITH_ZONE_INFO)}.`;
break;
case LocalDateTimeAmbiguityStatus.OVERLAP:
resolvingResult.message =
`The ${fieldName}, ${moment.format(DATE_FORMAT_WITHOUT_ZONE_INFO)},`
+ 'falls within the overlap period when clocks fall back at the end of DST.'
+ `It can refer to ${moment(info.earlierInterpretationTimestamp).format(DATE_FORMAT_WITH_ZONE_INFO)}`
+ `or ${moment(info.laterInterpretationTimestamp).format(DATE_FORMAT_WITH_ZONE_INFO)}.`
+ 'It was resolved to %s.';
break;
default:
}
return resolvingResult;
}),
);
}
}
| getMomentInstance | identifier_name |
timezone.service.ts | import { Injectable } from '@angular/core';
import moment from 'moment-timezone';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { default as timezone } from '../data/timezone.json';
import { HttpRequestService } from './http-request.service';
import { ResourceEndpoints } from '../types/api-endpoints';
import { LocalDateTimeAmbiguityStatus, LocalDateTimeInfo, TimeZones } from '../types/api-output';
/**
* The date time format used in date time resolution.
*/
export const LOCAL_DATE_TIME_FORMAT: string = 'YYYY-MM-DD HH:mm';
/**
* The resolving result of a local data time.
*/
export interface TimeResolvingResult {
timestamp: number;
message: string;
}
/**
* Handles timezone information provision.
*/
@Injectable({
providedIn: 'root',
})
export class TimezoneService {
tzVersion: string = '';
tzOffsets: Record<string, number> = {};
guessedTimezone: string = '';
// These short timezones are not supported by Java
private readonly badZones: Record<string, boolean> = {
EST: true, 'GMT+0': true, 'GMT-0': true, HST: true, MST: true, ROC: true,
};
constructor(private httpRequestService: HttpRequestService) {
const d: Date = new Date();
moment.tz.load(timezone);
this.tzVersion = moment.tz.dataVersion;
moment.tz.names()
.filter((tz: string) => !this.isBadZone(tz))
.forEach((tz: string) => {
const offset: number = moment.tz.zone(tz).utcOffset(d) * -1;
this.tzOffsets[tz] = offset;
});
this.guessedTimezone = moment.tz.guess();
}
/**
* Gets the timezone database version.
*/
getTzVersion(): string {
return this.tzVersion;
}
/**
* Gets the mapping of time zone ID to offset values.
*/
getTzOffsets(): Record<string, number> {
return this.tzOffsets;
}
/**
* Guesses the timezone based on the web browser's settings.
*/
guessTimezone(): string {
return this.guessedTimezone;
}
/**
* Returns true if the specified time zone ID is "bad", i.e. not supported by back-end.
*/
isBadZone(tz: string): boolean |
getTimeZone(): Observable<TimeZones> {
return this.httpRequestService.get(ResourceEndpoints.TIMEZONE);
}
formatToString(timestamp: number, timeZone: string, format: string): string {
return moment(timestamp).tz(timeZone).format(format);
}
getMomentInstance(timestamp: number | null, timeZone: string): any {
if (!timestamp) {
return moment.tz(timeZone);
}
return moment(timestamp).tz(timeZone);
}
/**
* Gets the resolved UNIX timestamp from a local data time with time zone.
*/
getResolvedTimestamp(localDateTime: string, timeZone: string, fieldName: string): Observable<TimeResolvingResult> {
const params: Record<string, string> = { localdatetime: localDateTime, timezone: timeZone };
return this.httpRequestService.get(ResourceEndpoints.LOCAL_DATE_TIME, params).pipe(
map((info: LocalDateTimeInfo) => {
const resolvingResult: TimeResolvingResult = {
timestamp: info.resolvedTimestamp,
message: '',
};
const DATE_FORMAT_WITHOUT_ZONE_INFO: any = 'ddd, DD MMM, YYYY hh:mm A';
const DATE_FORMAT_WITH_ZONE_INFO: any = "ddd, DD MMM, YYYY hh:mm A z ('UTC'Z)";
switch (info.resolvedStatus) {
case LocalDateTimeAmbiguityStatus.UNAMBIGUOUS:
break;
case LocalDateTimeAmbiguityStatus.GAP:
resolvingResult.message =
`The ${fieldName}, ${moment.format(DATE_FORMAT_WITHOUT_ZONE_INFO)},`
+ 'falls within the gap period when clocks spring forward at the start of DST. '
+ `It was resolved to ${moment(info.resolvedTimestamp).format(DATE_FORMAT_WITH_ZONE_INFO)}.`;
break;
case LocalDateTimeAmbiguityStatus.OVERLAP:
resolvingResult.message =
`The ${fieldName}, ${moment.format(DATE_FORMAT_WITHOUT_ZONE_INFO)},`
+ 'falls within the overlap period when clocks fall back at the end of DST.'
+ `It can refer to ${moment(info.earlierInterpretationTimestamp).format(DATE_FORMAT_WITH_ZONE_INFO)}`
+ `or ${moment(info.laterInterpretationTimestamp).format(DATE_FORMAT_WITH_ZONE_INFO)}.`
+ 'It was resolved to %s.';
break;
default:
}
return resolvingResult;
}),
);
}
}
| {
return this.badZones[tz];
} | identifier_body |
timezone.service.ts | import { Injectable } from '@angular/core';
import moment from 'moment-timezone';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { default as timezone } from '../data/timezone.json';
import { HttpRequestService } from './http-request.service';
import { ResourceEndpoints } from '../types/api-endpoints';
import { LocalDateTimeAmbiguityStatus, LocalDateTimeInfo, TimeZones } from '../types/api-output';
/**
* The date time format used in date time resolution.
*/
export const LOCAL_DATE_TIME_FORMAT: string = 'YYYY-MM-DD HH:mm';
/**
* The resolving result of a local data time.
*/
export interface TimeResolvingResult {
timestamp: number;
message: string;
}
/**
* Handles timezone information provision.
*/
@Injectable({
providedIn: 'root',
})
export class TimezoneService {
tzVersion: string = '';
tzOffsets: Record<string, number> = {};
guessedTimezone: string = '';
// These short timezones are not supported by Java
private readonly badZones: Record<string, boolean> = {
EST: true, 'GMT+0': true, 'GMT-0': true, HST: true, MST: true, ROC: true,
};
constructor(private httpRequestService: HttpRequestService) {
const d: Date = new Date();
moment.tz.load(timezone);
this.tzVersion = moment.tz.dataVersion;
moment.tz.names()
.filter((tz: string) => !this.isBadZone(tz))
.forEach((tz: string) => {
const offset: number = moment.tz.zone(tz).utcOffset(d) * -1;
this.tzOffsets[tz] = offset;
}); | this.guessedTimezone = moment.tz.guess();
}
/**
* Gets the timezone database version.
*/
getTzVersion(): string {
return this.tzVersion;
}
/**
* Gets the mapping of time zone ID to offset values.
*/
getTzOffsets(): Record<string, number> {
return this.tzOffsets;
}
/**
* Guesses the timezone based on the web browser's settings.
*/
guessTimezone(): string {
return this.guessedTimezone;
}
/**
* Returns true if the specified time zone ID is "bad", i.e. not supported by back-end.
*/
isBadZone(tz: string): boolean {
return this.badZones[tz];
}
getTimeZone(): Observable<TimeZones> {
return this.httpRequestService.get(ResourceEndpoints.TIMEZONE);
}
formatToString(timestamp: number, timeZone: string, format: string): string {
return moment(timestamp).tz(timeZone).format(format);
}
getMomentInstance(timestamp: number | null, timeZone: string): any {
if (!timestamp) {
return moment.tz(timeZone);
}
return moment(timestamp).tz(timeZone);
}
/**
* Gets the resolved UNIX timestamp from a local data time with time zone.
*/
getResolvedTimestamp(localDateTime: string, timeZone: string, fieldName: string): Observable<TimeResolvingResult> {
const params: Record<string, string> = { localdatetime: localDateTime, timezone: timeZone };
return this.httpRequestService.get(ResourceEndpoints.LOCAL_DATE_TIME, params).pipe(
map((info: LocalDateTimeInfo) => {
const resolvingResult: TimeResolvingResult = {
timestamp: info.resolvedTimestamp,
message: '',
};
const DATE_FORMAT_WITHOUT_ZONE_INFO: any = 'ddd, DD MMM, YYYY hh:mm A';
const DATE_FORMAT_WITH_ZONE_INFO: any = "ddd, DD MMM, YYYY hh:mm A z ('UTC'Z)";
switch (info.resolvedStatus) {
case LocalDateTimeAmbiguityStatus.UNAMBIGUOUS:
break;
case LocalDateTimeAmbiguityStatus.GAP:
resolvingResult.message =
`The ${fieldName}, ${moment.format(DATE_FORMAT_WITHOUT_ZONE_INFO)},`
+ 'falls within the gap period when clocks spring forward at the start of DST. '
+ `It was resolved to ${moment(info.resolvedTimestamp).format(DATE_FORMAT_WITH_ZONE_INFO)}.`;
break;
case LocalDateTimeAmbiguityStatus.OVERLAP:
resolvingResult.message =
`The ${fieldName}, ${moment.format(DATE_FORMAT_WITHOUT_ZONE_INFO)},`
+ 'falls within the overlap period when clocks fall back at the end of DST.'
+ `It can refer to ${moment(info.earlierInterpretationTimestamp).format(DATE_FORMAT_WITH_ZONE_INFO)}`
+ `or ${moment(info.laterInterpretationTimestamp).format(DATE_FORMAT_WITH_ZONE_INFO)}.`
+ 'It was resolved to %s.';
break;
default:
}
return resolvingResult;
}),
);
}
} | random_line_split |
|
bitflags.rs | RIGHT.
//
// 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.
//! The `bitflags!` macro generates a `struct` that holds a set of C-style
//! bitmask flags. It is useful for creating typesafe wrappers for C APIs.
//!
//! The flags should only be defined for integer types, otherwise unexpected
//! type errors may occur at compile time.
//!
//! # Example
//!
//! ~~~rust
//! bitflags!(
//! flags Flags: u32 {
//! static FlagA = 0x00000001,
//! static FlagB = 0x00000010,
//! static FlagC = 0x00000100,
//! static FlagABC = FlagA.bits
//! | FlagB.bits
//! | FlagC.bits
//! }
//! )
//!
//! fn main() {
//! let e1 = FlagA | FlagC;
//! let e2 = FlagB | FlagC;
//! assert!((e1 | e2) == FlagABC); // union
//! assert!((e1 & e2) == FlagC); // intersection
//! assert!((e1 - e2) == FlagA); // set difference
//! }
//! ~~~
//!
//! The generated `struct`s can also be extended with type and trait implementations:
//!
//! ~~~rust
//! use std::fmt;
//!
//! bitflags!(
//! flags Flags: u32 {
//! static FlagA = 0x00000001,
//! static FlagB = 0x00000010
//! }
//! )
//!
//! impl Flags {
//! pub fn clear(&mut self) {
//! self.bits = 0; // The `bits` field can be accessed from within the
//! // same module where the `bitflags!` macro was invoked.
//! }
//! }
//!
//! impl fmt::Show for Flags {
//! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! write!(f.buf, "hi!")
//! }
//! }
//!
//! fn main() {
//! let mut flags = FlagA | FlagB;
//! flags.clear();
//! assert!(flags.is_empty());
//! assert_eq!(format!("{}", flags).as_slice(), "hi!");
//! }
//! ~~~
//!
//! # Attributes
//!
//! Attributes can be attached to the generated `struct` by placing them
//! before the `flags` keyword.
//!
//! # Derived traits
//!
//! The `Eq` and `Clone` traits are automatically derived for the `struct` using
//! the `deriving` attribute. Additional traits can be derived by providing an
//! explicit `deriving` attribute on `flags`.
//!
//! # Operators
//!
//! The following operator traits are implemented for the generated `struct`:
//!
//! - `BitOr`: union
//! - `BitAnd`: intersection
//! - `Sub`: set difference
//!
//! # Methods
//!
//! The following methods are defined for the generated `struct`:
//!
//! - `empty`: an empty set of flags
//! - `bits`: the raw value of the flags currently stored
//! - `is_empty`: `true` if no flags are currently stored
//! - `intersects`: `true` if there are flags common to both `self` and `other`
//! - `contains`: `true` all of the flags in `other` are contained within `self`
//! - `insert`: inserts the specified flags in-place
//! - `remove`: removes the specified flags in-place
#![macro_escape]
#[macro_export]
macro_rules! bitflags(
($(#[$attr:meta])* flags $BitFlags:ident: $T:ty {
$($(#[$Flag_attr:meta])* static $Flag:ident = $value:expr),+
}) => (
#[deriving(Eq, TotalEq, Clone)]
$(#[$attr])*
pub struct $BitFlags {
bits: $T,
}
$($(#[$Flag_attr])* pub static $Flag: $BitFlags = $BitFlags { bits: $value };)+
impl $BitFlags {
/// Returns an empty set of flags.
pub fn empty() -> $BitFlags {
$BitFlags { bits: 0 }
}
/// Returns the raw value of the flags currently stored.
pub fn bits(&self) -> $T {
self.bits
}
/// Convert from underlying bit representation. Unsafe because the
/// bits are not guaranteed to represent valid flags.
pub unsafe fn from_bits(bits: $T) -> $BitFlags {
$BitFlags { bits: bits }
}
/// Returns `true` if no flags are currently stored.
pub fn is_empty(&self) -> bool {
*self == $BitFlags::empty()
}
/// Returns `true` if there are flags common to both `self` and `other`.
pub fn intersects(&self, other: $BitFlags) -> bool {
!(self & other).is_empty()
}
/// Returns `true` all of the flags in `other` are contained within `self`.
pub fn contains(&self, other: $BitFlags) -> bool {
(self & other) == other
}
/// Inserts the specified flags in-place.
pub fn insert(&mut self, other: $BitFlags) {
self.bits |= other.bits;
}
/// Removes the specified flags in-place.
pub fn remove(&mut self, other: $BitFlags) {
self.bits &= !other.bits;
}
}
impl BitOr<$BitFlags, $BitFlags> for $BitFlags {
/// Returns the union of the two sets of flags.
#[inline]
fn bitor(&self, other: &$BitFlags) -> $BitFlags {
$BitFlags { bits: self.bits | other.bits }
}
}
impl BitAnd<$BitFlags, $BitFlags> for $BitFlags {
/// Returns the intersection between the two sets of flags.
#[inline]
fn bitand(&self, other: &$BitFlags) -> $BitFlags {
$BitFlags { bits: self.bits & other.bits }
}
}
impl Sub<$BitFlags, $BitFlags> for $BitFlags {
/// Returns the set difference of the two sets of flags.
#[inline]
fn sub(&self, other: &$BitFlags) -> $BitFlags {
$BitFlags { bits: self.bits & !other.bits }
}
}
)
)
#[cfg(test)]
mod tests {
use ops::{BitOr, BitAnd, Sub};
bitflags!(
flags Flags: u32 {
static FlagA = 0x00000001,
static FlagB = 0x00000010,
static FlagC = 0x00000100,
static FlagABC = FlagA.bits
| FlagB.bits
| FlagC.bits
}
)
#[test]
fn test_bits(){
assert_eq!(Flags::empty().bits(), 0x00000000);
assert_eq!(FlagA.bits(), 0x00000001);
assert_eq!(FlagABC.bits(), 0x00000111);
}
#[test]
fn test_is_empty(){
assert!(Flags::empty().is_empty());
assert!(!FlagA.is_empty());
assert!(!FlagABC.is_empty());
}
#[test]
fn test_two_empties_do_not_intersect() {
let e1 = Flags::empty();
let e2 = Flags::empty();
assert!(!e1.intersects(e2));
}
#[test]
fn test_empty_does_not_intersect_with_full() {
let e1 = Flags::empty();
let e2 = FlagABC;
assert!(!e1.intersects(e2));
}
#[test]
fn test_disjoint_intersects() {
let e1 = FlagA;
let e2 = FlagB;
assert!(!e1.intersects(e2));
}
#[test]
fn test_overlapping_intersects() {
let e1 = FlagA;
let e2 = FlagA | FlagB;
assert!(e1.intersects(e2));
}
#[test]
fn test_contains() {
let e1 = FlagA;
let e2 = FlagA | FlagB;
assert!(!e1.contains(e2));
assert!(e2.contains(e1));
assert!(FlagABC.contains(e2));
}
#[test]
fn test_insert() |
#[test]
fn test_remove(){
let mut e1 = FlagA | FlagB;
let e2 = FlagA | FlagC;
e1.remove(e2);
assert!(e1 == FlagB);
}
#[ | {
let mut e1 = FlagA;
let e2 = FlagA | FlagB;
e1.insert(e2);
assert!(e1 == e2);
} | identifier_body |
bitflags.rs | RIGHT.
//
// 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.
//! The `bitflags!` macro generates a `struct` that holds a set of C-style
//! bitmask flags. It is useful for creating typesafe wrappers for C APIs.
//!
//! The flags should only be defined for integer types, otherwise unexpected
//! type errors may occur at compile time.
//!
//! # Example
//!
//! ~~~rust
//! bitflags!(
//! flags Flags: u32 {
//! static FlagA = 0x00000001,
//! static FlagB = 0x00000010,
//! static FlagC = 0x00000100,
//! static FlagABC = FlagA.bits
//! | FlagB.bits
//! | FlagC.bits
//! }
//! )
//!
//! fn main() {
//! let e1 = FlagA | FlagC;
//! let e2 = FlagB | FlagC;
//! assert!((e1 | e2) == FlagABC); // union
//! assert!((e1 & e2) == FlagC); // intersection
//! assert!((e1 - e2) == FlagA); // set difference
//! }
//! ~~~
//!
//! The generated `struct`s can also be extended with type and trait implementations:
//!
//! ~~~rust
//! use std::fmt;
//!
//! bitflags!(
//! flags Flags: u32 {
//! static FlagA = 0x00000001,
//! static FlagB = 0x00000010
//! }
//! )
//!
//! impl Flags {
//! pub fn clear(&mut self) {
//! self.bits = 0; // The `bits` field can be accessed from within the
//! // same module where the `bitflags!` macro was invoked.
//! }
//! }
//!
//! impl fmt::Show for Flags {
//! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! write!(f.buf, "hi!")
//! }
//! }
//!
//! fn main() {
//! let mut flags = FlagA | FlagB;
//! flags.clear();
//! assert!(flags.is_empty());
//! assert_eq!(format!("{}", flags).as_slice(), "hi!");
//! }
//! ~~~
//!
//! # Attributes
//!
//! Attributes can be attached to the generated `struct` by placing them
//! before the `flags` keyword.
//!
//! # Derived traits
//!
//! The `Eq` and `Clone` traits are automatically derived for the `struct` using
//! the `deriving` attribute. Additional traits can be derived by providing an
//! explicit `deriving` attribute on `flags`.
//!
//! # Operators
//!
//! The following operator traits are implemented for the generated `struct`:
//!
//! - `BitOr`: union
//! - `BitAnd`: intersection
//! - `Sub`: set difference
//!
//! # Methods
//!
//! The following methods are defined for the generated `struct`:
//!
//! - `empty`: an empty set of flags
//! - `bits`: the raw value of the flags currently stored
//! - `is_empty`: `true` if no flags are currently stored
//! - `intersects`: `true` if there are flags common to both `self` and `other`
//! - `contains`: `true` all of the flags in `other` are contained within `self` | //! - `insert`: inserts the specified flags in-place
//! - `remove`: removes the specified flags in-place
#![macro_escape]
#[macro_export]
macro_rules! bitflags(
($(#[$attr:meta])* flags $BitFlags:ident: $T:ty {
$($(#[$Flag_attr:meta])* static $Flag:ident = $value:expr),+
}) => (
#[deriving(Eq, TotalEq, Clone)]
$(#[$attr])*
pub struct $BitFlags {
bits: $T,
}
$($(#[$Flag_attr])* pub static $Flag: $BitFlags = $BitFlags { bits: $value };)+
impl $BitFlags {
/// Returns an empty set of flags.
pub fn empty() -> $BitFlags {
$BitFlags { bits: 0 }
}
/// Returns the raw value of the flags currently stored.
pub fn bits(&self) -> $T {
self.bits
}
/// Convert from underlying bit representation. Unsafe because the
/// bits are not guaranteed to represent valid flags.
pub unsafe fn from_bits(bits: $T) -> $BitFlags {
$BitFlags { bits: bits }
}
/// Returns `true` if no flags are currently stored.
pub fn is_empty(&self) -> bool {
*self == $BitFlags::empty()
}
/// Returns `true` if there are flags common to both `self` and `other`.
pub fn intersects(&self, other: $BitFlags) -> bool {
!(self & other).is_empty()
}
/// Returns `true` all of the flags in `other` are contained within `self`.
pub fn contains(&self, other: $BitFlags) -> bool {
(self & other) == other
}
/// Inserts the specified flags in-place.
pub fn insert(&mut self, other: $BitFlags) {
self.bits |= other.bits;
}
/// Removes the specified flags in-place.
pub fn remove(&mut self, other: $BitFlags) {
self.bits &= !other.bits;
}
}
impl BitOr<$BitFlags, $BitFlags> for $BitFlags {
/// Returns the union of the two sets of flags.
#[inline]
fn bitor(&self, other: &$BitFlags) -> $BitFlags {
$BitFlags { bits: self.bits | other.bits }
}
}
impl BitAnd<$BitFlags, $BitFlags> for $BitFlags {
/// Returns the intersection between the two sets of flags.
#[inline]
fn bitand(&self, other: &$BitFlags) -> $BitFlags {
$BitFlags { bits: self.bits & other.bits }
}
}
impl Sub<$BitFlags, $BitFlags> for $BitFlags {
/// Returns the set difference of the two sets of flags.
#[inline]
fn sub(&self, other: &$BitFlags) -> $BitFlags {
$BitFlags { bits: self.bits & !other.bits }
}
}
)
)
#[cfg(test)]
mod tests {
use ops::{BitOr, BitAnd, Sub};
bitflags!(
flags Flags: u32 {
static FlagA = 0x00000001,
static FlagB = 0x00000010,
static FlagC = 0x00000100,
static FlagABC = FlagA.bits
| FlagB.bits
| FlagC.bits
}
)
#[test]
fn test_bits(){
assert_eq!(Flags::empty().bits(), 0x00000000);
assert_eq!(FlagA.bits(), 0x00000001);
assert_eq!(FlagABC.bits(), 0x00000111);
}
#[test]
fn test_is_empty(){
assert!(Flags::empty().is_empty());
assert!(!FlagA.is_empty());
assert!(!FlagABC.is_empty());
}
#[test]
fn test_two_empties_do_not_intersect() {
let e1 = Flags::empty();
let e2 = Flags::empty();
assert!(!e1.intersects(e2));
}
#[test]
fn test_empty_does_not_intersect_with_full() {
let e1 = Flags::empty();
let e2 = FlagABC;
assert!(!e1.intersects(e2));
}
#[test]
fn test_disjoint_intersects() {
let e1 = FlagA;
let e2 = FlagB;
assert!(!e1.intersects(e2));
}
#[test]
fn test_overlapping_intersects() {
let e1 = FlagA;
let e2 = FlagA | FlagB;
assert!(e1.intersects(e2));
}
#[test]
fn test_contains() {
let e1 = FlagA;
let e2 = FlagA | FlagB;
assert!(!e1.contains(e2));
assert!(e2.contains(e1));
assert!(FlagABC.contains(e2));
}
#[test]
fn test_insert(){
let mut e1 = FlagA;
let e2 = FlagA | FlagB;
e1.insert(e2);
assert!(e1 == e2);
}
#[test]
fn test_remove(){
let mut e1 = FlagA | FlagB;
let e2 = FlagA | FlagC;
e1.remove(e2);
assert!(e1 == FlagB);
}
#[test]
| random_line_split |
|
bitflags.rs | RIGHT.
//
// 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.
//! The `bitflags!` macro generates a `struct` that holds a set of C-style
//! bitmask flags. It is useful for creating typesafe wrappers for C APIs.
//!
//! The flags should only be defined for integer types, otherwise unexpected
//! type errors may occur at compile time.
//!
//! # Example
//!
//! ~~~rust
//! bitflags!(
//! flags Flags: u32 {
//! static FlagA = 0x00000001,
//! static FlagB = 0x00000010,
//! static FlagC = 0x00000100,
//! static FlagABC = FlagA.bits
//! | FlagB.bits
//! | FlagC.bits
//! }
//! )
//!
//! fn main() {
//! let e1 = FlagA | FlagC;
//! let e2 = FlagB | FlagC;
//! assert!((e1 | e2) == FlagABC); // union
//! assert!((e1 & e2) == FlagC); // intersection
//! assert!((e1 - e2) == FlagA); // set difference
//! }
//! ~~~
//!
//! The generated `struct`s can also be extended with type and trait implementations:
//!
//! ~~~rust
//! use std::fmt;
//!
//! bitflags!(
//! flags Flags: u32 {
//! static FlagA = 0x00000001,
//! static FlagB = 0x00000010
//! }
//! )
//!
//! impl Flags {
//! pub fn clear(&mut self) {
//! self.bits = 0; // The `bits` field can be accessed from within the
//! // same module where the `bitflags!` macro was invoked.
//! }
//! }
//!
//! impl fmt::Show for Flags {
//! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! write!(f.buf, "hi!")
//! }
//! }
//!
//! fn main() {
//! let mut flags = FlagA | FlagB;
//! flags.clear();
//! assert!(flags.is_empty());
//! assert_eq!(format!("{}", flags).as_slice(), "hi!");
//! }
//! ~~~
//!
//! # Attributes
//!
//! Attributes can be attached to the generated `struct` by placing them
//! before the `flags` keyword.
//!
//! # Derived traits
//!
//! The `Eq` and `Clone` traits are automatically derived for the `struct` using
//! the `deriving` attribute. Additional traits can be derived by providing an
//! explicit `deriving` attribute on `flags`.
//!
//! # Operators
//!
//! The following operator traits are implemented for the generated `struct`:
//!
//! - `BitOr`: union
//! - `BitAnd`: intersection
//! - `Sub`: set difference
//!
//! # Methods
//!
//! The following methods are defined for the generated `struct`:
//!
//! - `empty`: an empty set of flags
//! - `bits`: the raw value of the flags currently stored
//! - `is_empty`: `true` if no flags are currently stored
//! - `intersects`: `true` if there are flags common to both `self` and `other`
//! - `contains`: `true` all of the flags in `other` are contained within `self`
//! - `insert`: inserts the specified flags in-place
//! - `remove`: removes the specified flags in-place
#![macro_escape]
#[macro_export]
macro_rules! bitflags(
($(#[$attr:meta])* flags $BitFlags:ident: $T:ty {
$($(#[$Flag_attr:meta])* static $Flag:ident = $value:expr),+
}) => (
#[deriving(Eq, TotalEq, Clone)]
$(#[$attr])*
pub struct $BitFlags {
bits: $T,
}
$($(#[$Flag_attr])* pub static $Flag: $BitFlags = $BitFlags { bits: $value };)+
impl $BitFlags {
/// Returns an empty set of flags.
pub fn empty() -> $BitFlags {
$BitFlags { bits: 0 }
}
/// Returns the raw value of the flags currently stored.
pub fn bits(&self) -> $T {
self.bits
}
/// Convert from underlying bit representation. Unsafe because the
/// bits are not guaranteed to represent valid flags.
pub unsafe fn from_bits(bits: $T) -> $BitFlags {
$BitFlags { bits: bits }
}
/// Returns `true` if no flags are currently stored.
pub fn is_empty(&self) -> bool {
*self == $BitFlags::empty()
}
/// Returns `true` if there are flags common to both `self` and `other`.
pub fn intersects(&self, other: $BitFlags) -> bool {
!(self & other).is_empty()
}
/// Returns `true` all of the flags in `other` are contained within `self`.
pub fn contains(&self, other: $BitFlags) -> bool {
(self & other) == other
}
/// Inserts the specified flags in-place.
pub fn insert(&mut self, other: $BitFlags) {
self.bits |= other.bits;
}
/// Removes the specified flags in-place.
pub fn remove(&mut self, other: $BitFlags) {
self.bits &= !other.bits;
}
}
impl BitOr<$BitFlags, $BitFlags> for $BitFlags {
/// Returns the union of the two sets of flags.
#[inline]
fn bitor(&self, other: &$BitFlags) -> $BitFlags {
$BitFlags { bits: self.bits | other.bits }
}
}
impl BitAnd<$BitFlags, $BitFlags> for $BitFlags {
/// Returns the intersection between the two sets of flags.
#[inline]
fn bitand(&self, other: &$BitFlags) -> $BitFlags {
$BitFlags { bits: self.bits & other.bits }
}
}
impl Sub<$BitFlags, $BitFlags> for $BitFlags {
/// Returns the set difference of the two sets of flags.
#[inline]
fn sub(&self, other: &$BitFlags) -> $BitFlags {
$BitFlags { bits: self.bits & !other.bits }
}
}
)
)
#[cfg(test)]
mod tests {
use ops::{BitOr, BitAnd, Sub};
bitflags!(
flags Flags: u32 {
static FlagA = 0x00000001,
static FlagB = 0x00000010,
static FlagC = 0x00000100,
static FlagABC = FlagA.bits
| FlagB.bits
| FlagC.bits
}
)
#[test]
fn | (){
assert_eq!(Flags::empty().bits(), 0x00000000);
assert_eq!(FlagA.bits(), 0x00000001);
assert_eq!(FlagABC.bits(), 0x00000111);
}
#[test]
fn test_is_empty(){
assert!(Flags::empty().is_empty());
assert!(!FlagA.is_empty());
assert!(!FlagABC.is_empty());
}
#[test]
fn test_two_empties_do_not_intersect() {
let e1 = Flags::empty();
let e2 = Flags::empty();
assert!(!e1.intersects(e2));
}
#[test]
fn test_empty_does_not_intersect_with_full() {
let e1 = Flags::empty();
let e2 = FlagABC;
assert!(!e1.intersects(e2));
}
#[test]
fn test_disjoint_intersects() {
let e1 = FlagA;
let e2 = FlagB;
assert!(!e1.intersects(e2));
}
#[test]
fn test_overlapping_intersects() {
let e1 = FlagA;
let e2 = FlagA | FlagB;
assert!(e1.intersects(e2));
}
#[test]
fn test_contains() {
let e1 = FlagA;
let e2 = FlagA | FlagB;
assert!(!e1.contains(e2));
assert!(e2.contains(e1));
assert!(FlagABC.contains(e2));
}
#[test]
fn test_insert(){
let mut e1 = FlagA;
let e2 = FlagA | FlagB;
e1.insert(e2);
assert!(e1 == e2);
}
#[test]
fn test_remove(){
let mut e1 = FlagA | FlagB;
let e2 = FlagA | FlagC;
e1.remove(e2);
assert!(e1 == FlagB);
}
#[test | test_bits | identifier_name |
status-window.component.ts | import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { ColyseusGameService } from '../colyseus.game.service';
import { values, extend } from 'lodash';
import { LocalStorage } from 'ngx-webstorage';
import { timer } from 'rxjs';
@Component({
selector: 'app-status-window',
templateUrl: './status-window.component.html',
styleUrls: ['./status-window.component.scss']
})
export class StatusWindowComponent implements OnInit, OnDestroy {
@Input()
public size;
@LocalStorage() |
@LocalStorage()
public isMPPercent: boolean;
public effects = [];
private effect$: any;
public get player() {
return this.colyseusGame.character;
}
get healthPercent(): number {
if(!this.player) return 0;
return Math.floor(this.player.hp.__current / this.player.hp.maximum * 100);
}
get magicPercent(): number {
if(!this.player) return 0;
// show full bar even if 0/0
if(this.player.mp.maximum === 0) return 100;
return Math.floor(this.player.mp.__current / this.player.mp.maximum * 100);
}
get xpPercent(): number {
if(!this.player) return 0;
const baseXp = this.player.calcLevelXP(this.player.level);
const neededXp = this.player.calcLevelXP(this.player.level + 1);
return Math.floor(Math.min(100, (this.player.exp - baseXp) / (neededXp - baseXp) * 100));
}
get axpPercent(): number {
if(!this.player) return 0;
return Math.min(100, this.player.axp);
}
get allEffects(): any[] {
if(!this.player) return [];
return values(this.player.effects);
}
constructor(public colyseusGame: ColyseusGameService) { }
ngOnInit() {
this.effect$ = timer(0, 1000).subscribe(() => {
this.recalculateEffects();
});
}
ngOnDestroy() {
this.effect$.unsubscribe();
}
tryUnapplying(effect) {
this.colyseusGame.tryEffectUnapply(effect);
}
private recalculateEffects() {
const newEffects = this.allEffects;
this.effects.length = newEffects.length;
for(let i = 0; i < newEffects.length; i++) {
if(!this.effects[i]) {
this.effects[i] = newEffects[i];
} else {
Object.keys(this.effects[i]).forEach(key => delete this.effects[i][key]);
extend(this.effects[i], newEffects[i]);
}
}
}
} | public isXPPercent: boolean;
@LocalStorage()
public isHPPercent: boolean; | random_line_split |
status-window.component.ts | import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { ColyseusGameService } from '../colyseus.game.service';
import { values, extend } from 'lodash';
import { LocalStorage } from 'ngx-webstorage';
import { timer } from 'rxjs';
@Component({
selector: 'app-status-window',
templateUrl: './status-window.component.html',
styleUrls: ['./status-window.component.scss']
})
export class StatusWindowComponent implements OnInit, OnDestroy {
@Input()
public size;
@LocalStorage()
public isXPPercent: boolean;
@LocalStorage()
public isHPPercent: boolean;
@LocalStorage()
public isMPPercent: boolean;
public effects = [];
private effect$: any;
public get player() {
return this.colyseusGame.character;
}
get healthPercent(): number {
if(!this.player) return 0;
return Math.floor(this.player.hp.__current / this.player.hp.maximum * 100);
}
get magicPercent(): number {
if(!this.player) return 0;
// show full bar even if 0/0
if(this.player.mp.maximum === 0) return 100;
return Math.floor(this.player.mp.__current / this.player.mp.maximum * 100);
}
get xpPercent(): number {
if(!this.player) return 0;
const baseXp = this.player.calcLevelXP(this.player.level);
const neededXp = this.player.calcLevelXP(this.player.level + 1);
return Math.floor(Math.min(100, (this.player.exp - baseXp) / (neededXp - baseXp) * 100));
}
get axpPercent(): number {
if(!this.player) return 0;
return Math.min(100, this.player.axp);
}
get | (): any[] {
if(!this.player) return [];
return values(this.player.effects);
}
constructor(public colyseusGame: ColyseusGameService) { }
ngOnInit() {
this.effect$ = timer(0, 1000).subscribe(() => {
this.recalculateEffects();
});
}
ngOnDestroy() {
this.effect$.unsubscribe();
}
tryUnapplying(effect) {
this.colyseusGame.tryEffectUnapply(effect);
}
private recalculateEffects() {
const newEffects = this.allEffects;
this.effects.length = newEffects.length;
for(let i = 0; i < newEffects.length; i++) {
if(!this.effects[i]) {
this.effects[i] = newEffects[i];
} else {
Object.keys(this.effects[i]).forEach(key => delete this.effects[i][key]);
extend(this.effects[i], newEffects[i]);
}
}
}
}
| allEffects | identifier_name |
status-window.component.ts | import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { ColyseusGameService } from '../colyseus.game.service';
import { values, extend } from 'lodash';
import { LocalStorage } from 'ngx-webstorage';
import { timer } from 'rxjs';
@Component({
selector: 'app-status-window',
templateUrl: './status-window.component.html',
styleUrls: ['./status-window.component.scss']
})
export class StatusWindowComponent implements OnInit, OnDestroy {
@Input()
public size;
@LocalStorage()
public isXPPercent: boolean;
@LocalStorage()
public isHPPercent: boolean;
@LocalStorage()
public isMPPercent: boolean;
public effects = [];
private effect$: any;
public get player() {
return this.colyseusGame.character;
}
get healthPercent(): number {
if(!this.player) return 0;
return Math.floor(this.player.hp.__current / this.player.hp.maximum * 100);
}
get magicPercent(): number |
get xpPercent(): number {
if(!this.player) return 0;
const baseXp = this.player.calcLevelXP(this.player.level);
const neededXp = this.player.calcLevelXP(this.player.level + 1);
return Math.floor(Math.min(100, (this.player.exp - baseXp) / (neededXp - baseXp) * 100));
}
get axpPercent(): number {
if(!this.player) return 0;
return Math.min(100, this.player.axp);
}
get allEffects(): any[] {
if(!this.player) return [];
return values(this.player.effects);
}
constructor(public colyseusGame: ColyseusGameService) { }
ngOnInit() {
this.effect$ = timer(0, 1000).subscribe(() => {
this.recalculateEffects();
});
}
ngOnDestroy() {
this.effect$.unsubscribe();
}
tryUnapplying(effect) {
this.colyseusGame.tryEffectUnapply(effect);
}
private recalculateEffects() {
const newEffects = this.allEffects;
this.effects.length = newEffects.length;
for(let i = 0; i < newEffects.length; i++) {
if(!this.effects[i]) {
this.effects[i] = newEffects[i];
} else {
Object.keys(this.effects[i]).forEach(key => delete this.effects[i][key]);
extend(this.effects[i], newEffects[i]);
}
}
}
}
| {
if(!this.player) return 0;
// show full bar even if 0/0
if(this.player.mp.maximum === 0) return 100;
return Math.floor(this.player.mp.__current / this.player.mp.maximum * 100);
} | identifier_body |
test_user_registered.py | from django.test import TestCase
from django.contrib.auth.models import User
from django.http import HttpRequest
from .factories import UserReferrerFactory, UserFactory, CampaignFactory
from referral_module import constants
from referral_module import models
def make_cookie_file(user_referrer):
cookie_file = '{}:{}'.format(user_referrer.campaign.key, user_referrer.key)
return cookie_file
def get_request(user_referrer):
request = HttpRequest()
cookie = make_cookie_file(user_referrer)
request.COOKIES[constants.REFERRER_COOKIE_NAME] = cookie
return request
class UserRegisteredTestCase(TestCase):
def setUp(self):
campaign = CampaignFactory(
bonus_policy={
'click': 1,
'registration': 6,
}
)
self.user_referrer = UserReferrerFactory(
campaign=campaign
)
self.user = UserFactory()
def test_user_registered_with_referrer_user(self):
reward_before_new_user = self.user_referrer.reward
request = get_request(user_referrer=self.user_referrer)
models.associate_registered_user_with_referral("", user=self.user, request=request)
# referrer user sign as referrer to the new user
referrer_db = models.Referrer.objects.get(user_referrer=self.user_referrer)
self.assertEqual(referrer_db.registered_user.username, self.user.username)
# check reward update
reward_of_referrer_user = models.UserReferrer.objects.get(key=self.user_referrer.key).reward
reward_after_adding_user = reward_before_new_user + self.user_referrer.campaign.bonus_policy['registration']
self.assertEqual(reward_of_referrer_user, reward_after_adding_user)
def test_unreferred_user_registered(self):
request = HttpRequest()
models.associate_registered_user_with_referral("", user=self.user, request=request)
# new user is in the database
user_in_db = User.objects.get(username=self.user.username)
self.assertEqual(user_in_db.username, self.user.username)
def | (self):
real_user_campaign_key = self.user_referrer.campaign.key
# First check with fake campaign key
self.user_referrer.campaign.key = 77777 # random data
request = get_request(user_referrer=self.user_referrer)
self.assertEqual(
models.Referrer.objects.count(),
0
)
models.associate_registered_user_with_referral("", user=self.user, request=request)
self.assertEqual(
models.Referrer.objects.count(),
0
)
# check real campaign key and fake referrer
self.user_referrer.campaign.key = real_user_campaign_key
self.user_referrer.key = '232323' # fake data
request = get_request(user_referrer=self.user_referrer)
models.associate_registered_user_with_referral("", user=self.user, request=request)
self.assertEqual(
models.Referrer.objects.count(),
0
)
| test_illegal_referrer_data | identifier_name |
test_user_registered.py | from django.test import TestCase
from django.contrib.auth.models import User
from django.http import HttpRequest
from .factories import UserReferrerFactory, UserFactory, CampaignFactory
from referral_module import constants
from referral_module import models
def make_cookie_file(user_referrer):
cookie_file = '{}:{}'.format(user_referrer.campaign.key, user_referrer.key)
return cookie_file
def get_request(user_referrer):
request = HttpRequest()
cookie = make_cookie_file(user_referrer)
request.COOKIES[constants.REFERRER_COOKIE_NAME] = cookie
return request
class UserRegisteredTestCase(TestCase):
def setUp(self):
campaign = CampaignFactory(
bonus_policy={
'click': 1,
'registration': 6,
}
)
self.user_referrer = UserReferrerFactory(
campaign=campaign
)
self.user = UserFactory()
def test_user_registered_with_referrer_user(self):
|
def test_unreferred_user_registered(self):
request = HttpRequest()
models.associate_registered_user_with_referral("", user=self.user, request=request)
# new user is in the database
user_in_db = User.objects.get(username=self.user.username)
self.assertEqual(user_in_db.username, self.user.username)
def test_illegal_referrer_data(self):
real_user_campaign_key = self.user_referrer.campaign.key
# First check with fake campaign key
self.user_referrer.campaign.key = 77777 # random data
request = get_request(user_referrer=self.user_referrer)
self.assertEqual(
models.Referrer.objects.count(),
0
)
models.associate_registered_user_with_referral("", user=self.user, request=request)
self.assertEqual(
models.Referrer.objects.count(),
0
)
# check real campaign key and fake referrer
self.user_referrer.campaign.key = real_user_campaign_key
self.user_referrer.key = '232323' # fake data
request = get_request(user_referrer=self.user_referrer)
models.associate_registered_user_with_referral("", user=self.user, request=request)
self.assertEqual(
models.Referrer.objects.count(),
0
)
| reward_before_new_user = self.user_referrer.reward
request = get_request(user_referrer=self.user_referrer)
models.associate_registered_user_with_referral("", user=self.user, request=request)
# referrer user sign as referrer to the new user
referrer_db = models.Referrer.objects.get(user_referrer=self.user_referrer)
self.assertEqual(referrer_db.registered_user.username, self.user.username)
# check reward update
reward_of_referrer_user = models.UserReferrer.objects.get(key=self.user_referrer.key).reward
reward_after_adding_user = reward_before_new_user + self.user_referrer.campaign.bonus_policy['registration']
self.assertEqual(reward_of_referrer_user, reward_after_adding_user) | identifier_body |
test_user_registered.py | from django.test import TestCase
from django.contrib.auth.models import User
from django.http import HttpRequest
from .factories import UserReferrerFactory, UserFactory, CampaignFactory
from referral_module import constants
from referral_module import models
def make_cookie_file(user_referrer):
cookie_file = '{}:{}'.format(user_referrer.campaign.key, user_referrer.key)
return cookie_file
def get_request(user_referrer):
request = HttpRequest()
cookie = make_cookie_file(user_referrer)
request.COOKIES[constants.REFERRER_COOKIE_NAME] = cookie
return request
class UserRegisteredTestCase(TestCase):
def setUp(self):
campaign = CampaignFactory(
bonus_policy={
'click': 1,
'registration': 6,
}
)
self.user_referrer = UserReferrerFactory(
campaign=campaign
)
self.user = UserFactory() | def test_user_registered_with_referrer_user(self):
reward_before_new_user = self.user_referrer.reward
request = get_request(user_referrer=self.user_referrer)
models.associate_registered_user_with_referral("", user=self.user, request=request)
# referrer user sign as referrer to the new user
referrer_db = models.Referrer.objects.get(user_referrer=self.user_referrer)
self.assertEqual(referrer_db.registered_user.username, self.user.username)
# check reward update
reward_of_referrer_user = models.UserReferrer.objects.get(key=self.user_referrer.key).reward
reward_after_adding_user = reward_before_new_user + self.user_referrer.campaign.bonus_policy['registration']
self.assertEqual(reward_of_referrer_user, reward_after_adding_user)
def test_unreferred_user_registered(self):
request = HttpRequest()
models.associate_registered_user_with_referral("", user=self.user, request=request)
# new user is in the database
user_in_db = User.objects.get(username=self.user.username)
self.assertEqual(user_in_db.username, self.user.username)
def test_illegal_referrer_data(self):
real_user_campaign_key = self.user_referrer.campaign.key
# First check with fake campaign key
self.user_referrer.campaign.key = 77777 # random data
request = get_request(user_referrer=self.user_referrer)
self.assertEqual(
models.Referrer.objects.count(),
0
)
models.associate_registered_user_with_referral("", user=self.user, request=request)
self.assertEqual(
models.Referrer.objects.count(),
0
)
# check real campaign key and fake referrer
self.user_referrer.campaign.key = real_user_campaign_key
self.user_referrer.key = '232323' # fake data
request = get_request(user_referrer=self.user_referrer)
models.associate_registered_user_with_referral("", user=self.user, request=request)
self.assertEqual(
models.Referrer.objects.count(),
0
) | random_line_split |
|
gen_events.py | #!/usr/bin/python
'''
This script is used to generate a set of random-ish events to
simulate log data from a Juniper Netscreen FW. It was built
around using netcat to feed data into Flume for ingestion
into a Hadoop cluster.
Once you have Flume configured you would use the following
command to populate data:
./gen_events.py 2>&1 | nc 127.0.0.1 9999
'''
import random
from netaddr import *
from time import sleep
protocols = ['6', '17']
common_ports = ['20','21','22','23','25','80','109','110','119','143','156','161','389','443']
action_list = ['Deny', 'Accept', 'Drop', 'Reject'];
src_network = IPNetwork('192.168.1.0/24')
dest_network = IPNetwork('172.35.0.0/16')
fo = open("replay_log.txt", "w")
while (1 == 1):
proto_index = random.randint(0,1)
protocol = protocols[proto_index]
src_port_index = random.randint(0,13)
dest_port_index = random.randint(0,13)
src_port = common_ports[src_port_index]
dest_port = common_ports[dest_port_index]
action_index = random.randint(0,3)
action = action_list[action_index]
src_ip_index = random.randint(1,254)
src_ip = src_network[src_ip_index]
dest_ip_index = random.randint(1,65535)
dest_ip = dest_network[dest_ip_index]
event = "192.168.1.3 Netscreen-FW1: NetScreen device_id=Netscreen-FW1 [Root]system-notification-00257(traffic): start_time=\"YYYY-MM-DD HH:MM:SS\" duration=0 policy_id=125 service=syslog proto=%s src zone=Untrust dst zone=Trust action=%s sent=0 rcvd=0 src=%s dst=%s src_port=%s dst_port=%s session_id=0" % (protocol, action, src_ip, dest_ip, src_port, dest_port)
fo.write(event + "\n")
print event | sleep(0.3)
fo.close() | random_line_split |
|
gen_events.py | #!/usr/bin/python
'''
This script is used to generate a set of random-ish events to
simulate log data from a Juniper Netscreen FW. It was built
around using netcat to feed data into Flume for ingestion
into a Hadoop cluster.
Once you have Flume configured you would use the following
command to populate data:
./gen_events.py 2>&1 | nc 127.0.0.1 9999
'''
import random
from netaddr import *
from time import sleep
protocols = ['6', '17']
common_ports = ['20','21','22','23','25','80','109','110','119','143','156','161','389','443']
action_list = ['Deny', 'Accept', 'Drop', 'Reject'];
src_network = IPNetwork('192.168.1.0/24')
dest_network = IPNetwork('172.35.0.0/16')
fo = open("replay_log.txt", "w")
while (1 == 1):
|
fo.close()
| proto_index = random.randint(0,1)
protocol = protocols[proto_index]
src_port_index = random.randint(0,13)
dest_port_index = random.randint(0,13)
src_port = common_ports[src_port_index]
dest_port = common_ports[dest_port_index]
action_index = random.randint(0,3)
action = action_list[action_index]
src_ip_index = random.randint(1,254)
src_ip = src_network[src_ip_index]
dest_ip_index = random.randint(1,65535)
dest_ip = dest_network[dest_ip_index]
event = "192.168.1.3 Netscreen-FW1: NetScreen device_id=Netscreen-FW1 [Root]system-notification-00257(traffic): start_time=\"YYYY-MM-DD HH:MM:SS\" duration=0 policy_id=125 service=syslog proto=%s src zone=Untrust dst zone=Trust action=%s sent=0 rcvd=0 src=%s dst=%s src_port=%s dst_port=%s session_id=0" % (protocol, action, src_ip, dest_ip, src_port, dest_port)
fo.write(event + "\n")
print event
sleep(0.3) | conditional_block |
statement_flow.ts | import {expect} from "chai";
import {Registry} from "../../src/registry";
import {MemoryFile} from "../../src/files/memory_file";
import {LanguageServer} from "../../src";
describe("LSP, statement flow", () => {
it("basic", async () => {
const abap = `
CLASS zcl_foobar DEFINITION PUBLIC CREATE PUBLIC.
PUBLIC SECTION.
METHODS method1. | ENDMETHOD.
METHOD method2.
DATA foo.
IF 2 = 1.
WRITE 'sdf'.
ENDIF.
ENDMETHOD.
ENDCLASS.
`;
const file = new MemoryFile("zcl_foobar.clas.abap", abap);
const reg = new Registry().addFile(file);
await reg.parseAsync();
const dump = new LanguageServer(reg).dumpStatementFlows({uri: file.getFilename()});
expect(dump).to.not.equal(undefined);
});
}); | METHODS method2.
ENDCLASS.
CLASS zcl_foobar IMPLEMENTATION.
METHOD method1.
WRITE 'sdf'. | random_line_split |
construct-translation-ids.service.spec.ts | // Copyright 2020 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// | // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for ConstructTranslationIdsService.
*/
import { TestBed } from '@angular/core/testing';
import { ConstructTranslationIdsService } from
'services/construct-translation-ids.service';
describe('Construct Translation Ids Service', () => {
let ctis: ConstructTranslationIdsService;
beforeEach(() => {
ctis = TestBed.get(ConstructTranslationIdsService);
});
it('should get library id', () => {
expect(ctis.getLibraryId('categories', 'Algorithms'))
.toBe('I18N_LIBRARY_CATEGORIES_ALGORITHMS');
expect(ctis.getLibraryId('', '')).toBe('I18N_LIBRARY__');
});
}); | random_line_split |
|
ModalExportWallets.spec.js | import Vue from 'vue'
import Vuelidate from 'vuelidate'
import { shallowMount } from '@vue/test-utils'
import useI18nGlobally from '../../__utils__/i18n'
import ModalExportWallets from '@/components/Modal/ModalExportWallets'
import StringMixin from '@/mixins/strings'
import WalletMixin from '@/mixins/wallet'
Vue.use(Vuelidate)
const i18n = useI18nGlobally()
describe('ModalExportWallets', () => {
const mountComponent = () => {
const wallets = [
{ address: 'A1', name: null, balance: 0 },
{ address: 'A2', name: '', balance: 1 },
{ address: 'A3', name: 'wallet_a3', balance: 0 },
{ address: 'A4', name: 'wallet_a4', balance: 1 }
]
const ledgerWallets = [
{ address: 'A5', name: null, balance: 0 },
{ address: 'A6', name: 'ledger_a6', balance: 1 }
]
return shallowMount(ModalExportWallets, {
i18n,
mixins: [StringMixin, WalletMixin],
mocks: { | $store: {
getters: {
'delegate/byAddress': jest.fn(),
'wallet/contactsByProfileId': () => [],
'wallet/byProfileId': () => wallets,
'ledger/wallets': () => ledgerWallets
}
}
}
})
}
it('should render modal', () => {
const wrapper = mountComponent()
expect(wrapper.isVueInstance()).toBeTrue()
})
describe('toggleOption', () => {
it('should exclude empty wallets', () => {
const wrapper = mountComponent()
wrapper.vm.toggleOption('excludeEmpty')
const walletsWithBalance = [
{ address: 'A2', name: '', balance: 1 },
{ address: 'A4', name: 'wallet_a4', balance: 1 }
]
expect(wrapper.vm.wallets).toEqual(walletsWithBalance)
})
it('should exclude wallets with no name', () => {
const wrapper = mountComponent()
wrapper.vm.toggleOption('excludeUnnamed')
const walletsWithName = [
{ address: 'A3', name: 'wallet_a3', balance: 0 },
{ address: 'A4', name: 'wallet_a4', balance: 1 }
]
expect(wrapper.vm.wallets).toEqual(walletsWithName)
})
})
}) | session_network: {
knownWallets: {}
}, | random_line_split |
tokenizer.rs | //! A whitespace and comment preserving lexer designed for use in both the compiler frontend
//! and IDEs.
//!
//! The output of the tokenizer is lightweight, and only contains information about the
//! type of a [Token] and where it occurred in the source.
use std::ops::Range;
use itertools::Itertools;
use logos::Lexer;
use logos::Logos;
use secsp_parser::syntax::TokenKind;
use crate::token::Token;
struct Tokenizer<'a> {
lexer: Lexer<TokenKind, &'a str>,
seen_eof: bool,
}
impl<'a> Tokenizer<'a> {
fn new(text: &'a str) -> Self {
Tokenizer {
lexer: TokenKind::lexer(text),
seen_eof: false,
}
} | }
impl<'a> Iterator for Tokenizer<'a> {
type Item = (TokenKind, Range<usize>);
fn next(&mut self) -> Option<Self::Item> {
if self.seen_eof {
return None;
}
let ty = self.lexer.token;
let range = self.lexer.range();
self.lexer.advance();
if ty == TokenKind::Eof {
self.seen_eof = true;
}
Some((ty, range))
}
}
/// Runs the tokenizer on an input string and collects all of the output tokens
/// into a list, continuing past lex errors.
pub fn tokenize<S: AsRef<str>>(str: S) -> Vec<Token> {
let tokenizer = Tokenizer::new(str.as_ref());
let mut tokens: Vec<Token> = vec![];
let mut iter = tokenizer.peekable();
while let Some((token, range)) = iter.next() {
match token {
TokenKind::Illegal | TokenKind::Whitespace | TokenKind::LineComment => {
let range = iter
.peeking_take_while(|(ty, _)| *ty == token)
.map(|(_, range)| range)
.last()
.map_or(range.clone(), |to| range.start..to.end);
tokens.push(Token::new(token, range))
}
_ => tokens.push(Token::new(token, range)),
}
}
tokens
}
#[test]
fn preserves_whitespace() {
let types: Vec<TokenKind> = tokenize("test abc 123")
.into_iter()
.map(|t| t.into())
.collect();
assert_eq!(
vec![
TokenKind::Name,
TokenKind::Whitespace,
TokenKind::Name,
TokenKind::Whitespace,
TokenKind::Integer,
TokenKind::Eof,
],
types
);
} | random_line_split |
|
tokenizer.rs | //! A whitespace and comment preserving lexer designed for use in both the compiler frontend
//! and IDEs.
//!
//! The output of the tokenizer is lightweight, and only contains information about the
//! type of a [Token] and where it occurred in the source.
use std::ops::Range;
use itertools::Itertools;
use logos::Lexer;
use logos::Logos;
use secsp_parser::syntax::TokenKind;
use crate::token::Token;
struct Tokenizer<'a> {
lexer: Lexer<TokenKind, &'a str>,
seen_eof: bool,
}
impl<'a> Tokenizer<'a> {
fn new(text: &'a str) -> Self {
Tokenizer {
lexer: TokenKind::lexer(text),
seen_eof: false,
}
}
}
impl<'a> Iterator for Tokenizer<'a> {
type Item = (TokenKind, Range<usize>);
fn next(&mut self) -> Option<Self::Item> {
if self.seen_eof {
return None;
}
let ty = self.lexer.token;
let range = self.lexer.range();
self.lexer.advance();
if ty == TokenKind::Eof {
self.seen_eof = true;
}
Some((ty, range))
}
}
/// Runs the tokenizer on an input string and collects all of the output tokens
/// into a list, continuing past lex errors.
pub fn tokenize<S: AsRef<str>>(str: S) -> Vec<Token> {
let tokenizer = Tokenizer::new(str.as_ref());
let mut tokens: Vec<Token> = vec![];
let mut iter = tokenizer.peekable();
while let Some((token, range)) = iter.next() {
match token {
TokenKind::Illegal | TokenKind::Whitespace | TokenKind::LineComment => {
let range = iter
.peeking_take_while(|(ty, _)| *ty == token)
.map(|(_, range)| range)
.last()
.map_or(range.clone(), |to| range.start..to.end);
tokens.push(Token::new(token, range))
}
_ => tokens.push(Token::new(token, range)),
}
}
tokens
}
#[test]
fn preserves_whitespace() | {
let types: Vec<TokenKind> = tokenize("test abc 123")
.into_iter()
.map(|t| t.into())
.collect();
assert_eq!(
vec![
TokenKind::Name,
TokenKind::Whitespace,
TokenKind::Name,
TokenKind::Whitespace,
TokenKind::Integer,
TokenKind::Eof,
],
types
);
} | identifier_body |
|
tokenizer.rs | //! A whitespace and comment preserving lexer designed for use in both the compiler frontend
//! and IDEs.
//!
//! The output of the tokenizer is lightweight, and only contains information about the
//! type of a [Token] and where it occurred in the source.
use std::ops::Range;
use itertools::Itertools;
use logos::Lexer;
use logos::Logos;
use secsp_parser::syntax::TokenKind;
use crate::token::Token;
struct | <'a> {
lexer: Lexer<TokenKind, &'a str>,
seen_eof: bool,
}
impl<'a> Tokenizer<'a> {
fn new(text: &'a str) -> Self {
Tokenizer {
lexer: TokenKind::lexer(text),
seen_eof: false,
}
}
}
impl<'a> Iterator for Tokenizer<'a> {
type Item = (TokenKind, Range<usize>);
fn next(&mut self) -> Option<Self::Item> {
if self.seen_eof {
return None;
}
let ty = self.lexer.token;
let range = self.lexer.range();
self.lexer.advance();
if ty == TokenKind::Eof {
self.seen_eof = true;
}
Some((ty, range))
}
}
/// Runs the tokenizer on an input string and collects all of the output tokens
/// into a list, continuing past lex errors.
pub fn tokenize<S: AsRef<str>>(str: S) -> Vec<Token> {
let tokenizer = Tokenizer::new(str.as_ref());
let mut tokens: Vec<Token> = vec![];
let mut iter = tokenizer.peekable();
while let Some((token, range)) = iter.next() {
match token {
TokenKind::Illegal | TokenKind::Whitespace | TokenKind::LineComment => {
let range = iter
.peeking_take_while(|(ty, _)| *ty == token)
.map(|(_, range)| range)
.last()
.map_or(range.clone(), |to| range.start..to.end);
tokens.push(Token::new(token, range))
}
_ => tokens.push(Token::new(token, range)),
}
}
tokens
}
#[test]
fn preserves_whitespace() {
let types: Vec<TokenKind> = tokenize("test abc 123")
.into_iter()
.map(|t| t.into())
.collect();
assert_eq!(
vec![
TokenKind::Name,
TokenKind::Whitespace,
TokenKind::Name,
TokenKind::Whitespace,
TokenKind::Integer,
TokenKind::Eof,
],
types
);
}
| Tokenizer | identifier_name |
frame.py | from collections import deque
from lcdui import common
from lcdui.ui import widget
import array
import time
class Frame(object):
def __init__(self, ui):
self._ui = ui
self._widgets = {}
self._position = {}
self._span = {}
self._screen_buffer = ScreenBuffer(self.rows(), self.cols())
self.onInitialize()
def BuildWidget(self, widget_cls, name=None, row=0, col=0, span=None, **kwargs):
widget_obj = widget_cls(self, **kwargs)
if name is None:
name = widget_obj
self.AddWidget(widget_obj, name, row, col, span)
return widget_obj
def rows(self):
"""Returns the number of rows in the frame."""
return self._ui.rows()
def cols(self):
"""Returns the number of columns in the frame."""
return self._ui.cols()
def onInitialize(self):
pass
def AddWidget(self, widget_obj, name, row=0, col=0, span=None):
"""Adds a widget to the current frame.
Args:
widget_obj: the widget to be added
name: the name of the widget
row: the row position of the widget
col: the column position of the widget
span: the character mask for the widget (or None if no mask)
"""
self._widgets[name] = widget_obj
self._position[name] = (row, col)
self._span[name] = span or max(0, self.cols() - col)
def GetWidget(self, name):
return self._widgets.get(name)
def RemoveWidget(self, name):
"""Removes the widget with the given name."""
del self._widgets[name]
del self._position[name]
del self._span[name]
def Paint(self):
"""Causes a repaint to happen, updating any internal buffers."""
for name, w in self._widgets.iteritems():
outstr = w.Paint()
row, col = self._position[name]
span = self._span[name]
self._screen_buffer.Write(array.array('c', outstr), row, col, span)
return self._screen_buffer
class TextFrame(Frame):
def __init__(self, ui, title='', lines=None):
Frame.__init__(self, ui)
self._title = title
if lines is None:
lines = []
self._lines = lines
self._UpdateText()
def _UpdateText(self):
lineno = 0
if self._title:
title_text = '_' + self._title
lineno = 1
if len(title_text) < (self.cols() - 1):
title_text += '_'*(self.cols() - len(title_text) - 1)
self.BuildWidget(widget.LineWidget, name='line0',
row=0, col=0, contents=title_text)
idx = 0
for lineno in xrange(lineno, self.rows()):
if idx < len(self._lines):
content = self._lines[idx]
else:
content = ''
idx += 1
line_name = 'line%i' % lineno
self.BuildWidget(widget.LineWidget, 'line%i' % lineno,
row=lineno, col=0, contents=content)
def SetTitle(self, title):
self._title = title
self._UpdateText()
def AddLine(self, line):
self._lines.append(str(line))
self._UpdateText()
class MultiFrame(Frame):
def __init__(self, ui):
Frame.__init__(self, ui)
self._inner_frames = deque()
self._display_time = {}
self._last_rotate = None
def AddWidget(self, widget_obj, name, row=0, col=0, span=None):
raise NotImplementedError
def GetWidget(self, name):
raise NotImplementedError
def RemoveWidget(self, name):
raise NotImplementedError
def frames(self):
return self._inner_frames
def AddFrame(self, frame, display_time):
self._inner_frames.append(frame)
self._display_time[frame] = display_time
def RemoveFrame(self, frame):
self._inner_frames.remove(frame)
del self._display_time[frame]
def Paint(self):
if not self._inner_frames:
return ''
now = time.time()
if self._last_rotate:
active_time = now - self._last_rotate
else:
self._last_rotate = now
active_time = 0
curr = self._inner_frames[0]
if len(self._inner_frames) > 1:
max_time = self._display_time[curr]
if active_time > max_time:
self._inner_frames.rotate(-1)
self._last_rotate = now
return curr.Paint()
class MenuFrame(Frame):
def onInitialize(self):
self._show_back = False
self._items = []
self._cursor_pos = 0
self._window_pos = 0
self._window_size = self.rows() - 1
self._title_widget = self.BuildWidget(widget.LineWidget, row=0, col=0)
self.setTitle('')
self._item_widgets = []
for i in xrange(self._window_size):
w = self.BuildWidget(widget.LineWidget, row=i+1, col=0)
self._item_widgets.append(w)
self._rebuildMenu()
def showBack(self, enable):
self._show_back = enable
self._rebuildMenu() | def addItem(self, key, value):
self._items.append((key, value))
self._rebuildMenu()
def scrollUp(self):
if self._cursor_pos == 0:
return
self._cursor_pos -= 1
self._updateWindowPos()
self._rebuildMenu()
def scrollDown(self):
if (self._cursor_pos + 1) == len(self._items):
return
self._cursor_pos += 1
self._updateWindowPos()
self._rebuildMenu()
def _rebuildMenu(self):
items = self._items[self._window_pos:self._window_pos+self._window_size]
num_blank = self._window_size - len(items)
symbol_up = self._ui.GetSymbol(common.SYMBOL.MENU_LIST_UP)
symbol_down = self._ui.GetSymbol(common.SYMBOL.MENU_LIST_DOWN)
symbol_cursor = self._ui.GetSymbol(common.SYMBOL.MENU_CURSOR)
for item_pos in xrange(len(items)):
item_id, item_value = items[item_pos]
w = self._item_widgets[item_pos]
w.set_contents(item_value)
for blank_pos in xrange(len(items), self._window_size):
w = self._item_widgets[blank_pos]
w.set_contents('')
# draw cursor
for i in xrange(len(self._item_widgets)):
w = self._item_widgets[i]
if i == (self._cursor_pos % self._window_size):
w.set_prefix(symbol_cursor + '|')
else:
w.set_prefix(' |')
w.set_postfix('| ')
if self._window_pos > 0:
self._item_widgets[0].set_postfix('|' + symbol_up)
if (self._window_pos + self._window_size) < len(self._items):
self._item_widgets[-1].set_postfix('|' + symbol_down)
def _updateWindowPos(self):
self._window_pos = self._cursor_pos - (self._cursor_pos % self._window_size)
def setTitle(self, title):
prefix = ''
symbol_back = self._ui.GetSymbol(common.SYMBOL.FRAME_BACK)
if self._show_back:
postfix = '_' + symbol_back + '_'
else:
postfix = ''
avail = self.cols()
title_str = title
if len(title_str) < avail:
title_str += '_' * (avail - len(title_str))
self._title_widget.set_contents(title_str)
self._title_widget.set_prefix(prefix)
self._title_widget.set_postfix(postfix)
def onLoad(self, lcd):
pass
class ScreenBuffer:
def __init__(self, rows, cols):
self._rows = rows
self._cols = cols
self._array = array.array('c', [' '] * (rows * cols))
def __eq__(self, other):
if isinstance(other, ScreenMatrix):
return self._array == other._array
return False
def array(self):
return self._array
def _AllocNewArray(self):
return array.array('c', [' '] * (self._rows * self._cols))
def _GetOffset(self, row, col):
return row*self._cols + col
def Clear(self):
self._array = self._AllocNewArray()
def Write(self, data, row, col, span):
""" replace data at row, col in this matrix """
assert row in range(self._rows)
assert col in range(self._cols)
start = self._GetOffset(row, col)
datalen = min(len(data), span)
end = start + datalen
self._array[start:end] = data[:datalen]
def __str__(self):
return self._array.tostring() | random_line_split |
|
frame.py | from collections import deque
from lcdui import common
from lcdui.ui import widget
import array
import time
class Frame(object):
def __init__(self, ui):
self._ui = ui
self._widgets = {}
self._position = {}
self._span = {}
self._screen_buffer = ScreenBuffer(self.rows(), self.cols())
self.onInitialize()
def BuildWidget(self, widget_cls, name=None, row=0, col=0, span=None, **kwargs):
widget_obj = widget_cls(self, **kwargs)
if name is None:
name = widget_obj
self.AddWidget(widget_obj, name, row, col, span)
return widget_obj
def rows(self):
"""Returns the number of rows in the frame."""
return self._ui.rows()
def cols(self):
"""Returns the number of columns in the frame."""
return self._ui.cols()
def onInitialize(self):
pass
def AddWidget(self, widget_obj, name, row=0, col=0, span=None):
"""Adds a widget to the current frame.
Args:
widget_obj: the widget to be added
name: the name of the widget
row: the row position of the widget
col: the column position of the widget
span: the character mask for the widget (or None if no mask)
"""
self._widgets[name] = widget_obj
self._position[name] = (row, col)
self._span[name] = span or max(0, self.cols() - col)
def GetWidget(self, name):
return self._widgets.get(name)
def RemoveWidget(self, name):
"""Removes the widget with the given name."""
del self._widgets[name]
del self._position[name]
del self._span[name]
def Paint(self):
"""Causes a repaint to happen, updating any internal buffers."""
for name, w in self._widgets.iteritems():
outstr = w.Paint()
row, col = self._position[name]
span = self._span[name]
self._screen_buffer.Write(array.array('c', outstr), row, col, span)
return self._screen_buffer
class TextFrame(Frame):
def __init__(self, ui, title='', lines=None):
Frame.__init__(self, ui)
self._title = title
if lines is None:
lines = []
self._lines = lines
self._UpdateText()
def _UpdateText(self):
lineno = 0
if self._title:
title_text = '_' + self._title
lineno = 1
if len(title_text) < (self.cols() - 1):
title_text += '_'*(self.cols() - len(title_text) - 1)
self.BuildWidget(widget.LineWidget, name='line0',
row=0, col=0, contents=title_text)
idx = 0
for lineno in xrange(lineno, self.rows()):
if idx < len(self._lines):
content = self._lines[idx]
else:
content = ''
idx += 1
line_name = 'line%i' % lineno
self.BuildWidget(widget.LineWidget, 'line%i' % lineno,
row=lineno, col=0, contents=content)
def SetTitle(self, title):
self._title = title
self._UpdateText()
def AddLine(self, line):
self._lines.append(str(line))
self._UpdateText()
class | (Frame):
def __init__(self, ui):
Frame.__init__(self, ui)
self._inner_frames = deque()
self._display_time = {}
self._last_rotate = None
def AddWidget(self, widget_obj, name, row=0, col=0, span=None):
raise NotImplementedError
def GetWidget(self, name):
raise NotImplementedError
def RemoveWidget(self, name):
raise NotImplementedError
def frames(self):
return self._inner_frames
def AddFrame(self, frame, display_time):
self._inner_frames.append(frame)
self._display_time[frame] = display_time
def RemoveFrame(self, frame):
self._inner_frames.remove(frame)
del self._display_time[frame]
def Paint(self):
if not self._inner_frames:
return ''
now = time.time()
if self._last_rotate:
active_time = now - self._last_rotate
else:
self._last_rotate = now
active_time = 0
curr = self._inner_frames[0]
if len(self._inner_frames) > 1:
max_time = self._display_time[curr]
if active_time > max_time:
self._inner_frames.rotate(-1)
self._last_rotate = now
return curr.Paint()
class MenuFrame(Frame):
def onInitialize(self):
self._show_back = False
self._items = []
self._cursor_pos = 0
self._window_pos = 0
self._window_size = self.rows() - 1
self._title_widget = self.BuildWidget(widget.LineWidget, row=0, col=0)
self.setTitle('')
self._item_widgets = []
for i in xrange(self._window_size):
w = self.BuildWidget(widget.LineWidget, row=i+1, col=0)
self._item_widgets.append(w)
self._rebuildMenu()
def showBack(self, enable):
self._show_back = enable
self._rebuildMenu()
def addItem(self, key, value):
self._items.append((key, value))
self._rebuildMenu()
def scrollUp(self):
if self._cursor_pos == 0:
return
self._cursor_pos -= 1
self._updateWindowPos()
self._rebuildMenu()
def scrollDown(self):
if (self._cursor_pos + 1) == len(self._items):
return
self._cursor_pos += 1
self._updateWindowPos()
self._rebuildMenu()
def _rebuildMenu(self):
items = self._items[self._window_pos:self._window_pos+self._window_size]
num_blank = self._window_size - len(items)
symbol_up = self._ui.GetSymbol(common.SYMBOL.MENU_LIST_UP)
symbol_down = self._ui.GetSymbol(common.SYMBOL.MENU_LIST_DOWN)
symbol_cursor = self._ui.GetSymbol(common.SYMBOL.MENU_CURSOR)
for item_pos in xrange(len(items)):
item_id, item_value = items[item_pos]
w = self._item_widgets[item_pos]
w.set_contents(item_value)
for blank_pos in xrange(len(items), self._window_size):
w = self._item_widgets[blank_pos]
w.set_contents('')
# draw cursor
for i in xrange(len(self._item_widgets)):
w = self._item_widgets[i]
if i == (self._cursor_pos % self._window_size):
w.set_prefix(symbol_cursor + '|')
else:
w.set_prefix(' |')
w.set_postfix('| ')
if self._window_pos > 0:
self._item_widgets[0].set_postfix('|' + symbol_up)
if (self._window_pos + self._window_size) < len(self._items):
self._item_widgets[-1].set_postfix('|' + symbol_down)
def _updateWindowPos(self):
self._window_pos = self._cursor_pos - (self._cursor_pos % self._window_size)
def setTitle(self, title):
prefix = ''
symbol_back = self._ui.GetSymbol(common.SYMBOL.FRAME_BACK)
if self._show_back:
postfix = '_' + symbol_back + '_'
else:
postfix = ''
avail = self.cols()
title_str = title
if len(title_str) < avail:
title_str += '_' * (avail - len(title_str))
self._title_widget.set_contents(title_str)
self._title_widget.set_prefix(prefix)
self._title_widget.set_postfix(postfix)
def onLoad(self, lcd):
pass
class ScreenBuffer:
def __init__(self, rows, cols):
self._rows = rows
self._cols = cols
self._array = array.array('c', [' '] * (rows * cols))
def __eq__(self, other):
if isinstance(other, ScreenMatrix):
return self._array == other._array
return False
def array(self):
return self._array
def _AllocNewArray(self):
return array.array('c', [' '] * (self._rows * self._cols))
def _GetOffset(self, row, col):
return row*self._cols + col
def Clear(self):
self._array = self._AllocNewArray()
def Write(self, data, row, col, span):
""" replace data at row, col in this matrix """
assert row in range(self._rows)
assert col in range(self._cols)
start = self._GetOffset(row, col)
datalen = min(len(data), span)
end = start + datalen
self._array[start:end] = data[:datalen]
def __str__(self):
return self._array.tostring()
| MultiFrame | identifier_name |
frame.py | from collections import deque
from lcdui import common
from lcdui.ui import widget
import array
import time
class Frame(object):
def __init__(self, ui):
self._ui = ui
self._widgets = {}
self._position = {}
self._span = {}
self._screen_buffer = ScreenBuffer(self.rows(), self.cols())
self.onInitialize()
def BuildWidget(self, widget_cls, name=None, row=0, col=0, span=None, **kwargs):
widget_obj = widget_cls(self, **kwargs)
if name is None:
name = widget_obj
self.AddWidget(widget_obj, name, row, col, span)
return widget_obj
def rows(self):
"""Returns the number of rows in the frame."""
return self._ui.rows()
def cols(self):
"""Returns the number of columns in the frame."""
return self._ui.cols()
def onInitialize(self):
pass
def AddWidget(self, widget_obj, name, row=0, col=0, span=None):
"""Adds a widget to the current frame.
Args:
widget_obj: the widget to be added
name: the name of the widget
row: the row position of the widget
col: the column position of the widget
span: the character mask for the widget (or None if no mask)
"""
self._widgets[name] = widget_obj
self._position[name] = (row, col)
self._span[name] = span or max(0, self.cols() - col)
def GetWidget(self, name):
return self._widgets.get(name)
def RemoveWidget(self, name):
"""Removes the widget with the given name."""
del self._widgets[name]
del self._position[name]
del self._span[name]
def Paint(self):
"""Causes a repaint to happen, updating any internal buffers."""
for name, w in self._widgets.iteritems():
outstr = w.Paint()
row, col = self._position[name]
span = self._span[name]
self._screen_buffer.Write(array.array('c', outstr), row, col, span)
return self._screen_buffer
class TextFrame(Frame):
def __init__(self, ui, title='', lines=None):
Frame.__init__(self, ui)
self._title = title
if lines is None:
lines = []
self._lines = lines
self._UpdateText()
def _UpdateText(self):
lineno = 0
if self._title:
title_text = '_' + self._title
lineno = 1
if len(title_text) < (self.cols() - 1):
title_text += '_'*(self.cols() - len(title_text) - 1)
self.BuildWidget(widget.LineWidget, name='line0',
row=0, col=0, contents=title_text)
idx = 0
for lineno in xrange(lineno, self.rows()):
if idx < len(self._lines):
content = self._lines[idx]
else:
content = ''
idx += 1
line_name = 'line%i' % lineno
self.BuildWidget(widget.LineWidget, 'line%i' % lineno,
row=lineno, col=0, contents=content)
def SetTitle(self, title):
self._title = title
self._UpdateText()
def AddLine(self, line):
self._lines.append(str(line))
self._UpdateText()
class MultiFrame(Frame):
def __init__(self, ui):
Frame.__init__(self, ui)
self._inner_frames = deque()
self._display_time = {}
self._last_rotate = None
def AddWidget(self, widget_obj, name, row=0, col=0, span=None):
raise NotImplementedError
def GetWidget(self, name):
raise NotImplementedError
def RemoveWidget(self, name):
raise NotImplementedError
def frames(self):
return self._inner_frames
def AddFrame(self, frame, display_time):
self._inner_frames.append(frame)
self._display_time[frame] = display_time
def RemoveFrame(self, frame):
self._inner_frames.remove(frame)
del self._display_time[frame]
def Paint(self):
if not self._inner_frames:
return ''
now = time.time()
if self._last_rotate:
active_time = now - self._last_rotate
else:
self._last_rotate = now
active_time = 0
curr = self._inner_frames[0]
if len(self._inner_frames) > 1:
max_time = self._display_time[curr]
if active_time > max_time:
self._inner_frames.rotate(-1)
self._last_rotate = now
return curr.Paint()
class MenuFrame(Frame):
def onInitialize(self):
self._show_back = False
self._items = []
self._cursor_pos = 0
self._window_pos = 0
self._window_size = self.rows() - 1
self._title_widget = self.BuildWidget(widget.LineWidget, row=0, col=0)
self.setTitle('')
self._item_widgets = []
for i in xrange(self._window_size):
w = self.BuildWidget(widget.LineWidget, row=i+1, col=0)
self._item_widgets.append(w)
self._rebuildMenu()
def showBack(self, enable):
self._show_back = enable
self._rebuildMenu()
def addItem(self, key, value):
self._items.append((key, value))
self._rebuildMenu()
def scrollUp(self):
if self._cursor_pos == 0:
return
self._cursor_pos -= 1
self._updateWindowPos()
self._rebuildMenu()
def scrollDown(self):
if (self._cursor_pos + 1) == len(self._items):
return
self._cursor_pos += 1
self._updateWindowPos()
self._rebuildMenu()
def _rebuildMenu(self):
items = self._items[self._window_pos:self._window_pos+self._window_size]
num_blank = self._window_size - len(items)
symbol_up = self._ui.GetSymbol(common.SYMBOL.MENU_LIST_UP)
symbol_down = self._ui.GetSymbol(common.SYMBOL.MENU_LIST_DOWN)
symbol_cursor = self._ui.GetSymbol(common.SYMBOL.MENU_CURSOR)
for item_pos in xrange(len(items)):
item_id, item_value = items[item_pos]
w = self._item_widgets[item_pos]
w.set_contents(item_value)
for blank_pos in xrange(len(items), self._window_size):
w = self._item_widgets[blank_pos]
w.set_contents('')
# draw cursor
for i in xrange(len(self._item_widgets)):
w = self._item_widgets[i]
if i == (self._cursor_pos % self._window_size):
w.set_prefix(symbol_cursor + '|')
else:
w.set_prefix(' |')
w.set_postfix('| ')
if self._window_pos > 0:
|
if (self._window_pos + self._window_size) < len(self._items):
self._item_widgets[-1].set_postfix('|' + symbol_down)
def _updateWindowPos(self):
self._window_pos = self._cursor_pos - (self._cursor_pos % self._window_size)
def setTitle(self, title):
prefix = ''
symbol_back = self._ui.GetSymbol(common.SYMBOL.FRAME_BACK)
if self._show_back:
postfix = '_' + symbol_back + '_'
else:
postfix = ''
avail = self.cols()
title_str = title
if len(title_str) < avail:
title_str += '_' * (avail - len(title_str))
self._title_widget.set_contents(title_str)
self._title_widget.set_prefix(prefix)
self._title_widget.set_postfix(postfix)
def onLoad(self, lcd):
pass
class ScreenBuffer:
def __init__(self, rows, cols):
self._rows = rows
self._cols = cols
self._array = array.array('c', [' '] * (rows * cols))
def __eq__(self, other):
if isinstance(other, ScreenMatrix):
return self._array == other._array
return False
def array(self):
return self._array
def _AllocNewArray(self):
return array.array('c', [' '] * (self._rows * self._cols))
def _GetOffset(self, row, col):
return row*self._cols + col
def Clear(self):
self._array = self._AllocNewArray()
def Write(self, data, row, col, span):
""" replace data at row, col in this matrix """
assert row in range(self._rows)
assert col in range(self._cols)
start = self._GetOffset(row, col)
datalen = min(len(data), span)
end = start + datalen
self._array[start:end] = data[:datalen]
def __str__(self):
return self._array.tostring()
| self._item_widgets[0].set_postfix('|' + symbol_up) | conditional_block |
frame.py | from collections import deque
from lcdui import common
from lcdui.ui import widget
import array
import time
class Frame(object):
def __init__(self, ui):
self._ui = ui
self._widgets = {}
self._position = {}
self._span = {}
self._screen_buffer = ScreenBuffer(self.rows(), self.cols())
self.onInitialize()
def BuildWidget(self, widget_cls, name=None, row=0, col=0, span=None, **kwargs):
widget_obj = widget_cls(self, **kwargs)
if name is None:
name = widget_obj
self.AddWidget(widget_obj, name, row, col, span)
return widget_obj
def rows(self):
"""Returns the number of rows in the frame."""
return self._ui.rows()
def cols(self):
"""Returns the number of columns in the frame."""
return self._ui.cols()
def onInitialize(self):
pass
def AddWidget(self, widget_obj, name, row=0, col=0, span=None):
"""Adds a widget to the current frame.
Args:
widget_obj: the widget to be added
name: the name of the widget
row: the row position of the widget
col: the column position of the widget
span: the character mask for the widget (or None if no mask)
"""
self._widgets[name] = widget_obj
self._position[name] = (row, col)
self._span[name] = span or max(0, self.cols() - col)
def GetWidget(self, name):
return self._widgets.get(name)
def RemoveWidget(self, name):
"""Removes the widget with the given name."""
del self._widgets[name]
del self._position[name]
del self._span[name]
def Paint(self):
"""Causes a repaint to happen, updating any internal buffers."""
for name, w in self._widgets.iteritems():
outstr = w.Paint()
row, col = self._position[name]
span = self._span[name]
self._screen_buffer.Write(array.array('c', outstr), row, col, span)
return self._screen_buffer
class TextFrame(Frame):
def __init__(self, ui, title='', lines=None):
Frame.__init__(self, ui)
self._title = title
if lines is None:
lines = []
self._lines = lines
self._UpdateText()
def _UpdateText(self):
lineno = 0
if self._title:
title_text = '_' + self._title
lineno = 1
if len(title_text) < (self.cols() - 1):
title_text += '_'*(self.cols() - len(title_text) - 1)
self.BuildWidget(widget.LineWidget, name='line0',
row=0, col=0, contents=title_text)
idx = 0
for lineno in xrange(lineno, self.rows()):
if idx < len(self._lines):
content = self._lines[idx]
else:
content = ''
idx += 1
line_name = 'line%i' % lineno
self.BuildWidget(widget.LineWidget, 'line%i' % lineno,
row=lineno, col=0, contents=content)
def SetTitle(self, title):
self._title = title
self._UpdateText()
def AddLine(self, line):
self._lines.append(str(line))
self._UpdateText()
class MultiFrame(Frame):
def __init__(self, ui):
Frame.__init__(self, ui)
self._inner_frames = deque()
self._display_time = {}
self._last_rotate = None
def AddWidget(self, widget_obj, name, row=0, col=0, span=None):
raise NotImplementedError
def GetWidget(self, name):
raise NotImplementedError
def RemoveWidget(self, name):
raise NotImplementedError
def frames(self):
return self._inner_frames
def AddFrame(self, frame, display_time):
self._inner_frames.append(frame)
self._display_time[frame] = display_time
def RemoveFrame(self, frame):
self._inner_frames.remove(frame)
del self._display_time[frame]
def Paint(self):
if not self._inner_frames:
return ''
now = time.time()
if self._last_rotate:
active_time = now - self._last_rotate
else:
self._last_rotate = now
active_time = 0
curr = self._inner_frames[0]
if len(self._inner_frames) > 1:
max_time = self._display_time[curr]
if active_time > max_time:
self._inner_frames.rotate(-1)
self._last_rotate = now
return curr.Paint()
class MenuFrame(Frame):
def onInitialize(self):
self._show_back = False
self._items = []
self._cursor_pos = 0
self._window_pos = 0
self._window_size = self.rows() - 1
self._title_widget = self.BuildWidget(widget.LineWidget, row=0, col=0)
self.setTitle('')
self._item_widgets = []
for i in xrange(self._window_size):
w = self.BuildWidget(widget.LineWidget, row=i+1, col=0)
self._item_widgets.append(w)
self._rebuildMenu()
def showBack(self, enable):
self._show_back = enable
self._rebuildMenu()
def addItem(self, key, value):
self._items.append((key, value))
self._rebuildMenu()
def scrollUp(self):
if self._cursor_pos == 0:
return
self._cursor_pos -= 1
self._updateWindowPos()
self._rebuildMenu()
def scrollDown(self):
if (self._cursor_pos + 1) == len(self._items):
return
self._cursor_pos += 1
self._updateWindowPos()
self._rebuildMenu()
def _rebuildMenu(self):
| else:
w.set_prefix(' |')
w.set_postfix('| ')
if self._window_pos > 0:
self._item_widgets[0].set_postfix('|' + symbol_up)
if (self._window_pos + self._window_size) < len(self._items):
self._item_widgets[-1].set_postfix('|' + symbol_down)
def _updateWindowPos(self):
self._window_pos = self._cursor_pos - (self._cursor_pos % self._window_size)
def setTitle(self, title):
prefix = ''
symbol_back = self._ui.GetSymbol(common.SYMBOL.FRAME_BACK)
if self._show_back:
postfix = '_' + symbol_back + '_'
else:
postfix = ''
avail = self.cols()
title_str = title
if len(title_str) < avail:
title_str += '_' * (avail - len(title_str))
self._title_widget.set_contents(title_str)
self._title_widget.set_prefix(prefix)
self._title_widget.set_postfix(postfix)
def onLoad(self, lcd):
pass
class ScreenBuffer:
def __init__(self, rows, cols):
self._rows = rows
self._cols = cols
self._array = array.array('c', [' '] * (rows * cols))
def __eq__(self, other):
if isinstance(other, ScreenMatrix):
return self._array == other._array
return False
def array(self):
return self._array
def _AllocNewArray(self):
return array.array('c', [' '] * (self._rows * self._cols))
def _GetOffset(self, row, col):
return row*self._cols + col
def Clear(self):
self._array = self._AllocNewArray()
def Write(self, data, row, col, span):
""" replace data at row, col in this matrix """
assert row in range(self._rows)
assert col in range(self._cols)
start = self._GetOffset(row, col)
datalen = min(len(data), span)
end = start + datalen
self._array[start:end] = data[:datalen]
def __str__(self):
return self._array.tostring()
| items = self._items[self._window_pos:self._window_pos+self._window_size]
num_blank = self._window_size - len(items)
symbol_up = self._ui.GetSymbol(common.SYMBOL.MENU_LIST_UP)
symbol_down = self._ui.GetSymbol(common.SYMBOL.MENU_LIST_DOWN)
symbol_cursor = self._ui.GetSymbol(common.SYMBOL.MENU_CURSOR)
for item_pos in xrange(len(items)):
item_id, item_value = items[item_pos]
w = self._item_widgets[item_pos]
w.set_contents(item_value)
for blank_pos in xrange(len(items), self._window_size):
w = self._item_widgets[blank_pos]
w.set_contents('')
# draw cursor
for i in xrange(len(self._item_widgets)):
w = self._item_widgets[i]
if i == (self._cursor_pos % self._window_size):
w.set_prefix(symbol_cursor + '|') | identifier_body |
main.rs | extern crate rustbox;
extern crate memmap;
extern crate clap;
use std::error::Error;
// use std::default::Default;
// use std::cmp;
// use std::char;
use std::env;
use memmap::{Mmap, Protection};
use rustbox::{Color, RustBox, Key, Event};
use clap::{App, Arg};
fn longest_prefix<'a>(a: &'a str, b: &'a str) -> usize {
a.chars().zip(b.chars()).take_while(|&(c1, c2)| c1 == c2).count()
}
fn header(width: usize) -> String {
format!("{:1$}0 1 2 3 4 5 6 7 8 9 A B C D E F", "", width + 3)
}
fn string_repeat(s: &str, n: usize) -> String {
std::iter::repeat(s).take(n).collect::<String>()
}
fn offset(offset: usize, width: usize, trimming_offset: Option<String>) -> String {
match trimming_offset {
None => { format!("{:01$x}: ", offset, width) }
Some(trimming_string) => {
let new_fmt = format!("{:01$x}: ", offset, width);
let n_chars_to_remove = longest_prefix(&new_fmt, &trimming_string);
let padding = string_repeat(" ", n_chars_to_remove);
padding + &new_fmt[n_chars_to_remove..]
}
}
}
fn offset_width(num_bytes: usize) -> usize {
// +1 byte for the final EOF symbol
// +1 for the base-16 computation
(((num_bytes + 1) as f64).log(16.0) as usize) + 1
}
fn try_open_file(file_path: &str) -> Result<(Mmap, bool), std::io::Error> {
let mut is_read_only = false;
let mut file_mmap_try = Mmap::open_path(file_path, Protection::ReadWrite);
if file_mmap_try.is_err() {
file_mmap_try = Mmap::open_path(file_path, Protection::Read);
is_read_only = true;
}
file_mmap_try.map(|x| (x, is_read_only))
}
fn standard_output(file_path: &str) {
let file_mmap = Mmap::open_path(file_path, Protection::Read).unwrap();
let bytes: &[u8] = unsafe { file_mmap.as_slice() };
let offset_width = offset_width(bytes.len());
println!("{}\n", header(offset_width));
let mut prev_offset: String = offset(0, offset_width, None);
let mut should_trim = true;
print!("{}", prev_offset);
for (idx, chunk) in bytes.chunks(16).enumerate() {
if chunk.iter().all(|&x| x == 0) {
should_trim = false;
continue;
}
for b in chunk {
match *b {
// ASCII printable
0x20u8...0x7e => { print!(".{} ", *b as char) }
0x00 => { print!(" ") }
0xFF => { print!("## ") }
_ => { print!("{:02X} ", b) }
}
}
let trimming_offset = if should_trim { Some(prev_offset.clone()) } else { None };
let new_offset = offset((idx + 1) * 16, offset_width, trimming_offset); // TODO: idx + 1 is wrong
print!("\n{}", new_offset);
prev_offset = new_offset;
should_trim = true;
}
if should_trim { // that means just skipped a bunch of zeroes at the end
}
println!("Ω⸫");
}
struct EditorState {
open_file: Option<Mmap>,
read_only: bool,
}
fn rustbox_output(file_path: &str) {
let rustbox = match RustBox::init(Default::default()) {
Result::Ok(v) => v,
Result::Err(e) => panic!("{}", e),
};
let mut state = EditorState { open_file: None, read_only: false };
// rustbox.print(1, 1, rustbox::RB_BOLD, Color::White, Color::Black, "Hello, world!");
// rustbox.print(1, 3, rustbox::RB_BOLD, Color::White, Color::Black,
// "Press 'q' to quit.");
// let mut file_mmap_try = try_open_file(file_path);
// let offset_width = offset_width(bytes.len());
loop {
rustbox.print(rustbox.width() - 10, 0, rustbox::RB_BOLD, Color::White, Color::Black, "HexRS");
rustbox.present();
match rustbox.poll_event(false).unwrap() {
Event::KeyEvent(key) => {
match key {
Key::Char('q') => { return; }
Key::Esc => { return; }
_ => { }
}
}
_ => { }
}
}
}
fn main() {
let matches = App::new("HexRS").version("0.1").args_from_usage( | "-i, --interactive 'Use the interactive version instead of outputting to stdout'
[INPUT] 'Specifies the input file to use'").get_matches();
if let Some(file_path) = matches.value_of("INPUT") {
if matches.is_present("interactive") {
rustbox_output(&file_path);
} else {
standard_output(&file_path);
}
}
} | random_line_split |
|
main.rs | extern crate rustbox;
extern crate memmap;
extern crate clap;
use std::error::Error;
// use std::default::Default;
// use std::cmp;
// use std::char;
use std::env;
use memmap::{Mmap, Protection};
use rustbox::{Color, RustBox, Key, Event};
use clap::{App, Arg};
fn longest_prefix<'a>(a: &'a str, b: &'a str) -> usize {
a.chars().zip(b.chars()).take_while(|&(c1, c2)| c1 == c2).count()
}
fn header(width: usize) -> String |
fn string_repeat(s: &str, n: usize) -> String {
std::iter::repeat(s).take(n).collect::<String>()
}
fn offset(offset: usize, width: usize, trimming_offset: Option<String>) -> String {
match trimming_offset {
None => { format!("{:01$x}: ", offset, width) }
Some(trimming_string) => {
let new_fmt = format!("{:01$x}: ", offset, width);
let n_chars_to_remove = longest_prefix(&new_fmt, &trimming_string);
let padding = string_repeat(" ", n_chars_to_remove);
padding + &new_fmt[n_chars_to_remove..]
}
}
}
fn offset_width(num_bytes: usize) -> usize {
// +1 byte for the final EOF symbol
// +1 for the base-16 computation
(((num_bytes + 1) as f64).log(16.0) as usize) + 1
}
fn try_open_file(file_path: &str) -> Result<(Mmap, bool), std::io::Error> {
let mut is_read_only = false;
let mut file_mmap_try = Mmap::open_path(file_path, Protection::ReadWrite);
if file_mmap_try.is_err() {
file_mmap_try = Mmap::open_path(file_path, Protection::Read);
is_read_only = true;
}
file_mmap_try.map(|x| (x, is_read_only))
}
fn standard_output(file_path: &str) {
let file_mmap = Mmap::open_path(file_path, Protection::Read).unwrap();
let bytes: &[u8] = unsafe { file_mmap.as_slice() };
let offset_width = offset_width(bytes.len());
println!("{}\n", header(offset_width));
let mut prev_offset: String = offset(0, offset_width, None);
let mut should_trim = true;
print!("{}", prev_offset);
for (idx, chunk) in bytes.chunks(16).enumerate() {
if chunk.iter().all(|&x| x == 0) {
should_trim = false;
continue;
}
for b in chunk {
match *b {
// ASCII printable
0x20u8...0x7e => { print!(".{} ", *b as char) }
0x00 => { print!(" ") }
0xFF => { print!("## ") }
_ => { print!("{:02X} ", b) }
}
}
let trimming_offset = if should_trim { Some(prev_offset.clone()) } else { None };
let new_offset = offset((idx + 1) * 16, offset_width, trimming_offset); // TODO: idx + 1 is wrong
print!("\n{}", new_offset);
prev_offset = new_offset;
should_trim = true;
}
if should_trim { // that means just skipped a bunch of zeroes at the end
}
println!("Ω⸫");
}
struct EditorState {
open_file: Option<Mmap>,
read_only: bool,
}
fn rustbox_output(file_path: &str) {
let rustbox = match RustBox::init(Default::default()) {
Result::Ok(v) => v,
Result::Err(e) => panic!("{}", e),
};
let mut state = EditorState { open_file: None, read_only: false };
// rustbox.print(1, 1, rustbox::RB_BOLD, Color::White, Color::Black, "Hello, world!");
// rustbox.print(1, 3, rustbox::RB_BOLD, Color::White, Color::Black,
// "Press 'q' to quit.");
// let mut file_mmap_try = try_open_file(file_path);
// let offset_width = offset_width(bytes.len());
loop {
rustbox.print(rustbox.width() - 10, 0, rustbox::RB_BOLD, Color::White, Color::Black, "HexRS");
rustbox.present();
match rustbox.poll_event(false).unwrap() {
Event::KeyEvent(key) => {
match key {
Key::Char('q') => { return; }
Key::Esc => { return; }
_ => { }
}
}
_ => { }
}
}
}
fn main() {
let matches = App::new("HexRS").version("0.1").args_from_usage(
"-i, --interactive 'Use the interactive version instead of outputting to stdout'
[INPUT] 'Specifies the input file to use'").get_matches();
if let Some(file_path) = matches.value_of("INPUT") {
if matches.is_present("interactive") {
rustbox_output(&file_path);
} else {
standard_output(&file_path);
}
}
}
| {
format!("{:1$}0 1 2 3 4 5 6 7 8 9 A B C D E F", "", width + 3)
} | identifier_body |
main.rs | extern crate rustbox;
extern crate memmap;
extern crate clap;
use std::error::Error;
// use std::default::Default;
// use std::cmp;
// use std::char;
use std::env;
use memmap::{Mmap, Protection};
use rustbox::{Color, RustBox, Key, Event};
use clap::{App, Arg};
fn longest_prefix<'a>(a: &'a str, b: &'a str) -> usize {
a.chars().zip(b.chars()).take_while(|&(c1, c2)| c1 == c2).count()
}
fn header(width: usize) -> String {
format!("{:1$}0 1 2 3 4 5 6 7 8 9 A B C D E F", "", width + 3)
}
fn string_repeat(s: &str, n: usize) -> String {
std::iter::repeat(s).take(n).collect::<String>()
}
fn offset(offset: usize, width: usize, trimming_offset: Option<String>) -> String {
match trimming_offset {
None => { format!("{:01$x}: ", offset, width) }
Some(trimming_string) => {
let new_fmt = format!("{:01$x}: ", offset, width);
let n_chars_to_remove = longest_prefix(&new_fmt, &trimming_string);
let padding = string_repeat(" ", n_chars_to_remove);
padding + &new_fmt[n_chars_to_remove..]
}
}
}
fn offset_width(num_bytes: usize) -> usize {
// +1 byte for the final EOF symbol
// +1 for the base-16 computation
(((num_bytes + 1) as f64).log(16.0) as usize) + 1
}
fn try_open_file(file_path: &str) -> Result<(Mmap, bool), std::io::Error> {
let mut is_read_only = false;
let mut file_mmap_try = Mmap::open_path(file_path, Protection::ReadWrite);
if file_mmap_try.is_err() {
file_mmap_try = Mmap::open_path(file_path, Protection::Read);
is_read_only = true;
}
file_mmap_try.map(|x| (x, is_read_only))
}
fn standard_output(file_path: &str) {
let file_mmap = Mmap::open_path(file_path, Protection::Read).unwrap();
let bytes: &[u8] = unsafe { file_mmap.as_slice() };
let offset_width = offset_width(bytes.len());
println!("{}\n", header(offset_width));
let mut prev_offset: String = offset(0, offset_width, None);
let mut should_trim = true;
print!("{}", prev_offset);
for (idx, chunk) in bytes.chunks(16).enumerate() {
if chunk.iter().all(|&x| x == 0) {
should_trim = false;
continue;
}
for b in chunk {
match *b {
// ASCII printable
0x20u8...0x7e => { print!(".{} ", *b as char) }
0x00 => |
0xFF => { print!("## ") }
_ => { print!("{:02X} ", b) }
}
}
let trimming_offset = if should_trim { Some(prev_offset.clone()) } else { None };
let new_offset = offset((idx + 1) * 16, offset_width, trimming_offset); // TODO: idx + 1 is wrong
print!("\n{}", new_offset);
prev_offset = new_offset;
should_trim = true;
}
if should_trim { // that means just skipped a bunch of zeroes at the end
}
println!("Ω⸫");
}
struct EditorState {
open_file: Option<Mmap>,
read_only: bool,
}
fn rustbox_output(file_path: &str) {
let rustbox = match RustBox::init(Default::default()) {
Result::Ok(v) => v,
Result::Err(e) => panic!("{}", e),
};
let mut state = EditorState { open_file: None, read_only: false };
// rustbox.print(1, 1, rustbox::RB_BOLD, Color::White, Color::Black, "Hello, world!");
// rustbox.print(1, 3, rustbox::RB_BOLD, Color::White, Color::Black,
// "Press 'q' to quit.");
// let mut file_mmap_try = try_open_file(file_path);
// let offset_width = offset_width(bytes.len());
loop {
rustbox.print(rustbox.width() - 10, 0, rustbox::RB_BOLD, Color::White, Color::Black, "HexRS");
rustbox.present();
match rustbox.poll_event(false).unwrap() {
Event::KeyEvent(key) => {
match key {
Key::Char('q') => { return; }
Key::Esc => { return; }
_ => { }
}
}
_ => { }
}
}
}
fn main() {
let matches = App::new("HexRS").version("0.1").args_from_usage(
"-i, --interactive 'Use the interactive version instead of outputting to stdout'
[INPUT] 'Specifies the input file to use'").get_matches();
if let Some(file_path) = matches.value_of("INPUT") {
if matches.is_present("interactive") {
rustbox_output(&file_path);
} else {
standard_output(&file_path);
}
}
}
| { print!(" ") } | conditional_block |
main.rs | extern crate rustbox;
extern crate memmap;
extern crate clap;
use std::error::Error;
// use std::default::Default;
// use std::cmp;
// use std::char;
use std::env;
use memmap::{Mmap, Protection};
use rustbox::{Color, RustBox, Key, Event};
use clap::{App, Arg};
fn longest_prefix<'a>(a: &'a str, b: &'a str) -> usize {
a.chars().zip(b.chars()).take_while(|&(c1, c2)| c1 == c2).count()
}
fn header(width: usize) -> String {
format!("{:1$}0 1 2 3 4 5 6 7 8 9 A B C D E F", "", width + 3)
}
fn string_repeat(s: &str, n: usize) -> String {
std::iter::repeat(s).take(n).collect::<String>()
}
fn offset(offset: usize, width: usize, trimming_offset: Option<String>) -> String {
match trimming_offset {
None => { format!("{:01$x}: ", offset, width) }
Some(trimming_string) => {
let new_fmt = format!("{:01$x}: ", offset, width);
let n_chars_to_remove = longest_prefix(&new_fmt, &trimming_string);
let padding = string_repeat(" ", n_chars_to_remove);
padding + &new_fmt[n_chars_to_remove..]
}
}
}
fn offset_width(num_bytes: usize) -> usize {
// +1 byte for the final EOF symbol
// +1 for the base-16 computation
(((num_bytes + 1) as f64).log(16.0) as usize) + 1
}
fn try_open_file(file_path: &str) -> Result<(Mmap, bool), std::io::Error> {
let mut is_read_only = false;
let mut file_mmap_try = Mmap::open_path(file_path, Protection::ReadWrite);
if file_mmap_try.is_err() {
file_mmap_try = Mmap::open_path(file_path, Protection::Read);
is_read_only = true;
}
file_mmap_try.map(|x| (x, is_read_only))
}
fn standard_output(file_path: &str) {
let file_mmap = Mmap::open_path(file_path, Protection::Read).unwrap();
let bytes: &[u8] = unsafe { file_mmap.as_slice() };
let offset_width = offset_width(bytes.len());
println!("{}\n", header(offset_width));
let mut prev_offset: String = offset(0, offset_width, None);
let mut should_trim = true;
print!("{}", prev_offset);
for (idx, chunk) in bytes.chunks(16).enumerate() {
if chunk.iter().all(|&x| x == 0) {
should_trim = false;
continue;
}
for b in chunk {
match *b {
// ASCII printable
0x20u8...0x7e => { print!(".{} ", *b as char) }
0x00 => { print!(" ") }
0xFF => { print!("## ") }
_ => { print!("{:02X} ", b) }
}
}
let trimming_offset = if should_trim { Some(prev_offset.clone()) } else { None };
let new_offset = offset((idx + 1) * 16, offset_width, trimming_offset); // TODO: idx + 1 is wrong
print!("\n{}", new_offset);
prev_offset = new_offset;
should_trim = true;
}
if should_trim { // that means just skipped a bunch of zeroes at the end
}
println!("Ω⸫");
}
struct EditorState {
open_file: Option<Mmap>,
read_only: bool,
}
fn rus | le_path: &str) {
let rustbox = match RustBox::init(Default::default()) {
Result::Ok(v) => v,
Result::Err(e) => panic!("{}", e),
};
let mut state = EditorState { open_file: None, read_only: false };
// rustbox.print(1, 1, rustbox::RB_BOLD, Color::White, Color::Black, "Hello, world!");
// rustbox.print(1, 3, rustbox::RB_BOLD, Color::White, Color::Black,
// "Press 'q' to quit.");
// let mut file_mmap_try = try_open_file(file_path);
// let offset_width = offset_width(bytes.len());
loop {
rustbox.print(rustbox.width() - 10, 0, rustbox::RB_BOLD, Color::White, Color::Black, "HexRS");
rustbox.present();
match rustbox.poll_event(false).unwrap() {
Event::KeyEvent(key) => {
match key {
Key::Char('q') => { return; }
Key::Esc => { return; }
_ => { }
}
}
_ => { }
}
}
}
fn main() {
let matches = App::new("HexRS").version("0.1").args_from_usage(
"-i, --interactive 'Use the interactive version instead of outputting to stdout'
[INPUT] 'Specifies the input file to use'").get_matches();
if let Some(file_path) = matches.value_of("INPUT") {
if matches.is_present("interactive") {
rustbox_output(&file_path);
} else {
standard_output(&file_path);
}
}
}
| tbox_output(fi | identifier_name |
index.tsx | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
import * as React from 'react';
import { findIndex } from 'lodash';
import { AbilityButtonInfo } from 'hud/AbilityBar/AbilityButton/AbilityButtonView';
import AbilityQueueList, { QueuedAbilities } from './components/AbilityQueueList';
export interface AbilityQueueProps {
}
export interface AbilityQueueState {
queuedAbilities: QueuedAbilities;
}
class | extends React.Component<AbilityQueueProps, AbilityQueueState> {
private eventHandles: {[id: string]: EventHandle} = {};
constructor(props: AbilityQueueProps) {
super(props);
this.state = {
queuedAbilities: {},
};
}
public render() {
return (
<AbilityQueueList queuedAbilities={this.state.queuedAbilities} />
);
}
public componentDidMount() {
camelotunchained.game.store.onUpdated(this.initAbilityButtonEvents);
}
public componentWillUnmount() {
Object.keys(this.eventHandles).forEach((eventKey) => {
// Clear events
this.eventHandles[eventKey].clear();
delete this.eventHandles[eventKey];
});
}
private handleAbilityQueueEvent = (ability: AbilityButtonInfo) => {
const queuedAbilities = { ...this.state.queuedAbilities };
const track = this.getTrack(ability.track);
const activeOrQueued = ability.status & AbilityButtonState.Queued ||
ability.status & AbilityButtonState.Preparation ||
ability.status & AbilityButtonState.Held;
if (activeOrQueued) {
// Add active or queued ability to the AbilityQueue list
const abilityIndex = findIndex(queuedAbilities[track], queuedAbility => queuedAbility.id === ability.id);
if (abilityIndex > -1) {
queuedAbilities[track][abilityIndex] = ability;
} else {
queuedAbilities[track] = queuedAbilities[track] ? [...queuedAbilities[track], ability] : [ability];
}
} else {
// Ability is no longer active or queued, remove from the AbilityQueue list
Object.keys(queuedAbilities).forEach((track) => {
if (queuedAbilities[track].find(queuedAbility => queuedAbility.id === ability.id)) {
queuedAbilities[track] = queuedAbilities[track].filter(queuedAbility => queuedAbility.id !== ability.id);
if (queuedAbilities[track].length === 0) {
delete queuedAbilities[track];
}
}
});
}
this.setState({ queuedAbilities });
}
private initAbilityButtonEvents = () => {
if (camelotunchained.game.store.myCharacter && camelotunchained.game.store.myCharacter.abilities) {
camelotunchained.game.store.myCharacter.abilities.forEach((ability) => {
if (ability && !this.eventHandles[ability.id]) {
this.eventHandles[ability.id] = game.on('abilitybutton-' + ability.id, this.handleAbilityQueueEvent);
}
});
}
}
private getTrack = (track: AbilityTrack) => {
if (track & AbilityTrack.BothWeapons) {
return AbilityTrack[AbilityTrack.BothWeapons];
}
if (track & AbilityTrack.PrimaryWeapon) {
return AbilityTrack[AbilityTrack.PrimaryWeapon];
}
if (track & AbilityTrack.SecondaryWeapon) {
return AbilityTrack[AbilityTrack.SecondaryWeapon];
}
if (track & AbilityTrack.Voice) {
return AbilityTrack[AbilityTrack.Voice];
}
if (track & AbilityTrack.Mind) {
return AbilityTrack[AbilityTrack.Mind];
}
return AbilityTrack[AbilityTrack.None];
}
}
export default AbilityQueue;
| AbilityQueue | identifier_name |
index.tsx | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
import * as React from 'react';
import { findIndex } from 'lodash';
import { AbilityButtonInfo } from 'hud/AbilityBar/AbilityButton/AbilityButtonView';
import AbilityQueueList, { QueuedAbilities } from './components/AbilityQueueList';
export interface AbilityQueueProps {
}
export interface AbilityQueueState {
queuedAbilities: QueuedAbilities;
}
class AbilityQueue extends React.Component<AbilityQueueProps, AbilityQueueState> {
private eventHandles: {[id: string]: EventHandle} = {};
constructor(props: AbilityQueueProps) {
super(props);
this.state = {
queuedAbilities: {},
};
}
public render() {
return (
<AbilityQueueList queuedAbilities={this.state.queuedAbilities} />
);
}
public componentDidMount() {
camelotunchained.game.store.onUpdated(this.initAbilityButtonEvents);
}
public componentWillUnmount() {
Object.keys(this.eventHandles).forEach((eventKey) => {
// Clear events
this.eventHandles[eventKey].clear();
delete this.eventHandles[eventKey];
});
}
private handleAbilityQueueEvent = (ability: AbilityButtonInfo) => {
const queuedAbilities = { ...this.state.queuedAbilities };
const track = this.getTrack(ability.track);
const activeOrQueued = ability.status & AbilityButtonState.Queued ||
ability.status & AbilityButtonState.Preparation ||
ability.status & AbilityButtonState.Held;
if (activeOrQueued) {
// Add active or queued ability to the AbilityQueue list
const abilityIndex = findIndex(queuedAbilities[track], queuedAbility => queuedAbility.id === ability.id);
if (abilityIndex > -1) {
queuedAbilities[track][abilityIndex] = ability;
} else {
queuedAbilities[track] = queuedAbilities[track] ? [...queuedAbilities[track], ability] : [ability];
}
} else {
// Ability is no longer active or queued, remove from the AbilityQueue list
Object.keys(queuedAbilities).forEach((track) => {
if (queuedAbilities[track].find(queuedAbility => queuedAbility.id === ability.id)) {
queuedAbilities[track] = queuedAbilities[track].filter(queuedAbility => queuedAbility.id !== ability.id);
if (queuedAbilities[track].length === 0) {
delete queuedAbilities[track];
}
}
});
}
this.setState({ queuedAbilities });
}
private initAbilityButtonEvents = () => {
if (camelotunchained.game.store.myCharacter && camelotunchained.game.store.myCharacter.abilities) {
camelotunchained.game.store.myCharacter.abilities.forEach((ability) => {
if (ability && !this.eventHandles[ability.id]) {
this.eventHandles[ability.id] = game.on('abilitybutton-' + ability.id, this.handleAbilityQueueEvent);
}
});
}
}
private getTrack = (track: AbilityTrack) => {
if (track & AbilityTrack.BothWeapons) {
return AbilityTrack[AbilityTrack.BothWeapons];
}
if (track & AbilityTrack.PrimaryWeapon) {
return AbilityTrack[AbilityTrack.PrimaryWeapon];
}
if (track & AbilityTrack.SecondaryWeapon) {
return AbilityTrack[AbilityTrack.SecondaryWeapon];
}
if (track & AbilityTrack.Voice) |
if (track & AbilityTrack.Mind) {
return AbilityTrack[AbilityTrack.Mind];
}
return AbilityTrack[AbilityTrack.None];
}
}
export default AbilityQueue;
| {
return AbilityTrack[AbilityTrack.Voice];
} | conditional_block |
index.tsx | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
import * as React from 'react';
import { findIndex } from 'lodash';
import { AbilityButtonInfo } from 'hud/AbilityBar/AbilityButton/AbilityButtonView';
import AbilityQueueList, { QueuedAbilities } from './components/AbilityQueueList';
export interface AbilityQueueProps {
}
export interface AbilityQueueState {
queuedAbilities: QueuedAbilities;
}
class AbilityQueue extends React.Component<AbilityQueueProps, AbilityQueueState> {
private eventHandles: {[id: string]: EventHandle} = {};
constructor(props: AbilityQueueProps) {
super(props);
this.state = {
queuedAbilities: {},
};
}
public render() {
return (
<AbilityQueueList queuedAbilities={this.state.queuedAbilities} />
); | }
public componentDidMount() {
camelotunchained.game.store.onUpdated(this.initAbilityButtonEvents);
}
public componentWillUnmount() {
Object.keys(this.eventHandles).forEach((eventKey) => {
// Clear events
this.eventHandles[eventKey].clear();
delete this.eventHandles[eventKey];
});
}
private handleAbilityQueueEvent = (ability: AbilityButtonInfo) => {
const queuedAbilities = { ...this.state.queuedAbilities };
const track = this.getTrack(ability.track);
const activeOrQueued = ability.status & AbilityButtonState.Queued ||
ability.status & AbilityButtonState.Preparation ||
ability.status & AbilityButtonState.Held;
if (activeOrQueued) {
// Add active or queued ability to the AbilityQueue list
const abilityIndex = findIndex(queuedAbilities[track], queuedAbility => queuedAbility.id === ability.id);
if (abilityIndex > -1) {
queuedAbilities[track][abilityIndex] = ability;
} else {
queuedAbilities[track] = queuedAbilities[track] ? [...queuedAbilities[track], ability] : [ability];
}
} else {
// Ability is no longer active or queued, remove from the AbilityQueue list
Object.keys(queuedAbilities).forEach((track) => {
if (queuedAbilities[track].find(queuedAbility => queuedAbility.id === ability.id)) {
queuedAbilities[track] = queuedAbilities[track].filter(queuedAbility => queuedAbility.id !== ability.id);
if (queuedAbilities[track].length === 0) {
delete queuedAbilities[track];
}
}
});
}
this.setState({ queuedAbilities });
}
private initAbilityButtonEvents = () => {
if (camelotunchained.game.store.myCharacter && camelotunchained.game.store.myCharacter.abilities) {
camelotunchained.game.store.myCharacter.abilities.forEach((ability) => {
if (ability && !this.eventHandles[ability.id]) {
this.eventHandles[ability.id] = game.on('abilitybutton-' + ability.id, this.handleAbilityQueueEvent);
}
});
}
}
private getTrack = (track: AbilityTrack) => {
if (track & AbilityTrack.BothWeapons) {
return AbilityTrack[AbilityTrack.BothWeapons];
}
if (track & AbilityTrack.PrimaryWeapon) {
return AbilityTrack[AbilityTrack.PrimaryWeapon];
}
if (track & AbilityTrack.SecondaryWeapon) {
return AbilityTrack[AbilityTrack.SecondaryWeapon];
}
if (track & AbilityTrack.Voice) {
return AbilityTrack[AbilityTrack.Voice];
}
if (track & AbilityTrack.Mind) {
return AbilityTrack[AbilityTrack.Mind];
}
return AbilityTrack[AbilityTrack.None];
}
}
export default AbilityQueue; | random_line_split |
|
index.tsx | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
import * as React from 'react';
import { findIndex } from 'lodash';
import { AbilityButtonInfo } from 'hud/AbilityBar/AbilityButton/AbilityButtonView';
import AbilityQueueList, { QueuedAbilities } from './components/AbilityQueueList';
export interface AbilityQueueProps {
}
export interface AbilityQueueState {
queuedAbilities: QueuedAbilities;
}
class AbilityQueue extends React.Component<AbilityQueueProps, AbilityQueueState> {
private eventHandles: {[id: string]: EventHandle} = {};
constructor(props: AbilityQueueProps) {
super(props);
this.state = {
queuedAbilities: {},
};
}
public render() |
public componentDidMount() {
camelotunchained.game.store.onUpdated(this.initAbilityButtonEvents);
}
public componentWillUnmount() {
Object.keys(this.eventHandles).forEach((eventKey) => {
// Clear events
this.eventHandles[eventKey].clear();
delete this.eventHandles[eventKey];
});
}
private handleAbilityQueueEvent = (ability: AbilityButtonInfo) => {
const queuedAbilities = { ...this.state.queuedAbilities };
const track = this.getTrack(ability.track);
const activeOrQueued = ability.status & AbilityButtonState.Queued ||
ability.status & AbilityButtonState.Preparation ||
ability.status & AbilityButtonState.Held;
if (activeOrQueued) {
// Add active or queued ability to the AbilityQueue list
const abilityIndex = findIndex(queuedAbilities[track], queuedAbility => queuedAbility.id === ability.id);
if (abilityIndex > -1) {
queuedAbilities[track][abilityIndex] = ability;
} else {
queuedAbilities[track] = queuedAbilities[track] ? [...queuedAbilities[track], ability] : [ability];
}
} else {
// Ability is no longer active or queued, remove from the AbilityQueue list
Object.keys(queuedAbilities).forEach((track) => {
if (queuedAbilities[track].find(queuedAbility => queuedAbility.id === ability.id)) {
queuedAbilities[track] = queuedAbilities[track].filter(queuedAbility => queuedAbility.id !== ability.id);
if (queuedAbilities[track].length === 0) {
delete queuedAbilities[track];
}
}
});
}
this.setState({ queuedAbilities });
}
private initAbilityButtonEvents = () => {
if (camelotunchained.game.store.myCharacter && camelotunchained.game.store.myCharacter.abilities) {
camelotunchained.game.store.myCharacter.abilities.forEach((ability) => {
if (ability && !this.eventHandles[ability.id]) {
this.eventHandles[ability.id] = game.on('abilitybutton-' + ability.id, this.handleAbilityQueueEvent);
}
});
}
}
private getTrack = (track: AbilityTrack) => {
if (track & AbilityTrack.BothWeapons) {
return AbilityTrack[AbilityTrack.BothWeapons];
}
if (track & AbilityTrack.PrimaryWeapon) {
return AbilityTrack[AbilityTrack.PrimaryWeapon];
}
if (track & AbilityTrack.SecondaryWeapon) {
return AbilityTrack[AbilityTrack.SecondaryWeapon];
}
if (track & AbilityTrack.Voice) {
return AbilityTrack[AbilityTrack.Voice];
}
if (track & AbilityTrack.Mind) {
return AbilityTrack[AbilityTrack.Mind];
}
return AbilityTrack[AbilityTrack.None];
}
}
export default AbilityQueue;
| {
return (
<AbilityQueueList queuedAbilities={this.state.queuedAbilities} />
);
} | identifier_body |
history.rs | use std::io::prelude::*;
use std::path::Path;
use curl::http;
use yaml_rust::Yaml;
use super::file;
use super::yaml_util;
use super::request::SpagRequest;
use super::remember;
const HISTORY_DIR: &'static str = ".spag";
const HISTORY_FILE: &'static str = ".spag/history.yml";
const HISTORY_LIMIT: usize = 100;
pub fn ensure_history_exists() {
if !Path::new(HISTORY_FILE).exists() {
file::ensure_dir_exists(HISTORY_DIR);
file::write_file(HISTORY_FILE, "[]");
}
}
pub fn append(req: &SpagRequest, resp: &http::Response) -> Result<(), String> {
ensure_history_exists();
let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE));
if let Yaml::Array(ref mut arr) = *y {
// Trim the history, -1 so that our request fits under the limit
if arr.len() > HISTORY_LIMIT - 1 {
while arr.len() > HISTORY_LIMIT - 1 {
arr.remove(0);
}
} |
Ok(try!(yaml_util::dump_yaml_file(HISTORY_FILE, &y)))
}
pub fn list() -> Result<Vec<String>, String> {
ensure_history_exists();
let mut result = Vec::new();
let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE));
if let Yaml::Array(ref mut arr) = *y {
for y in arr.iter() {
let method = try!(yaml_util::get_value_as_string(&y, &["request", "method"]));
let endpoint = try!(yaml_util::get_value_as_string(&y, &["request", "endpoint"]));
let uri = try!(yaml_util::get_value_as_string(&y, &["request", "uri"]));
let s = format!("{} {}{}", method, endpoint, uri);
result.push(s);
}
}
Ok(result)
}
pub fn get(raw_index: &String) -> Result<String, String> {
ensure_history_exists();
let index = raw_index.parse().unwrap();
let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE));
if let Yaml::Array(ref mut arr) = *y {
let target = match arr.get(index) {
Some(yaml) => yaml,
None => return Err(format!("No request at #{}", index)),
};
// Request data
let mut output = "-------------------- Request ---------------------\n".to_string();
let method = try!(yaml_util::get_value_as_string(&target, &["request", "method"]));
let endpoint = try!(yaml_util::get_value_as_string(&target, &["request", "endpoint"]));
let uri = try!(yaml_util::get_value_as_string(&target, &["request", "uri"]));
let body = try!(yaml_util::get_value_as_string(&target, &["request", "body"]));
output.push_str(format!("{} {}{}\n", method, endpoint, uri).as_str());
match yaml_util::get_nested_value(&target, &["request", "headers"]) {
Some(&Yaml::Hash(ref headers)) => {
for (key, value) in headers.iter() {
output.push_str(format!("{}: {}\n", key.as_str().unwrap(),
value.as_str().unwrap()).as_str());
}
},
None => {},
_ => { return Err(format!("Invalid headers in request history #{}.", index))},
};
output.push_str(format!("Body:\n{}\n", body).as_str());
// Response Data
output.push_str("-------------------- Response ---------------------\n");
let body = try!(yaml_util::get_value_as_string(&target, &["response", "body"]));
let status = try!(yaml_util::get_value_as_string(&target, &["response", "status"]));
output.push_str(format!("Status code {}\n", status).as_str());
match yaml_util::get_nested_value(&target, &["response", "headers"]) {
Some(&Yaml::Hash(ref headers)) => {
for (key, value) in headers.iter() {
output.push_str(format!("{}: {}\n", key.as_str().unwrap(),
value.as_str().unwrap()).as_str());
}
},
None => {},
_ => { return Err(format!("Invalid headers in request history #{}.", index))},
};
output.push_str(format!("Body:\n{}\n", body).as_str());
Ok(output.to_string())
} else {
Err(format!("Failed to load history file {}", HISTORY_FILE))
}
} |
let new_entry = remember::serialize(req, resp);
arr.insert(0, new_entry);
} | random_line_split |
history.rs | use std::io::prelude::*;
use std::path::Path;
use curl::http;
use yaml_rust::Yaml;
use super::file;
use super::yaml_util;
use super::request::SpagRequest;
use super::remember;
const HISTORY_DIR: &'static str = ".spag";
const HISTORY_FILE: &'static str = ".spag/history.yml";
const HISTORY_LIMIT: usize = 100;
pub fn ensure_history_exists() {
if !Path::new(HISTORY_FILE).exists() {
file::ensure_dir_exists(HISTORY_DIR);
file::write_file(HISTORY_FILE, "[]");
}
}
pub fn append(req: &SpagRequest, resp: &http::Response) -> Result<(), String> {
ensure_history_exists();
let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE));
if let Yaml::Array(ref mut arr) = *y {
// Trim the history, -1 so that our request fits under the limit
if arr.len() > HISTORY_LIMIT - 1 {
while arr.len() > HISTORY_LIMIT - 1 {
arr.remove(0);
}
}
let new_entry = remember::serialize(req, resp);
arr.insert(0, new_entry);
}
Ok(try!(yaml_util::dump_yaml_file(HISTORY_FILE, &y)))
}
pub fn list() -> Result<Vec<String>, String> {
ensure_history_exists();
let mut result = Vec::new();
let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE));
if let Yaml::Array(ref mut arr) = *y {
for y in arr.iter() {
let method = try!(yaml_util::get_value_as_string(&y, &["request", "method"]));
let endpoint = try!(yaml_util::get_value_as_string(&y, &["request", "endpoint"]));
let uri = try!(yaml_util::get_value_as_string(&y, &["request", "uri"]));
let s = format!("{} {}{}", method, endpoint, uri);
result.push(s);
}
}
Ok(result)
}
pub fn get(raw_index: &String) -> Result<String, String> {
ensure_history_exists();
let index = raw_index.parse().unwrap();
let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE));
if let Yaml::Array(ref mut arr) = *y {
let target = match arr.get(index) {
Some(yaml) => yaml,
None => return Err(format!("No request at #{}", index)),
};
// Request data
let mut output = "-------------------- Request ---------------------\n".to_string();
let method = try!(yaml_util::get_value_as_string(&target, &["request", "method"]));
let endpoint = try!(yaml_util::get_value_as_string(&target, &["request", "endpoint"]));
let uri = try!(yaml_util::get_value_as_string(&target, &["request", "uri"]));
let body = try!(yaml_util::get_value_as_string(&target, &["request", "body"]));
output.push_str(format!("{} {}{}\n", method, endpoint, uri).as_str());
match yaml_util::get_nested_value(&target, &["request", "headers"]) {
Some(&Yaml::Hash(ref headers)) => {
for (key, value) in headers.iter() {
output.push_str(format!("{}: {}\n", key.as_str().unwrap(),
value.as_str().unwrap()).as_str());
}
},
None => {},
_ => { return Err(format!("Invalid headers in request history #{}.", index))},
};
output.push_str(format!("Body:\n{}\n", body).as_str());
// Response Data
output.push_str("-------------------- Response ---------------------\n");
let body = try!(yaml_util::get_value_as_string(&target, &["response", "body"]));
let status = try!(yaml_util::get_value_as_string(&target, &["response", "status"]));
output.push_str(format!("Status code {}\n", status).as_str());
match yaml_util::get_nested_value(&target, &["response", "headers"]) {
Some(&Yaml::Hash(ref headers)) => {
for (key, value) in headers.iter() {
output.push_str(format!("{}: {}\n", key.as_str().unwrap(),
value.as_str().unwrap()).as_str());
}
},
None => | ,
_ => { return Err(format!("Invalid headers in request history #{}.", index))},
};
output.push_str(format!("Body:\n{}\n", body).as_str());
Ok(output.to_string())
} else {
Err(format!("Failed to load history file {}", HISTORY_FILE))
}
}
| {} | conditional_block |
history.rs | use std::io::prelude::*;
use std::path::Path;
use curl::http;
use yaml_rust::Yaml;
use super::file;
use super::yaml_util;
use super::request::SpagRequest;
use super::remember;
const HISTORY_DIR: &'static str = ".spag";
const HISTORY_FILE: &'static str = ".spag/history.yml";
const HISTORY_LIMIT: usize = 100;
pub fn ensure_history_exists() {
if !Path::new(HISTORY_FILE).exists() {
file::ensure_dir_exists(HISTORY_DIR);
file::write_file(HISTORY_FILE, "[]");
}
}
pub fn append(req: &SpagRequest, resp: &http::Response) -> Result<(), String> | }
pub fn list() -> Result<Vec<String>, String> {
ensure_history_exists();
let mut result = Vec::new();
let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE));
if let Yaml::Array(ref mut arr) = *y {
for y in arr.iter() {
let method = try!(yaml_util::get_value_as_string(&y, &["request", "method"]));
let endpoint = try!(yaml_util::get_value_as_string(&y, &["request", "endpoint"]));
let uri = try!(yaml_util::get_value_as_string(&y, &["request", "uri"]));
let s = format!("{} {}{}", method, endpoint, uri);
result.push(s);
}
}
Ok(result)
}
pub fn get(raw_index: &String) -> Result<String, String> {
ensure_history_exists();
let index = raw_index.parse().unwrap();
let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE));
if let Yaml::Array(ref mut arr) = *y {
let target = match arr.get(index) {
Some(yaml) => yaml,
None => return Err(format!("No request at #{}", index)),
};
// Request data
let mut output = "-------------------- Request ---------------------\n".to_string();
let method = try!(yaml_util::get_value_as_string(&target, &["request", "method"]));
let endpoint = try!(yaml_util::get_value_as_string(&target, &["request", "endpoint"]));
let uri = try!(yaml_util::get_value_as_string(&target, &["request", "uri"]));
let body = try!(yaml_util::get_value_as_string(&target, &["request", "body"]));
output.push_str(format!("{} {}{}\n", method, endpoint, uri).as_str());
match yaml_util::get_nested_value(&target, &["request", "headers"]) {
Some(&Yaml::Hash(ref headers)) => {
for (key, value) in headers.iter() {
output.push_str(format!("{}: {}\n", key.as_str().unwrap(),
value.as_str().unwrap()).as_str());
}
},
None => {},
_ => { return Err(format!("Invalid headers in request history #{}.", index))},
};
output.push_str(format!("Body:\n{}\n", body).as_str());
// Response Data
output.push_str("-------------------- Response ---------------------\n");
let body = try!(yaml_util::get_value_as_string(&target, &["response", "body"]));
let status = try!(yaml_util::get_value_as_string(&target, &["response", "status"]));
output.push_str(format!("Status code {}\n", status).as_str());
match yaml_util::get_nested_value(&target, &["response", "headers"]) {
Some(&Yaml::Hash(ref headers)) => {
for (key, value) in headers.iter() {
output.push_str(format!("{}: {}\n", key.as_str().unwrap(),
value.as_str().unwrap()).as_str());
}
},
None => {},
_ => { return Err(format!("Invalid headers in request history #{}.", index))},
};
output.push_str(format!("Body:\n{}\n", body).as_str());
Ok(output.to_string())
} else {
Err(format!("Failed to load history file {}", HISTORY_FILE))
}
}
| {
ensure_history_exists();
let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE));
if let Yaml::Array(ref mut arr) = *y {
// Trim the history, -1 so that our request fits under the limit
if arr.len() > HISTORY_LIMIT - 1 {
while arr.len() > HISTORY_LIMIT - 1 {
arr.remove(0);
}
}
let new_entry = remember::serialize(req, resp);
arr.insert(0, new_entry);
}
Ok(try!(yaml_util::dump_yaml_file(HISTORY_FILE, &y))) | identifier_body |
history.rs | use std::io::prelude::*;
use std::path::Path;
use curl::http;
use yaml_rust::Yaml;
use super::file;
use super::yaml_util;
use super::request::SpagRequest;
use super::remember;
const HISTORY_DIR: &'static str = ".spag";
const HISTORY_FILE: &'static str = ".spag/history.yml";
const HISTORY_LIMIT: usize = 100;
pub fn | () {
if !Path::new(HISTORY_FILE).exists() {
file::ensure_dir_exists(HISTORY_DIR);
file::write_file(HISTORY_FILE, "[]");
}
}
pub fn append(req: &SpagRequest, resp: &http::Response) -> Result<(), String> {
ensure_history_exists();
let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE));
if let Yaml::Array(ref mut arr) = *y {
// Trim the history, -1 so that our request fits under the limit
if arr.len() > HISTORY_LIMIT - 1 {
while arr.len() > HISTORY_LIMIT - 1 {
arr.remove(0);
}
}
let new_entry = remember::serialize(req, resp);
arr.insert(0, new_entry);
}
Ok(try!(yaml_util::dump_yaml_file(HISTORY_FILE, &y)))
}
pub fn list() -> Result<Vec<String>, String> {
ensure_history_exists();
let mut result = Vec::new();
let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE));
if let Yaml::Array(ref mut arr) = *y {
for y in arr.iter() {
let method = try!(yaml_util::get_value_as_string(&y, &["request", "method"]));
let endpoint = try!(yaml_util::get_value_as_string(&y, &["request", "endpoint"]));
let uri = try!(yaml_util::get_value_as_string(&y, &["request", "uri"]));
let s = format!("{} {}{}", method, endpoint, uri);
result.push(s);
}
}
Ok(result)
}
pub fn get(raw_index: &String) -> Result<String, String> {
ensure_history_exists();
let index = raw_index.parse().unwrap();
let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE));
if let Yaml::Array(ref mut arr) = *y {
let target = match arr.get(index) {
Some(yaml) => yaml,
None => return Err(format!("No request at #{}", index)),
};
// Request data
let mut output = "-------------------- Request ---------------------\n".to_string();
let method = try!(yaml_util::get_value_as_string(&target, &["request", "method"]));
let endpoint = try!(yaml_util::get_value_as_string(&target, &["request", "endpoint"]));
let uri = try!(yaml_util::get_value_as_string(&target, &["request", "uri"]));
let body = try!(yaml_util::get_value_as_string(&target, &["request", "body"]));
output.push_str(format!("{} {}{}\n", method, endpoint, uri).as_str());
match yaml_util::get_nested_value(&target, &["request", "headers"]) {
Some(&Yaml::Hash(ref headers)) => {
for (key, value) in headers.iter() {
output.push_str(format!("{}: {}\n", key.as_str().unwrap(),
value.as_str().unwrap()).as_str());
}
},
None => {},
_ => { return Err(format!("Invalid headers in request history #{}.", index))},
};
output.push_str(format!("Body:\n{}\n", body).as_str());
// Response Data
output.push_str("-------------------- Response ---------------------\n");
let body = try!(yaml_util::get_value_as_string(&target, &["response", "body"]));
let status = try!(yaml_util::get_value_as_string(&target, &["response", "status"]));
output.push_str(format!("Status code {}\n", status).as_str());
match yaml_util::get_nested_value(&target, &["response", "headers"]) {
Some(&Yaml::Hash(ref headers)) => {
for (key, value) in headers.iter() {
output.push_str(format!("{}: {}\n", key.as_str().unwrap(),
value.as_str().unwrap()).as_str());
}
},
None => {},
_ => { return Err(format!("Invalid headers in request history #{}.", index))},
};
output.push_str(format!("Body:\n{}\n", body).as_str());
Ok(output.to_string())
} else {
Err(format!("Failed to load history file {}", HISTORY_FILE))
}
}
| ensure_history_exists | identifier_name |
models.py | 1_KEY = 'geojson:%d'
BOUNDARY_LEVEL_2_KEY = 'geojson:%d:%s'
@python_2_unicode_compatible
class Org(SmartModel):
name = models.CharField(
verbose_name=_("Name"), max_length=128,
help_text=_("The name of this organization"))
logo = models.ImageField(
upload_to='logos', null=True, blank=True,
help_text=_("The logo that should be used for this organization"))
administrators = models.ManyToManyField(
User, verbose_name=_("Administrators"), related_name="org_admins",
help_text=_("The administrators in your organization"))
viewers = models.ManyToManyField(
User, verbose_name=_("Viewers"), related_name="org_viewers",
help_text=_("The viewers in your organization"))
editors = models.ManyToManyField(
User, verbose_name=_("Editors"), related_name="org_editors",
help_text=_("The editors in your organization"))
language = models.CharField(
verbose_name=_("Language"), max_length=64, null=True, blank=True,
help_text=_("The main language used by this organization"))
subdomain = models.SlugField(
verbose_name=_("Subdomain"), null=True, blank=True, max_length=255, unique=True,
error_messages=dict(unique=_("This subdomain is not available")),
help_text=_("The subdomain for this organization"))
domain = models.CharField(
verbose_name=_("Domain"), null=True, blank=True, max_length=255, unique=True,
error_messages=dict(unique=_("This domain is not available")),
help_text=_("The custom domain for this organization"))
timezone = models.CharField(
verbose_name=_("Timezone"), max_length=64, default='UTC',
help_text=_("The timezone your organization is in."))
api_token = models.CharField(
max_length=128, null=True, blank=True,
help_text=_("The API token for the RapidPro account this dashboard "
"is tied to"))
config = models.TextField(
null=True, blank=True,
help_text=_("JSON blob used to store configuration information "
"associated with this organization"))
def set_timezone(self, timezone):
self.timezone = timezone
self._tzinfo = None
def get_timezone(self):
tzinfo = getattr(self, '_tzinfo', None)
if not tzinfo:
# we need to build the pytz timezone object with a context of now
tzinfo = timezone.now().astimezone(pytz.timezone(self.timezone)).tzinfo
self._tzinfo = tzinfo
return tzinfo
def get_config(self, name):
config = getattr(self, '_config', None)
if config is None:
if not self.config:
return None
config = json.loads(self.config)
self._config = config
return config.get(name, None)
def set_config(self, name, value, commit=True):
if not self.config:
config = dict()
else:
config = json.loads(self.config)
config[name] = value
self.config = json.dumps(config)
self._config = config
if commit:
self.save()
def get_org_admins(self):
return self.administrators.all()
def get_org_editors(self):
return self.editors.all()
def get_org_viewers(self):
return self.viewers.all()
def get_org_users(self):
org_users = self.get_org_admins() | self.get_org_editors() | self.get_org_viewers()
return org_users.distinct()
def get_user_org_group(self, user):
if user in self.get_org_admins():
user._org_group = Group.objects.get(name="Administrators")
elif user in self.get_org_editors():
user._org_group = Group.objects.get(name="Editors")
elif user in self.get_org_viewers():
user._org_group = Group.objects.get(name="Viewers")
else:
user._org_group = None
return getattr(user, '_org_group', None)
def | (self):
user = self.administrators.filter(is_active=True).first()
if user:
org_user = user
org_user.set_org(self)
return org_user
def get_temba_client(self):
host = getattr(settings, 'SITE_API_HOST', None)
agent = getattr(settings, 'SITE_API_USER_AGENT', None)
if not host:
host = '%s/api/v1' % settings.API_ENDPOINT # UReport sites use this
return TembaClient(host, self.api_token, user_agent=agent)
def get_api(self):
return API(self)
def build_host_link(self, user_authenticated=False):
host_tld = getattr(settings, "HOSTNAME", 'locahost')
is_secure = getattr(settings, 'SESSION_COOKIE_SECURE', False)
prefix = 'http://'
if self.domain and is_secure and not user_authenticated:
return prefix + str(self.domain)
if is_secure:
prefix = 'https://'
if self.subdomain == '':
return prefix + host_tld
return prefix + force_text(self.subdomain) + "." + host_tld
@classmethod
def rebuild_org_boundaries_task(cls, org):
from dash.orgs.tasks import rebuild_org_boundaries
rebuild_org_boundaries.delay(org.pk)
def build_boundaries(self):
this_time = datetime.now()
temba_client = self.get_temba_client()
client_boundaries = temba_client.get_boundaries()
# we now build our cached versions of level 1 (all states) and level 2
# (all districts for each state) geojson
states = []
districts_by_state = dict()
for boundary in client_boundaries:
if boundary.level == STATE:
states.append(boundary)
elif boundary.level == DISTRICT:
osm_id = boundary.parent
if osm_id not in districts_by_state:
districts_by_state[osm_id] = []
districts = districts_by_state[osm_id]
districts.append(boundary)
# mini function to convert a list of boundary objects to geojson
def to_geojson(boundary_list):
features = [dict(type='Feature',
geometry=dict(type=b.geometry.type,
coordinates=b.geometry.coordinates),
properties=dict(name=b.name, id=b.boundary, level=b.level))
for b in boundary_list]
return dict(type='FeatureCollection', features=features)
boundaries = dict()
boundaries[BOUNDARY_LEVEL_1_KEY % self.id] = to_geojson(states)
for state_id in districts_by_state.keys():
boundaries[BOUNDARY_LEVEL_2_KEY % (self.id, state_id)] = to_geojson(
districts_by_state[state_id])
key = BOUNDARY_CACHE_KEY % self.pk
value = {'time': datetime_to_ms(this_time), 'results': boundaries}
cache.set(key, value, BOUNDARY_CACHE_TIME)
return boundaries
def get_boundaries(self):
key = BOUNDARY_CACHE_KEY % self.pk
cached_value = cache.get(key, None)
if cached_value:
return cached_value['results']
Org.rebuild_org_boundaries_task(self)
def get_country_geojson(self):
boundaries = self.get_boundaries()
if boundaries:
key = BOUNDARY_LEVEL_1_KEY % self.id
return boundaries.get(key, None)
def get_state_geojson(self, state_id):
boundaries = self.get_boundaries()
if boundaries:
key = BOUNDARY_LEVEL_2_KEY % (self.id, state_id)
return boundaries.get(key, None)
def get_top_level_geojson_ids(self):
org_country_boundaries = self.get_country_geojson()
return [elt['properties']['id'] for elt in org_country_boundaries['features']]
@classmethod
def create_user(cls, email, password):
user = User.objects.create_user(username=email, email=email, password=password)
return user
@classmethod
def get_org(cls, user):
if not user:
return None
if not hasattr(user, '_org'):
org = Org.objects.filter(administrators=user, is_active=True).first()
if org:
user._org = org
return getattr(user, '_org', None)
def __str__(self):
return self.name
def get_org(obj):
return getattr(obj, '_org', None)
User.get_org = get_org
def set_org(obj, org):
obj._org = org
User.set_org = set_org
def get_user_orgs(user):
if user.is_superuser:
return Org.objects.all()
user_orgs = user.org_admins.all() | user.org_editors.all() | user.org_viewers.all()
return user_orgs.distinct()
User.get_user_orgs = get_user_orgs
def get_org_group(obj):
org_group = None
org = obj.get_org()
if org:
org_group = org.get_user_org_group(obj)
return org_group
User.get_org_group = get_org_group
USER_GROUPS = (('A', _("Administrator")),
('E', _("Editor")),
('V', _("Viewer")))
class Invitation(SmartModel):
org = models.ForeignKey(
Org, verbose_name=_("Org"), related_name="invitations",
help_text=_("The organization to which the account is invited to view"))
email = models.EmailField(
verbose_name=_("Email"),
help_text=_("The email to which we send the invitation of the viewer"))
secret = models.CharField(
verbose_name=_("Secret"), max_length=64, unique | get_user | identifier_name |
models.py | 1_KEY = 'geojson:%d'
BOUNDARY_LEVEL_2_KEY = 'geojson:%d:%s'
@python_2_unicode_compatible
class Org(SmartModel):
name = models.CharField(
verbose_name=_("Name"), max_length=128,
help_text=_("The name of this organization"))
logo = models.ImageField(
upload_to='logos', null=True, blank=True,
help_text=_("The logo that should be used for this organization"))
administrators = models.ManyToManyField(
User, verbose_name=_("Administrators"), related_name="org_admins",
help_text=_("The administrators in your organization"))
viewers = models.ManyToManyField(
User, verbose_name=_("Viewers"), related_name="org_viewers",
help_text=_("The viewers in your organization"))
editors = models.ManyToManyField(
User, verbose_name=_("Editors"), related_name="org_editors",
help_text=_("The editors in your organization"))
language = models.CharField(
verbose_name=_("Language"), max_length=64, null=True, blank=True,
help_text=_("The main language used by this organization"))
subdomain = models.SlugField(
verbose_name=_("Subdomain"), null=True, blank=True, max_length=255, unique=True,
error_messages=dict(unique=_("This subdomain is not available")),
help_text=_("The subdomain for this organization"))
domain = models.CharField(
verbose_name=_("Domain"), null=True, blank=True, max_length=255, unique=True,
error_messages=dict(unique=_("This domain is not available")),
help_text=_("The custom domain for this organization"))
timezone = models.CharField(
verbose_name=_("Timezone"), max_length=64, default='UTC',
help_text=_("The timezone your organization is in."))
api_token = models.CharField(
max_length=128, null=True, blank=True,
help_text=_("The API token for the RapidPro account this dashboard "
"is tied to"))
config = models.TextField(
null=True, blank=True,
help_text=_("JSON blob used to store configuration information "
"associated with this organization"))
def set_timezone(self, timezone):
self.timezone = timezone
self._tzinfo = None
def get_timezone(self):
tzinfo = getattr(self, '_tzinfo', None)
if not tzinfo:
# we need to build the pytz timezone object with a context of now
tzinfo = timezone.now().astimezone(pytz.timezone(self.timezone)).tzinfo
self._tzinfo = tzinfo
return tzinfo
def get_config(self, name):
config = getattr(self, '_config', None)
if config is None:
if not self.config:
return None
config = json.loads(self.config)
self._config = config
return config.get(name, None)
def set_config(self, name, value, commit=True):
if not self.config:
config = dict()
else:
config = json.loads(self.config)
config[name] = value
self.config = json.dumps(config)
self._config = config
if commit:
self.save()
def get_org_admins(self):
return self.administrators.all()
def get_org_editors(self):
return self.editors.all()
def get_org_viewers(self):
return self.viewers.all()
def get_org_users(self):
org_users = self.get_org_admins() | self.get_org_editors() | self.get_org_viewers()
return org_users.distinct()
def get_user_org_group(self, user):
if user in self.get_org_admins():
user._org_group = Group.objects.get(name="Administrators")
elif user in self.get_org_editors():
user._org_group = Group.objects.get(name="Editors")
elif user in self.get_org_viewers():
user._org_group = Group.objects.get(name="Viewers")
else:
user._org_group = None
return getattr(user, '_org_group', None)
def get_user(self):
user = self.administrators.filter(is_active=True).first()
if user:
org_user = user
org_user.set_org(self)
return org_user
def get_temba_client(self):
host = getattr(settings, 'SITE_API_HOST', None)
agent = getattr(settings, 'SITE_API_USER_AGENT', None)
if not host:
host = '%s/api/v1' % settings.API_ENDPOINT # UReport sites use this
return TembaClient(host, self.api_token, user_agent=agent)
def get_api(self):
return API(self)
def build_host_link(self, user_authenticated=False):
host_tld = getattr(settings, "HOSTNAME", 'locahost')
is_secure = getattr(settings, 'SESSION_COOKIE_SECURE', False)
prefix = 'http://'
if self.domain and is_secure and not user_authenticated:
return prefix + str(self.domain)
if is_secure:
prefix = 'https://'
if self.subdomain == '':
return prefix + host_tld
return prefix + force_text(self.subdomain) + "." + host_tld
@classmethod
def rebuild_org_boundaries_task(cls, org):
from dash.orgs.tasks import rebuild_org_boundaries
rebuild_org_boundaries.delay(org.pk)
def build_boundaries(self):
this_time = datetime.now()
temba_client = self.get_temba_client()
client_boundaries = temba_client.get_boundaries()
# we now build our cached versions of level 1 (all states) and level 2
# (all districts for each state) geojson
states = []
districts_by_state = dict()
for boundary in client_boundaries:
if boundary.level == STATE:
states.append(boundary)
elif boundary.level == DISTRICT:
osm_id = boundary.parent
if osm_id not in districts_by_state:
districts_by_state[osm_id] = []
districts = districts_by_state[osm_id]
districts.append(boundary)
# mini function to convert a list of boundary objects to geojson
def to_geojson(boundary_list):
features = [dict(type='Feature',
geometry=dict(type=b.geometry.type,
coordinates=b.geometry.coordinates),
properties=dict(name=b.name, id=b.boundary, level=b.level))
for b in boundary_list]
return dict(type='FeatureCollection', features=features)
boundaries = dict()
boundaries[BOUNDARY_LEVEL_1_KEY % self.id] = to_geojson(states)
for state_id in districts_by_state.keys():
boundaries[BOUNDARY_LEVEL_2_KEY % (self.id, state_id)] = to_geojson(
districts_by_state[state_id])
key = BOUNDARY_CACHE_KEY % self.pk
value = {'time': datetime_to_ms(this_time), 'results': boundaries}
cache.set(key, value, BOUNDARY_CACHE_TIME)
return boundaries
def get_boundaries(self):
key = BOUNDARY_CACHE_KEY % self.pk
cached_value = cache.get(key, None)
if cached_value:
return cached_value['results']
Org.rebuild_org_boundaries_task(self)
def get_country_geojson(self):
boundaries = self.get_boundaries()
if boundaries:
key = BOUNDARY_LEVEL_1_KEY % self.id
return boundaries.get(key, None)
def get_state_geojson(self, state_id):
boundaries = self.get_boundaries()
if boundaries:
key = BOUNDARY_LEVEL_2_KEY % (self.id, state_id)
return boundaries.get(key, None)
def get_top_level_geojson_ids(self):
org_country_boundaries = self.get_country_geojson()
return [elt['properties']['id'] for elt in org_country_boundaries['features']]
@classmethod
def create_user(cls, email, password):
user = User.objects.create_user(username=email, email=email, password=password)
return user
@classmethod
def get_org(cls, user):
if not user:
return None
if not hasattr(user, '_org'):
org = Org.objects.filter(administrators=user, is_active=True).first()
if org:
user._org = org
return getattr(user, '_org', None)
def __str__(self):
return self.name
def get_org(obj):
return getattr(obj, '_org', None)
User.get_org = get_org
def set_org(obj, org):
obj._org = org
User.set_org = set_org
def get_user_orgs(user):
|
User.get_user_orgs = get_user_orgs
def get_org_group(obj):
org_group = None
org = obj.get_org()
if org:
org_group = org.get_user_org_group(obj)
return org_group
User.get_org_group = get_org_group
USER_GROUPS = (('A', _("Administrator")),
('E', _("Editor")),
('V', _("Viewer")))
class Invitation(SmartModel):
org = models.ForeignKey(
Org, verbose_name=_("Org"), related_name="invitations",
help_text=_("The organization to which the account is invited to view"))
email = models.EmailField(
verbose_name=_("Email"),
help_text=_("The email to which we send the invitation of the viewer"))
secret = models.CharField(
verbose_name=_("Secret"), max_length=64, unique | if user.is_superuser:
return Org.objects.all()
user_orgs = user.org_admins.all() | user.org_editors.all() | user.org_viewers.all()
return user_orgs.distinct() | identifier_body |
models.py | 1_KEY = 'geojson:%d'
BOUNDARY_LEVEL_2_KEY = 'geojson:%d:%s'
@python_2_unicode_compatible
class Org(SmartModel):
name = models.CharField(
verbose_name=_("Name"), max_length=128,
help_text=_("The name of this organization"))
logo = models.ImageField(
upload_to='logos', null=True, blank=True,
help_text=_("The logo that should be used for this organization"))
administrators = models.ManyToManyField(
User, verbose_name=_("Administrators"), related_name="org_admins",
help_text=_("The administrators in your organization"))
viewers = models.ManyToManyField(
User, verbose_name=_("Viewers"), related_name="org_viewers",
help_text=_("The viewers in your organization"))
editors = models.ManyToManyField(
User, verbose_name=_("Editors"), related_name="org_editors",
help_text=_("The editors in your organization"))
language = models.CharField(
verbose_name=_("Language"), max_length=64, null=True, blank=True,
help_text=_("The main language used by this organization"))
subdomain = models.SlugField(
verbose_name=_("Subdomain"), null=True, blank=True, max_length=255, unique=True,
error_messages=dict(unique=_("This subdomain is not available")),
help_text=_("The subdomain for this organization"))
domain = models.CharField(
verbose_name=_("Domain"), null=True, blank=True, max_length=255, unique=True,
error_messages=dict(unique=_("This domain is not available")),
help_text=_("The custom domain for this organization"))
timezone = models.CharField(
verbose_name=_("Timezone"), max_length=64, default='UTC',
help_text=_("The timezone your organization is in."))
api_token = models.CharField(
max_length=128, null=True, blank=True,
help_text=_("The API token for the RapidPro account this dashboard "
"is tied to"))
config = models.TextField(
null=True, blank=True,
help_text=_("JSON blob used to store configuration information "
"associated with this organization"))
def set_timezone(self, timezone):
self.timezone = timezone
self._tzinfo = None
def get_timezone(self):
tzinfo = getattr(self, '_tzinfo', None)
if not tzinfo:
# we need to build the pytz timezone object with a context of now
tzinfo = timezone.now().astimezone(pytz.timezone(self.timezone)).tzinfo
self._tzinfo = tzinfo
return tzinfo
def get_config(self, name):
config = getattr(self, '_config', None)
if config is None:
if not self.config:
return None
config = json.loads(self.config)
self._config = config
return config.get(name, None)
def set_config(self, name, value, commit=True):
if not self.config:
config = dict()
else:
config = json.loads(self.config)
config[name] = value
self.config = json.dumps(config)
self._config = config
if commit:
self.save()
def get_org_admins(self):
return self.administrators.all()
def get_org_editors(self):
return self.editors.all()
def get_org_viewers(self):
return self.viewers.all()
def get_org_users(self):
org_users = self.get_org_admins() | self.get_org_editors() | self.get_org_viewers()
return org_users.distinct()
def get_user_org_group(self, user):
if user in self.get_org_admins():
user._org_group = Group.objects.get(name="Administrators")
elif user in self.get_org_editors():
user._org_group = Group.objects.get(name="Editors")
elif user in self.get_org_viewers():
user._org_group = Group.objects.get(name="Viewers")
else:
user._org_group = None
return getattr(user, '_org_group', None)
def get_user(self):
user = self.administrators.filter(is_active=True).first()
if user:
org_user = user
org_user.set_org(self)
return org_user
def get_temba_client(self):
host = getattr(settings, 'SITE_API_HOST', None)
agent = getattr(settings, 'SITE_API_USER_AGENT', None)
if not host:
host = '%s/api/v1' % settings.API_ENDPOINT # UReport sites use this
return TembaClient(host, self.api_token, user_agent=agent)
def get_api(self):
return API(self)
def build_host_link(self, user_authenticated=False):
host_tld = getattr(settings, "HOSTNAME", 'locahost')
is_secure = getattr(settings, 'SESSION_COOKIE_SECURE', False)
prefix = 'http://'
if self.domain and is_secure and not user_authenticated:
return prefix + str(self.domain)
if is_secure:
prefix = 'https://'
if self.subdomain == '':
return prefix + host_tld
return prefix + force_text(self.subdomain) + "." + host_tld
@classmethod
def rebuild_org_boundaries_task(cls, org):
from dash.orgs.tasks import rebuild_org_boundaries
rebuild_org_boundaries.delay(org.pk)
def build_boundaries(self):
this_time = datetime.now()
temba_client = self.get_temba_client()
client_boundaries = temba_client.get_boundaries()
# we now build our cached versions of level 1 (all states) and level 2
# (all districts for each state) geojson
states = []
districts_by_state = dict()
for boundary in client_boundaries:
if boundary.level == STATE:
states.append(boundary)
elif boundary.level == DISTRICT: | districts = districts_by_state[osm_id]
districts.append(boundary)
# mini function to convert a list of boundary objects to geojson
def to_geojson(boundary_list):
features = [dict(type='Feature',
geometry=dict(type=b.geometry.type,
coordinates=b.geometry.coordinates),
properties=dict(name=b.name, id=b.boundary, level=b.level))
for b in boundary_list]
return dict(type='FeatureCollection', features=features)
boundaries = dict()
boundaries[BOUNDARY_LEVEL_1_KEY % self.id] = to_geojson(states)
for state_id in districts_by_state.keys():
boundaries[BOUNDARY_LEVEL_2_KEY % (self.id, state_id)] = to_geojson(
districts_by_state[state_id])
key = BOUNDARY_CACHE_KEY % self.pk
value = {'time': datetime_to_ms(this_time), 'results': boundaries}
cache.set(key, value, BOUNDARY_CACHE_TIME)
return boundaries
def get_boundaries(self):
key = BOUNDARY_CACHE_KEY % self.pk
cached_value = cache.get(key, None)
if cached_value:
return cached_value['results']
Org.rebuild_org_boundaries_task(self)
def get_country_geojson(self):
boundaries = self.get_boundaries()
if boundaries:
key = BOUNDARY_LEVEL_1_KEY % self.id
return boundaries.get(key, None)
def get_state_geojson(self, state_id):
boundaries = self.get_boundaries()
if boundaries:
key = BOUNDARY_LEVEL_2_KEY % (self.id, state_id)
return boundaries.get(key, None)
def get_top_level_geojson_ids(self):
org_country_boundaries = self.get_country_geojson()
return [elt['properties']['id'] for elt in org_country_boundaries['features']]
@classmethod
def create_user(cls, email, password):
user = User.objects.create_user(username=email, email=email, password=password)
return user
@classmethod
def get_org(cls, user):
if not user:
return None
if not hasattr(user, '_org'):
org = Org.objects.filter(administrators=user, is_active=True).first()
if org:
user._org = org
return getattr(user, '_org', None)
def __str__(self):
return self.name
def get_org(obj):
return getattr(obj, '_org', None)
User.get_org = get_org
def set_org(obj, org):
obj._org = org
User.set_org = set_org
def get_user_orgs(user):
if user.is_superuser:
return Org.objects.all()
user_orgs = user.org_admins.all() | user.org_editors.all() | user.org_viewers.all()
return user_orgs.distinct()
User.get_user_orgs = get_user_orgs
def get_org_group(obj):
org_group = None
org = obj.get_org()
if org:
org_group = org.get_user_org_group(obj)
return org_group
User.get_org_group = get_org_group
USER_GROUPS = (('A', _("Administrator")),
('E', _("Editor")),
('V', _("Viewer")))
class Invitation(SmartModel):
org = models.ForeignKey(
Org, verbose_name=_("Org"), related_name="invitations",
help_text=_("The organization to which the account is invited to view"))
email = models.EmailField(
verbose_name=_("Email"),
help_text=_("The email to which we send the invitation of the viewer"))
secret = models.CharField(
verbose_name=_("Secret"), max_length=64, unique=True | osm_id = boundary.parent
if osm_id not in districts_by_state:
districts_by_state[osm_id] = []
| random_line_split |
models.py | _KEY = 'geojson:%d'
BOUNDARY_LEVEL_2_KEY = 'geojson:%d:%s'
@python_2_unicode_compatible
class Org(SmartModel):
name = models.CharField(
verbose_name=_("Name"), max_length=128,
help_text=_("The name of this organization"))
logo = models.ImageField(
upload_to='logos', null=True, blank=True,
help_text=_("The logo that should be used for this organization"))
administrators = models.ManyToManyField(
User, verbose_name=_("Administrators"), related_name="org_admins",
help_text=_("The administrators in your organization"))
viewers = models.ManyToManyField(
User, verbose_name=_("Viewers"), related_name="org_viewers",
help_text=_("The viewers in your organization"))
editors = models.ManyToManyField(
User, verbose_name=_("Editors"), related_name="org_editors",
help_text=_("The editors in your organization"))
language = models.CharField(
verbose_name=_("Language"), max_length=64, null=True, blank=True,
help_text=_("The main language used by this organization"))
subdomain = models.SlugField(
verbose_name=_("Subdomain"), null=True, blank=True, max_length=255, unique=True,
error_messages=dict(unique=_("This subdomain is not available")),
help_text=_("The subdomain for this organization"))
domain = models.CharField(
verbose_name=_("Domain"), null=True, blank=True, max_length=255, unique=True,
error_messages=dict(unique=_("This domain is not available")),
help_text=_("The custom domain for this organization"))
timezone = models.CharField(
verbose_name=_("Timezone"), max_length=64, default='UTC',
help_text=_("The timezone your organization is in."))
api_token = models.CharField(
max_length=128, null=True, blank=True,
help_text=_("The API token for the RapidPro account this dashboard "
"is tied to"))
config = models.TextField(
null=True, blank=True,
help_text=_("JSON blob used to store configuration information "
"associated with this organization"))
def set_timezone(self, timezone):
self.timezone = timezone
self._tzinfo = None
def get_timezone(self):
tzinfo = getattr(self, '_tzinfo', None)
if not tzinfo:
# we need to build the pytz timezone object with a context of now
tzinfo = timezone.now().astimezone(pytz.timezone(self.timezone)).tzinfo
self._tzinfo = tzinfo
return tzinfo
def get_config(self, name):
config = getattr(self, '_config', None)
if config is None:
if not self.config:
return None
config = json.loads(self.config)
self._config = config
return config.get(name, None)
def set_config(self, name, value, commit=True):
if not self.config:
config = dict()
else:
config = json.loads(self.config)
config[name] = value
self.config = json.dumps(config)
self._config = config
if commit:
self.save()
def get_org_admins(self):
return self.administrators.all()
def get_org_editors(self):
return self.editors.all()
def get_org_viewers(self):
return self.viewers.all()
def get_org_users(self):
org_users = self.get_org_admins() | self.get_org_editors() | self.get_org_viewers()
return org_users.distinct()
def get_user_org_group(self, user):
if user in self.get_org_admins():
user._org_group = Group.objects.get(name="Administrators")
elif user in self.get_org_editors():
user._org_group = Group.objects.get(name="Editors")
elif user in self.get_org_viewers():
user._org_group = Group.objects.get(name="Viewers")
else:
user._org_group = None
return getattr(user, '_org_group', None)
def get_user(self):
user = self.administrators.filter(is_active=True).first()
if user:
org_user = user
org_user.set_org(self)
return org_user
def get_temba_client(self):
host = getattr(settings, 'SITE_API_HOST', None)
agent = getattr(settings, 'SITE_API_USER_AGENT', None)
if not host:
host = '%s/api/v1' % settings.API_ENDPOINT # UReport sites use this
return TembaClient(host, self.api_token, user_agent=agent)
def get_api(self):
return API(self)
def build_host_link(self, user_authenticated=False):
host_tld = getattr(settings, "HOSTNAME", 'locahost')
is_secure = getattr(settings, 'SESSION_COOKIE_SECURE', False)
prefix = 'http://'
if self.domain and is_secure and not user_authenticated:
return prefix + str(self.domain)
if is_secure:
prefix = 'https://'
if self.subdomain == '':
return prefix + host_tld
return prefix + force_text(self.subdomain) + "." + host_tld
@classmethod
def rebuild_org_boundaries_task(cls, org):
from dash.orgs.tasks import rebuild_org_boundaries
rebuild_org_boundaries.delay(org.pk)
def build_boundaries(self):
this_time = datetime.now()
temba_client = self.get_temba_client()
client_boundaries = temba_client.get_boundaries()
# we now build our cached versions of level 1 (all states) and level 2
# (all districts for each state) geojson
states = []
districts_by_state = dict()
for boundary in client_boundaries:
if boundary.level == STATE:
states.append(boundary)
elif boundary.level == DISTRICT:
osm_id = boundary.parent
if osm_id not in districts_by_state:
|
districts = districts_by_state[osm_id]
districts.append(boundary)
# mini function to convert a list of boundary objects to geojson
def to_geojson(boundary_list):
features = [dict(type='Feature',
geometry=dict(type=b.geometry.type,
coordinates=b.geometry.coordinates),
properties=dict(name=b.name, id=b.boundary, level=b.level))
for b in boundary_list]
return dict(type='FeatureCollection', features=features)
boundaries = dict()
boundaries[BOUNDARY_LEVEL_1_KEY % self.id] = to_geojson(states)
for state_id in districts_by_state.keys():
boundaries[BOUNDARY_LEVEL_2_KEY % (self.id, state_id)] = to_geojson(
districts_by_state[state_id])
key = BOUNDARY_CACHE_KEY % self.pk
value = {'time': datetime_to_ms(this_time), 'results': boundaries}
cache.set(key, value, BOUNDARY_CACHE_TIME)
return boundaries
def get_boundaries(self):
key = BOUNDARY_CACHE_KEY % self.pk
cached_value = cache.get(key, None)
if cached_value:
return cached_value['results']
Org.rebuild_org_boundaries_task(self)
def get_country_geojson(self):
boundaries = self.get_boundaries()
if boundaries:
key = BOUNDARY_LEVEL_1_KEY % self.id
return boundaries.get(key, None)
def get_state_geojson(self, state_id):
boundaries = self.get_boundaries()
if boundaries:
key = BOUNDARY_LEVEL_2_KEY % (self.id, state_id)
return boundaries.get(key, None)
def get_top_level_geojson_ids(self):
org_country_boundaries = self.get_country_geojson()
return [elt['properties']['id'] for elt in org_country_boundaries['features']]
@classmethod
def create_user(cls, email, password):
user = User.objects.create_user(username=email, email=email, password=password)
return user
@classmethod
def get_org(cls, user):
if not user:
return None
if not hasattr(user, '_org'):
org = Org.objects.filter(administrators=user, is_active=True).first()
if org:
user._org = org
return getattr(user, '_org', None)
def __str__(self):
return self.name
def get_org(obj):
return getattr(obj, '_org', None)
User.get_org = get_org
def set_org(obj, org):
obj._org = org
User.set_org = set_org
def get_user_orgs(user):
if user.is_superuser:
return Org.objects.all()
user_orgs = user.org_admins.all() | user.org_editors.all() | user.org_viewers.all()
return user_orgs.distinct()
User.get_user_orgs = get_user_orgs
def get_org_group(obj):
org_group = None
org = obj.get_org()
if org:
org_group = org.get_user_org_group(obj)
return org_group
User.get_org_group = get_org_group
USER_GROUPS = (('A', _("Administrator")),
('E', _("Editor")),
('V', _("Viewer")))
class Invitation(SmartModel):
org = models.ForeignKey(
Org, verbose_name=_("Org"), related_name="invitations",
help_text=_("The organization to which the account is invited to view"))
email = models.EmailField(
verbose_name=_("Email"),
help_text=_("The email to which we send the invitation of the viewer"))
secret = models.CharField(
verbose_name=_("Secret"), max_length=64, unique | districts_by_state[osm_id] = [] | conditional_block |
demo.js | /*global console*/
var AutoCompleteView = require('../ampersand-autocomplete-view');
var FormView = require('ampersand-form-view');
var Model = require('ampersand-state').extend({
props: {
mbid: 'string',
name: 'string',
listeners: 'string'
},
derived: {
id: function() {
return this.name;
}
}
});
var Collection = require('ampersand-rest-collection').extend({
model: Model,
url: 'http://ws.audioscrobbler.com/2.0/?method=artist.search&api_key=cef6d600c717ecadfbe965380c9bac8b&format=json',
parse: function(response, options) {
if (response.results) {
return response.results.artistmatches.artist;
}
}
});
/*
var collection = new Collection([
{ id: 'red', title: 'Red' },
{ id: 'yellow', title: 'Yellow' },
{ id: 'blue', title: 'Blue' },
{ id: 'rat', title: 'Rat' }
]);
*/
var BaseView = FormView.extend({
fields: function () {
return [
new AutoCompleteView({
name: 'autocomplete',
parent: this,
options: new Collection(),
queryKey: 'artist',
idAttribute: 'name',
textAttribute: 'name',
placeHolder: 'Please choose one',
minKeywordLength: 3,
maxResults: 10
})
];
}
});
|
document.addEventListener('DOMContentLoaded', function () {
var baseView = new BaseView({el: document.body });
baseView.on('all', function (name, field) {
console.log('Got event', name, field.value, field.valid);
});
baseView.render();
}); | random_line_split |
|
demo.js |
/*global console*/
var AutoCompleteView = require('../ampersand-autocomplete-view');
var FormView = require('ampersand-form-view');
var Model = require('ampersand-state').extend({
props: {
mbid: 'string',
name: 'string',
listeners: 'string'
},
derived: {
id: function() {
return this.name;
}
}
});
var Collection = require('ampersand-rest-collection').extend({
model: Model,
url: 'http://ws.audioscrobbler.com/2.0/?method=artist.search&api_key=cef6d600c717ecadfbe965380c9bac8b&format=json',
parse: function(response, options) {
if (response.results) |
}
});
/*
var collection = new Collection([
{ id: 'red', title: 'Red' },
{ id: 'yellow', title: 'Yellow' },
{ id: 'blue', title: 'Blue' },
{ id: 'rat', title: 'Rat' }
]);
*/
var BaseView = FormView.extend({
fields: function () {
return [
new AutoCompleteView({
name: 'autocomplete',
parent: this,
options: new Collection(),
queryKey: 'artist',
idAttribute: 'name',
textAttribute: 'name',
placeHolder: 'Please choose one',
minKeywordLength: 3,
maxResults: 10
})
];
}
});
document.addEventListener('DOMContentLoaded', function () {
var baseView = new BaseView({el: document.body });
baseView.on('all', function (name, field) {
console.log('Got event', name, field.value, field.valid);
});
baseView.render();
}); | {
return response.results.artistmatches.artist;
} | conditional_block |
postMessage.js | /*
Module handles message posting.
*/
'use strict';
const AWS = require('aws-sdk'),
Joi = require('joi'),
config = require('../environments/config'),
dynamodb = new AWS.DynamoDB({ region: 'us-east-1' });
/* Joi validation object */
const postMessageValidate = Joi.object().keys({
UserName: Joi
.string()
.not('')
.default('Anonymous')
.description('Name of user who posts the message.'),
MessageBody: Joi
.string()
.not('')
.description('The message content.'),
Extra: Joi
.string()
.default('')
.description('Any additional info about the message.')
}).requiredKeys(
'UserName', 'MessageBody'
);
/* params for postMessage */
const postMessageParams = (query) => {
let curTime = (new Date()).getTime();
let item = {
'UserName': {
S: query.UserName
},
'TimeStamp': {
S: curTime.toString()
},
'MessageBody': {
S: query.MessageBody
}
};
if(query.Extra && query.Extra !== ''){
item['Extra'] = {
S: query.Extra
};
}
return {
TableName: config.dynamodb,
Item: item
};
};
/* Handler for postMessage */
const postMessage = (req, resp) => {
let query = req.query,
params = postMessageParams(query);
dynamodb.putItem(params, (err, data) => {
if(err){ | });
};
module.exports = {
postMessageParams,
config: {
handler: postMessage,
description: 'Allow user to post a message.',
tags: ['api'],
validate: {
query: postMessageValidate
}
}
}; | console.log('ERR: ' + err);
resp({Error: err}).code(400);
} else {
resp({mete: {status: "Success"}, data: data}).code(200);
} | random_line_split |
postMessage.js | /*
Module handles message posting.
*/
'use strict';
const AWS = require('aws-sdk'),
Joi = require('joi'),
config = require('../environments/config'),
dynamodb = new AWS.DynamoDB({ region: 'us-east-1' });
/* Joi validation object */
const postMessageValidate = Joi.object().keys({
UserName: Joi
.string()
.not('')
.default('Anonymous')
.description('Name of user who posts the message.'),
MessageBody: Joi
.string()
.not('')
.description('The message content.'),
Extra: Joi
.string()
.default('')
.description('Any additional info about the message.')
}).requiredKeys(
'UserName', 'MessageBody'
);
/* params for postMessage */
const postMessageParams = (query) => {
let curTime = (new Date()).getTime();
let item = {
'UserName': {
S: query.UserName
},
'TimeStamp': {
S: curTime.toString()
},
'MessageBody': {
S: query.MessageBody
}
};
if(query.Extra && query.Extra !== ''){
item['Extra'] = {
S: query.Extra
};
}
return {
TableName: config.dynamodb,
Item: item
};
};
/* Handler for postMessage */
const postMessage = (req, resp) => {
let query = req.query,
params = postMessageParams(query);
dynamodb.putItem(params, (err, data) => {
if(err){
console.log('ERR: ' + err);
resp({Error: err}).code(400);
} else |
});
};
module.exports = {
postMessageParams,
config: {
handler: postMessage,
description: 'Allow user to post a message.',
tags: ['api'],
validate: {
query: postMessageValidate
}
}
};
| {
resp({mete: {status: "Success"}, data: data}).code(200);
} | conditional_block |
all_62.js | var searchData=
[
['backtrace',['backtrace',['../class_logger.html#a5deb9b10c43285287a9113f280ee8fab',1,'Logger']]], | ['basic_2ephp',['Basic.php',['../_auth_2_basic_8php.html',1,'']]],
['basic_2ephp',['Basic.php',['../_t_mail_2_basic_8php.html',1,'']]],
['basic_2ephp',['Basic.php',['../_form_2_basic_8php.html',1,'']]],
['basic_2ephp',['Basic.php',['../_grid_2_basic_8php.html',1,'']]],
['basicauth',['BasicAuth',['../class_basic_auth.html',1,'']]],
['basicauth_2ephp',['BasicAuth.php',['../_basic_auth_8php.html',1,'']]],
['beforedelete',['beforeDelete',['../class_s_q_l___relation.html#a44c9d7a3b22619b53d4f49f1070d5235',1,'SQL_Relation']]],
['beforefield',['beforeField',['../class_form___field.html#aa4bbfb40048e1c3fe939621179652be1',1,'Form_Field']]],
['beforeinsert',['beforeInsert',['../class_s_q_l___relation.html#ada6a7f2abf3ba1c19e4ba3711da1a61e',1,'SQL_Relation']]],
['beforeload',['beforeLoad',['../class_s_q_l___relation.html#a665492752f54f9cbc3fd2cae51ca4373',1,'SQL_Relation']]],
['beforemodify',['beforeModify',['../class_s_q_l___relation.html#a3ad587772d12f99af11a3db64d879210',1,'SQL_Relation']]],
['beforesave',['beforeSave',['../class_s_q_l___relation.html#ab9e4fb36c177d9633b81fc184f7bd933',1,'SQL_Relation']]],
['begintransaction',['beginTransaction',['../class_d_b.html#af3380f3b13931d581fa973a382946b32',1,'DB\beginTransaction()'],['../class_d_blite__mysql.html#a06fdc3063ff49b8de811683aae3483e6',1,'DBlite_mysql\beginTransaction()']]],
['belowfield',['belowField',['../class_form___field.html#a27cd7c6e75ed8c09aae8af32905a888d',1,'Form_Field']]],
['box_2ephp',['Box.php',['../_box_8php.html',1,'']]],
['breakhook',['breakHook',['../class_abstract_object.html#a446b3f8327b3272c838ae46f40a9da06',1,'AbstractObject']]],
['bt',['bt',['../class_d_b__dsql.html#aa374d1bfaabf3f546fe8862d09f4a096',1,'DB_dsql']]],
['button',['Button',['../class_button.html',1,'']]],
['button_2ephp',['Button.php',['../_button_8php.html',1,'']]],
['button_2ephp',['Button.php',['../_form_2_button_8php.html',1,'']]],
['button_2ephp',['Button.php',['../_view_2_button_8php.html',1,'']]],
['buttonset',['ButtonSet',['../class_button_set.html',1,'']]],
['buttonset_2ephp',['ButtonSet.php',['../_button_set_8php.html',1,'']]],
['buttonset_2ephp',['ButtonSet.php',['../_view_2_button_set_8php.html',1,'']]]
]; | ['baseexception',['BaseException',['../class_base_exception.html',1,'']]],
['baseexception_2ephp',['BaseException.php',['../_base_exception_8php.html',1,'']]],
['basic_2ephp',['Basic.php',['../_menu_2_basic_8php.html',1,'']]],
['basic_2ephp',['Basic.php',['../_paginator_2_basic_8php.html',1,'']]], | random_line_split |
Calculator.py | # Numbers 数字
print(2 + 2) # 4
print(50 - 5*6) # 20
print((50 - 5*6) / 4) # 5.0
print(8/5) # 1.6
print(17 / 3) # 5.666666666666667 float
print(17 // 3) # 5 取整
print(17 % 3) # 2 取模
print(5*3+2) # 17 先乘除,后加减
print(2+5*3) # 17 先乘除,后加减
print(5**2) # 5的平方 25
print(5**3) # 5的立方 125
print(2**7) # 2的7次方128
print("--华丽的分割线--")
# 给变量赋值,使用“ = ”号,不需要定义变量的类型
width=50
height=10*10
print(width*height) # 5000
|
tax = 12.5 / 100
price = 100.50
print(price * tax)
# print(price+_); #在控制台可行,但是在本文件中不行,提示ameError: name '_' is not defined
# round(_, 2) #在控制台可行,但是在本文件中不行,提示ameError: name '_' is not defined
print("--华丽的分割线--")
# Strings 字符串
print('spam eggs')
print( 'doesn\'t') # \' 会进行转义
print("doesn't") # 也可使用双引号来输出,此时‘ 就不需要转义
print('"Yes," he said.') # 被单引号包含的双引号会被当成字符处理
print("\"Yes,\" he said.") # 被双引号包含中的双银行需要转义
print('"Isn\'t," she said.') #被单引号包含的单引号需要进行转义,不是用print函数打印时'"Isn\'t," she said.'
s = 'First line.\nSecond line.'
print(s) # 使用print打印\n会被转义换行 ,使用命令行是\n不会被转义 First line.\nSecond line.
print("----")
print('C:\some\name') # 这里 \n 会被转义
print(r'C:\some\name' ) # 声明 r' 后面的字符串不会被转义
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
# """...""" or '''...''' 相当于html中p标签的作用,允许多行,排列格式
# 不加\ : 空一行
print(3 * 'un' + 'ium') # 字符串可以跟数字进行相乘
print('Py' 'thon') # Python ,在同一个print方法中,用多个空格隔开,最终会拼接成一个
prefix = 'Py'
#prefix 'thon' #不能连接变量和字符串文字
#print(('un' * 3)* 'ium')
print(prefix + 'thon') # 字符串用+ 进行拼接
text = ('Put several strings within parentheses to have them joined together.')
print(text)
word = 'Python'
print(word[0]) # 字符串也可以当成数组来取值
print(word[5])
print(word[-1]) # 截取最后一个字符
print(word[-2]) # 截取最后第二个字符
print(word[-6]) # 截取最后第六个字符
print(word[0:2]) # 从第一个字符所在索引截取2个字符
print(word[2:5]) # 从第三个字符所在索引截取5个字符
print(word[:2] + word[2:]) # s[:i] + s[i:] = s ,不管i为某个整数
print(word[:4] + word[4:])
print(word[:70] + word[70:])
print(word[:2]) # 从第一个字符开始取2个 字符
print(word[4:]) # 从第四个字符取到最后的 字符
print(word[-2:]) # 从最后第二个字符取到最后的 字符
print("---------");
# +---+---+---+---+---+---+
# | P | y | t | h | o | n |
# +---+---+---+---+---+---+
# 0 1 2 3 4 5 6
# -6 -5 -4 -3 -2 -1
print( word[4:42]) #从第四个字符取到最后的 字符
print(word[42:]) #从第42个字符取到最后的字符 空
# word[0] = 'J'
# word[2:] = 'py' 不允许修改字符串
print('J' + word[1:]) #可以重新拼接新字符串
print(word[:2] + 'py')
s = 'supercalifragilisticexpialidocious'
print(len(s)) # 获取字符串的长度 | # n # n 没有定义 NameError: name 'n' is not defined
print(4 * 3.75 - 1) | random_line_split |
models.py | from django.db import models
from django.conf import settings
from django.contrib.auth.models import User, Group |
DEFAULT_STORE_SLUG = getattr(settings, 'DEFAULT_STORE_SLUG', 'public')
class Store(models.Model):
slug = models.SlugField(primary_key=True)
name = models.CharField(max_length=128)
query_endpoint = models.URLField()
update_endpoint = models.URLField(null=True, blank=True)
graph_store_endpoint = models.URLField(null=True, blank=True)
def __unicode__(self):
return self.name
def query(self, *args, **kwargs):
return Endpoint(self.query_endpoint).query(*args, **kwargs)
class Meta:
permissions = (('administer_store', 'can administer'),
('query_store', 'can query'),
('update_store', 'can update'))
class UserPrivileges(models.Model):
user = models.ForeignKey(User, null=True, blank=True)
group = models.ForeignKey(Group, null=True, blank=True)
allow_concurrent_queries = models.BooleanField()
disable_throttle = models.BooleanField()
throttle_threshold = models.FloatField(null=True, blank=True)
deny_threshold = models.FloatField(null=True, blank=True)
intensity_decay = models.FloatField(null=True, blank=True)
disable_timeout = models.BooleanField()
maximum_timeout = models.IntegerField(null=True) |
from .endpoint import Endpoint | random_line_split |
models.py | from django.db import models
from django.conf import settings
from django.contrib.auth.models import User, Group
from .endpoint import Endpoint
DEFAULT_STORE_SLUG = getattr(settings, 'DEFAULT_STORE_SLUG', 'public')
class Store(models.Model):
slug = models.SlugField(primary_key=True)
name = models.CharField(max_length=128)
query_endpoint = models.URLField()
update_endpoint = models.URLField(null=True, blank=True)
graph_store_endpoint = models.URLField(null=True, blank=True)
def __unicode__(self):
return self.name
def | (self, *args, **kwargs):
return Endpoint(self.query_endpoint).query(*args, **kwargs)
class Meta:
permissions = (('administer_store', 'can administer'),
('query_store', 'can query'),
('update_store', 'can update'))
class UserPrivileges(models.Model):
user = models.ForeignKey(User, null=True, blank=True)
group = models.ForeignKey(Group, null=True, blank=True)
allow_concurrent_queries = models.BooleanField()
disable_throttle = models.BooleanField()
throttle_threshold = models.FloatField(null=True, blank=True)
deny_threshold = models.FloatField(null=True, blank=True)
intensity_decay = models.FloatField(null=True, blank=True)
disable_timeout = models.BooleanField()
maximum_timeout = models.IntegerField(null=True)
| query | identifier_name |
models.py | from django.db import models
from django.conf import settings
from django.contrib.auth.models import User, Group
from .endpoint import Endpoint
DEFAULT_STORE_SLUG = getattr(settings, 'DEFAULT_STORE_SLUG', 'public')
class Store(models.Model):
slug = models.SlugField(primary_key=True)
name = models.CharField(max_length=128)
query_endpoint = models.URLField()
update_endpoint = models.URLField(null=True, blank=True)
graph_store_endpoint = models.URLField(null=True, blank=True)
def __unicode__(self):
return self.name
def query(self, *args, **kwargs):
return Endpoint(self.query_endpoint).query(*args, **kwargs)
class Meta:
permissions = (('administer_store', 'can administer'),
('query_store', 'can query'),
('update_store', 'can update'))
class UserPrivileges(models.Model):
| user = models.ForeignKey(User, null=True, blank=True)
group = models.ForeignKey(Group, null=True, blank=True)
allow_concurrent_queries = models.BooleanField()
disable_throttle = models.BooleanField()
throttle_threshold = models.FloatField(null=True, blank=True)
deny_threshold = models.FloatField(null=True, blank=True)
intensity_decay = models.FloatField(null=True, blank=True)
disable_timeout = models.BooleanField()
maximum_timeout = models.IntegerField(null=True) | identifier_body |
|
extract_symbols.py | #!/usr/bin/env python
# Copyright (c) 2014, Bo Tian <[email protected]>
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
# 3. Neither the name of the copyright holder 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.
import sys
def main():
args = sys.argv
print str(args)
extract_symbols(args[1], args[2])
def extract_symbols(input_file, output_file):
fin = open(input_file, 'r')
fout = open(output_file, 'w')
for line in fin:
if '|' in line:
cols = line.split('|')
if not '$' in cols[1]: # Skip preferred shares, warrant etc.
|
fin.close()
fout.close()
if __name__ == "__main__":
main()
| symbol = cols[1].replace('.', '-') # e.g., BRK.B -> BRK-B for Yahoo finance.
fout.write(symbol + '\n') | conditional_block |
extract_symbols.py | #!/usr/bin/env python
# Copyright (c) 2014, Bo Tian <[email protected]>
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
# 3. Neither the name of the copyright holder 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.
import sys
def main():
|
def extract_symbols(input_file, output_file):
fin = open(input_file, 'r')
fout = open(output_file, 'w')
for line in fin:
if '|' in line:
cols = line.split('|')
if not '$' in cols[1]: # Skip preferred shares, warrant etc.
symbol = cols[1].replace('.', '-') # e.g., BRK.B -> BRK-B for Yahoo finance.
fout.write(symbol + '\n')
fin.close()
fout.close()
if __name__ == "__main__":
main()
| args = sys.argv
print str(args)
extract_symbols(args[1], args[2]) | identifier_body |
extract_symbols.py | #!/usr/bin/env python
# Copyright (c) 2014, Bo Tian <[email protected]>
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
# 3. Neither the name of the copyright holder 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.
import sys
def main():
args = sys.argv
print str(args)
extract_symbols(args[1], args[2])
def | (input_file, output_file):
fin = open(input_file, 'r')
fout = open(output_file, 'w')
for line in fin:
if '|' in line:
cols = line.split('|')
if not '$' in cols[1]: # Skip preferred shares, warrant etc.
symbol = cols[1].replace('.', '-') # e.g., BRK.B -> BRK-B for Yahoo finance.
fout.write(symbol + '\n')
fin.close()
fout.close()
if __name__ == "__main__":
main()
| extract_symbols | identifier_name |
extract_symbols.py | #!/usr/bin/env python
# Copyright (c) 2014, Bo Tian <[email protected]>
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
# 3. Neither the name of the copyright holder 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 | # 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.
import sys
def main():
args = sys.argv
print str(args)
extract_symbols(args[1], args[2])
def extract_symbols(input_file, output_file):
fin = open(input_file, 'r')
fout = open(output_file, 'w')
for line in fin:
if '|' in line:
cols = line.split('|')
if not '$' in cols[1]: # Skip preferred shares, warrant etc.
symbol = cols[1].replace('.', '-') # e.g., BRK.B -> BRK-B for Yahoo finance.
fout.write(symbol + '\n')
fin.close()
fout.close()
if __name__ == "__main__":
main() | # 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, | random_line_split |
query_string.py | import urllib
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.tag
def query_string(parser, token):
"""
Allows to manipulate the query string of a page by adding and removing keywords.
If a given value is a context variable it will resolve it.
Usage:
http://www.url.com/{% query_string "param_to_add=value, param_to_add=value" "param_to_remove, params_to_remove" %}
"""
try:
tag_name, add_string, remove_string = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires two arguments" % token.contents.split()[0]
if not (add_string[0] == add_string[-1] and add_string[0] in ('"', "'")) or not (remove_string[0] == remove_string[-1] and remove_string[0] in ('"', "'")):
raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
add = string_to_dict(add_string[1:-1])
remove = string_to_list(remove_string[1:-1])
return QueryStringNode(add, remove)
class QueryStringNode(template.Node):
def | (self, add, remove):
self.add = add
self.remove = remove
def render(self, context):
p = {}
for k, v in context["request"].GET.items():
p[k] = v
return get_query_string(p, self.add, self.remove, context)
def get_query_string(p, new_params, remove, context):
"""
Add and remove query parameters. From `django.contrib.admin`.
"""
for r in remove:
for k in p.keys():
if k.startswith(r):
del p[k]
for k, v in new_params.items():
if k in p and v is None:
del p[k]
elif v is not None:
p[k] = v
for k, v in p.items():
try:
p[k] = template.Variable(v).resolve(context)
except:
p[k] = v
return mark_safe('?' + '&'.join([u'%s=%s' % (urllib.quote_plus(str(k)), urllib.quote_plus(str(v))) for k, v in p.items()]))
# Taken from lib/utils.py
def string_to_dict(string):
kwargs = {}
if string:
string = str(string)
if ',' not in string:
# ensure at least one ','
string += ','
for arg in string.split(','):
arg = arg.strip()
if arg == '':
continue
kw, val = arg.split('=', 1)
kwargs[kw] = val
return kwargs
def string_to_list(string):
args = []
if string:
string = str(string)
if ',' not in string:
# ensure at least one ','
string += ','
for arg in string.split(','):
arg = arg.strip()
if arg == '':
continue
args.append(arg)
return args
| __init__ | identifier_name |
query_string.py | import urllib
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.tag
def query_string(parser, token):
"""
Allows to manipulate the query string of a page by adding and removing keywords.
If a given value is a context variable it will resolve it.
Usage:
http://www.url.com/{% query_string "param_to_add=value, param_to_add=value" "param_to_remove, params_to_remove" %}
"""
try:
tag_name, add_string, remove_string = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires two arguments" % token.contents.split()[0]
if not (add_string[0] == add_string[-1] and add_string[0] in ('"', "'")) or not (remove_string[0] == remove_string[-1] and remove_string[0] in ('"', "'")):
raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
add = string_to_dict(add_string[1:-1])
remove = string_to_list(remove_string[1:-1])
return QueryStringNode(add, remove)
class QueryStringNode(template.Node):
def __init__(self, add, remove):
self.add = add
self.remove = remove
def render(self, context):
p = {}
for k, v in context["request"].GET.items():
p[k] = v
return get_query_string(p, self.add, self.remove, context)
def get_query_string(p, new_params, remove, context):
"""
Add and remove query parameters. From `django.contrib.admin`.
"""
for r in remove:
for k in p.keys():
if k.startswith(r):
del p[k]
for k, v in new_params.items():
if k in p and v is None:
del p[k]
elif v is not None:
p[k] = v
for k, v in p.items():
try:
p[k] = template.Variable(v).resolve(context)
except:
p[k] = v
return mark_safe('?' + '&'.join([u'%s=%s' % (urllib.quote_plus(str(k)), urllib.quote_plus(str(v))) for k, v in p.items()]))
# Taken from lib/utils.py
def string_to_dict(string): |
if string:
string = str(string)
if ',' not in string:
# ensure at least one ','
string += ','
for arg in string.split(','):
arg = arg.strip()
if arg == '':
continue
kw, val = arg.split('=', 1)
kwargs[kw] = val
return kwargs
def string_to_list(string):
args = []
if string:
string = str(string)
if ',' not in string:
# ensure at least one ','
string += ','
for arg in string.split(','):
arg = arg.strip()
if arg == '':
continue
args.append(arg)
return args | kwargs = {} | random_line_split |
query_string.py | import urllib
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.tag
def query_string(parser, token):
"""
Allows to manipulate the query string of a page by adding and removing keywords.
If a given value is a context variable it will resolve it.
Usage:
http://www.url.com/{% query_string "param_to_add=value, param_to_add=value" "param_to_remove, params_to_remove" %}
"""
try:
tag_name, add_string, remove_string = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires two arguments" % token.contents.split()[0]
if not (add_string[0] == add_string[-1] and add_string[0] in ('"', "'")) or not (remove_string[0] == remove_string[-1] and remove_string[0] in ('"', "'")):
raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
add = string_to_dict(add_string[1:-1])
remove = string_to_list(remove_string[1:-1])
return QueryStringNode(add, remove)
class QueryStringNode(template.Node):
def __init__(self, add, remove):
self.add = add
self.remove = remove
def render(self, context):
p = {}
for k, v in context["request"].GET.items():
p[k] = v
return get_query_string(p, self.add, self.remove, context)
def get_query_string(p, new_params, remove, context):
"""
Add and remove query parameters. From `django.contrib.admin`.
"""
for r in remove:
for k in p.keys():
if k.startswith(r):
|
for k, v in new_params.items():
if k in p and v is None:
del p[k]
elif v is not None:
p[k] = v
for k, v in p.items():
try:
p[k] = template.Variable(v).resolve(context)
except:
p[k] = v
return mark_safe('?' + '&'.join([u'%s=%s' % (urllib.quote_plus(str(k)), urllib.quote_plus(str(v))) for k, v in p.items()]))
# Taken from lib/utils.py
def string_to_dict(string):
kwargs = {}
if string:
string = str(string)
if ',' not in string:
# ensure at least one ','
string += ','
for arg in string.split(','):
arg = arg.strip()
if arg == '':
continue
kw, val = arg.split('=', 1)
kwargs[kw] = val
return kwargs
def string_to_list(string):
args = []
if string:
string = str(string)
if ',' not in string:
# ensure at least one ','
string += ','
for arg in string.split(','):
arg = arg.strip()
if arg == '':
continue
args.append(arg)
return args
| del p[k] | conditional_block |
query_string.py | import urllib
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.tag
def query_string(parser, token):
"""
Allows to manipulate the query string of a page by adding and removing keywords.
If a given value is a context variable it will resolve it.
Usage:
http://www.url.com/{% query_string "param_to_add=value, param_to_add=value" "param_to_remove, params_to_remove" %}
"""
try:
tag_name, add_string, remove_string = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires two arguments" % token.contents.split()[0]
if not (add_string[0] == add_string[-1] and add_string[0] in ('"', "'")) or not (remove_string[0] == remove_string[-1] and remove_string[0] in ('"', "'")):
raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
add = string_to_dict(add_string[1:-1])
remove = string_to_list(remove_string[1:-1])
return QueryStringNode(add, remove)
class QueryStringNode(template.Node):
def __init__(self, add, remove):
|
def render(self, context):
p = {}
for k, v in context["request"].GET.items():
p[k] = v
return get_query_string(p, self.add, self.remove, context)
def get_query_string(p, new_params, remove, context):
"""
Add and remove query parameters. From `django.contrib.admin`.
"""
for r in remove:
for k in p.keys():
if k.startswith(r):
del p[k]
for k, v in new_params.items():
if k in p and v is None:
del p[k]
elif v is not None:
p[k] = v
for k, v in p.items():
try:
p[k] = template.Variable(v).resolve(context)
except:
p[k] = v
return mark_safe('?' + '&'.join([u'%s=%s' % (urllib.quote_plus(str(k)), urllib.quote_plus(str(v))) for k, v in p.items()]))
# Taken from lib/utils.py
def string_to_dict(string):
kwargs = {}
if string:
string = str(string)
if ',' not in string:
# ensure at least one ','
string += ','
for arg in string.split(','):
arg = arg.strip()
if arg == '':
continue
kw, val = arg.split('=', 1)
kwargs[kw] = val
return kwargs
def string_to_list(string):
args = []
if string:
string = str(string)
if ',' not in string:
# ensure at least one ','
string += ','
for arg in string.split(','):
arg = arg.strip()
if arg == '':
continue
args.append(arg)
return args
| self.add = add
self.remove = remove | identifier_body |
extern-return-TwoU32s.rs | // Copyright 2012 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.
// pretty-expanded FIXME #23616
pub struct TwoU32s {
one: u32, two: u32
}
#[link(name = "rust_test_helpers")]
extern { | }
pub fn main() {
unsafe {
let y = rust_dbg_extern_return_TwoU32s();
assert_eq!(y.one, 10);
assert_eq!(y.two, 20);
}
} | pub fn rust_dbg_extern_return_TwoU32s() -> TwoU32s; | random_line_split |
extern-return-TwoU32s.rs | // Copyright 2012 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.
// pretty-expanded FIXME #23616
pub struct | {
one: u32, two: u32
}
#[link(name = "rust_test_helpers")]
extern {
pub fn rust_dbg_extern_return_TwoU32s() -> TwoU32s;
}
pub fn main() {
unsafe {
let y = rust_dbg_extern_return_TwoU32s();
assert_eq!(y.one, 10);
assert_eq!(y.two, 20);
}
}
| TwoU32s | identifier_name |
htmlselectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods;
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods;
use dom::bindings::codegen::UnionTypes::HTMLElementOrLong;
use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlelement::HTMLElement;
use dom::htmlfieldsetelement::HTMLFieldSetElement;
use dom::htmlformelement::{FormDatumValue, FormControl, FormDatum, HTMLFormElement};
use dom::htmloptionelement::HTMLOptionElement;
use dom::node::{Node, UnbindContext, window_from_node};
use dom::nodelist::NodeList;
use dom::validation::Validatable;
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use string_cache::Atom;
use style::attr::AttrValue;
use style::element_state::*;
#[dom_struct]
pub struct HTMLSelectElement {
htmlelement: HTMLElement
}
static DEFAULT_SELECT_SIZE: u32 = 0;
impl HTMLSelectElement {
fn new_inherited(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLSelectElement {
HTMLSelectElement {
htmlelement:
HTMLElement::new_inherited_with_state(IN_ENABLED_STATE,
localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLSelectElement> {
let element = HTMLSelectElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap)
}
// https://html.spec.whatwg.org/multipage/#ask-for-a-reset
pub fn ask_for_reset(&self) {
if self.Multiple() {
return;
}
let mut first_enabled: Option<Root<HTMLOptionElement>> = None;
let mut last_selected: Option<Root<HTMLOptionElement>> = None;
let node = self.upcast::<Node>();
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) {
if opt.Selected() {
opt.set_selectedness(false);
last_selected = Some(Root::from_ref(opt.r()));
}
let element = opt.upcast::<Element>();
if first_enabled.is_none() && !element.disabled_state() {
first_enabled = Some(Root::from_ref(opt.r()));
}
}
if let Some(last_selected) = last_selected {
last_selected.set_selectedness(true);
} else {
if self.display_size() == 1 {
if let Some(first_enabled) = first_enabled {
first_enabled.set_selectedness(true);
}
}
}
}
pub fn push_form_data(&self, data_set: &mut Vec<FormDatum>) {
let node = self.upcast::<Node>();
if self.Name().is_empty() {
return;
}
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) {
let element = opt.upcast::<Element>();
if opt.Selected() && element.enabled_state() {
data_set.push(FormDatum {
ty: self.Type(),
name: self.Name(),
value: FormDatumValue::String(opt.Value())
});
}
}
}
// https://html.spec.whatwg.org/multipage/#concept-select-pick
pub fn pick_option(&self, picked: &HTMLOptionElement) {
if !self.Multiple() {
let node = self.upcast::<Node>();
let picked = picked.upcast();
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) {
if opt.upcast::<HTMLElement>() != picked {
opt.set_selectedness(false);
}
}
}
}
// https://html.spec.whatwg.org/multipage/#concept-select-size
fn display_size(&self) -> u32 {
if self.Size() == 0 {
if self.Multiple() {
4
} else {
1
}
} else {
self.Size()
}
}
}
impl HTMLSelectElementMethods for HTMLSelectElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> |
// Note: this function currently only exists for union.html.
// https://html.spec.whatwg.org/multipage/#dom-select-add
fn Add(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) {
}
// https://html.spec.whatwg.org/multipage/#dom-fe-disabled
make_bool_getter!(Disabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fe-disabled
make_bool_setter!(SetDisabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn GetForm(&self) -> Option<Root<HTMLFormElement>> {
self.form_owner()
}
// https://html.spec.whatwg.org/multipage/#dom-select-multiple
make_bool_getter!(Multiple, "multiple");
// https://html.spec.whatwg.org/multipage/#dom-select-multiple
make_bool_setter!(SetMultiple, "multiple");
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_getter!(Name, "name");
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_setter!(SetName, "name");
// https://html.spec.whatwg.org/multipage/#dom-select-size
make_uint_getter!(Size, "size", DEFAULT_SELECT_SIZE);
// https://html.spec.whatwg.org/multipage/#dom-select-size
make_uint_setter!(SetSize, "size", DEFAULT_SELECT_SIZE);
// https://html.spec.whatwg.org/multipage/#dom-select-type
fn Type(&self) -> DOMString {
DOMString::from(if self.Multiple() {
"select-multiple"
} else {
"select-one"
})
}
// https://html.spec.whatwg.org/multipage/#dom-lfe-labels
fn Labels(&self) -> Root<NodeList> {
self.upcast::<HTMLElement>().labels()
}
}
impl VirtualMethods for HTMLSelectElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
if attr.local_name() == &atom!("disabled") {
let el = self.upcast::<Element>();
match mutation {
AttributeMutation::Set(_) => {
el.set_disabled_state(true);
el.set_enabled_state(false);
},
AttributeMutation::Removed => {
el.set_disabled_state(false);
el.set_enabled_state(true);
el.check_ancestors_disabled_state_for_form_control();
}
}
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
self.upcast::<Element>().check_ancestors_disabled_state_for_form_control();
}
fn unbind_from_tree(&self, context: &UnbindContext) {
self.super_type().unwrap().unbind_from_tree(context);
let node = self.upcast::<Node>();
let el = self.upcast::<Element>();
if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) {
el.check_ancestors_disabled_state_for_form_control();
} else {
el.check_disabled_attribute();
}
}
fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue {
match *local_name {
atom!("size") => AttrValue::from_u32(value.into(), DEFAULT_SELECT_SIZE),
_ => self.super_type().unwrap().parse_plain_attribute(local_name, value),
}
}
}
impl FormControl for HTMLSelectElement {}
impl Validatable for HTMLSelectElement {}
| {
let window = window_from_node(self);
ValidityState::new(window.r(), self.upcast())
} | identifier_body |
htmlselectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods;
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods;
use dom::bindings::codegen::UnionTypes::HTMLElementOrLong;
use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlelement::HTMLElement;
use dom::htmlfieldsetelement::HTMLFieldSetElement;
use dom::htmlformelement::{FormDatumValue, FormControl, FormDatum, HTMLFormElement};
use dom::htmloptionelement::HTMLOptionElement;
use dom::node::{Node, UnbindContext, window_from_node};
use dom::nodelist::NodeList;
use dom::validation::Validatable;
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use string_cache::Atom;
use style::attr::AttrValue;
use style::element_state::*;
#[dom_struct]
pub struct HTMLSelectElement {
htmlelement: HTMLElement
}
static DEFAULT_SELECT_SIZE: u32 = 0;
impl HTMLSelectElement {
fn new_inherited(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLSelectElement {
HTMLSelectElement {
htmlelement:
HTMLElement::new_inherited_with_state(IN_ENABLED_STATE,
localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLSelectElement> {
let element = HTMLSelectElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap)
}
// https://html.spec.whatwg.org/multipage/#ask-for-a-reset
pub fn ask_for_reset(&self) {
if self.Multiple() {
return;
}
let mut first_enabled: Option<Root<HTMLOptionElement>> = None;
let mut last_selected: Option<Root<HTMLOptionElement>> = None;
let node = self.upcast::<Node>();
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) {
if opt.Selected() {
opt.set_selectedness(false);
last_selected = Some(Root::from_ref(opt.r()));
}
let element = opt.upcast::<Element>();
if first_enabled.is_none() && !element.disabled_state() {
first_enabled = Some(Root::from_ref(opt.r()));
}
}
if let Some(last_selected) = last_selected {
last_selected.set_selectedness(true);
} else {
if self.display_size() == 1 {
if let Some(first_enabled) = first_enabled {
first_enabled.set_selectedness(true);
}
}
}
}
pub fn push_form_data(&self, data_set: &mut Vec<FormDatum>) {
let node = self.upcast::<Node>();
if self.Name().is_empty() {
return;
}
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) {
let element = opt.upcast::<Element>();
if opt.Selected() && element.enabled_state() {
data_set.push(FormDatum {
ty: self.Type(),
name: self.Name(),
value: FormDatumValue::String(opt.Value())
});
}
}
}
// https://html.spec.whatwg.org/multipage/#concept-select-pick
pub fn pick_option(&self, picked: &HTMLOptionElement) {
if !self.Multiple() {
let node = self.upcast::<Node>();
let picked = picked.upcast();
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) {
if opt.upcast::<HTMLElement>() != picked {
opt.set_selectedness(false);
}
}
}
}
// https://html.spec.whatwg.org/multipage/#concept-select-size
fn display_size(&self) -> u32 {
if self.Size() == 0 {
if self.Multiple() {
4
} else {
1
}
} else {
self.Size()
}
}
}
impl HTMLSelectElementMethods for HTMLSelectElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r(), self.upcast())
}
// Note: this function currently only exists for union.html.
// https://html.spec.whatwg.org/multipage/#dom-select-add
fn Add(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) {
}
// https://html.spec.whatwg.org/multipage/#dom-fe-disabled
make_bool_getter!(Disabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fe-disabled
make_bool_setter!(SetDisabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn GetForm(&self) -> Option<Root<HTMLFormElement>> {
self.form_owner()
}
// https://html.spec.whatwg.org/multipage/#dom-select-multiple
make_bool_getter!(Multiple, "multiple");
// https://html.spec.whatwg.org/multipage/#dom-select-multiple
make_bool_setter!(SetMultiple, "multiple");
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_getter!(Name, "name");
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_setter!(SetName, "name");
// https://html.spec.whatwg.org/multipage/#dom-select-size
make_uint_getter!(Size, "size", DEFAULT_SELECT_SIZE);
// https://html.spec.whatwg.org/multipage/#dom-select-size
make_uint_setter!(SetSize, "size", DEFAULT_SELECT_SIZE);
// https://html.spec.whatwg.org/multipage/#dom-select-type
fn Type(&self) -> DOMString {
DOMString::from(if self.Multiple() {
"select-multiple"
} else {
"select-one"
})
}
// https://html.spec.whatwg.org/multipage/#dom-lfe-labels
fn Labels(&self) -> Root<NodeList> {
self.upcast::<HTMLElement>().labels()
}
}
impl VirtualMethods for HTMLSelectElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
if attr.local_name() == &atom!("disabled") {
let el = self.upcast::<Element>();
match mutation {
AttributeMutation::Set(_) => {
el.set_disabled_state(true);
el.set_enabled_state(false);
},
AttributeMutation::Removed => {
el.set_disabled_state(false);
el.set_enabled_state(true);
el.check_ancestors_disabled_state_for_form_control();
}
}
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
self.upcast::<Element>().check_ancestors_disabled_state_for_form_control();
}
fn unbind_from_tree(&self, context: &UnbindContext) {
self.super_type().unwrap().unbind_from_tree(context);
let node = self.upcast::<Node>();
let el = self.upcast::<Element>();
if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) | else {
el.check_disabled_attribute();
}
}
fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue {
match *local_name {
atom!("size") => AttrValue::from_u32(value.into(), DEFAULT_SELECT_SIZE),
_ => self.super_type().unwrap().parse_plain_attribute(local_name, value),
}
}
}
impl FormControl for HTMLSelectElement {}
impl Validatable for HTMLSelectElement {}
| {
el.check_ancestors_disabled_state_for_form_control();
} | conditional_block |
htmlselectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods;
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods;
use dom::bindings::codegen::UnionTypes::HTMLElementOrLong;
use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlelement::HTMLElement;
use dom::htmlfieldsetelement::HTMLFieldSetElement;
use dom::htmlformelement::{FormDatumValue, FormControl, FormDatum, HTMLFormElement};
use dom::htmloptionelement::HTMLOptionElement;
use dom::node::{Node, UnbindContext, window_from_node};
use dom::nodelist::NodeList;
use dom::validation::Validatable;
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use string_cache::Atom;
use style::attr::AttrValue;
use style::element_state::*;
#[dom_struct]
pub struct HTMLSelectElement {
htmlelement: HTMLElement
}
static DEFAULT_SELECT_SIZE: u32 = 0;
impl HTMLSelectElement {
fn new_inherited(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLSelectElement {
HTMLSelectElement {
htmlelement:
HTMLElement::new_inherited_with_state(IN_ENABLED_STATE,
localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLSelectElement> {
let element = HTMLSelectElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap)
}
// https://html.spec.whatwg.org/multipage/#ask-for-a-reset
pub fn ask_for_reset(&self) {
if self.Multiple() {
return;
}
let mut first_enabled: Option<Root<HTMLOptionElement>> = None;
let mut last_selected: Option<Root<HTMLOptionElement>> = None;
let node = self.upcast::<Node>();
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) {
if opt.Selected() {
opt.set_selectedness(false);
last_selected = Some(Root::from_ref(opt.r()));
}
let element = opt.upcast::<Element>();
if first_enabled.is_none() && !element.disabled_state() {
first_enabled = Some(Root::from_ref(opt.r()));
}
}
if let Some(last_selected) = last_selected {
last_selected.set_selectedness(true);
} else {
if self.display_size() == 1 {
if let Some(first_enabled) = first_enabled {
first_enabled.set_selectedness(true);
}
}
}
}
pub fn push_form_data(&self, data_set: &mut Vec<FormDatum>) {
let node = self.upcast::<Node>();
if self.Name().is_empty() {
return;
}
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) {
let element = opt.upcast::<Element>();
if opt.Selected() && element.enabled_state() {
data_set.push(FormDatum {
ty: self.Type(),
name: self.Name(),
value: FormDatumValue::String(opt.Value())
});
}
}
}
// https://html.spec.whatwg.org/multipage/#concept-select-pick
pub fn pick_option(&self, picked: &HTMLOptionElement) {
if !self.Multiple() {
let node = self.upcast::<Node>();
let picked = picked.upcast();
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) {
if opt.upcast::<HTMLElement>() != picked {
opt.set_selectedness(false);
}
}
}
}
// https://html.spec.whatwg.org/multipage/#concept-select-size
fn display_size(&self) -> u32 {
if self.Size() == 0 {
if self.Multiple() {
4
} else {
1
}
} else {
self.Size()
}
}
}
impl HTMLSelectElementMethods for HTMLSelectElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r(), self.upcast())
}
| fn Add(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) {
}
// https://html.spec.whatwg.org/multipage/#dom-fe-disabled
make_bool_getter!(Disabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fe-disabled
make_bool_setter!(SetDisabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn GetForm(&self) -> Option<Root<HTMLFormElement>> {
self.form_owner()
}
// https://html.spec.whatwg.org/multipage/#dom-select-multiple
make_bool_getter!(Multiple, "multiple");
// https://html.spec.whatwg.org/multipage/#dom-select-multiple
make_bool_setter!(SetMultiple, "multiple");
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_getter!(Name, "name");
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_setter!(SetName, "name");
// https://html.spec.whatwg.org/multipage/#dom-select-size
make_uint_getter!(Size, "size", DEFAULT_SELECT_SIZE);
// https://html.spec.whatwg.org/multipage/#dom-select-size
make_uint_setter!(SetSize, "size", DEFAULT_SELECT_SIZE);
// https://html.spec.whatwg.org/multipage/#dom-select-type
fn Type(&self) -> DOMString {
DOMString::from(if self.Multiple() {
"select-multiple"
} else {
"select-one"
})
}
// https://html.spec.whatwg.org/multipage/#dom-lfe-labels
fn Labels(&self) -> Root<NodeList> {
self.upcast::<HTMLElement>().labels()
}
}
impl VirtualMethods for HTMLSelectElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
if attr.local_name() == &atom!("disabled") {
let el = self.upcast::<Element>();
match mutation {
AttributeMutation::Set(_) => {
el.set_disabled_state(true);
el.set_enabled_state(false);
},
AttributeMutation::Removed => {
el.set_disabled_state(false);
el.set_enabled_state(true);
el.check_ancestors_disabled_state_for_form_control();
}
}
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
self.upcast::<Element>().check_ancestors_disabled_state_for_form_control();
}
fn unbind_from_tree(&self, context: &UnbindContext) {
self.super_type().unwrap().unbind_from_tree(context);
let node = self.upcast::<Node>();
let el = self.upcast::<Element>();
if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) {
el.check_ancestors_disabled_state_for_form_control();
} else {
el.check_disabled_attribute();
}
}
fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue {
match *local_name {
atom!("size") => AttrValue::from_u32(value.into(), DEFAULT_SELECT_SIZE),
_ => self.super_type().unwrap().parse_plain_attribute(local_name, value),
}
}
}
impl FormControl for HTMLSelectElement {}
impl Validatable for HTMLSelectElement {} | // Note: this function currently only exists for union.html.
// https://html.spec.whatwg.org/multipage/#dom-select-add | random_line_split |
htmlselectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods;
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods;
use dom::bindings::codegen::UnionTypes::HTMLElementOrLong;
use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlelement::HTMLElement;
use dom::htmlfieldsetelement::HTMLFieldSetElement;
use dom::htmlformelement::{FormDatumValue, FormControl, FormDatum, HTMLFormElement};
use dom::htmloptionelement::HTMLOptionElement;
use dom::node::{Node, UnbindContext, window_from_node};
use dom::nodelist::NodeList;
use dom::validation::Validatable;
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use string_cache::Atom;
use style::attr::AttrValue;
use style::element_state::*;
#[dom_struct]
pub struct HTMLSelectElement {
htmlelement: HTMLElement
}
static DEFAULT_SELECT_SIZE: u32 = 0;
impl HTMLSelectElement {
fn new_inherited(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLSelectElement {
HTMLSelectElement {
htmlelement:
HTMLElement::new_inherited_with_state(IN_ENABLED_STATE,
localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLSelectElement> {
let element = HTMLSelectElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap)
}
// https://html.spec.whatwg.org/multipage/#ask-for-a-reset
pub fn ask_for_reset(&self) {
if self.Multiple() {
return;
}
let mut first_enabled: Option<Root<HTMLOptionElement>> = None;
let mut last_selected: Option<Root<HTMLOptionElement>> = None;
let node = self.upcast::<Node>();
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) {
if opt.Selected() {
opt.set_selectedness(false);
last_selected = Some(Root::from_ref(opt.r()));
}
let element = opt.upcast::<Element>();
if first_enabled.is_none() && !element.disabled_state() {
first_enabled = Some(Root::from_ref(opt.r()));
}
}
if let Some(last_selected) = last_selected {
last_selected.set_selectedness(true);
} else {
if self.display_size() == 1 {
if let Some(first_enabled) = first_enabled {
first_enabled.set_selectedness(true);
}
}
}
}
pub fn push_form_data(&self, data_set: &mut Vec<FormDatum>) {
let node = self.upcast::<Node>();
if self.Name().is_empty() {
return;
}
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) {
let element = opt.upcast::<Element>();
if opt.Selected() && element.enabled_state() {
data_set.push(FormDatum {
ty: self.Type(),
name: self.Name(),
value: FormDatumValue::String(opt.Value())
});
}
}
}
// https://html.spec.whatwg.org/multipage/#concept-select-pick
pub fn pick_option(&self, picked: &HTMLOptionElement) {
if !self.Multiple() {
let node = self.upcast::<Node>();
let picked = picked.upcast();
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) {
if opt.upcast::<HTMLElement>() != picked {
opt.set_selectedness(false);
}
}
}
}
// https://html.spec.whatwg.org/multipage/#concept-select-size
fn display_size(&self) -> u32 {
if self.Size() == 0 {
if self.Multiple() {
4
} else {
1
}
} else {
self.Size()
}
}
}
impl HTMLSelectElementMethods for HTMLSelectElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r(), self.upcast())
}
// Note: this function currently only exists for union.html.
// https://html.spec.whatwg.org/multipage/#dom-select-add
fn | (&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) {
}
// https://html.spec.whatwg.org/multipage/#dom-fe-disabled
make_bool_getter!(Disabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fe-disabled
make_bool_setter!(SetDisabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn GetForm(&self) -> Option<Root<HTMLFormElement>> {
self.form_owner()
}
// https://html.spec.whatwg.org/multipage/#dom-select-multiple
make_bool_getter!(Multiple, "multiple");
// https://html.spec.whatwg.org/multipage/#dom-select-multiple
make_bool_setter!(SetMultiple, "multiple");
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_getter!(Name, "name");
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_setter!(SetName, "name");
// https://html.spec.whatwg.org/multipage/#dom-select-size
make_uint_getter!(Size, "size", DEFAULT_SELECT_SIZE);
// https://html.spec.whatwg.org/multipage/#dom-select-size
make_uint_setter!(SetSize, "size", DEFAULT_SELECT_SIZE);
// https://html.spec.whatwg.org/multipage/#dom-select-type
fn Type(&self) -> DOMString {
DOMString::from(if self.Multiple() {
"select-multiple"
} else {
"select-one"
})
}
// https://html.spec.whatwg.org/multipage/#dom-lfe-labels
fn Labels(&self) -> Root<NodeList> {
self.upcast::<HTMLElement>().labels()
}
}
impl VirtualMethods for HTMLSelectElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
if attr.local_name() == &atom!("disabled") {
let el = self.upcast::<Element>();
match mutation {
AttributeMutation::Set(_) => {
el.set_disabled_state(true);
el.set_enabled_state(false);
},
AttributeMutation::Removed => {
el.set_disabled_state(false);
el.set_enabled_state(true);
el.check_ancestors_disabled_state_for_form_control();
}
}
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
self.upcast::<Element>().check_ancestors_disabled_state_for_form_control();
}
fn unbind_from_tree(&self, context: &UnbindContext) {
self.super_type().unwrap().unbind_from_tree(context);
let node = self.upcast::<Node>();
let el = self.upcast::<Element>();
if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) {
el.check_ancestors_disabled_state_for_form_control();
} else {
el.check_disabled_attribute();
}
}
fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue {
match *local_name {
atom!("size") => AttrValue::from_u32(value.into(), DEFAULT_SELECT_SIZE),
_ => self.super_type().unwrap().parse_plain_attribute(local_name, value),
}
}
}
impl FormControl for HTMLSelectElement {}
impl Validatable for HTMLSelectElement {}
| Add | identifier_name |
qmp_basic_rhel6.py | 3. key is of type keytype
If any of these checks fails, error.TestFail is raised.
"""
fail_no_key(qmp_dict, key)
if not isinstance(qmp_dict[key], keytype):
raise error.TestFail("'%s' key is not of type '%s', it's '%s'" %
(key, keytype, type(qmp_dict[key])))
def check_key_is_dict(qmp_dict, key):
check_dict_key(qmp_dict, key, dict)
def check_key_is_list(qmp_dict, key):
check_dict_key(qmp_dict, key, list)
def check_key_is_str(qmp_dict, key):
check_dict_key(qmp_dict, key, unicode)
def check_str_key(qmp_dict, keyname, value=None):
check_dict_key(qmp_dict, keyname, unicode)
if value and value != qmp_dict[keyname]:
raise error.TestFail("'%s' key value '%s' should be '%s'" %
(keyname, str(qmp_dict[keyname]), str(value)))
def check_key_is_int(qmp_dict, key):
fail_no_key(qmp_dict, key)
try:
int(qmp_dict[key])
except Exception:
raise error.TestFail("'%s' key is not of type int, it's '%s'" %
(key, type(qmp_dict[key])))
def check_bool_key(qmp_dict, keyname, value=None):
check_dict_key(qmp_dict, keyname, bool)
if value and value != qmp_dict[keyname]:
raise error.TestFail("'%s' key value '%s' should be '%s'" %
(keyname, str(qmp_dict[keyname]), str(value)))
def check_success_resp(resp, empty=False):
"""
Check QMP OK response.
:param resp: QMP response
:param empty: if True, response should not contain data to return
"""
check_key_is_dict(resp, "return")
if empty and len(resp["return"]) > 0:
raise error.TestFail("success response is not empty ('%s')" %
str(resp))
def check_error_resp(resp, classname=None, datadict=None):
"""
Check QMP error response.
:param resp: QMP response
:param classname: Expected error class name
:param datadict: Expected error data dictionary
"""
logging.debug("resp %s", str(resp))
check_key_is_dict(resp, "error")
check_key_is_str(resp["error"], "class")
if classname and resp["error"]["class"] != classname:
raise error.TestFail("got error class '%s' expected '%s'" %
(resp["error"]["class"], classname))
check_key_is_dict(resp["error"], "data")
if datadict and resp["error"]["data"] != datadict:
raise error.TestFail("got data dict '%s' expected '%s'" %
(resp["error"]["data"], datadict))
def test_version(version):
"""
Check the QMP greeting message version key which, according to QMP's
documentation, should be:
{ "qemu": { "major": json-int, "minor": json-int, "micro": json-int }
"package": json-string }
"""
check_key_is_dict(version, "qemu")
check_key_is_str(version, "package")
def test_greeting(greeting):
check_key_is_dict(greeting, "QMP")
check_key_is_dict(greeting["QMP"], "version")
check_key_is_list(greeting["QMP"], "capabilities")
def greeting_suite(monitor):
"""
Check the greeting message format, as described in the QMP
specfication section '2.2 Server Greeting'.
{ "QMP": { "version": json-object, "capabilities": json-array } }
"""
greeting = monitor.get_greeting()
test_greeting(greeting)
test_version(greeting["QMP"]["version"])
def json_parsing_errors_suite(monitor):
"""
Check that QMP's parser is able to recover from parsing errors, please
check the JSON spec for more info on the JSON syntax (RFC 4627).
"""
# We're quite simple right now and the focus is on parsing errors that
# have already biten us in the past.
#
# TODO: The following test-cases are missing:
#
# - JSON numbers, strings and arrays
# - More invalid characters or malformed structures
# - Valid, but not obvious syntax, like zillion of spaces or
# strings with unicode chars (different suite maybe?)
bad_json = []
# A JSON value MUST be an object, array, number, string, true, false,
# or null
#
# NOTE: QMP seems to ignore a number of chars, like: | and ?
bad_json.append(":")
bad_json.append(",")
# Malformed json-objects
#
# NOTE: sending only "}" seems to break QMP
# NOTE: Duplicate keys are accepted (should it?)
bad_json.append("{ \"execute\" }")
bad_json.append("{ \"execute\": \"query-version\", }")
bad_json.append("{ 1: \"query-version\" }")
bad_json.append("{ true: \"query-version\" }")
bad_json.append("{ []: \"query-version\" }")
bad_json.append("{ {}: \"query-version\" }")
for cmd in bad_json:
resp = monitor.cmd_raw(cmd)
check_error_resp(resp, "JSONParsing")
def test_id_key(monitor):
"""
Check that QMP's "id" key is correctly handled.
"""
# The "id" key must be echoed back in error responses
id_key = "virt-test"
resp = monitor.cmd_qmp("eject", {"foobar": True}, q_id=id_key)
check_error_resp(resp)
check_str_key(resp, "id", id_key)
# The "id" key must be echoed back in success responses
resp = monitor.cmd_qmp("query-status", q_id=id_key)
check_success_resp(resp)
check_str_key(resp, "id", id_key)
# The "id" key can be any json-object
for id_key in (True, 1234, "string again!", [1, [], {}, True, "foo"],
{"key": {}}):
resp = monitor.cmd_qmp("query-status", q_id=id_key)
check_success_resp(resp)
if resp["id"] != id_key:
raise error.TestFail("expected id '%s' but got '%s'" %
(str(id_key), str(resp["id"])))
def test_invalid_arg_key(monitor):
"""
Currently, the only supported keys in the input object are: "execute",
"arguments" and "id". Although expansion is supported, invalid key
names must be detected.
"""
resp = monitor.cmd_obj({"execute": "eject", "foobar": True})
expected_error = "QMPExtraInputObjectMember"
data_dict = {"member": "foobar"}
check_error_resp(resp, expected_error, data_dict)
def test_bad_arguments_key_type(monitor):
"""
The "arguments" key must be an json-object.
We use the eject command to perform the tests, but that's a random
choice, any command that accepts arguments will do, as the command
doesn't get called.
"""
for item in (True, [], 1, "foo"):
resp = monitor.cmd_obj({"execute": "eject", "arguments": item})
check_error_resp(resp, "QMPBadInputObjectMember",
{"member": "arguments", "expected": "object"})
def test_bad_execute_key_type(monitor):
"""
The "execute" key must be a json-string.
"""
for item in (False, 1, {}, []):
resp = monitor.cmd_obj({"execute": item})
check_error_resp(resp, "QMPBadInputObjectMember",
{"member": "execute", "expected": "string"})
def test_no_execute_key(monitor):
"""
The "execute" key must exist, we also test for some stupid parsing
errors.
"""
for cmd in ({}, {"execut": "qmp_capabilities"},
{"executee": "qmp_capabilities"}, {"foo": "bar"}):
resp = monitor.cmd_obj(cmd)
check_error_resp(resp) # XXX: check class and data dict?
def test_bad_input_obj_type(monitor):
"""
The input object must be... an json-object.
"""
for cmd in ("foo", [], True, 1):
|
def test_good_input_obj(monitor):
"""
Basic success tests for issuing QMP commands.
"""
# NOTE: We don't use the cmd_qmp() method here because the command
# object is in a 'random' order
resp = monitor.cmd_obj({"execute": "query-version"})
check_success_resp(resp)
resp = monitor.cmd_obj({"arguments": {}, "execute": "query-version"})
check_success_resp(resp)
id_key = "1234foo"
resp = monitor.cmd_obj({"id": id_key, "execute": "query-version | resp = monitor.cmd_obj(cmd)
check_error_resp(resp, "QMPBadInputObject", {"expected": "object"}) | conditional_block |
qmp_basic_rhel6.py | 3. key is of type keytype
If any of these checks fails, error.TestFail is raised.
"""
fail_no_key(qmp_dict, key)
if not isinstance(qmp_dict[key], keytype):
raise error.TestFail("'%s' key is not of type '%s', it's '%s'" %
(key, keytype, type(qmp_dict[key])))
def check_key_is_dict(qmp_dict, key):
check_dict_key(qmp_dict, key, dict)
def check_key_is_list(qmp_dict, key):
check_dict_key(qmp_dict, key, list)
def check_key_is_str(qmp_dict, key):
check_dict_key(qmp_dict, key, unicode)
def check_str_key(qmp_dict, keyname, value=None):
check_dict_key(qmp_dict, keyname, unicode)
if value and value != qmp_dict[keyname]:
raise error.TestFail("'%s' key value '%s' should be '%s'" %
(keyname, str(qmp_dict[keyname]), str(value)))
def check_key_is_int(qmp_dict, key):
fail_no_key(qmp_dict, key)
try:
int(qmp_dict[key])
except Exception:
raise error.TestFail("'%s' key is not of type int, it's '%s'" %
(key, type(qmp_dict[key])))
def check_bool_key(qmp_dict, keyname, value=None):
check_dict_key(qmp_dict, keyname, bool)
if value and value != qmp_dict[keyname]:
raise error.TestFail("'%s' key value '%s' should be '%s'" %
(keyname, str(qmp_dict[keyname]), str(value)))
def check_success_resp(resp, empty=False):
"""
Check QMP OK response.
:param resp: QMP response
:param empty: if True, response should not contain data to return
"""
check_key_is_dict(resp, "return")
if empty and len(resp["return"]) > 0:
raise error.TestFail("success response is not empty ('%s')" %
str(resp))
def check_error_resp(resp, classname=None, datadict=None):
"""
Check QMP error response.
:param resp: QMP response
:param classname: Expected error class name
:param datadict: Expected error data dictionary
"""
logging.debug("resp %s", str(resp))
check_key_is_dict(resp, "error")
check_key_is_str(resp["error"], "class")
if classname and resp["error"]["class"] != classname:
raise error.TestFail("got error class '%s' expected '%s'" %
(resp["error"]["class"], classname))
check_key_is_dict(resp["error"], "data")
if datadict and resp["error"]["data"] != datadict:
raise error.TestFail("got data dict '%s' expected '%s'" %
(resp["error"]["data"], datadict))
def test_version(version):
"""
Check the QMP greeting message version key which, according to QMP's
documentation, should be:
{ "qemu": { "major": json-int, "minor": json-int, "micro": json-int }
"package": json-string }
"""
check_key_is_dict(version, "qemu")
check_key_is_str(version, "package")
def test_greeting(greeting):
check_key_is_dict(greeting, "QMP")
check_key_is_dict(greeting["QMP"], "version")
check_key_is_list(greeting["QMP"], "capabilities")
def greeting_suite(monitor):
"""
Check the greeting message format, as described in the QMP
specfication section '2.2 Server Greeting'.
{ "QMP": { "version": json-object, "capabilities": json-array } }
"""
greeting = monitor.get_greeting()
test_greeting(greeting)
test_version(greeting["QMP"]["version"])
def json_parsing_errors_suite(monitor):
"""
Check that QMP's parser is able to recover from parsing errors, please
check the JSON spec for more info on the JSON syntax (RFC 4627).
"""
# We're quite simple right now and the focus is on parsing errors that
# have already biten us in the past.
#
# TODO: The following test-cases are missing:
#
# - JSON numbers, strings and arrays
# - More invalid characters or malformed structures
# - Valid, but not obvious syntax, like zillion of spaces or
# strings with unicode chars (different suite maybe?)
bad_json = []
# A JSON value MUST be an object, array, number, string, true, false,
# or null
#
# NOTE: QMP seems to ignore a number of chars, like: | and ?
bad_json.append(":")
bad_json.append(",")
# Malformed json-objects
#
# NOTE: sending only "}" seems to break QMP
# NOTE: Duplicate keys are accepted (should it?)
bad_json.append("{ \"execute\" }")
bad_json.append("{ \"execute\": \"query-version\", }")
bad_json.append("{ 1: \"query-version\" }")
bad_json.append("{ true: \"query-version\" }")
bad_json.append("{ []: \"query-version\" }")
bad_json.append("{ {}: \"query-version\" }")
for cmd in bad_json:
resp = monitor.cmd_raw(cmd)
check_error_resp(resp, "JSONParsing")
def test_id_key(monitor):
"""
Check that QMP's "id" key is correctly handled.
"""
# The "id" key must be echoed back in error responses
id_key = "virt-test"
resp = monitor.cmd_qmp("eject", {"foobar": True}, q_id=id_key)
check_error_resp(resp)
check_str_key(resp, "id", id_key)
# The "id" key must be echoed back in success responses
resp = monitor.cmd_qmp("query-status", q_id=id_key)
check_success_resp(resp)
check_str_key(resp, "id", id_key)
# The "id" key can be any json-object
for id_key in (True, 1234, "string again!", [1, [], {}, True, "foo"],
{"key": {}}):
resp = monitor.cmd_qmp("query-status", q_id=id_key)
check_success_resp(resp)
if resp["id"] != id_key:
raise error.TestFail("expected id '%s' but got '%s'" %
(str(id_key), str(resp["id"])))
def test_invalid_arg_key(monitor):
"""
Currently, the only supported keys in the input object are: "execute",
"arguments" and "id". Although expansion is supported, invalid key
names must be detected.
"""
resp = monitor.cmd_obj({"execute": "eject", "foobar": True})
expected_error = "QMPExtraInputObjectMember"
data_dict = {"member": "foobar"}
check_error_resp(resp, expected_error, data_dict)
def test_bad_arguments_key_type(monitor):
"""
The "arguments" key must be an json-object.
We use the eject command to perform the tests, but that's a random | doesn't get called.
"""
for item in (True, [], 1, "foo"):
resp = monitor.cmd_obj({"execute": "eject", "arguments": item})
check_error_resp(resp, "QMPBadInputObjectMember",
{"member": "arguments", "expected": "object"})
def test_bad_execute_key_type(monitor):
"""
The "execute" key must be a json-string.
"""
for item in (False, 1, {}, []):
resp = monitor.cmd_obj({"execute": item})
check_error_resp(resp, "QMPBadInputObjectMember",
{"member": "execute", "expected": "string"})
def test_no_execute_key(monitor):
"""
The "execute" key must exist, we also test for some stupid parsing
errors.
"""
for cmd in ({}, {"execut": "qmp_capabilities"},
{"executee": "qmp_capabilities"}, {"foo": "bar"}):
resp = monitor.cmd_obj(cmd)
check_error_resp(resp) # XXX: check class and data dict?
def test_bad_input_obj_type(monitor):
"""
The input object must be... an json-object.
"""
for cmd in ("foo", [], True, 1):
resp = monitor.cmd_obj(cmd)
check_error_resp(resp, "QMPBadInputObject", {"expected": "object"})
def test_good_input_obj(monitor):
"""
Basic success tests for issuing QMP commands.
"""
# NOTE: We don't use the cmd_qmp() method here because the command
# object is in a 'random' order
resp = monitor.cmd_obj({"execute": "query-version"})
check_success_resp(resp)
resp = monitor.cmd_obj({"arguments": {}, "execute": "query-version"})
check_success_resp(resp)
id_key = "1234foo"
resp = monitor.cmd_obj({"id": id_key, "execute": "query-version",
| choice, any command that accepts arguments will do, as the command | random_line_split |
qmp_basic_rhel6.py | '%s' key is not of type '%s', it's '%s'" %
(key, keytype, type(qmp_dict[key])))
def check_key_is_dict(qmp_dict, key):
check_dict_key(qmp_dict, key, dict)
def check_key_is_list(qmp_dict, key):
check_dict_key(qmp_dict, key, list)
def check_key_is_str(qmp_dict, key):
check_dict_key(qmp_dict, key, unicode)
def check_str_key(qmp_dict, keyname, value=None):
check_dict_key(qmp_dict, keyname, unicode)
if value and value != qmp_dict[keyname]:
raise error.TestFail("'%s' key value '%s' should be '%s'" %
(keyname, str(qmp_dict[keyname]), str(value)))
def check_key_is_int(qmp_dict, key):
fail_no_key(qmp_dict, key)
try:
int(qmp_dict[key])
except Exception:
raise error.TestFail("'%s' key is not of type int, it's '%s'" %
(key, type(qmp_dict[key])))
def check_bool_key(qmp_dict, keyname, value=None):
check_dict_key(qmp_dict, keyname, bool)
if value and value != qmp_dict[keyname]:
raise error.TestFail("'%s' key value '%s' should be '%s'" %
(keyname, str(qmp_dict[keyname]), str(value)))
def check_success_resp(resp, empty=False):
"""
Check QMP OK response.
:param resp: QMP response
:param empty: if True, response should not contain data to return
"""
check_key_is_dict(resp, "return")
if empty and len(resp["return"]) > 0:
raise error.TestFail("success response is not empty ('%s')" %
str(resp))
def check_error_resp(resp, classname=None, datadict=None):
"""
Check QMP error response.
:param resp: QMP response
:param classname: Expected error class name
:param datadict: Expected error data dictionary
"""
logging.debug("resp %s", str(resp))
check_key_is_dict(resp, "error")
check_key_is_str(resp["error"], "class")
if classname and resp["error"]["class"] != classname:
raise error.TestFail("got error class '%s' expected '%s'" %
(resp["error"]["class"], classname))
check_key_is_dict(resp["error"], "data")
if datadict and resp["error"]["data"] != datadict:
raise error.TestFail("got data dict '%s' expected '%s'" %
(resp["error"]["data"], datadict))
def test_version(version):
"""
Check the QMP greeting message version key which, according to QMP's
documentation, should be:
{ "qemu": { "major": json-int, "minor": json-int, "micro": json-int }
"package": json-string }
"""
check_key_is_dict(version, "qemu")
check_key_is_str(version, "package")
def test_greeting(greeting):
check_key_is_dict(greeting, "QMP")
check_key_is_dict(greeting["QMP"], "version")
check_key_is_list(greeting["QMP"], "capabilities")
def greeting_suite(monitor):
"""
Check the greeting message format, as described in the QMP
specfication section '2.2 Server Greeting'.
{ "QMP": { "version": json-object, "capabilities": json-array } }
"""
greeting = monitor.get_greeting()
test_greeting(greeting)
test_version(greeting["QMP"]["version"])
def json_parsing_errors_suite(monitor):
"""
Check that QMP's parser is able to recover from parsing errors, please
check the JSON spec for more info on the JSON syntax (RFC 4627).
"""
# We're quite simple right now and the focus is on parsing errors that
# have already biten us in the past.
#
# TODO: The following test-cases are missing:
#
# - JSON numbers, strings and arrays
# - More invalid characters or malformed structures
# - Valid, but not obvious syntax, like zillion of spaces or
# strings with unicode chars (different suite maybe?)
bad_json = []
# A JSON value MUST be an object, array, number, string, true, false,
# or null
#
# NOTE: QMP seems to ignore a number of chars, like: | and ?
bad_json.append(":")
bad_json.append(",")
# Malformed json-objects
#
# NOTE: sending only "}" seems to break QMP
# NOTE: Duplicate keys are accepted (should it?)
bad_json.append("{ \"execute\" }")
bad_json.append("{ \"execute\": \"query-version\", }")
bad_json.append("{ 1: \"query-version\" }")
bad_json.append("{ true: \"query-version\" }")
bad_json.append("{ []: \"query-version\" }")
bad_json.append("{ {}: \"query-version\" }")
for cmd in bad_json:
resp = monitor.cmd_raw(cmd)
check_error_resp(resp, "JSONParsing")
def test_id_key(monitor):
"""
Check that QMP's "id" key is correctly handled.
"""
# The "id" key must be echoed back in error responses
id_key = "virt-test"
resp = monitor.cmd_qmp("eject", {"foobar": True}, q_id=id_key)
check_error_resp(resp)
check_str_key(resp, "id", id_key)
# The "id" key must be echoed back in success responses
resp = monitor.cmd_qmp("query-status", q_id=id_key)
check_success_resp(resp)
check_str_key(resp, "id", id_key)
# The "id" key can be any json-object
for id_key in (True, 1234, "string again!", [1, [], {}, True, "foo"],
{"key": {}}):
resp = monitor.cmd_qmp("query-status", q_id=id_key)
check_success_resp(resp)
if resp["id"] != id_key:
raise error.TestFail("expected id '%s' but got '%s'" %
(str(id_key), str(resp["id"])))
def test_invalid_arg_key(monitor):
"""
Currently, the only supported keys in the input object are: "execute",
"arguments" and "id". Although expansion is supported, invalid key
names must be detected.
"""
resp = monitor.cmd_obj({"execute": "eject", "foobar": True})
expected_error = "QMPExtraInputObjectMember"
data_dict = {"member": "foobar"}
check_error_resp(resp, expected_error, data_dict)
def test_bad_arguments_key_type(monitor):
"""
The "arguments" key must be an json-object.
We use the eject command to perform the tests, but that's a random
choice, any command that accepts arguments will do, as the command
doesn't get called.
"""
for item in (True, [], 1, "foo"):
resp = monitor.cmd_obj({"execute": "eject", "arguments": item})
check_error_resp(resp, "QMPBadInputObjectMember",
{"member": "arguments", "expected": "object"})
def test_bad_execute_key_type(monitor):
"""
The "execute" key must be a json-string.
"""
for item in (False, 1, {}, []):
resp = monitor.cmd_obj({"execute": item})
check_error_resp(resp, "QMPBadInputObjectMember",
{"member": "execute", "expected": "string"})
def test_no_execute_key(monitor):
"""
The "execute" key must exist, we also test for some stupid parsing
errors.
"""
for cmd in ({}, {"execut": "qmp_capabilities"},
{"executee": "qmp_capabilities"}, {"foo": "bar"}):
resp = monitor.cmd_obj(cmd)
check_error_resp(resp) # XXX: check class and data dict?
def test_bad_input_obj_type(monitor):
"""
The input object must be... an json-object.
"""
for cmd in ("foo", [], True, 1):
resp = monitor.cmd_obj(cmd)
check_error_resp(resp, "QMPBadInputObject", {"expected": "object"})
def test_good_input_obj(monitor):
| """
Basic success tests for issuing QMP commands.
"""
# NOTE: We don't use the cmd_qmp() method here because the command
# object is in a 'random' order
resp = monitor.cmd_obj({"execute": "query-version"})
check_success_resp(resp)
resp = monitor.cmd_obj({"arguments": {}, "execute": "query-version"})
check_success_resp(resp)
id_key = "1234foo"
resp = monitor.cmd_obj({"id": id_key, "execute": "query-version",
"arguments": {}})
check_success_resp(resp)
check_str_key(resp, "id", id_key)
# TODO: would be good to test simple argument usage, but we don't have
# a read-only command that accepts arguments. | identifier_body |
|
qmp_basic_rhel6.py | (qmp_dict, key):
if not isinstance(qmp_dict, dict):
raise error.TestFail("qmp_dict is not a dict (it's '%s')" %
type(qmp_dict))
if key not in qmp_dict:
raise error.TestFail("'%s' key doesn't exist in dict ('%s')" %
(key, str(qmp_dict)))
def check_dict_key(qmp_dict, key, keytype):
"""
Performs the following checks on a QMP dict key:
1. qmp_dict is a dict
2. key exists in qmp_dict
3. key is of type keytype
If any of these checks fails, error.TestFail is raised.
"""
fail_no_key(qmp_dict, key)
if not isinstance(qmp_dict[key], keytype):
raise error.TestFail("'%s' key is not of type '%s', it's '%s'" %
(key, keytype, type(qmp_dict[key])))
def check_key_is_dict(qmp_dict, key):
check_dict_key(qmp_dict, key, dict)
def check_key_is_list(qmp_dict, key):
check_dict_key(qmp_dict, key, list)
def check_key_is_str(qmp_dict, key):
check_dict_key(qmp_dict, key, unicode)
def check_str_key(qmp_dict, keyname, value=None):
check_dict_key(qmp_dict, keyname, unicode)
if value and value != qmp_dict[keyname]:
raise error.TestFail("'%s' key value '%s' should be '%s'" %
(keyname, str(qmp_dict[keyname]), str(value)))
def check_key_is_int(qmp_dict, key):
fail_no_key(qmp_dict, key)
try:
int(qmp_dict[key])
except Exception:
raise error.TestFail("'%s' key is not of type int, it's '%s'" %
(key, type(qmp_dict[key])))
def check_bool_key(qmp_dict, keyname, value=None):
check_dict_key(qmp_dict, keyname, bool)
if value and value != qmp_dict[keyname]:
raise error.TestFail("'%s' key value '%s' should be '%s'" %
(keyname, str(qmp_dict[keyname]), str(value)))
def check_success_resp(resp, empty=False):
"""
Check QMP OK response.
:param resp: QMP response
:param empty: if True, response should not contain data to return
"""
check_key_is_dict(resp, "return")
if empty and len(resp["return"]) > 0:
raise error.TestFail("success response is not empty ('%s')" %
str(resp))
def check_error_resp(resp, classname=None, datadict=None):
"""
Check QMP error response.
:param resp: QMP response
:param classname: Expected error class name
:param datadict: Expected error data dictionary
"""
logging.debug("resp %s", str(resp))
check_key_is_dict(resp, "error")
check_key_is_str(resp["error"], "class")
if classname and resp["error"]["class"] != classname:
raise error.TestFail("got error class '%s' expected '%s'" %
(resp["error"]["class"], classname))
check_key_is_dict(resp["error"], "data")
if datadict and resp["error"]["data"] != datadict:
raise error.TestFail("got data dict '%s' expected '%s'" %
(resp["error"]["data"], datadict))
def test_version(version):
"""
Check the QMP greeting message version key which, according to QMP's
documentation, should be:
{ "qemu": { "major": json-int, "minor": json-int, "micro": json-int }
"package": json-string }
"""
check_key_is_dict(version, "qemu")
check_key_is_str(version, "package")
def test_greeting(greeting):
check_key_is_dict(greeting, "QMP")
check_key_is_dict(greeting["QMP"], "version")
check_key_is_list(greeting["QMP"], "capabilities")
def greeting_suite(monitor):
"""
Check the greeting message format, as described in the QMP
specfication section '2.2 Server Greeting'.
{ "QMP": { "version": json-object, "capabilities": json-array } }
"""
greeting = monitor.get_greeting()
test_greeting(greeting)
test_version(greeting["QMP"]["version"])
def json_parsing_errors_suite(monitor):
"""
Check that QMP's parser is able to recover from parsing errors, please
check the JSON spec for more info on the JSON syntax (RFC 4627).
"""
# We're quite simple right now and the focus is on parsing errors that
# have already biten us in the past.
#
# TODO: The following test-cases are missing:
#
# - JSON numbers, strings and arrays
# - More invalid characters or malformed structures
# - Valid, but not obvious syntax, like zillion of spaces or
# strings with unicode chars (different suite maybe?)
bad_json = []
# A JSON value MUST be an object, array, number, string, true, false,
# or null
#
# NOTE: QMP seems to ignore a number of chars, like: | and ?
bad_json.append(":")
bad_json.append(",")
# Malformed json-objects
#
# NOTE: sending only "}" seems to break QMP
# NOTE: Duplicate keys are accepted (should it?)
bad_json.append("{ \"execute\" }")
bad_json.append("{ \"execute\": \"query-version\", }")
bad_json.append("{ 1: \"query-version\" }")
bad_json.append("{ true: \"query-version\" }")
bad_json.append("{ []: \"query-version\" }")
bad_json.append("{ {}: \"query-version\" }")
for cmd in bad_json:
resp = monitor.cmd_raw(cmd)
check_error_resp(resp, "JSONParsing")
def test_id_key(monitor):
"""
Check that QMP's "id" key is correctly handled.
"""
# The "id" key must be echoed back in error responses
id_key = "virt-test"
resp = monitor.cmd_qmp("eject", {"foobar": True}, q_id=id_key)
check_error_resp(resp)
check_str_key(resp, "id", id_key)
# The "id" key must be echoed back in success responses
resp = monitor.cmd_qmp("query-status", q_id=id_key)
check_success_resp(resp)
check_str_key(resp, "id", id_key)
# The "id" key can be any json-object
for id_key in (True, 1234, "string again!", [1, [], {}, True, "foo"],
{"key": {}}):
resp = monitor.cmd_qmp("query-status", q_id=id_key)
check_success_resp(resp)
if resp["id"] != id_key:
raise error.TestFail("expected id '%s' but got '%s'" %
(str(id_key), str(resp["id"])))
def test_invalid_arg_key(monitor):
"""
Currently, the only supported keys in the input object are: "execute",
"arguments" and "id". Although expansion is supported, invalid key
names must be detected.
"""
resp = monitor.cmd_obj({"execute": "eject", "foobar": True})
expected_error = "QMPExtraInputObjectMember"
data_dict = {"member": "foobar"}
check_error_resp(resp, expected_error, data_dict)
def test_bad_arguments_key_type(monitor):
"""
The "arguments" key must be an json-object.
We use the eject command to perform the tests, but that's a random
choice, any command that accepts arguments will do, as the command
doesn't get called.
"""
for item in (True, [], 1, "foo"):
resp = monitor.cmd_obj({"execute": "eject", "arguments": item})
check_error_resp(resp, "QMPBadInputObjectMember",
{"member": "arguments", "expected": "object"})
def test_bad_execute_key_type(monitor):
"""
The "execute" key must be a json-string.
"""
for item in (False, 1, {}, []):
resp = monitor.cmd_obj({"execute": item})
check_error_resp(resp, "QMPBadInputObjectMember",
{"member": "execute", "expected": "string"})
def test_no_execute_key(monitor):
"""
The "execute" key must exist, we also test for some stupid parsing
errors.
"""
for cmd in ({}, {"execut": "qmp_capabilities"},
{"executee": "qmp_capabilities"}, {"foo": "bar"}):
resp = monitor.cmd_obj(cmd)
check_error_resp(resp) # XXX: check class and data dict?
def test_bad_input_obj_type(monitor):
"""
The input object must be... an json-object.
"""
for cmd in ("foo", [], True, 1):
resp = monitor.cmd_obj(cmd)
check_error_resp(resp, "QMPBad | fail_no_key | identifier_name |
|
NavButton.js | import React, { Component, PropTypes } from 'react';
/*** Third Party Components ***/
import Dialog from 'react-toolbox/lib/dialog';
import { Button, IconButton } from 'react-toolbox/lib/button';
import Icon from 'react-fa';
import style from './style.scss';
class NavButton extends Component {
constructor(props) {
super(props);
this.state = {
open: false
};
}
handleOpen = () => { | };
handleClose = () => {
this.setState({
open: false
});
};
render() {
return (
<div className={`${style.root} ${this.props.className}`} >
<IconButton
className={style.navBars}
neutral={false}
onClick={this.handleOpen}>
<Icon
name={this.state.open ? 'times-circle-o' : 'bars'} />
</IconButton>
<Dialog
active={this.state.open}
onOverlayClick={this.handleClose}
className={style.dialog} >
<Button
flat
label="What is this?"
target="_blank"
neutral={false}
className={style.link} />
<Button
flat
label="Why?"
target="_blank"
neutral={false}
className={style.link} />
<Button
flat
label="Contact"
target="_blank"
neutral={false}
className={style.link} />
</Dialog>
</div>
);
}
}
export default NavButton; | this.setState({
open: true
}); | random_line_split |
NavButton.js | import React, { Component, PropTypes } from 'react';
/*** Third Party Components ***/
import Dialog from 'react-toolbox/lib/dialog';
import { Button, IconButton } from 'react-toolbox/lib/button';
import Icon from 'react-fa';
import style from './style.scss';
class NavButton extends Component {
constructor(props) {
super(props);
this.state = {
open: false
};
}
handleOpen = () => {
this.setState({
open: true
});
};
handleClose = () => {
this.setState({
open: false
});
};
| () {
return (
<div className={`${style.root} ${this.props.className}`} >
<IconButton
className={style.navBars}
neutral={false}
onClick={this.handleOpen}>
<Icon
name={this.state.open ? 'times-circle-o' : 'bars'} />
</IconButton>
<Dialog
active={this.state.open}
onOverlayClick={this.handleClose}
className={style.dialog} >
<Button
flat
label="What is this?"
target="_blank"
neutral={false}
className={style.link} />
<Button
flat
label="Why?"
target="_blank"
neutral={false}
className={style.link} />
<Button
flat
label="Contact"
target="_blank"
neutral={false}
className={style.link} />
</Dialog>
</div>
);
}
}
export default NavButton; | render | identifier_name |
NavButton.js | import React, { Component, PropTypes } from 'react';
/*** Third Party Components ***/
import Dialog from 'react-toolbox/lib/dialog';
import { Button, IconButton } from 'react-toolbox/lib/button';
import Icon from 'react-fa';
import style from './style.scss';
class NavButton extends Component {
constructor(props) {
super(props);
this.state = {
open: false
};
}
handleOpen = () => {
this.setState({
open: true
});
};
handleClose = () => {
this.setState({
open: false
});
};
render() | neutral={false}
className={style.link} />
<Button
flat
label="Why?"
target="_blank"
neutral={false}
className={style.link} />
<Button
flat
label="Contact"
target="_blank"
neutral={false}
className={style.link} />
</Dialog>
</div>
);
}
}
export default NavButton; | {
return (
<div className={`${style.root} ${this.props.className}`} >
<IconButton
className={style.navBars}
neutral={false}
onClick={this.handleOpen}>
<Icon
name={this.state.open ? 'times-circle-o' : 'bars'} />
</IconButton>
<Dialog
active={this.state.open}
onOverlayClick={this.handleClose}
className={style.dialog} >
<Button
flat
label="What is this?"
target="_blank" | identifier_body |
close_on_drop.rs | #![cfg(all(feature = "os-poll", feature = "net"))]
use std::io::Read;
use log::debug;
use mio::net::{TcpListener, TcpStream};
use mio::{Events, Interest, Poll, Token};
mod util;
use util::{any_local_address, init};
use self::TestState::{AfterRead, Initial};
const SERVER: Token = Token(0);
const CLIENT: Token = Token(1);
#[derive(Debug, PartialEq)]
enum TestState {
Initial,
AfterRead,
}
struct TestHandler {
srv: TcpListener,
cli: TcpStream,
state: TestState,
shutdown: bool,
}
impl TestHandler {
fn new(srv: TcpListener, cli: TcpStream) -> TestHandler {
TestHandler {
srv,
cli,
state: Initial,
shutdown: false,
}
}
fn handle_read(&mut self, poll: &mut Poll, tok: Token) {
debug!("readable; tok={:?}", tok);
match tok {
SERVER => {
debug!("server connection ready for accept");
let _ = self.srv.accept().unwrap();
}
CLIENT => {
debug!("client readable");
match self.state {
Initial => {
let mut buf = [0; 4096];
debug!("GOT={:?}", self.cli.read(&mut buf[..]));
self.state = AfterRead;
}
AfterRead => {}
}
let mut buf = Vec::with_capacity(1024);
match self.cli.read(&mut buf) {
Ok(0) => self.shutdown = true,
Ok(_) => panic!("the client socket should not be readable"),
Err(e) => panic!("Unexpected error {:?}", e),
}
}
_ => panic!("received unknown token {:?}", tok),
}
poll.registry()
.reregister(&mut self.cli, CLIENT, Interest::READABLE)
.unwrap();
}
fn handle_write(&mut self, poll: &mut Poll, tok: Token) {
match tok {
SERVER => panic!("received writable for token 0"),
CLIENT => {
debug!("client connected");
poll.registry()
.reregister(&mut self.cli, CLIENT, Interest::READABLE)
.unwrap();
}
_ => panic!("received unknown token {:?}", tok),
}
}
}
#[test]
pub fn | () {
init();
debug!("Starting TEST_CLOSE_ON_DROP");
let mut poll = Poll::new().unwrap();
// == Create & setup server socket
let mut srv = TcpListener::bind(any_local_address()).unwrap();
let addr = srv.local_addr().unwrap();
poll.registry()
.register(&mut srv, SERVER, Interest::READABLE)
.unwrap();
// == Create & setup client socket
let mut sock = TcpStream::connect(addr).unwrap();
poll.registry()
.register(&mut sock, CLIENT, Interest::WRITABLE)
.unwrap();
// == Create storage for events
let mut events = Events::with_capacity(1024);
// == Setup test handler
let mut handler = TestHandler::new(srv, sock);
// == Run test
while !handler.shutdown {
poll.poll(&mut events, None).unwrap();
for event in &events {
if event.is_readable() {
handler.handle_read(&mut poll, event.token());
}
if event.is_writable() {
handler.handle_write(&mut poll, event.token());
}
}
}
assert!(handler.state == AfterRead, "actual={:?}", handler.state);
}
| close_on_drop | identifier_name |
close_on_drop.rs | #![cfg(all(feature = "os-poll", feature = "net"))]
use std::io::Read;
use log::debug;
use mio::net::{TcpListener, TcpStream};
use mio::{Events, Interest, Poll, Token};
mod util;
use util::{any_local_address, init};
use self::TestState::{AfterRead, Initial};
const SERVER: Token = Token(0);
const CLIENT: Token = Token(1);
#[derive(Debug, PartialEq)]
enum TestState {
Initial,
AfterRead,
}
struct TestHandler {
srv: TcpListener,
cli: TcpStream,
state: TestState,
shutdown: bool,
}
impl TestHandler {
fn new(srv: TcpListener, cli: TcpStream) -> TestHandler {
TestHandler {
srv,
cli,
state: Initial,
shutdown: false,
}
}
fn handle_read(&mut self, poll: &mut Poll, tok: Token) {
debug!("readable; tok={:?}", tok);
match tok {
SERVER => {
debug!("server connection ready for accept");
let _ = self.srv.accept().unwrap();
}
CLIENT => {
debug!("client readable");
match self.state {
Initial => {
let mut buf = [0; 4096];
debug!("GOT={:?}", self.cli.read(&mut buf[..]));
self.state = AfterRead;
}
AfterRead => {}
}
let mut buf = Vec::with_capacity(1024);
match self.cli.read(&mut buf) {
Ok(0) => self.shutdown = true,
Ok(_) => panic!("the client socket should not be readable"),
Err(e) => panic!("Unexpected error {:?}", e),
}
}
_ => panic!("received unknown token {:?}", tok),
}
poll.registry()
.reregister(&mut self.cli, CLIENT, Interest::READABLE)
.unwrap();
}
fn handle_write(&mut self, poll: &mut Poll, tok: Token) {
match tok {
SERVER => panic!("received writable for token 0"),
CLIENT => {
debug!("client connected");
poll.registry()
.reregister(&mut self.cli, CLIENT, Interest::READABLE)
.unwrap();
}
_ => panic!("received unknown token {:?}", tok),
}
}
}
#[test]
pub fn close_on_drop() {
init();
debug!("Starting TEST_CLOSE_ON_DROP");
let mut poll = Poll::new().unwrap();
// == Create & setup server socket
let mut srv = TcpListener::bind(any_local_address()).unwrap();
let addr = srv.local_addr().unwrap();
poll.registry()
.register(&mut srv, SERVER, Interest::READABLE)
.unwrap();
// == Create & setup client socket
let mut sock = TcpStream::connect(addr).unwrap();
poll.registry()
.register(&mut sock, CLIENT, Interest::WRITABLE)
.unwrap();
// == Create storage for events
let mut events = Events::with_capacity(1024);
// == Setup test handler
let mut handler = TestHandler::new(srv, sock);
// == Run test
while !handler.shutdown {
poll.poll(&mut events, None).unwrap();
for event in &events {
if event.is_readable() {
handler.handle_read(&mut poll, event.token());
}
if event.is_writable() |
}
}
assert!(handler.state == AfterRead, "actual={:?}", handler.state);
}
| {
handler.handle_write(&mut poll, event.token());
} | conditional_block |
close_on_drop.rs | #![cfg(all(feature = "os-poll", feature = "net"))]
use std::io::Read;
use log::debug;
use mio::net::{TcpListener, TcpStream};
use mio::{Events, Interest, Poll, Token};
mod util;
use util::{any_local_address, init};
use self::TestState::{AfterRead, Initial};
const SERVER: Token = Token(0);
const CLIENT: Token = Token(1);
#[derive(Debug, PartialEq)]
enum TestState {
Initial,
AfterRead,
}
struct TestHandler {
srv: TcpListener,
cli: TcpStream,
state: TestState,
shutdown: bool,
}
impl TestHandler {
fn new(srv: TcpListener, cli: TcpStream) -> TestHandler {
TestHandler {
srv,
cli,
state: Initial,
shutdown: false,
}
}
fn handle_read(&mut self, poll: &mut Poll, tok: Token) {
debug!("readable; tok={:?}", tok);
match tok {
SERVER => {
debug!("server connection ready for accept");
let _ = self.srv.accept().unwrap();
}
CLIENT => {
debug!("client readable");
match self.state {
Initial => {
let mut buf = [0; 4096];
debug!("GOT={:?}", self.cli.read(&mut buf[..]));
self.state = AfterRead;
}
AfterRead => {}
}
let mut buf = Vec::with_capacity(1024);
match self.cli.read(&mut buf) {
Ok(0) => self.shutdown = true,
Ok(_) => panic!("the client socket should not be readable"),
Err(e) => panic!("Unexpected error {:?}", e),
}
}
_ => panic!("received unknown token {:?}", tok),
}
poll.registry()
.reregister(&mut self.cli, CLIENT, Interest::READABLE)
.unwrap();
}
fn handle_write(&mut self, poll: &mut Poll, tok: Token) |
}
#[test]
pub fn close_on_drop() {
init();
debug!("Starting TEST_CLOSE_ON_DROP");
let mut poll = Poll::new().unwrap();
// == Create & setup server socket
let mut srv = TcpListener::bind(any_local_address()).unwrap();
let addr = srv.local_addr().unwrap();
poll.registry()
.register(&mut srv, SERVER, Interest::READABLE)
.unwrap();
// == Create & setup client socket
let mut sock = TcpStream::connect(addr).unwrap();
poll.registry()
.register(&mut sock, CLIENT, Interest::WRITABLE)
.unwrap();
// == Create storage for events
let mut events = Events::with_capacity(1024);
// == Setup test handler
let mut handler = TestHandler::new(srv, sock);
// == Run test
while !handler.shutdown {
poll.poll(&mut events, None).unwrap();
for event in &events {
if event.is_readable() {
handler.handle_read(&mut poll, event.token());
}
if event.is_writable() {
handler.handle_write(&mut poll, event.token());
}
}
}
assert!(handler.state == AfterRead, "actual={:?}", handler.state);
}
| {
match tok {
SERVER => panic!("received writable for token 0"),
CLIENT => {
debug!("client connected");
poll.registry()
.reregister(&mut self.cli, CLIENT, Interest::READABLE)
.unwrap();
}
_ => panic!("received unknown token {:?}", tok),
}
} | identifier_body |
close_on_drop.rs | #![cfg(all(feature = "os-poll", feature = "net"))]
use std::io::Read;
use log::debug;
use mio::net::{TcpListener, TcpStream};
use mio::{Events, Interest, Poll, Token};
mod util;
use util::{any_local_address, init};
use self::TestState::{AfterRead, Initial};
const SERVER: Token = Token(0);
const CLIENT: Token = Token(1);
#[derive(Debug, PartialEq)]
enum TestState {
Initial,
AfterRead,
}
struct TestHandler {
srv: TcpListener,
cli: TcpStream,
state: TestState,
shutdown: bool,
}
impl TestHandler {
fn new(srv: TcpListener, cli: TcpStream) -> TestHandler {
TestHandler {
srv,
cli,
state: Initial,
shutdown: false,
}
}
fn handle_read(&mut self, poll: &mut Poll, tok: Token) {
debug!("readable; tok={:?}", tok);
match tok {
SERVER => {
debug!("server connection ready for accept");
let _ = self.srv.accept().unwrap();
}
CLIENT => {
debug!("client readable");
match self.state {
Initial => {
let mut buf = [0; 4096];
debug!("GOT={:?}", self.cli.read(&mut buf[..]));
self.state = AfterRead;
}
AfterRead => {}
}
let mut buf = Vec::with_capacity(1024);
match self.cli.read(&mut buf) {
Ok(0) => self.shutdown = true,
Ok(_) => panic!("the client socket should not be readable"),
Err(e) => panic!("Unexpected error {:?}", e),
}
}
_ => panic!("received unknown token {:?}", tok),
}
poll.registry()
.reregister(&mut self.cli, CLIENT, Interest::READABLE)
.unwrap();
}
fn handle_write(&mut self, poll: &mut Poll, tok: Token) {
match tok {
SERVER => panic!("received writable for token 0"),
CLIENT => {
debug!("client connected");
poll.registry()
.reregister(&mut self.cli, CLIENT, Interest::READABLE)
.unwrap();
}
_ => panic!("received unknown token {:?}", tok),
}
}
}
#[test]
pub fn close_on_drop() {
init();
debug!("Starting TEST_CLOSE_ON_DROP");
let mut poll = Poll::new().unwrap();
// == Create & setup server socket
let mut srv = TcpListener::bind(any_local_address()).unwrap();
let addr = srv.local_addr().unwrap(); |
// == Create & setup client socket
let mut sock = TcpStream::connect(addr).unwrap();
poll.registry()
.register(&mut sock, CLIENT, Interest::WRITABLE)
.unwrap();
// == Create storage for events
let mut events = Events::with_capacity(1024);
// == Setup test handler
let mut handler = TestHandler::new(srv, sock);
// == Run test
while !handler.shutdown {
poll.poll(&mut events, None).unwrap();
for event in &events {
if event.is_readable() {
handler.handle_read(&mut poll, event.token());
}
if event.is_writable() {
handler.handle_write(&mut poll, event.token());
}
}
}
assert!(handler.state == AfterRead, "actual={:?}", handler.state);
} |
poll.registry()
.register(&mut srv, SERVER, Interest::READABLE)
.unwrap(); | random_line_split |
angryProfessor.js | // Problem - https://www.hackerrank.com/challenges/angry-professor
function processData(input) {
var lines = input.split('\n'),
numberTestCases = parseInt(lines.shift());
for (var i = 0; i < numberTestCases*2; i += 2) {
var leastNumber = lines[i].split(' ')[1],
studentsArrival = lines[i + 1].split(' '),
arrivedInTime = 0;
studentsArrival.forEach(function(time) {
if (time <= 0) {
arrivedInTime++;
}
});
if (leastNumber <= arrivedInTime) {
console.log("NO");
} else {
console.log("YES"); | }
}
}
processData("10\n"+
"10 4\n" +
"-93 -86 49 -62 -90 -63 40 72 11 67\n" +
"10 10\n" +
"23 -35 -2 58 -67 -56 -42 -73 -19 37\n" +
"10 9\n" +
"13 91 56 -62 96 -5 -84 -36 -46 -13\n" +
"10 8\n" +
"45 67 64 -50 -8 78 84 -51 99 60\n" +
"10 7\n" +
"26 94 -95 34 67 -97 17 52 1 86\n" +
"10 2\n" +
"19 29 -17 -71 -75 -27 -56 -53 65 83\n" +
"10 10\n" +
"-32 -3 -70 8 -40 -96 -18 -46 -21 -79\n" +
"10 9\n" +
"-50 0 64 14 -56 -91 -65 -36 51 -28\n" +
"10 6\n" +
"-58 -29 -35 -18 43 -28 -76 43 -13 6\n" +
"10 1\n" +
"88 -17 -96 43 83 99 25 90 -39 86\n"); | random_line_split |
|
angryProfessor.js | // Problem - https://www.hackerrank.com/challenges/angry-professor
function processData(input) {
var lines = input.split('\n'),
numberTestCases = parseInt(lines.shift());
for (var i = 0; i < numberTestCases*2; i += 2) |
}
processData("10\n"+
"10 4\n" +
"-93 -86 49 -62 -90 -63 40 72 11 67\n" +
"10 10\n" +
"23 -35 -2 58 -67 -56 -42 -73 -19 37\n" +
"10 9\n" +
"13 91 56 -62 96 -5 -84 -36 -46 -13\n" +
"10 8\n" +
"45 67 64 -50 -8 78 84 -51 99 60\n" +
"10 7\n" +
"26 94 -95 34 67 -97 17 52 1 86\n" +
"10 2\n" +
"19 29 -17 -71 -75 -27 -56 -53 65 83\n" +
"10 10\n" +
"-32 -3 -70 8 -40 -96 -18 -46 -21 -79\n" +
"10 9\n" +
"-50 0 64 14 -56 -91 -65 -36 51 -28\n" +
"10 6\n" +
"-58 -29 -35 -18 43 -28 -76 43 -13 6\n" +
"10 1\n" +
"88 -17 -96 43 83 99 25 90 -39 86\n"); | {
var leastNumber = lines[i].split(' ')[1],
studentsArrival = lines[i + 1].split(' '),
arrivedInTime = 0;
studentsArrival.forEach(function(time) {
if (time <= 0) {
arrivedInTime++;
}
});
if (leastNumber <= arrivedInTime) {
console.log("NO");
} else {
console.log("YES");
}
} | conditional_block |
angryProfessor.js | // Problem - https://www.hackerrank.com/challenges/angry-professor
function processData(input) | }
}
processData("10\n"+
"10 4\n" +
"-93 -86 49 -62 -90 -63 40 72 11 67\n" +
"10 10\n" +
"23 -35 -2 58 -67 -56 -42 -73 -19 37\n" +
"10 9\n" +
"13 91 56 -62 96 -5 -84 -36 -46 -13\n" +
"10 8\n" +
"45 67 64 -50 -8 78 84 -51 99 60\n" +
"10 7\n" +
"26 94 -95 34 67 -97 17 52 1 86\n" +
"10 2\n" +
"19 29 -17 -71 -75 -27 -56 -53 65 83\n" +
"10 10\n" +
"-32 -3 -70 8 -40 -96 -18 -46 -21 -79\n" +
"10 9\n" +
"-50 0 64 14 -56 -91 -65 -36 51 -28\n" +
"10 6\n" +
"-58 -29 -35 -18 43 -28 -76 43 -13 6\n" +
"10 1\n" +
"88 -17 -96 43 83 99 25 90 -39 86\n"); | {
var lines = input.split('\n'),
numberTestCases = parseInt(lines.shift());
for (var i = 0; i < numberTestCases*2; i += 2) {
var leastNumber = lines[i].split(' ')[1],
studentsArrival = lines[i + 1].split(' '),
arrivedInTime = 0;
studentsArrival.forEach(function(time) {
if (time <= 0) {
arrivedInTime++;
}
});
if (leastNumber <= arrivedInTime) {
console.log("NO");
} else {
console.log("YES");
} | identifier_body |
angryProfessor.js | // Problem - https://www.hackerrank.com/challenges/angry-professor
function | (input) {
var lines = input.split('\n'),
numberTestCases = parseInt(lines.shift());
for (var i = 0; i < numberTestCases*2; i += 2) {
var leastNumber = lines[i].split(' ')[1],
studentsArrival = lines[i + 1].split(' '),
arrivedInTime = 0;
studentsArrival.forEach(function(time) {
if (time <= 0) {
arrivedInTime++;
}
});
if (leastNumber <= arrivedInTime) {
console.log("NO");
} else {
console.log("YES");
}
}
}
processData("10\n"+
"10 4\n" +
"-93 -86 49 -62 -90 -63 40 72 11 67\n" +
"10 10\n" +
"23 -35 -2 58 -67 -56 -42 -73 -19 37\n" +
"10 9\n" +
"13 91 56 -62 96 -5 -84 -36 -46 -13\n" +
"10 8\n" +
"45 67 64 -50 -8 78 84 -51 99 60\n" +
"10 7\n" +
"26 94 -95 34 67 -97 17 52 1 86\n" +
"10 2\n" +
"19 29 -17 -71 -75 -27 -56 -53 65 83\n" +
"10 10\n" +
"-32 -3 -70 8 -40 -96 -18 -46 -21 -79\n" +
"10 9\n" +
"-50 0 64 14 -56 -91 -65 -36 51 -28\n" +
"10 6\n" +
"-58 -29 -35 -18 43 -28 -76 43 -13 6\n" +
"10 1\n" +
"88 -17 -96 43 83 99 25 90 -39 86\n"); | processData | identifier_name |
transaction-relay.component.ts | import {Component, Output, Injectable, OnInit, Input, OnChanges} from '@angular/core';
import {CommonModelRelayService, Filter} from "../common/common-model-relay.service";
import {Transaction} from "./transaction";
import {TransactionReqService} from "./transaction-req.service";
import {CommonRelayComponent} from "../common/common-relay.component";
@Injectable()
export class TransactionModelRelayService extends CommonModelRelayService<Transaction> {
constructor(svc: TransactionReqService) { super(svc); }
}
@Component({
selector: 'transaction-relay',
template: `<div *ngIf="false"> Transactions: {{transactions | async | json}}</div>`
})
export class TransactionRelayComponent extends CommonRelayComponent<Transaction> implements OnInit {
@Input('filter') filterField: Filter;
@Output() transactions = this.relay.changed;
| super(relay);
}
ngOnInit(): void {
this.filter(this.filterField);
this.refresh();
}
//TODO change name
sendFilter() {
this.filter(this.filterField);
}
} | constructor(relay: TransactionModelRelayService) { | random_line_split |
transaction-relay.component.ts | import {Component, Output, Injectable, OnInit, Input, OnChanges} from '@angular/core';
import {CommonModelRelayService, Filter} from "../common/common-model-relay.service";
import {Transaction} from "./transaction";
import {TransactionReqService} from "./transaction-req.service";
import {CommonRelayComponent} from "../common/common-relay.component";
@Injectable()
export class TransactionModelRelayService extends CommonModelRelayService<Transaction> {
| (svc: TransactionReqService) { super(svc); }
}
@Component({
selector: 'transaction-relay',
template: `<div *ngIf="false"> Transactions: {{transactions | async | json}}</div>`
})
export class TransactionRelayComponent extends CommonRelayComponent<Transaction> implements OnInit {
@Input('filter') filterField: Filter;
@Output() transactions = this.relay.changed;
constructor(relay: TransactionModelRelayService) {
super(relay);
}
ngOnInit(): void {
this.filter(this.filterField);
this.refresh();
}
//TODO change name
sendFilter() {
this.filter(this.filterField);
}
} | constructor | identifier_name |
manage.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import subprocess
from flask.ext.script import Manager, Shell, Server
from flask.ext.migrate import MigrateCommand
from foobar.app import create_app
from foobar.user.models import User
from foobar.settings import DevConfig, ProdConfig
from foobar.database import db
if os.environ.get("FOOBAR_ENV") == 'prod':
app = create_app(ProdConfig)
else:
|
HERE = os.path.abspath(os.path.dirname(__file__))
TEST_PATH = os.path.join(HERE, 'tests')
manager = Manager(app)
def _make_context():
"""Return context dict for a shell session so you can access
app, db, and the User model by default.
"""
return {'app': app, 'db': db, 'User': User}
@manager.command
def test():
"""Run the tests."""
import pytest
exit_code = pytest.main([TEST_PATH, '--verbose'])
return exit_code
manager.add_command('server', Server())
manager.add_command('shell', Shell(make_context=_make_context))
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
| app = create_app(DevConfig) | conditional_block |
manage.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import subprocess
from flask.ext.script import Manager, Shell, Server
from flask.ext.migrate import MigrateCommand
from foobar.app import create_app
from foobar.user.models import User
from foobar.settings import DevConfig, ProdConfig
from foobar.database import db
if os.environ.get("FOOBAR_ENV") == 'prod':
app = create_app(ProdConfig)
else:
app = create_app(DevConfig)
HERE = os.path.abspath(os.path.dirname(__file__))
TEST_PATH = os.path.join(HERE, 'tests')
manager = Manager(app)
def _make_context():
"""Return context dict for a shell session so you can access
app, db, and the User model by default.
"""
return {'app': app, 'db': db, 'User': User}
| def test():
"""Run the tests."""
import pytest
exit_code = pytest.main([TEST_PATH, '--verbose'])
return exit_code
manager.add_command('server', Server())
manager.add_command('shell', Shell(make_context=_make_context))
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run() | @manager.command | random_line_split |
manage.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import subprocess
from flask.ext.script import Manager, Shell, Server
from flask.ext.migrate import MigrateCommand
from foobar.app import create_app
from foobar.user.models import User
from foobar.settings import DevConfig, ProdConfig
from foobar.database import db
if os.environ.get("FOOBAR_ENV") == 'prod':
app = create_app(ProdConfig)
else:
app = create_app(DevConfig)
HERE = os.path.abspath(os.path.dirname(__file__))
TEST_PATH = os.path.join(HERE, 'tests')
manager = Manager(app)
def | ():
"""Return context dict for a shell session so you can access
app, db, and the User model by default.
"""
return {'app': app, 'db': db, 'User': User}
@manager.command
def test():
"""Run the tests."""
import pytest
exit_code = pytest.main([TEST_PATH, '--verbose'])
return exit_code
manager.add_command('server', Server())
manager.add_command('shell', Shell(make_context=_make_context))
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
| _make_context | identifier_name |
manage.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import subprocess
from flask.ext.script import Manager, Shell, Server
from flask.ext.migrate import MigrateCommand
from foobar.app import create_app
from foobar.user.models import User
from foobar.settings import DevConfig, ProdConfig
from foobar.database import db
if os.environ.get("FOOBAR_ENV") == 'prod':
app = create_app(ProdConfig)
else:
app = create_app(DevConfig)
HERE = os.path.abspath(os.path.dirname(__file__))
TEST_PATH = os.path.join(HERE, 'tests')
manager = Manager(app)
def _make_context():
|
@manager.command
def test():
"""Run the tests."""
import pytest
exit_code = pytest.main([TEST_PATH, '--verbose'])
return exit_code
manager.add_command('server', Server())
manager.add_command('shell', Shell(make_context=_make_context))
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
| """Return context dict for a shell session so you can access
app, db, and the User model by default.
"""
return {'app': app, 'db': db, 'User': User} | identifier_body |
lib.rs | // Copyright (C) 2020 Natanael Mojica <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 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
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Suite 500,
// Boston, MA 02110-1335, USA.
use gst::gst_plugin_define;
mod filter;
fn plugin_init(plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
filter::register(plugin)?;
Ok(())
}
gst_plugin_define!(
csound,
env!("CARGO_PKG_DESCRIPTION"),
plugin_init,
concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")),
"MIT/X11",
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_REPOSITORY"), | env!("BUILD_REL_DATE")
); | random_line_split |
|
lib.rs | // Copyright (C) 2020 Natanael Mojica <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 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
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Suite 500,
// Boston, MA 02110-1335, USA.
use gst::gst_plugin_define;
mod filter;
fn | (plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
filter::register(plugin)?;
Ok(())
}
gst_plugin_define!(
csound,
env!("CARGO_PKG_DESCRIPTION"),
plugin_init,
concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")),
"MIT/X11",
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_REPOSITORY"),
env!("BUILD_REL_DATE")
);
| plugin_init | identifier_name |
lib.rs | // Copyright (C) 2020 Natanael Mojica <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 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
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Suite 500,
// Boston, MA 02110-1335, USA.
use gst::gst_plugin_define;
mod filter;
fn plugin_init(plugin: &gst::Plugin) -> Result<(), glib::BoolError> |
gst_plugin_define!(
csound,
env!("CARGO_PKG_DESCRIPTION"),
plugin_init,
concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")),
"MIT/X11",
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_REPOSITORY"),
env!("BUILD_REL_DATE")
);
| {
filter::register(plugin)?;
Ok(())
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.